status
stringclasses
1 value
repo_name
stringclasses
31 values
repo_url
stringclasses
31 values
issue_id
int64
1
104k
title
stringlengths
4
369
body
stringlengths
0
254k
issue_url
stringlengths
37
56
pull_url
stringlengths
37
54
before_fix_sha
stringlengths
40
40
after_fix_sha
stringlengths
40
40
report_datetime
timestamp[us, tz=UTC]
language
stringclasses
5 values
commit_datetime
timestamp[us, tz=UTC]
updated_file
stringlengths
4
188
file_content
stringlengths
0
5.12M
closed
electron/electron
https://github.com/electron/electron
18,119
Windows chrome and context menu should be aware of dark mode setting
<!-- As an open source project with a dedicated but small maintainer team, it can sometimes take a long time for issues to be addressed so please be patient and we will get back to you as soon as we can. --> ### Preflight Checklist <!-- Please ensure you've completed the following steps by replacing [ ] with [x]--> * [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. * [x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. * [x] I have searched the issue tracker for a feature request that matches the one I want to file, without success. ### Problem Description Recent builds of Windows 10 support a "dark mode" that changes the chrome and context menus to fit better with the rest of the OS. https://www.digitaltrends.com/computing/how-to-enable-dark-mode-in-windows-10/ has a write up of how to enable this. Here's a side-by-side of Explorer and the Quick Start app on Windows `10.0.17763.437`: ![](https://user-images.githubusercontent.com/359239/57080976-2b782b00-6cca-11e9-8c41-5097e39526d1.png) This is complementary to #15316 but not the whole solution: - it'd be great if the defaults "just worked" based on this setting, so app developers and users would get this benefit without needing to manage configuration themselves - some apps choose to roll their own themes, but they don't have control over the main menu or context menu without also rolling their own implementations of those and hiding the default chrome To go into more detail, here's what a context menu looks like that respects the dark mode setting: ![](https://user-images.githubusercontent.com/359239/57081074-5ebaba00-6cca-11e9-97f7-d30fc030c759.png) And here's the equivalent main menu and context menu in the Electron Quick Start when using Electron 5: ![](https://user-images.githubusercontent.com/359239/57081076-5ebaba00-6cca-11e9-926b-9a18be540bef.png) ![](https://user-images.githubusercontent.com/359239/57081077-5ebaba00-6cca-11e9-8f3e-d3b0d61d3e72.png) ### Proposed Solution I'm not familiar with how this works under the hood, but happy to go spelunking if this is something that interests the maintainers to gather more information. ### Alternatives Considered As mentioned above, app developers can roll their own dark theme for menus and switch to use a chromeless `BrowserWindow`. That's fine for people who want to invest in that, but if there's lots of interest in the default chrome working better then maybe this is worth diving into? ### Additional Information <!-- Add any other context about the problem here. -->
https://github.com/electron/electron/issues/18119
https://github.com/electron/electron/pull/33624
21ef8501e7c71cd8d56828e21d310d07f9d86510
4c7c0b41c2027db27cf563e9eabb95cc8adf96bb
2019-05-02T14:14:11Z
c++
2022-06-14T16:27:28Z
buildflags/BUILD.gn
# Copyright (c) 2018 GitHub, Inc. # Use of this source code is governed by the MIT license that can be # found in the LICENSE file. import("//build/buildflag_header.gni") import("//electron/buildflags/buildflags.gni") buildflag_header("buildflags") { header = "buildflags.h" flags = [ "ENABLE_DESKTOP_CAPTURER=$enable_desktop_capturer", "ENABLE_RUN_AS_NODE=$enable_run_as_node", "ENABLE_OSR=$enable_osr", "ENABLE_VIEWS_API=$enable_views_api", "ENABLE_PDF_VIEWER=$enable_pdf_viewer", "ENABLE_TTS=$enable_tts", "ENABLE_COLOR_CHOOSER=$enable_color_chooser", "ENABLE_ELECTRON_EXTENSIONS=$enable_electron_extensions", "ENABLE_BUILTIN_SPELLCHECKER=$enable_builtin_spellchecker", "ENABLE_PICTURE_IN_PICTURE=$enable_picture_in_picture", "ENABLE_WIN_DARK_MODE_WINDOW_UI=$enable_win_dark_mode_window_ui", "OVERRIDE_LOCATION_PROVIDER=$enable_fake_location_provider", ] }
closed
electron/electron
https://github.com/electron/electron
18,119
Windows chrome and context menu should be aware of dark mode setting
<!-- As an open source project with a dedicated but small maintainer team, it can sometimes take a long time for issues to be addressed so please be patient and we will get back to you as soon as we can. --> ### Preflight Checklist <!-- Please ensure you've completed the following steps by replacing [ ] with [x]--> * [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. * [x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. * [x] I have searched the issue tracker for a feature request that matches the one I want to file, without success. ### Problem Description Recent builds of Windows 10 support a "dark mode" that changes the chrome and context menus to fit better with the rest of the OS. https://www.digitaltrends.com/computing/how-to-enable-dark-mode-in-windows-10/ has a write up of how to enable this. Here's a side-by-side of Explorer and the Quick Start app on Windows `10.0.17763.437`: ![](https://user-images.githubusercontent.com/359239/57080976-2b782b00-6cca-11e9-8c41-5097e39526d1.png) This is complementary to #15316 but not the whole solution: - it'd be great if the defaults "just worked" based on this setting, so app developers and users would get this benefit without needing to manage configuration themselves - some apps choose to roll their own themes, but they don't have control over the main menu or context menu without also rolling their own implementations of those and hiding the default chrome To go into more detail, here's what a context menu looks like that respects the dark mode setting: ![](https://user-images.githubusercontent.com/359239/57081074-5ebaba00-6cca-11e9-97f7-d30fc030c759.png) And here's the equivalent main menu and context menu in the Electron Quick Start when using Electron 5: ![](https://user-images.githubusercontent.com/359239/57081076-5ebaba00-6cca-11e9-926b-9a18be540bef.png) ![](https://user-images.githubusercontent.com/359239/57081077-5ebaba00-6cca-11e9-8f3e-d3b0d61d3e72.png) ### Proposed Solution I'm not familiar with how this works under the hood, but happy to go spelunking if this is something that interests the maintainers to gather more information. ### Alternatives Considered As mentioned above, app developers can roll their own dark theme for menus and switch to use a chromeless `BrowserWindow`. That's fine for people who want to invest in that, but if there's lots of interest in the default chrome working better then maybe this is worth diving into? ### Additional Information <!-- Add any other context about the problem here. -->
https://github.com/electron/electron/issues/18119
https://github.com/electron/electron/pull/33624
21ef8501e7c71cd8d56828e21d310d07f9d86510
4c7c0b41c2027db27cf563e9eabb95cc8adf96bb
2019-05-02T14:14:11Z
c++
2022-06-14T16:27:28Z
buildflags/buildflags.gni
# Copyright (c) 2018 GitHub, Inc. # Use of this source code is governed by the MIT license that can be # found in the LICENSE file. declare_args() { enable_desktop_capturer = true # Allow running Electron as a node binary. enable_run_as_node = true enable_osr = true enable_views_api = true enable_pdf_viewer = true enable_tts = true enable_color_chooser = true enable_picture_in_picture = true # Provide a fake location provider for mocking # the geolocation responses. Disable it if you # need to test with chromium's location provider. # Should not be enabled for release build. enable_fake_location_provider = !is_official_build # Enable Chrome extensions support. enable_electron_extensions = true # Enable Spellchecker support enable_builtin_spellchecker = true # Undocumented Windows dark mode API enable_win_dark_mode_window_ui = false }
closed
electron/electron
https://github.com/electron/electron
18,119
Windows chrome and context menu should be aware of dark mode setting
<!-- As an open source project with a dedicated but small maintainer team, it can sometimes take a long time for issues to be addressed so please be patient and we will get back to you as soon as we can. --> ### Preflight Checklist <!-- Please ensure you've completed the following steps by replacing [ ] with [x]--> * [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. * [x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. * [x] I have searched the issue tracker for a feature request that matches the one I want to file, without success. ### Problem Description Recent builds of Windows 10 support a "dark mode" that changes the chrome and context menus to fit better with the rest of the OS. https://www.digitaltrends.com/computing/how-to-enable-dark-mode-in-windows-10/ has a write up of how to enable this. Here's a side-by-side of Explorer and the Quick Start app on Windows `10.0.17763.437`: ![](https://user-images.githubusercontent.com/359239/57080976-2b782b00-6cca-11e9-8c41-5097e39526d1.png) This is complementary to #15316 but not the whole solution: - it'd be great if the defaults "just worked" based on this setting, so app developers and users would get this benefit without needing to manage configuration themselves - some apps choose to roll their own themes, but they don't have control over the main menu or context menu without also rolling their own implementations of those and hiding the default chrome To go into more detail, here's what a context menu looks like that respects the dark mode setting: ![](https://user-images.githubusercontent.com/359239/57081074-5ebaba00-6cca-11e9-97f7-d30fc030c759.png) And here's the equivalent main menu and context menu in the Electron Quick Start when using Electron 5: ![](https://user-images.githubusercontent.com/359239/57081076-5ebaba00-6cca-11e9-926b-9a18be540bef.png) ![](https://user-images.githubusercontent.com/359239/57081077-5ebaba00-6cca-11e9-8f3e-d3b0d61d3e72.png) ### Proposed Solution I'm not familiar with how this works under the hood, but happy to go spelunking if this is something that interests the maintainers to gather more information. ### Alternatives Considered As mentioned above, app developers can roll their own dark theme for menus and switch to use a chromeless `BrowserWindow`. That's fine for people who want to invest in that, but if there's lots of interest in the default chrome working better then maybe this is worth diving into? ### Additional Information <!-- Add any other context about the problem here. -->
https://github.com/electron/electron/issues/18119
https://github.com/electron/electron/pull/33624
21ef8501e7c71cd8d56828e21d310d07f9d86510
4c7c0b41c2027db27cf563e9eabb95cc8adf96bb
2019-05-02T14:14:11Z
c++
2022-06-14T16:27:28Z
filenames.gni
filenames = { default_app_ts_sources = [ "default_app/default_app.ts", "default_app/main.ts", "default_app/preload.ts", ] default_app_static_sources = [ "default_app/icon.png", "default_app/index.html", "default_app/package.json", "default_app/styles.css", ] default_app_octicon_sources = [ "node_modules/@primer/octicons/build/build.css", "node_modules/@primer/octicons/build/svg/book-24.svg", "node_modules/@primer/octicons/build/svg/code-square-24.svg", "node_modules/@primer/octicons/build/svg/gift-24.svg", "node_modules/@primer/octicons/build/svg/mark-github-16.svg", "node_modules/@primer/octicons/build/svg/star-fill-24.svg", ] lib_sources_linux = [ "shell/browser/browser_linux.cc", "shell/browser/lib/power_observer_linux.cc", "shell/browser/lib/power_observer_linux.h", "shell/browser/linux/unity_service.cc", "shell/browser/linux/unity_service.h", "shell/browser/notifications/linux/libnotify_notification.cc", "shell/browser/notifications/linux/libnotify_notification.h", "shell/browser/notifications/linux/notification_presenter_linux.cc", "shell/browser/notifications/linux/notification_presenter_linux.h", "shell/browser/relauncher_linux.cc", "shell/browser/ui/electron_desktop_window_tree_host_linux.cc", "shell/browser/ui/file_dialog_gtk.cc", "shell/browser/ui/message_box_gtk.cc", "shell/browser/ui/tray_icon_gtk.cc", "shell/browser/ui/tray_icon_gtk.h", "shell/browser/ui/views/client_frame_view_linux.cc", "shell/browser/ui/views/client_frame_view_linux.h", "shell/common/application_info_linux.cc", "shell/common/language_util_linux.cc", "shell/common/node_bindings_linux.cc", "shell/common/node_bindings_linux.h", "shell/common/platform_util_linux.cc", ] lib_sources_linux_x11 = [ "shell/browser/ui/views/global_menu_bar_registrar_x11.cc", "shell/browser/ui/views/global_menu_bar_registrar_x11.h", "shell/browser/ui/views/global_menu_bar_x11.cc", "shell/browser/ui/views/global_menu_bar_x11.h", "shell/browser/ui/x/event_disabler.cc", "shell/browser/ui/x/event_disabler.h", "shell/browser/ui/x/x_window_utils.cc", "shell/browser/ui/x/x_window_utils.h", ] lib_sources_posix = [ "shell/browser/electron_browser_main_parts_posix.cc" ] lib_sources_win = [ "shell/browser/api/electron_api_power_monitor_win.cc", "shell/browser/api/electron_api_system_preferences_win.cc", "shell/browser/browser_win.cc", "shell/browser/native_window_views_win.cc", "shell/browser/notifications/win/notification_presenter_win.cc", "shell/browser/notifications/win/notification_presenter_win.h", "shell/browser/notifications/win/notification_presenter_win7.cc", "shell/browser/notifications/win/notification_presenter_win7.h", "shell/browser/notifications/win/win32_desktop_notifications/common.h", "shell/browser/notifications/win/win32_desktop_notifications/desktop_notification_controller.cc", "shell/browser/notifications/win/win32_desktop_notifications/desktop_notification_controller.h", "shell/browser/notifications/win/win32_desktop_notifications/toast_uia.cc", "shell/browser/notifications/win/win32_desktop_notifications/toast_uia.h", "shell/browser/notifications/win/win32_desktop_notifications/toast.cc", "shell/browser/notifications/win/win32_desktop_notifications/toast.h", "shell/browser/notifications/win/win32_notification.cc", "shell/browser/notifications/win/win32_notification.h", "shell/browser/notifications/win/windows_toast_notification.cc", "shell/browser/notifications/win/windows_toast_notification.h", "shell/browser/relauncher_win.cc", "shell/browser/ui/certificate_trust_win.cc", "shell/browser/ui/file_dialog_win.cc", "shell/browser/ui/message_box_win.cc", "shell/browser/ui/tray_icon_win.cc", "shell/browser/ui/views/electron_views_delegate_win.cc", "shell/browser/ui/views/win_frame_view.cc", "shell/browser/ui/views/win_frame_view.h", "shell/browser/ui/views/win_caption_button.cc", "shell/browser/ui/views/win_caption_button.h", "shell/browser/ui/views/win_caption_button_container.cc", "shell/browser/ui/views/win_caption_button_container.h", "shell/browser/ui/win/dialog_thread.cc", "shell/browser/ui/win/dialog_thread.h", "shell/browser/ui/win/electron_desktop_native_widget_aura.cc", "shell/browser/ui/win/electron_desktop_native_widget_aura.h", "shell/browser/ui/win/electron_desktop_window_tree_host_win.cc", "shell/browser/ui/win/electron_desktop_window_tree_host_win.h", "shell/browser/ui/win/jump_list.cc", "shell/browser/ui/win/jump_list.h", "shell/browser/ui/win/notify_icon_host.cc", "shell/browser/ui/win/notify_icon_host.h", "shell/browser/ui/win/notify_icon.cc", "shell/browser/ui/win/notify_icon.h", "shell/browser/ui/win/taskbar_host.cc", "shell/browser/ui/win/taskbar_host.h", "shell/browser/win/scoped_hstring.cc", "shell/browser/win/scoped_hstring.h", "shell/common/api/electron_api_native_image_win.cc", "shell/common/application_info_win.cc", "shell/common/language_util_win.cc", "shell/common/node_bindings_win.cc", "shell/common/node_bindings_win.h", "shell/common/platform_util_win.cc", ] lib_sources_mac = [ "shell/app/electron_main_delegate_mac.h", "shell/app/electron_main_delegate_mac.mm", "shell/browser/api/electron_api_app_mac.mm", "shell/browser/api/electron_api_browser_window_mac.mm", "shell/browser/api/electron_api_menu_mac.h", "shell/browser/api/electron_api_menu_mac.mm", "shell/browser/api/electron_api_native_theme_mac.mm", "shell/browser/api/electron_api_power_monitor_mac.mm", "shell/browser/api/electron_api_system_preferences_mac.mm", "shell/browser/api/electron_api_web_contents_mac.mm", "shell/browser/auto_updater_mac.mm", "shell/browser/browser_mac.mm", "shell/browser/electron_browser_main_parts_mac.mm", "shell/browser/mac/dict_util.h", "shell/browser/mac/dict_util.mm", "shell/browser/mac/electron_application_delegate.h", "shell/browser/mac/electron_application_delegate.mm", "shell/browser/mac/electron_application.h", "shell/browser/mac/electron_application.mm", "shell/browser/mac/in_app_purchase_observer.h", "shell/browser/mac/in_app_purchase_observer.mm", "shell/browser/mac/in_app_purchase_product.h", "shell/browser/mac/in_app_purchase_product.mm", "shell/browser/mac/in_app_purchase.h", "shell/browser/mac/in_app_purchase.mm", "shell/browser/native_browser_view_mac.h", "shell/browser/native_browser_view_mac.mm", "shell/browser/native_window_mac.h", "shell/browser/native_window_mac.mm", "shell/browser/notifications/mac/cocoa_notification.h", "shell/browser/notifications/mac/cocoa_notification.mm", "shell/browser/notifications/mac/notification_center_delegate.h", "shell/browser/notifications/mac/notification_center_delegate.mm", "shell/browser/notifications/mac/notification_presenter_mac.h", "shell/browser/notifications/mac/notification_presenter_mac.mm", "shell/browser/relauncher_mac.cc", "shell/browser/ui/certificate_trust_mac.mm", "shell/browser/ui/cocoa/delayed_native_view_host.cc", "shell/browser/ui/cocoa/delayed_native_view_host.h", "shell/browser/ui/cocoa/electron_bundle_mover.h", "shell/browser/ui/cocoa/electron_bundle_mover.mm", "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.h", "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm", "shell/browser/ui/cocoa/electron_menu_controller.h", "shell/browser/ui/cocoa/electron_menu_controller.mm", "shell/browser/ui/cocoa/electron_native_widget_mac.h", "shell/browser/ui/cocoa/electron_native_widget_mac.mm", "shell/browser/ui/cocoa/electron_ns_window_delegate.h", "shell/browser/ui/cocoa/electron_ns_window_delegate.mm", "shell/browser/ui/cocoa/electron_ns_panel.h", "shell/browser/ui/cocoa/electron_ns_panel.mm", "shell/browser/ui/cocoa/electron_ns_window.h", "shell/browser/ui/cocoa/electron_ns_window.mm", "shell/browser/ui/cocoa/electron_preview_item.h", "shell/browser/ui/cocoa/electron_preview_item.mm", "shell/browser/ui/cocoa/electron_touch_bar.h", "shell/browser/ui/cocoa/electron_touch_bar.mm", "shell/browser/ui/cocoa/event_dispatching_window.h", "shell/browser/ui/cocoa/event_dispatching_window.mm", "shell/browser/ui/cocoa/NSColor+Hex.h", "shell/browser/ui/cocoa/NSColor+Hex.mm", "shell/browser/ui/cocoa/NSString+ANSI.h", "shell/browser/ui/cocoa/NSString+ANSI.mm", "shell/browser/ui/cocoa/root_view_mac.h", "shell/browser/ui/cocoa/root_view_mac.mm", "shell/browser/ui/cocoa/views_delegate_mac.h", "shell/browser/ui/cocoa/views_delegate_mac.mm", "shell/browser/ui/cocoa/window_buttons_proxy.h", "shell/browser/ui/cocoa/window_buttons_proxy.mm", "shell/browser/ui/drag_util_mac.mm", "shell/browser/ui/file_dialog_mac.mm", "shell/browser/ui/inspectable_web_contents_view_mac.h", "shell/browser/ui/inspectable_web_contents_view_mac.mm", "shell/browser/ui/message_box_mac.mm", "shell/browser/ui/tray_icon_cocoa.h", "shell/browser/ui/tray_icon_cocoa.mm", "shell/common/api/electron_api_clipboard_mac.mm", "shell/common/api/electron_api_native_image_mac.mm", "shell/common/asar/archive_mac.mm", "shell/common/application_info_mac.mm", "shell/common/language_util_mac.mm", "shell/common/mac/main_application_bundle.h", "shell/common/mac/main_application_bundle.mm", "shell/common/node_bindings_mac.cc", "shell/common/node_bindings_mac.h", "shell/common/platform_util_mac.mm", ] lib_sources_views = [ "shell/browser/api/electron_api_browser_window_views.cc", "shell/browser/api/electron_api_menu_views.cc", "shell/browser/api/electron_api_menu_views.h", "shell/browser/native_browser_view_views.cc", "shell/browser/native_browser_view_views.h", "shell/browser/native_window_views.cc", "shell/browser/native_window_views.h", "shell/browser/ui/drag_util_views.cc", "shell/browser/ui/views/autofill_popup_view.cc", "shell/browser/ui/views/autofill_popup_view.h", "shell/browser/ui/views/electron_views_delegate.cc", "shell/browser/ui/views/electron_views_delegate.h", "shell/browser/ui/views/frameless_view.cc", "shell/browser/ui/views/frameless_view.h", "shell/browser/ui/views/inspectable_web_contents_view_views.cc", "shell/browser/ui/views/inspectable_web_contents_view_views.h", "shell/browser/ui/views/menu_bar.cc", "shell/browser/ui/views/menu_bar.h", "shell/browser/ui/views/menu_delegate.cc", "shell/browser/ui/views/menu_delegate.h", "shell/browser/ui/views/menu_model_adapter.cc", "shell/browser/ui/views/menu_model_adapter.h", "shell/browser/ui/views/native_frame_view.cc", "shell/browser/ui/views/native_frame_view.h", "shell/browser/ui/views/root_view.cc", "shell/browser/ui/views/root_view.h", "shell/browser/ui/views/submenu_button.cc", "shell/browser/ui/views/submenu_button.h", ] lib_sources = [ "shell/app/command_line_args.cc", "shell/app/command_line_args.h", "shell/app/electron_content_client.cc", "shell/app/electron_content_client.h", "shell/app/electron_crash_reporter_client.cc", "shell/app/electron_crash_reporter_client.h", "shell/app/electron_main_delegate.cc", "shell/app/electron_main_delegate.h", "shell/app/uv_task_runner.cc", "shell/app/uv_task_runner.h", "shell/browser/api/electron_api_app.cc", "shell/browser/api/electron_api_app.h", "shell/browser/api/electron_api_auto_updater.cc", "shell/browser/api/electron_api_auto_updater.h", "shell/browser/api/electron_api_base_window.cc", "shell/browser/api/electron_api_base_window.h", "shell/browser/api/electron_api_browser_view.cc", "shell/browser/api/electron_api_browser_view.h", "shell/browser/api/electron_api_browser_window.cc", "shell/browser/api/electron_api_browser_window.h", "shell/browser/api/electron_api_content_tracing.cc", "shell/browser/api/electron_api_cookies.cc", "shell/browser/api/electron_api_cookies.h", "shell/browser/api/electron_api_crash_reporter.cc", "shell/browser/api/electron_api_crash_reporter.h", "shell/browser/api/electron_api_data_pipe_holder.cc", "shell/browser/api/electron_api_data_pipe_holder.h", "shell/browser/api/electron_api_debugger.cc", "shell/browser/api/electron_api_debugger.h", "shell/browser/api/electron_api_dialog.cc", "shell/browser/api/electron_api_download_item.cc", "shell/browser/api/electron_api_download_item.h", "shell/browser/api/electron_api_event.cc", "shell/browser/api/electron_api_event_emitter.cc", "shell/browser/api/electron_api_event_emitter.h", "shell/browser/api/electron_api_global_shortcut.cc", "shell/browser/api/electron_api_global_shortcut.h", "shell/browser/api/electron_api_in_app_purchase.cc", "shell/browser/api/electron_api_in_app_purchase.h", "shell/browser/api/electron_api_menu.cc", "shell/browser/api/electron_api_menu.h", "shell/browser/api/electron_api_native_theme.cc", "shell/browser/api/electron_api_native_theme.h", "shell/browser/api/electron_api_net.cc", "shell/browser/api/electron_api_net_log.cc", "shell/browser/api/electron_api_net_log.h", "shell/browser/api/electron_api_notification.cc", "shell/browser/api/electron_api_notification.h", "shell/browser/api/electron_api_power_monitor.cc", "shell/browser/api/electron_api_power_monitor.h", "shell/browser/api/electron_api_power_save_blocker.cc", "shell/browser/api/electron_api_power_save_blocker.h", "shell/browser/api/electron_api_printing.cc", "shell/browser/api/electron_api_protocol.cc", "shell/browser/api/electron_api_protocol.h", "shell/browser/api/electron_api_safe_storage.cc", "shell/browser/api/electron_api_safe_storage.h", "shell/browser/api/electron_api_screen.cc", "shell/browser/api/electron_api_screen.h", "shell/browser/api/electron_api_service_worker_context.cc", "shell/browser/api/electron_api_service_worker_context.h", "shell/browser/api/electron_api_session.cc", "shell/browser/api/electron_api_session.h", "shell/browser/api/electron_api_system_preferences.cc", "shell/browser/api/electron_api_system_preferences.h", "shell/browser/api/electron_api_tray.cc", "shell/browser/api/electron_api_tray.h", "shell/browser/api/electron_api_url_loader.cc", "shell/browser/api/electron_api_url_loader.h", "shell/browser/api/electron_api_view.cc", "shell/browser/api/electron_api_view.h", "shell/browser/api/electron_api_web_contents.cc", "shell/browser/api/electron_api_web_contents.h", "shell/browser/api/electron_api_web_contents_impl.cc", "shell/browser/api/electron_api_web_contents_view.cc", "shell/browser/api/electron_api_web_contents_view.h", "shell/browser/api/electron_api_web_frame_main.cc", "shell/browser/api/electron_api_web_frame_main.h", "shell/browser/api/electron_api_web_request.cc", "shell/browser/api/electron_api_web_request.h", "shell/browser/api/electron_api_web_view_manager.cc", "shell/browser/api/event.cc", "shell/browser/api/event.h", "shell/browser/api/frame_subscriber.cc", "shell/browser/api/frame_subscriber.h", "shell/browser/api/gpu_info_enumerator.cc", "shell/browser/api/gpu_info_enumerator.h", "shell/browser/api/gpuinfo_manager.cc", "shell/browser/api/gpuinfo_manager.h", "shell/browser/api/message_port.cc", "shell/browser/api/message_port.h", "shell/browser/api/process_metric.cc", "shell/browser/api/process_metric.h", "shell/browser/api/save_page_handler.cc", "shell/browser/api/save_page_handler.h", "shell/browser/api/ui_event.cc", "shell/browser/api/ui_event.h", "shell/browser/auto_updater.cc", "shell/browser/auto_updater.h", "shell/browser/badging/badge_manager.cc", "shell/browser/badging/badge_manager.h", "shell/browser/badging/badge_manager_factory.cc", "shell/browser/badging/badge_manager_factory.h", "shell/browser/bluetooth/electron_bluetooth_delegate.cc", "shell/browser/bluetooth/electron_bluetooth_delegate.h", "shell/browser/browser.cc", "shell/browser/browser.h", "shell/browser/browser_observer.h", "shell/browser/browser_process_impl.cc", "shell/browser/browser_process_impl.h", "shell/browser/child_web_contents_tracker.cc", "shell/browser/child_web_contents_tracker.h", "shell/browser/cookie_change_notifier.cc", "shell/browser/cookie_change_notifier.h", "shell/browser/electron_api_ipc_handler_impl.cc", "shell/browser/electron_api_ipc_handler_impl.h", "shell/browser/electron_autofill_driver.cc", "shell/browser/electron_autofill_driver.h", "shell/browser/electron_autofill_driver_factory.cc", "shell/browser/electron_autofill_driver_factory.h", "shell/browser/electron_browser_client.cc", "shell/browser/electron_browser_client.h", "shell/browser/electron_browser_context.cc", "shell/browser/electron_browser_context.h", "shell/browser/electron_browser_main_parts.cc", "shell/browser/electron_browser_main_parts.h", "shell/browser/electron_download_manager_delegate.cc", "shell/browser/electron_download_manager_delegate.h", "shell/browser/electron_gpu_client.cc", "shell/browser/electron_gpu_client.h", "shell/browser/electron_javascript_dialog_manager.cc", "shell/browser/electron_javascript_dialog_manager.h", "shell/browser/electron_navigation_throttle.cc", "shell/browser/electron_navigation_throttle.h", "shell/browser/electron_permission_manager.cc", "shell/browser/electron_permission_manager.h", "shell/browser/electron_quota_permission_context.cc", "shell/browser/electron_quota_permission_context.h", "shell/browser/electron_speech_recognition_manager_delegate.cc", "shell/browser/electron_speech_recognition_manager_delegate.h", "shell/browser/electron_web_contents_utility_handler_impl.cc", "shell/browser/electron_web_contents_utility_handler_impl.h", "shell/browser/electron_web_ui_controller_factory.cc", "shell/browser/electron_web_ui_controller_factory.h", "shell/browser/event_emitter_mixin.cc", "shell/browser/event_emitter_mixin.h", "shell/browser/extended_web_contents_observer.h", "shell/browser/feature_list.cc", "shell/browser/feature_list.h", "shell/browser/file_select_helper.cc", "shell/browser/file_select_helper.h", "shell/browser/file_select_helper_mac.mm", "shell/browser/font_defaults.cc", "shell/browser/font_defaults.h", "shell/browser/hid/electron_hid_delegate.cc", "shell/browser/hid/electron_hid_delegate.h", "shell/browser/hid/hid_chooser_context.cc", "shell/browser/hid/hid_chooser_context.h", "shell/browser/hid/hid_chooser_context_factory.cc", "shell/browser/hid/hid_chooser_context_factory.h", "shell/browser/hid/hid_chooser_controller.cc", "shell/browser/hid/hid_chooser_controller.h", "shell/browser/javascript_environment.cc", "shell/browser/javascript_environment.h", "shell/browser/lib/bluetooth_chooser.cc", "shell/browser/lib/bluetooth_chooser.h", "shell/browser/login_handler.cc", "shell/browser/login_handler.h", "shell/browser/media/media_capture_devices_dispatcher.cc", "shell/browser/media/media_capture_devices_dispatcher.h", "shell/browser/media/media_device_id_salt.cc", "shell/browser/media/media_device_id_salt.h", "shell/browser/media/media_stream_devices_controller.cc", "shell/browser/media/media_stream_devices_controller.h", "shell/browser/microtasks_runner.cc", "shell/browser/microtasks_runner.h", "shell/browser/native_browser_view.cc", "shell/browser/native_browser_view.h", "shell/browser/native_window.cc", "shell/browser/native_window.h", "shell/browser/native_window_features.cc", "shell/browser/native_window_features.h", "shell/browser/native_window_observer.h", "shell/browser/net/asar/asar_file_validator.cc", "shell/browser/net/asar/asar_file_validator.h", "shell/browser/net/asar/asar_url_loader.cc", "shell/browser/net/asar/asar_url_loader.h", "shell/browser/net/asar/asar_url_loader_factory.cc", "shell/browser/net/asar/asar_url_loader_factory.h", "shell/browser/net/cert_verifier_client.cc", "shell/browser/net/cert_verifier_client.h", "shell/browser/net/electron_url_loader_factory.cc", "shell/browser/net/electron_url_loader_factory.h", "shell/browser/net/network_context_service.cc", "shell/browser/net/network_context_service.h", "shell/browser/net/network_context_service_factory.cc", "shell/browser/net/network_context_service_factory.h", "shell/browser/net/node_stream_loader.cc", "shell/browser/net/node_stream_loader.h", "shell/browser/net/proxying_url_loader_factory.cc", "shell/browser/net/proxying_url_loader_factory.h", "shell/browser/net/proxying_websocket.cc", "shell/browser/net/proxying_websocket.h", "shell/browser/net/resolve_proxy_helper.cc", "shell/browser/net/resolve_proxy_helper.h", "shell/browser/net/system_network_context_manager.cc", "shell/browser/net/system_network_context_manager.h", "shell/browser/net/url_pipe_loader.cc", "shell/browser/net/url_pipe_loader.h", "shell/browser/net/web_request_api_interface.h", "shell/browser/network_hints_handler_impl.cc", "shell/browser/network_hints_handler_impl.h", "shell/browser/notifications/notification.cc", "shell/browser/notifications/notification.h", "shell/browser/notifications/notification_delegate.h", "shell/browser/notifications/notification_presenter.cc", "shell/browser/notifications/notification_presenter.h", "shell/browser/notifications/platform_notification_service.cc", "shell/browser/notifications/platform_notification_service.h", "shell/browser/plugins/plugin_utils.cc", "shell/browser/plugins/plugin_utils.h", "shell/browser/pref_store_delegate.cc", "shell/browser/pref_store_delegate.h", "shell/browser/protocol_registry.cc", "shell/browser/protocol_registry.h", "shell/browser/relauncher.cc", "shell/browser/relauncher.h", "shell/browser/serial/electron_serial_delegate.cc", "shell/browser/serial/electron_serial_delegate.h", "shell/browser/serial/serial_chooser_context.cc", "shell/browser/serial/serial_chooser_context.h", "shell/browser/serial/serial_chooser_context_factory.cc", "shell/browser/serial/serial_chooser_context_factory.h", "shell/browser/serial/serial_chooser_controller.cc", "shell/browser/serial/serial_chooser_controller.h", "shell/browser/session_preferences.cc", "shell/browser/session_preferences.h", "shell/browser/special_storage_policy.cc", "shell/browser/special_storage_policy.h", "shell/browser/ui/accelerator_util.cc", "shell/browser/ui/accelerator_util.h", "shell/browser/ui/autofill_popup.cc", "shell/browser/ui/autofill_popup.h", "shell/browser/ui/certificate_trust.h", "shell/browser/ui/devtools_manager_delegate.cc", "shell/browser/ui/devtools_manager_delegate.h", "shell/browser/ui/devtools_ui.cc", "shell/browser/ui/devtools_ui.h", "shell/browser/ui/drag_util.cc", "shell/browser/ui/drag_util.h", "shell/browser/ui/electron_menu_model.cc", "shell/browser/ui/electron_menu_model.h", "shell/browser/ui/file_dialog.h", "shell/browser/ui/inspectable_web_contents.cc", "shell/browser/ui/inspectable_web_contents.h", "shell/browser/ui/inspectable_web_contents_delegate.h", "shell/browser/ui/inspectable_web_contents_view.h", "shell/browser/ui/inspectable_web_contents_view_delegate.cc", "shell/browser/ui/inspectable_web_contents_view_delegate.h", "shell/browser/ui/message_box.h", "shell/browser/ui/tray_icon.cc", "shell/browser/ui/tray_icon.h", "shell/browser/ui/tray_icon_observer.h", "shell/browser/ui/webui/accessibility_ui.cc", "shell/browser/ui/webui/accessibility_ui.h", "shell/browser/unresponsive_suppressor.cc", "shell/browser/unresponsive_suppressor.h", "shell/browser/web_contents_permission_helper.cc", "shell/browser/web_contents_permission_helper.h", "shell/browser/web_contents_preferences.cc", "shell/browser/web_contents_preferences.h", "shell/browser/web_contents_zoom_controller.cc", "shell/browser/web_contents_zoom_controller.h", "shell/browser/web_view_guest_delegate.cc", "shell/browser/web_view_guest_delegate.h", "shell/browser/web_view_manager.cc", "shell/browser/web_view_manager.h", "shell/browser/window_list.cc", "shell/browser/window_list.h", "shell/browser/window_list_observer.h", "shell/browser/zoom_level_delegate.cc", "shell/browser/zoom_level_delegate.h", "shell/common/api/electron_api_asar.cc", "shell/common/api/electron_api_clipboard.cc", "shell/common/api/electron_api_clipboard.h", "shell/common/api/electron_api_command_line.cc", "shell/common/api/electron_api_environment.cc", "shell/common/api/electron_api_key_weak_map.h", "shell/common/api/electron_api_native_image.cc", "shell/common/api/electron_api_native_image.h", "shell/common/api/electron_api_shell.cc", "shell/common/api/electron_api_testing.cc", "shell/common/api/electron_api_v8_util.cc", "shell/common/api/electron_bindings.cc", "shell/common/api/electron_bindings.h", "shell/common/api/features.cc", "shell/common/api/object_life_monitor.cc", "shell/common/api/object_life_monitor.h", "shell/common/application_info.cc", "shell/common/application_info.h", "shell/common/asar/archive.cc", "shell/common/asar/archive.h", "shell/common/asar/asar_util.cc", "shell/common/asar/asar_util.h", "shell/common/asar/scoped_temporary_file.cc", "shell/common/asar/scoped_temporary_file.h", "shell/common/color_util.cc", "shell/common/color_util.h", "shell/common/crash_keys.cc", "shell/common/crash_keys.h", "shell/common/electron_command_line.cc", "shell/common/electron_command_line.h", "shell/common/electron_constants.cc", "shell/common/electron_constants.h", "shell/common/electron_paths.h", "shell/common/gin_converters/accelerator_converter.cc", "shell/common/gin_converters/accelerator_converter.h", "shell/common/gin_converters/base_converter.h", "shell/common/gin_converters/blink_converter.cc", "shell/common/gin_converters/blink_converter.h", "shell/common/gin_converters/callback_converter.h", "shell/common/gin_converters/content_converter.cc", "shell/common/gin_converters/content_converter.h", "shell/common/gin_converters/file_dialog_converter.cc", "shell/common/gin_converters/file_dialog_converter.h", "shell/common/gin_converters/file_path_converter.h", "shell/common/gin_converters/frame_converter.cc", "shell/common/gin_converters/frame_converter.h", "shell/common/gin_converters/gfx_converter.cc", "shell/common/gin_converters/gfx_converter.h", "shell/common/gin_converters/guid_converter.h", "shell/common/gin_converters/gurl_converter.h", "shell/common/gin_converters/hid_device_info_converter.h", "shell/common/gin_converters/image_converter.cc", "shell/common/gin_converters/image_converter.h", "shell/common/gin_converters/message_box_converter.cc", "shell/common/gin_converters/message_box_converter.h", "shell/common/gin_converters/native_window_converter.h", "shell/common/gin_converters/net_converter.cc", "shell/common/gin_converters/net_converter.h", "shell/common/gin_converters/std_converter.h", "shell/common/gin_converters/time_converter.cc", "shell/common/gin_converters/time_converter.h", "shell/common/gin_converters/value_converter.cc", "shell/common/gin_converters/value_converter.h", "shell/common/gin_helper/arguments.cc", "shell/common/gin_helper/arguments.h", "shell/common/gin_helper/callback.cc", "shell/common/gin_helper/callback.h", "shell/common/gin_helper/cleaned_up_at_exit.cc", "shell/common/gin_helper/cleaned_up_at_exit.h", "shell/common/gin_helper/constructible.h", "shell/common/gin_helper/constructor.h", "shell/common/gin_helper/destroyable.cc", "shell/common/gin_helper/destroyable.h", "shell/common/gin_helper/dictionary.h", "shell/common/gin_helper/error_thrower.cc", "shell/common/gin_helper/error_thrower.h", "shell/common/gin_helper/event_emitter.cc", "shell/common/gin_helper/event_emitter.h", "shell/common/gin_helper/event_emitter_caller.cc", "shell/common/gin_helper/event_emitter_caller.h", "shell/common/gin_helper/function_template.cc", "shell/common/gin_helper/function_template.h", "shell/common/gin_helper/function_template_extensions.h", "shell/common/gin_helper/locker.cc", "shell/common/gin_helper/locker.h", "shell/common/gin_helper/microtasks_scope.cc", "shell/common/gin_helper/microtasks_scope.h", "shell/common/gin_helper/object_template_builder.cc", "shell/common/gin_helper/object_template_builder.h", "shell/common/gin_helper/persistent_dictionary.cc", "shell/common/gin_helper/persistent_dictionary.h", "shell/common/gin_helper/pinnable.h", "shell/common/gin_helper/promise.cc", "shell/common/gin_helper/promise.h", "shell/common/gin_helper/trackable_object.cc", "shell/common/gin_helper/trackable_object.h", "shell/common/gin_helper/wrappable.cc", "shell/common/gin_helper/wrappable.h", "shell/common/gin_helper/wrappable_base.h", "shell/common/heap_snapshot.cc", "shell/common/heap_snapshot.h", "shell/common/key_weak_map.h", "shell/common/keyboard_util.cc", "shell/common/keyboard_util.h", "shell/common/language_util.h", "shell/common/logging.cc", "shell/common/logging.h", "shell/common/mouse_util.cc", "shell/common/mouse_util.h", "shell/common/node_bindings.cc", "shell/common/node_bindings.h", "shell/common/node_includes.h", "shell/common/node_util.cc", "shell/common/node_util.h", "shell/common/options_switches.cc", "shell/common/options_switches.h", "shell/common/platform_util.cc", "shell/common/platform_util.h", "shell/common/platform_util_internal.h", "shell/common/process_util.cc", "shell/common/process_util.h", "shell/common/skia_util.cc", "shell/common/skia_util.h", "shell/common/v8_value_converter.cc", "shell/common/v8_value_converter.h", "shell/common/v8_value_serializer.cc", "shell/common/v8_value_serializer.h", "shell/common/world_ids.h", "shell/renderer/api/context_bridge/object_cache.cc", "shell/renderer/api/context_bridge/object_cache.h", "shell/renderer/api/electron_api_context_bridge.cc", "shell/renderer/api/electron_api_context_bridge.h", "shell/renderer/api/electron_api_crash_reporter_renderer.cc", "shell/renderer/api/electron_api_ipc_renderer.cc", "shell/renderer/api/electron_api_spell_check_client.cc", "shell/renderer/api/electron_api_spell_check_client.h", "shell/renderer/api/electron_api_web_frame.cc", "shell/renderer/browser_exposed_renderer_interfaces.cc", "shell/renderer/browser_exposed_renderer_interfaces.h", "shell/renderer/content_settings_observer.cc", "shell/renderer/content_settings_observer.h", "shell/renderer/electron_api_service_impl.cc", "shell/renderer/electron_api_service_impl.h", "shell/renderer/electron_autofill_agent.cc", "shell/renderer/electron_autofill_agent.h", "shell/renderer/electron_render_frame_observer.cc", "shell/renderer/electron_render_frame_observer.h", "shell/renderer/electron_renderer_client.cc", "shell/renderer/electron_renderer_client.h", "shell/renderer/electron_renderer_pepper_host_factory.cc", "shell/renderer/electron_renderer_pepper_host_factory.h", "shell/renderer/electron_sandboxed_renderer_client.cc", "shell/renderer/electron_sandboxed_renderer_client.h", "shell/renderer/guest_view_container.cc", "shell/renderer/guest_view_container.h", "shell/renderer/renderer_client_base.cc", "shell/renderer/renderer_client_base.h", "shell/renderer/web_worker_observer.cc", "shell/renderer/web_worker_observer.h", "shell/utility/electron_content_utility_client.cc", "shell/utility/electron_content_utility_client.h", ] lib_sources_extensions = [ "shell/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.cc", "shell/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.h", "shell/browser/extensions/api/management/electron_management_api_delegate.cc", "shell/browser/extensions/api/management/electron_management_api_delegate.h", "shell/browser/extensions/api/resources_private/resources_private_api.cc", "shell/browser/extensions/api/resources_private/resources_private_api.h", "shell/browser/extensions/api/runtime/electron_runtime_api_delegate.cc", "shell/browser/extensions/api/runtime/electron_runtime_api_delegate.h", "shell/browser/extensions/api/streams_private/streams_private_api.cc", "shell/browser/extensions/api/streams_private/streams_private_api.h", "shell/browser/extensions/api/tabs/tabs_api.cc", "shell/browser/extensions/api/tabs/tabs_api.h", "shell/browser/extensions/electron_browser_context_keyed_service_factories.cc", "shell/browser/extensions/electron_browser_context_keyed_service_factories.h", "shell/browser/extensions/electron_component_extension_resource_manager.cc", "shell/browser/extensions/electron_component_extension_resource_manager.h", "shell/browser/extensions/electron_display_info_provider.cc", "shell/browser/extensions/electron_display_info_provider.h", "shell/browser/extensions/electron_extension_host_delegate.cc", "shell/browser/extensions/electron_extension_host_delegate.h", "shell/browser/extensions/electron_extension_loader.cc", "shell/browser/extensions/electron_extension_loader.h", "shell/browser/extensions/electron_extension_message_filter.cc", "shell/browser/extensions/electron_extension_message_filter.h", "shell/browser/extensions/electron_extension_system_factory.cc", "shell/browser/extensions/electron_extension_system_factory.h", "shell/browser/extensions/electron_extension_system.cc", "shell/browser/extensions/electron_extension_system.h", "shell/browser/extensions/electron_extension_web_contents_observer.cc", "shell/browser/extensions/electron_extension_web_contents_observer.h", "shell/browser/extensions/electron_extensions_api_client.cc", "shell/browser/extensions/electron_extensions_api_client.h", "shell/browser/extensions/electron_extensions_browser_api_provider.cc", "shell/browser/extensions/electron_extensions_browser_api_provider.h", "shell/browser/extensions/electron_extensions_browser_client.cc", "shell/browser/extensions/electron_extensions_browser_client.h", "shell/browser/extensions/electron_kiosk_delegate.cc", "shell/browser/extensions/electron_kiosk_delegate.h", "shell/browser/extensions/electron_messaging_delegate.cc", "shell/browser/extensions/electron_messaging_delegate.h", "shell/browser/extensions/electron_navigation_ui_data.cc", "shell/browser/extensions/electron_navigation_ui_data.h", "shell/browser/extensions/electron_process_manager_delegate.cc", "shell/browser/extensions/electron_process_manager_delegate.h", "shell/common/extensions/electron_extensions_api_provider.cc", "shell/common/extensions/electron_extensions_api_provider.h", "shell/common/extensions/electron_extensions_client.cc", "shell/common/extensions/electron_extensions_client.h", "shell/common/gin_converters/extension_converter.cc", "shell/common/gin_converters/extension_converter.h", "shell/renderer/extensions/electron_extensions_dispatcher_delegate.cc", "shell/renderer/extensions/electron_extensions_dispatcher_delegate.h", "shell/renderer/extensions/electron_extensions_renderer_client.cc", "shell/renderer/extensions/electron_extensions_renderer_client.h", ] framework_sources = [ "shell/app/electron_library_main.h", "shell/app/electron_library_main.mm", ] login_helper_sources = [ "shell/app/electron_login_helper.mm" ] }
closed
electron/electron
https://github.com/electron/electron
18,119
Windows chrome and context menu should be aware of dark mode setting
<!-- As an open source project with a dedicated but small maintainer team, it can sometimes take a long time for issues to be addressed so please be patient and we will get back to you as soon as we can. --> ### Preflight Checklist <!-- Please ensure you've completed the following steps by replacing [ ] with [x]--> * [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. * [x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. * [x] I have searched the issue tracker for a feature request that matches the one I want to file, without success. ### Problem Description Recent builds of Windows 10 support a "dark mode" that changes the chrome and context menus to fit better with the rest of the OS. https://www.digitaltrends.com/computing/how-to-enable-dark-mode-in-windows-10/ has a write up of how to enable this. Here's a side-by-side of Explorer and the Quick Start app on Windows `10.0.17763.437`: ![](https://user-images.githubusercontent.com/359239/57080976-2b782b00-6cca-11e9-8c41-5097e39526d1.png) This is complementary to #15316 but not the whole solution: - it'd be great if the defaults "just worked" based on this setting, so app developers and users would get this benefit without needing to manage configuration themselves - some apps choose to roll their own themes, but they don't have control over the main menu or context menu without also rolling their own implementations of those and hiding the default chrome To go into more detail, here's what a context menu looks like that respects the dark mode setting: ![](https://user-images.githubusercontent.com/359239/57081074-5ebaba00-6cca-11e9-97f7-d30fc030c759.png) And here's the equivalent main menu and context menu in the Electron Quick Start when using Electron 5: ![](https://user-images.githubusercontent.com/359239/57081076-5ebaba00-6cca-11e9-926b-9a18be540bef.png) ![](https://user-images.githubusercontent.com/359239/57081077-5ebaba00-6cca-11e9-8f3e-d3b0d61d3e72.png) ### Proposed Solution I'm not familiar with how this works under the hood, but happy to go spelunking if this is something that interests the maintainers to gather more information. ### Alternatives Considered As mentioned above, app developers can roll their own dark theme for menus and switch to use a chromeless `BrowserWindow`. That's fine for people who want to invest in that, but if there's lots of interest in the default chrome working better then maybe this is worth diving into? ### Additional Information <!-- Add any other context about the problem here. -->
https://github.com/electron/electron/issues/18119
https://github.com/electron/electron/pull/33624
21ef8501e7c71cd8d56828e21d310d07f9d86510
4c7c0b41c2027db27cf563e9eabb95cc8adf96bb
2019-05-02T14:14:11Z
c++
2022-06-14T16:27:28Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/win/electron_desktop_window_tree_host_win.h" #include "base/win/windows_version.h" #include "electron/buildflags/buildflags.h" #include "shell/browser/ui/views/win_frame_view.h" #include "ui/base/win/hwnd_metrics.h" #include "ui/base/win/shell.h" #if BUILDFLAG(ENABLE_WIN_DARK_MODE_WINDOW_UI) #include "shell/browser/win/dark_mode.h" #endif namespace electron { ElectronDesktopWindowTreeHostWin::ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura) : views::DesktopWindowTreeHostWin(native_window_view->widget(), desktop_native_widget_aura), native_window_view_(native_window_view) {} ElectronDesktopWindowTreeHostWin::~ElectronDesktopWindowTreeHostWin() = default; bool ElectronDesktopWindowTreeHostWin::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { #if BUILDFLAG(ENABLE_WIN_DARK_MODE_WINDOW_UI) if (message == WM_NCCREATE) { HWND const hwnd = GetAcceleratedWidget(); auto const theme_source = ui::NativeTheme::GetInstanceForNativeUi()->theme_source(); win::SetDarkModeForWindow(hwnd, theme_source); } #endif return native_window_view_->PreHandleMSG(message, w_param, l_param, result); } bool ElectronDesktopWindowTreeHostWin::ShouldPaintAsActive() const { // Tell Chromium to use system default behavior when rendering inactive // titlebar, otherwise it would render inactive titlebar as active under // some cases. // See also https://github.com/electron/electron/issues/24647. return false; } bool ElectronDesktopWindowTreeHostWin::HasNativeFrame() const { // Since we never use chromium's titlebar implementation, we can just say // that we use a native titlebar. This will disable the repaint locking when // DWM composition is disabled. // See also https://github.com/electron/electron/issues/1821. return !ui::win::IsAeroGlassEnabled(); } bool ElectronDesktopWindowTreeHostWin::GetDwmFrameInsetsInPixels( gfx::Insets* insets) const { // Set DWMFrameInsets to prevent maximized frameless window from bleeding // into other monitors. if (IsMaximized() && !native_window_view_->has_frame()) { // This would be equivalent to calling: // DwmExtendFrameIntoClientArea({0, 0, 0, 0}); // // which means do not extend window frame into client area. It is almost // a no-op, but it can tell Windows to not extend the window frame to be // larger than current workspace. // // See also: // https://devblogs.microsoft.com/oldnewthing/20150304-00/?p=44543 *insets = gfx::Insets(); return true; } return false; } bool ElectronDesktopWindowTreeHostWin::GetClientAreaInsets( gfx::Insets* insets, HMONITOR monitor) const { // Windows by deafult extends the maximized window slightly larger than // current workspace, for frameless window since the standard frame has been // removed, the client area would then be drew outside current workspace. // // Indenting the client area can fix this behavior. if (IsMaximized() && !native_window_view_->has_frame()) { // The insets would be eventually passed to WM_NCCALCSIZE, which takes // the metrics under the DPI of _main_ monitor instead of current monitor. // // Please make sure you tested maximized frameless window under multiple // monitors with different DPIs before changing this code. const int thickness = ::GetSystemMetrics(SM_CXSIZEFRAME) + ::GetSystemMetrics(SM_CXPADDEDBORDER); *insets = gfx::Insets::TLBR(thickness, thickness, thickness, thickness); return true; } return false; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
18,119
Windows chrome and context menu should be aware of dark mode setting
<!-- As an open source project with a dedicated but small maintainer team, it can sometimes take a long time for issues to be addressed so please be patient and we will get back to you as soon as we can. --> ### Preflight Checklist <!-- Please ensure you've completed the following steps by replacing [ ] with [x]--> * [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. * [x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. * [x] I have searched the issue tracker for a feature request that matches the one I want to file, without success. ### Problem Description Recent builds of Windows 10 support a "dark mode" that changes the chrome and context menus to fit better with the rest of the OS. https://www.digitaltrends.com/computing/how-to-enable-dark-mode-in-windows-10/ has a write up of how to enable this. Here's a side-by-side of Explorer and the Quick Start app on Windows `10.0.17763.437`: ![](https://user-images.githubusercontent.com/359239/57080976-2b782b00-6cca-11e9-8c41-5097e39526d1.png) This is complementary to #15316 but not the whole solution: - it'd be great if the defaults "just worked" based on this setting, so app developers and users would get this benefit without needing to manage configuration themselves - some apps choose to roll their own themes, but they don't have control over the main menu or context menu without also rolling their own implementations of those and hiding the default chrome To go into more detail, here's what a context menu looks like that respects the dark mode setting: ![](https://user-images.githubusercontent.com/359239/57081074-5ebaba00-6cca-11e9-97f7-d30fc030c759.png) And here's the equivalent main menu and context menu in the Electron Quick Start when using Electron 5: ![](https://user-images.githubusercontent.com/359239/57081076-5ebaba00-6cca-11e9-926b-9a18be540bef.png) ![](https://user-images.githubusercontent.com/359239/57081077-5ebaba00-6cca-11e9-8f3e-d3b0d61d3e72.png) ### Proposed Solution I'm not familiar with how this works under the hood, but happy to go spelunking if this is something that interests the maintainers to gather more information. ### Alternatives Considered As mentioned above, app developers can roll their own dark theme for menus and switch to use a chromeless `BrowserWindow`. That's fine for people who want to invest in that, but if there's lots of interest in the default chrome working better then maybe this is worth diving into? ### Additional Information <!-- Add any other context about the problem here. -->
https://github.com/electron/electron/issues/18119
https://github.com/electron/electron/pull/33624
21ef8501e7c71cd8d56828e21d310d07f9d86510
4c7c0b41c2027db27cf563e9eabb95cc8adf96bb
2019-05-02T14:14:11Z
c++
2022-06-14T16:27:28Z
shell/browser/ui/win/electron_desktop_window_tree_host_win.h
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_ #define ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_ #include <windows.h> #include "shell/browser/native_window_views.h" #include "ui/views/widget/desktop_aura/desktop_window_tree_host_win.h" namespace electron { class ElectronDesktopWindowTreeHostWin : public views::DesktopWindowTreeHostWin { public: ElectronDesktopWindowTreeHostWin( NativeWindowViews* native_window_view, views::DesktopNativeWidgetAura* desktop_native_widget_aura); ~ElectronDesktopWindowTreeHostWin() override; // disable copy ElectronDesktopWindowTreeHostWin(const ElectronDesktopWindowTreeHostWin&) = delete; ElectronDesktopWindowTreeHostWin& operator=( const ElectronDesktopWindowTreeHostWin&) = delete; protected: bool PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) override; bool ShouldPaintAsActive() const override; bool HasNativeFrame() const override; bool GetDwmFrameInsetsInPixels(gfx::Insets* insets) const override; bool GetClientAreaInsets(gfx::Insets* insets, HMONITOR monitor) const override; private: NativeWindowViews* native_window_view_; // weak ref }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_WIN_ELECTRON_DESKTOP_WINDOW_TREE_HOST_WIN_H_
closed
electron/electron
https://github.com/electron/electron
18,119
Windows chrome and context menu should be aware of dark mode setting
<!-- As an open source project with a dedicated but small maintainer team, it can sometimes take a long time for issues to be addressed so please be patient and we will get back to you as soon as we can. --> ### Preflight Checklist <!-- Please ensure you've completed the following steps by replacing [ ] with [x]--> * [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. * [x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. * [x] I have searched the issue tracker for a feature request that matches the one I want to file, without success. ### Problem Description Recent builds of Windows 10 support a "dark mode" that changes the chrome and context menus to fit better with the rest of the OS. https://www.digitaltrends.com/computing/how-to-enable-dark-mode-in-windows-10/ has a write up of how to enable this. Here's a side-by-side of Explorer and the Quick Start app on Windows `10.0.17763.437`: ![](https://user-images.githubusercontent.com/359239/57080976-2b782b00-6cca-11e9-8c41-5097e39526d1.png) This is complementary to #15316 but not the whole solution: - it'd be great if the defaults "just worked" based on this setting, so app developers and users would get this benefit without needing to manage configuration themselves - some apps choose to roll their own themes, but they don't have control over the main menu or context menu without also rolling their own implementations of those and hiding the default chrome To go into more detail, here's what a context menu looks like that respects the dark mode setting: ![](https://user-images.githubusercontent.com/359239/57081074-5ebaba00-6cca-11e9-97f7-d30fc030c759.png) And here's the equivalent main menu and context menu in the Electron Quick Start when using Electron 5: ![](https://user-images.githubusercontent.com/359239/57081076-5ebaba00-6cca-11e9-926b-9a18be540bef.png) ![](https://user-images.githubusercontent.com/359239/57081077-5ebaba00-6cca-11e9-8f3e-d3b0d61d3e72.png) ### Proposed Solution I'm not familiar with how this works under the hood, but happy to go spelunking if this is something that interests the maintainers to gather more information. ### Alternatives Considered As mentioned above, app developers can roll their own dark theme for menus and switch to use a chromeless `BrowserWindow`. That's fine for people who want to invest in that, but if there's lots of interest in the default chrome working better then maybe this is worth diving into? ### Additional Information <!-- Add any other context about the problem here. -->
https://github.com/electron/electron/issues/18119
https://github.com/electron/electron/pull/33624
21ef8501e7c71cd8d56828e21d310d07f9d86510
4c7c0b41c2027db27cf563e9eabb95cc8adf96bb
2019-05-02T14:14:11Z
c++
2022-06-14T16:27:28Z
shell/browser/win/dark_mode.cc
// Copyright (c) 2020 Microsoft Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #include "shell/browser/win/dark_mode.h" #include <dwmapi.h> // DwmSetWindowAttribute() #include "base/files/file_path.h" #include "base/scoped_native_library.h" #include "base/win/pe_image.h" #include "base/win/win_util.h" #include "base/win/windows_version.h" // This namespace contains code originally from // https://github.com/ysc3839/win32-darkmode/ // governed by the MIT license and (c) Richard Yu namespace { // 1903 18362 enum PreferredAppMode { Default, AllowDark, ForceDark, ForceLight, Max }; bool g_darkModeSupported = false; bool g_darkModeEnabled = false; DWORD g_buildNumber = 0; enum WINDOWCOMPOSITIONATTRIB { WCA_USEDARKMODECOLORS = 26 // build 18875+ }; struct WINDOWCOMPOSITIONATTRIBDATA { WINDOWCOMPOSITIONATTRIB Attrib; PVOID pvData; SIZE_T cbData; }; using fnSetWindowCompositionAttribute = BOOL(WINAPI*)(HWND hWnd, WINDOWCOMPOSITIONATTRIBDATA*); fnSetWindowCompositionAttribute _SetWindowCompositionAttribute = nullptr; bool IsHighContrast() { HIGHCONTRASTW highContrast = {sizeof(highContrast)}; if (SystemParametersInfoW(SPI_GETHIGHCONTRAST, sizeof(highContrast), &highContrast, FALSE)) return highContrast.dwFlags & HCF_HIGHCONTRASTON; return false; } void RefreshTitleBarThemeColor(HWND hWnd, bool dark) { LONG ldark = dark; if (g_buildNumber >= 20161) { // DWMA_USE_IMMERSIVE_DARK_MODE = 20 DwmSetWindowAttribute(hWnd, 20, &ldark, sizeof dark); return; } if (g_buildNumber >= 18363) { auto data = WINDOWCOMPOSITIONATTRIBDATA{WCA_USEDARKMODECOLORS, &ldark, sizeof ldark}; _SetWindowCompositionAttribute(hWnd, &data); return; } DwmSetWindowAttribute(hWnd, 0x13, &ldark, sizeof ldark); } void InitDarkMode() { // confirm that we're running on a version of Windows // where the Dark Mode API is known auto* os_info = base::win::OSInfo::GetInstance(); g_buildNumber = os_info->version_number().build; auto const version = os_info->version(); if ((version < base::win::Version::WIN10_RS5) || (version > base::win::Version::WIN10_20H1)) { return; } // load "SetWindowCompositionAttribute", used in RefreshTitleBarThemeColor() _SetWindowCompositionAttribute = reinterpret_cast<decltype(_SetWindowCompositionAttribute)>( base::win::GetUser32FunctionPointer("SetWindowCompositionAttribute")); if (_SetWindowCompositionAttribute == nullptr) { return; } // load the dark mode functions from uxtheme.dll // * RefreshImmersiveColorPolicyState() // * ShouldAppsUseDarkMode() // * AllowDarkModeForApp() // * SetPreferredAppMode() // * AllowDarkModeForApp() (build < 18362) // * SetPreferredAppMode() (build >= 18362) base::NativeLibrary uxtheme = base::PinSystemLibrary(FILE_PATH_LITERAL("uxtheme.dll")); if (!uxtheme) { return; } auto ux_pei = base::win::PEImage(uxtheme); auto get_ux_proc_from_ordinal = [&ux_pei](int ordinal, auto* setme) { FARPROC proc = ux_pei.GetProcAddress(reinterpret_cast<LPCSTR>(ordinal)); *setme = reinterpret_cast<decltype(*setme)>(proc); }; // ordinal 104 using fnRefreshImmersiveColorPolicyState = VOID(WINAPI*)(); fnRefreshImmersiveColorPolicyState _RefreshImmersiveColorPolicyState = {}; get_ux_proc_from_ordinal(104, &_RefreshImmersiveColorPolicyState); // ordinal 132 using fnShouldAppsUseDarkMode = BOOL(WINAPI*)(); fnShouldAppsUseDarkMode _ShouldAppsUseDarkMode = {}; get_ux_proc_from_ordinal(132, &_ShouldAppsUseDarkMode); // ordinal 135, in 1809 using fnAllowDarkModeForApp = BOOL(WINAPI*)(BOOL allow); fnAllowDarkModeForApp _AllowDarkModeForApp = {}; // ordinal 135, in 1903 typedef PreferredAppMode(WINAPI * fnSetPreferredAppMode)(PreferredAppMode appMode); fnSetPreferredAppMode _SetPreferredAppMode = {}; if (g_buildNumber < 18362) { get_ux_proc_from_ordinal(135, &_AllowDarkModeForApp); } else { get_ux_proc_from_ordinal(135, &_SetPreferredAppMode); } // dark mode is supported iff we found the functions g_darkModeSupported = _RefreshImmersiveColorPolicyState && _ShouldAppsUseDarkMode && (_AllowDarkModeForApp || _SetPreferredAppMode); if (!g_darkModeSupported) { return; } // initial setup: allow dark mode to be used if (_AllowDarkModeForApp) { _AllowDarkModeForApp(true); } else if (_SetPreferredAppMode) { _SetPreferredAppMode(AllowDark); } _RefreshImmersiveColorPolicyState(); // check to see if dark mode is currently enabled g_darkModeEnabled = _ShouldAppsUseDarkMode() && !IsHighContrast(); } } // namespace namespace electron { void EnsureInitialized() { static bool initialized = false; if (!initialized) { initialized = true; ::InitDarkMode(); } } bool IsDarkPreferred(ui::NativeTheme::ThemeSource theme_source) { switch (theme_source) { case ui::NativeTheme::ThemeSource::kForcedLight: return false; case ui::NativeTheme::ThemeSource::kForcedDark: return g_darkModeSupported; case ui::NativeTheme::ThemeSource::kSystem: return g_darkModeEnabled; } } namespace win { void SetDarkModeForWindow(HWND hWnd, ui::NativeTheme::ThemeSource theme_source) { EnsureInitialized(); RefreshTitleBarThemeColor(hWnd, IsDarkPreferred(theme_source)); } } // namespace win } // namespace electron
closed
electron/electron
https://github.com/electron/electron
18,119
Windows chrome and context menu should be aware of dark mode setting
<!-- As an open source project with a dedicated but small maintainer team, it can sometimes take a long time for issues to be addressed so please be patient and we will get back to you as soon as we can. --> ### Preflight Checklist <!-- Please ensure you've completed the following steps by replacing [ ] with [x]--> * [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. * [x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. * [x] I have searched the issue tracker for a feature request that matches the one I want to file, without success. ### Problem Description Recent builds of Windows 10 support a "dark mode" that changes the chrome and context menus to fit better with the rest of the OS. https://www.digitaltrends.com/computing/how-to-enable-dark-mode-in-windows-10/ has a write up of how to enable this. Here's a side-by-side of Explorer and the Quick Start app on Windows `10.0.17763.437`: ![](https://user-images.githubusercontent.com/359239/57080976-2b782b00-6cca-11e9-8c41-5097e39526d1.png) This is complementary to #15316 but not the whole solution: - it'd be great if the defaults "just worked" based on this setting, so app developers and users would get this benefit without needing to manage configuration themselves - some apps choose to roll their own themes, but they don't have control over the main menu or context menu without also rolling their own implementations of those and hiding the default chrome To go into more detail, here's what a context menu looks like that respects the dark mode setting: ![](https://user-images.githubusercontent.com/359239/57081074-5ebaba00-6cca-11e9-97f7-d30fc030c759.png) And here's the equivalent main menu and context menu in the Electron Quick Start when using Electron 5: ![](https://user-images.githubusercontent.com/359239/57081076-5ebaba00-6cca-11e9-926b-9a18be540bef.png) ![](https://user-images.githubusercontent.com/359239/57081077-5ebaba00-6cca-11e9-8f3e-d3b0d61d3e72.png) ### Proposed Solution I'm not familiar with how this works under the hood, but happy to go spelunking if this is something that interests the maintainers to gather more information. ### Alternatives Considered As mentioned above, app developers can roll their own dark theme for menus and switch to use a chromeless `BrowserWindow`. That's fine for people who want to invest in that, but if there's lots of interest in the default chrome working better then maybe this is worth diving into? ### Additional Information <!-- Add any other context about the problem here. -->
https://github.com/electron/electron/issues/18119
https://github.com/electron/electron/pull/33624
21ef8501e7c71cd8d56828e21d310d07f9d86510
4c7c0b41c2027db27cf563e9eabb95cc8adf96bb
2019-05-02T14:14:11Z
c++
2022-06-14T16:27:28Z
shell/browser/win/dark_mode.h
// Copyright (c) 2020 Microsoft Inc. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE-CHROMIUM file. #ifndef ELECTRON_SHELL_BROWSER_WIN_DARK_MODE_H_ #define ELECTRON_SHELL_BROWSER_WIN_DARK_MODE_H_ #ifdef WIN32_LEAN_AND_MEAN #include <Windows.h> #else #define WIN32_LEAN_AND_MEAN #include <Windows.h> #undef WIN32_LEAN_AND_MEAN #endif #include "ui/native_theme/native_theme.h" namespace electron { namespace win { void SetDarkModeForWindow(HWND hWnd, ui::NativeTheme::ThemeSource theme_source); } // namespace win } // namespace electron #endif // ELECTRON_SHELL_BROWSER_WIN_DARK_MODE_H_
closed
electron/electron
https://github.com/electron/electron
18,119
Windows chrome and context menu should be aware of dark mode setting
<!-- As an open source project with a dedicated but small maintainer team, it can sometimes take a long time for issues to be addressed so please be patient and we will get back to you as soon as we can. --> ### Preflight Checklist <!-- Please ensure you've completed the following steps by replacing [ ] with [x]--> * [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. * [x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. * [x] I have searched the issue tracker for a feature request that matches the one I want to file, without success. ### Problem Description Recent builds of Windows 10 support a "dark mode" that changes the chrome and context menus to fit better with the rest of the OS. https://www.digitaltrends.com/computing/how-to-enable-dark-mode-in-windows-10/ has a write up of how to enable this. Here's a side-by-side of Explorer and the Quick Start app on Windows `10.0.17763.437`: ![](https://user-images.githubusercontent.com/359239/57080976-2b782b00-6cca-11e9-8c41-5097e39526d1.png) This is complementary to #15316 but not the whole solution: - it'd be great if the defaults "just worked" based on this setting, so app developers and users would get this benefit without needing to manage configuration themselves - some apps choose to roll their own themes, but they don't have control over the main menu or context menu without also rolling their own implementations of those and hiding the default chrome To go into more detail, here's what a context menu looks like that respects the dark mode setting: ![](https://user-images.githubusercontent.com/359239/57081074-5ebaba00-6cca-11e9-97f7-d30fc030c759.png) And here's the equivalent main menu and context menu in the Electron Quick Start when using Electron 5: ![](https://user-images.githubusercontent.com/359239/57081076-5ebaba00-6cca-11e9-926b-9a18be540bef.png) ![](https://user-images.githubusercontent.com/359239/57081077-5ebaba00-6cca-11e9-8f3e-d3b0d61d3e72.png) ### Proposed Solution I'm not familiar with how this works under the hood, but happy to go spelunking if this is something that interests the maintainers to gather more information. ### Alternatives Considered As mentioned above, app developers can roll their own dark theme for menus and switch to use a chromeless `BrowserWindow`. That's fine for people who want to invest in that, but if there's lots of interest in the default chrome working better then maybe this is worth diving into? ### Additional Information <!-- Add any other context about the problem here. -->
https://github.com/electron/electron/issues/18119
https://github.com/electron/electron/pull/33624
21ef8501e7c71cd8d56828e21d310d07f9d86510
4c7c0b41c2027db27cf563e9eabb95cc8adf96bb
2019-05-02T14:14:11Z
c++
2022-06-14T16:27:28Z
shell/common/api/features.cc
// Copyright (c) 2018 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "printing/buildflags/buildflags.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" namespace { bool IsBuiltinSpellCheckerEnabled() { return BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER); } bool IsDesktopCapturerEnabled() { return BUILDFLAG(ENABLE_DESKTOP_CAPTURER); } bool IsOffscreenRenderingEnabled() { return BUILDFLAG(ENABLE_OSR); } bool IsPDFViewerEnabled() { return BUILDFLAG(ENABLE_PDF_VIEWER); } bool IsRunAsNodeEnabled() { return electron::fuses::IsRunAsNodeEnabled() && BUILDFLAG(ENABLE_RUN_AS_NODE); } bool IsFakeLocationProviderEnabled() { return BUILDFLAG(OVERRIDE_LOCATION_PROVIDER); } bool IsViewApiEnabled() { return BUILDFLAG(ENABLE_VIEWS_API); } bool IsTtsEnabled() { return BUILDFLAG(ENABLE_TTS); } bool IsPrintingEnabled() { return BUILDFLAG(ENABLE_PRINTING); } bool IsExtensionsEnabled() { return BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS); } bool IsPictureInPictureEnabled() { return BUILDFLAG(ENABLE_PICTURE_IN_PICTURE); } bool IsWinDarkModeWindowUiEnabled() { return BUILDFLAG(ENABLE_WIN_DARK_MODE_WINDOW_UI); } bool IsComponentBuild() { #if defined(COMPONENT_BUILD) return true; #else return false; #endif } void Initialize(v8::Local<v8::Object> exports, v8::Local<v8::Value> unused, v8::Local<v8::Context> context, void* priv) { gin_helper::Dictionary dict(context->GetIsolate(), exports); dict.SetMethod("isBuiltinSpellCheckerEnabled", &IsBuiltinSpellCheckerEnabled); dict.SetMethod("isDesktopCapturerEnabled", &IsDesktopCapturerEnabled); dict.SetMethod("isOffscreenRenderingEnabled", &IsOffscreenRenderingEnabled); dict.SetMethod("isPDFViewerEnabled", &IsPDFViewerEnabled); dict.SetMethod("isRunAsNodeEnabled", &IsRunAsNodeEnabled); dict.SetMethod("isFakeLocationProviderEnabled", &IsFakeLocationProviderEnabled); dict.SetMethod("isViewApiEnabled", &IsViewApiEnabled); dict.SetMethod("isTtsEnabled", &IsTtsEnabled); dict.SetMethod("isPrintingEnabled", &IsPrintingEnabled); dict.SetMethod("isPictureInPictureEnabled", &IsPictureInPictureEnabled); dict.SetMethod("isComponentBuild", &IsComponentBuild); dict.SetMethod("isExtensionsEnabled", &IsExtensionsEnabled); dict.SetMethod("isWinDarkModeWindowUiEnabled", &IsWinDarkModeWindowUiEnabled); } } // namespace NODE_LINKED_MODULE_CONTEXT_AWARE(electron_common_features, Initialize)
closed
electron/electron
https://github.com/electron/electron
18,119
Windows chrome and context menu should be aware of dark mode setting
<!-- As an open source project with a dedicated but small maintainer team, it can sometimes take a long time for issues to be addressed so please be patient and we will get back to you as soon as we can. --> ### Preflight Checklist <!-- Please ensure you've completed the following steps by replacing [ ] with [x]--> * [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/master/CONTRIBUTING.md) for this project. * [x] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/master/CODE_OF_CONDUCT.md) that this project adheres to. * [x] I have searched the issue tracker for a feature request that matches the one I want to file, without success. ### Problem Description Recent builds of Windows 10 support a "dark mode" that changes the chrome and context menus to fit better with the rest of the OS. https://www.digitaltrends.com/computing/how-to-enable-dark-mode-in-windows-10/ has a write up of how to enable this. Here's a side-by-side of Explorer and the Quick Start app on Windows `10.0.17763.437`: ![](https://user-images.githubusercontent.com/359239/57080976-2b782b00-6cca-11e9-8c41-5097e39526d1.png) This is complementary to #15316 but not the whole solution: - it'd be great if the defaults "just worked" based on this setting, so app developers and users would get this benefit without needing to manage configuration themselves - some apps choose to roll their own themes, but they don't have control over the main menu or context menu without also rolling their own implementations of those and hiding the default chrome To go into more detail, here's what a context menu looks like that respects the dark mode setting: ![](https://user-images.githubusercontent.com/359239/57081074-5ebaba00-6cca-11e9-97f7-d30fc030c759.png) And here's the equivalent main menu and context menu in the Electron Quick Start when using Electron 5: ![](https://user-images.githubusercontent.com/359239/57081076-5ebaba00-6cca-11e9-926b-9a18be540bef.png) ![](https://user-images.githubusercontent.com/359239/57081077-5ebaba00-6cca-11e9-8f3e-d3b0d61d3e72.png) ### Proposed Solution I'm not familiar with how this works under the hood, but happy to go spelunking if this is something that interests the maintainers to gather more information. ### Alternatives Considered As mentioned above, app developers can roll their own dark theme for menus and switch to use a chromeless `BrowserWindow`. That's fine for people who want to invest in that, but if there's lots of interest in the default chrome working better then maybe this is worth diving into? ### Additional Information <!-- Add any other context about the problem here. -->
https://github.com/electron/electron/issues/18119
https://github.com/electron/electron/pull/33624
21ef8501e7c71cd8d56828e21d310d07f9d86510
4c7c0b41c2027db27cf563e9eabb95cc8adf96bb
2019-05-02T14:14:11Z
c++
2022-06-14T16:27:28Z
typings/internal-ambient.d.ts
/* eslint-disable no-var */ declare var internalBinding: any; declare var binding: { get: (name: string) => any; process: NodeJS.Process; createPreloadScript: (src: string) => Function }; declare var isolatedApi: { guestViewInternal: any; allowGuestViewElementDefinition: NodeJS.InternalWebFrame['allowGuestViewElementDefinition']; setIsWebView: (iframe: HTMLIFrameElement) => void; } declare const BUILDFLAG: (flag: boolean) => boolean; declare const ENABLE_DESKTOP_CAPTURER: boolean; declare const ENABLE_VIEWS_API: boolean; declare namespace NodeJS { interface FeaturesBinding { isBuiltinSpellCheckerEnabled(): boolean; isDesktopCapturerEnabled(): boolean; isOffscreenRenderingEnabled(): boolean; isPDFViewerEnabled(): boolean; isRunAsNodeEnabled(): boolean; isFakeLocationProviderEnabled(): boolean; isViewApiEnabled(): boolean; isTtsEnabled(): boolean; isPrintingEnabled(): boolean; isPictureInPictureEnabled(): boolean; isExtensionsEnabled(): boolean; isComponentBuild(): boolean; isWinDarkModeWindowUiEnabled(): boolean; } interface IpcRendererBinding { send(internal: boolean, channel: string, args: any[]): void; sendSync(internal: boolean, channel: string, args: any[]): any; sendToHost(channel: string, args: any[]): void; sendTo(webContentsId: number, channel: string, args: any[]): void; invoke<T>(internal: boolean, channel: string, args: any[]): Promise<{ error: string, result: T }>; postMessage(channel: string, message: any, transferables: MessagePort[]): void; } interface V8UtilBinding { getHiddenValue<T>(obj: any, key: string): T; setHiddenValue<T>(obj: any, key: string, value: T): void; deleteHiddenValue(obj: any, key: string): void; requestGarbageCollectionForTesting(): void; runUntilIdle(): void; triggerFatalErrorForTesting(): void; } interface EnvironmentBinding { getVar(name: string): string | null; hasVar(name: string): boolean; setVar(name: string, value: string): boolean; unSetVar(name: string): boolean; } type AsarFileInfo = { size: number; unpacked: boolean; offset: number; integrity?: { algorithm: 'SHA256'; hash: string; } }; type AsarFileStat = { size: number; offset: number; isFile: boolean; isDirectory: boolean; isLink: boolean; } interface AsarArchive { getFileInfo(path: string): AsarFileInfo | false; stat(path: string): AsarFileStat | false; readdir(path: string): string[] | false; realpath(path: string): string | false; copyFileOut(path: string): string | false; getFdAndValidateIntegrityLater(): number | -1; } interface AsarBinding { Archive: { new(path: string): AsarArchive }; splitPath(path: string): { isAsar: false; } | { isAsar: true; asarPath: string; filePath: string; }; initAsarSupport(require: NodeJS.Require): void; } interface PowerMonitorBinding extends Electron.PowerMonitor { createPowerMonitor(): PowerMonitorBinding; setListeningForShutdown(listening: boolean): void; } interface WebViewManagerBinding { addGuest(guestInstanceId: number, embedder: Electron.WebContents, guest: Electron.WebContents, webPreferences: Electron.WebPreferences): void; removeGuest(embedder: Electron.WebContents, guestInstanceId: number): void; } interface InternalWebPreferences { isWebView: boolean; hiddenPage: boolean; nodeIntegration: boolean; preload: string preloadScripts: string[]; webviewTag: boolean; } interface InternalWebFrame extends Electron.WebFrame { getWebPreference<K extends keyof InternalWebPreferences>(name: K): InternalWebPreferences[K]; getWebFrameId(window: Window): number; allowGuestViewElementDefinition(context: object, callback: Function): void; } interface WebFrameBinding { mainFrame: InternalWebFrame; } type DataPipe = { write: (buf: Uint8Array) => Promise<void>; done: () => void; }; type BodyFunc = (pipe: DataPipe) => void; type CreateURLLoaderOptions = { method: string; url: string; extraHeaders?: Record<string, string>; useSessionCookies?: boolean; credentials?: 'include' | 'omit'; body: Uint8Array | BodyFunc; session?: Electron.Session; partition?: string; referrer?: string; origin?: string; hasUserActivation?: boolean; mode?: string; destination?: string; }; type ResponseHead = { statusCode: number; statusMessage: string; httpVersion: { major: number, minor: number }; rawHeaders: { key: string, value: string }[]; }; type RedirectInfo = { statusCode: number; newMethod: string; newUrl: string; newSiteForCookies: string; newReferrer: string; insecureSchemeWasUpgraded: boolean; isSignedExchangeFallbackRedirect: boolean; } interface URLLoader extends EventEmitter { cancel(): void; on(eventName: 'data', listener: (event: any, data: ArrayBuffer, resume: () => void) => void): this; on(eventName: 'response-started', listener: (event: any, finalUrl: string, responseHead: ResponseHead) => void): this; on(eventName: 'complete', listener: (event: any) => void): this; on(eventName: 'error', listener: (event: any, netErrorString: string) => void): this; on(eventName: 'login', listener: (event: any, authInfo: Electron.AuthInfo, callback: (username?: string, password?: string) => void) => void): this; on(eventName: 'redirect', listener: (event: any, redirectInfo: RedirectInfo, headers: Record<string, string>) => void): this; on(eventName: 'upload-progress', listener: (event: any, position: number, total: number) => void): this; on(eventName: 'download-progress', listener: (event: any, current: number) => void): this; } interface Process { internalBinding?(name: string): any; _linkedBinding(name: string): any; _linkedBinding(name: 'electron_common_asar'): AsarBinding; _linkedBinding(name: 'electron_common_clipboard'): Electron.Clipboard; _linkedBinding(name: 'electron_common_command_line'): Electron.CommandLine; _linkedBinding(name: 'electron_common_environment'): EnvironmentBinding; _linkedBinding(name: 'electron_common_features'): FeaturesBinding; _linkedBinding(name: 'electron_common_native_image'): { nativeImage: typeof Electron.NativeImage }; _linkedBinding(name: 'electron_common_native_theme'): { nativeTheme: Electron.NativeTheme }; _linkedBinding(name: 'electron_common_notification'): { isSupported(): boolean; Notification: typeof Electron.Notification; } _linkedBinding(name: 'electron_common_screen'): { createScreen(): Electron.Screen }; _linkedBinding(name: 'electron_common_shell'): Electron.Shell; _linkedBinding(name: 'electron_common_v8_util'): V8UtilBinding; _linkedBinding(name: 'electron_browser_app'): { app: Electron.App, App: Function }; _linkedBinding(name: 'electron_browser_auto_updater'): { autoUpdater: Electron.AutoUpdater }; _linkedBinding(name: 'electron_browser_browser_view'): { BrowserView: typeof Electron.BrowserView }; _linkedBinding(name: 'electron_browser_crash_reporter'): Omit<Electron.CrashReporter, 'start'> & { start(submitUrl: string, uploadToServer: boolean, ignoreSystemCrashHandler: boolean, rateLimit: boolean, compress: boolean, globalExtra: Record<string, string>, extra: Record<string, string>, isNodeProcess: boolean): void; }; _linkedBinding(name: 'electron_browser_desktop_capturer'): { createDesktopCapturer(): ElectronInternal.DesktopCapturer; }; _linkedBinding(name: 'electron_browser_event'): { createWithSender(sender: Electron.WebContents): Electron.Event; createEmpty(): Electron.Event; }; _linkedBinding(name: 'electron_browser_event_emitter'): { setEventEmitterPrototype(prototype: Object): void; }; _linkedBinding(name: 'electron_browser_global_shortcut'): { globalShortcut: Electron.GlobalShortcut }; _linkedBinding(name: 'electron_browser_image_view'): { ImageView: any }; _linkedBinding(name: 'electron_browser_in_app_purchase'): { inAppPurchase: Electron.InAppPurchase }; _linkedBinding(name: 'electron_browser_message_port'): { createPair(): { port1: Electron.MessagePortMain, port2: Electron.MessagePortMain }; }; _linkedBinding(name: 'electron_browser_net'): { isOnline(): boolean; isValidHeaderName: (headerName: string) => boolean; isValidHeaderValue: (headerValue: string) => boolean; fileURLToFilePath: (url: string) => string; Net: any; net: any; createURLLoader(options: CreateURLLoaderOptions): URLLoader; }; _linkedBinding(name: 'electron_browser_power_monitor'): PowerMonitorBinding; _linkedBinding(name: 'electron_browser_power_save_blocker'): { powerSaveBlocker: Electron.PowerSaveBlocker }; _linkedBinding(name: 'electron_browser_safe_storage'): { safeStorage: Electron.SafeStorage }; _linkedBinding(name: 'electron_browser_session'): typeof Electron.Session; _linkedBinding(name: 'electron_browser_system_preferences'): { systemPreferences: Electron.SystemPreferences }; _linkedBinding(name: 'electron_browser_tray'): { Tray: Electron.Tray }; _linkedBinding(name: 'electron_browser_view'): { View: Electron.View }; _linkedBinding(name: 'electron_browser_web_contents_view'): { WebContentsView: typeof Electron.WebContentsView }; _linkedBinding(name: 'electron_browser_web_view_manager'): WebViewManagerBinding; _linkedBinding(name: 'electron_browser_web_frame_main'): { WebFrameMain: typeof Electron.WebFrameMain; fromId(processId: number, routingId: number): Electron.WebFrameMain; } _linkedBinding(name: 'electron_renderer_crash_reporter'): Electron.CrashReporter; _linkedBinding(name: 'electron_renderer_ipc'): { ipc: IpcRendererBinding }; _linkedBinding(name: 'electron_renderer_web_frame'): WebFrameBinding; log: NodeJS.WriteStream['write']; activateUvLoop(): void; // Additional events once(event: 'document-start', listener: () => any): this; once(event: 'document-end', listener: () => any): this; // Additional properties _firstFileName?: string; helperExecPath: string; mainModule?: NodeJS.Module | undefined; } } declare module NodeJS { interface Global { require: NodeRequire; module: NodeModule; __filename: string; __dirname: string; } } interface ContextMenuItem { id: number; label: string; type: 'normal' | 'separator' | 'subMenu' | 'checkbox'; checked: boolean; enabled: boolean; subItems: ContextMenuItem[]; } declare interface Window { ELECTRON_DISABLE_SECURITY_WARNINGS?: boolean; ELECTRON_ENABLE_SECURITY_WARNINGS?: boolean; InspectorFrontendHost?: { showContextMenuAtPoint: (x: number, y: number, items: ContextMenuItem[]) => void }; DevToolsAPI?: { contextMenuItemSelected: (id: number) => void; contextMenuCleared: () => void }; UI?: { createFileSelectorElement: (callback: () => void) => HTMLSpanElement }; Persistence?: { FileSystemWorkspaceBinding: { completeURL: (project: string, path: string) => string; } }; WebView: typeof ElectronInternal.WebViewElement; trustedTypes: TrustedTypePolicyFactory; } // https://w3c.github.io/webappsec-trusted-types/dist/spec/#trusted-types type TrustedHTML = string; type TrustedScript = string; type TrustedScriptURL = string; type TrustedType = TrustedHTML | TrustedScript | TrustedScriptURL; type StringContext = 'TrustedHTML' | 'TrustedScript' | 'TrustedScriptURL'; // https://w3c.github.io/webappsec-trusted-types/dist/spec/#typedef-trustedtypepolicy interface TrustedTypePolicy { createHTML(input: string, ...arguments: any[]): TrustedHTML; createScript(input: string, ...arguments: any[]): TrustedScript; createScriptURL(input: string, ...arguments: any[]): TrustedScriptURL; } // https://w3c.github.io/webappsec-trusted-types/dist/spec/#typedef-trustedtypepolicyoptions interface TrustedTypePolicyOptions { createHTML?: (input: string, ...arguments: any[]) => TrustedHTML; createScript?: (input: string, ...arguments: any[]) => TrustedScript; createScriptURL?: (input: string, ...arguments: any[]) => TrustedScriptURL; } // https://w3c.github.io/webappsec-trusted-types/dist/spec/#typedef-trustedtypepolicyfactory interface TrustedTypePolicyFactory { createPolicy(policyName: string, policyOptions: TrustedTypePolicyOptions): TrustedTypePolicy isHTML(value: any): boolean; isScript(value: any): boolean; isScriptURL(value: any): boolean; readonly emptyHTML: TrustedHTML; readonly emptyScript: TrustedScript; getAttributeType(tagName: string, attribute: string, elementNs?: string, attrNs?: string): StringContext | null; getPropertyType(tagName: string, property: string, elementNs?: string): StringContext | null; readonly defaultPolicy: TrustedTypePolicy | null; }
closed
electron/electron
https://github.com/electron/electron
34,552
[Bug]: -webkit-app-region not recalculated when BrowserView bounds changed
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.3 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior If a BrowserView that contains a draggable region (-webkit-app-region: drag) is moved (has its bounds changed) within a BrowserWindow, the draggable region should effectively move with the BrowserView. ### Actual Behavior The draggable region does not move when the BrowserView does. The previous absolute BrowserWindow region remains draggable, and the new region the BrowserView occupies is not draggable. ### Testcase Gist URL https://gist.github.com/bff9757ccf3613446232a03f08bd8075 ### Additional Information Gist is fairly straightforward, as you move the view down, the original location of the draggable bar is the only draggable region.
https://github.com/electron/electron/issues/34552
https://github.com/electron/electron/pull/34582
d2e539c7d4fb16615164222fd9568ed81d7aacc1
20538c4f34a471677d40ef304e76ae46a3a3c3f1
2022-06-14T18:37:50Z
c++
2022-06-17T10:01:38Z
shell/browser/native_browser_view_views.cc
// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_browser_view_views.h" #include <vector> #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/views/inspectable_web_contents_view_views.h" #include "ui/gfx/geometry/rect.h" #include "ui/views/background.h" #include "ui/views/view.h" namespace electron { NativeBrowserViewViews::NativeBrowserViewViews( InspectableWebContents* inspectable_web_contents) : NativeBrowserView(inspectable_web_contents) {} NativeBrowserViewViews::~NativeBrowserViewViews() = default; void NativeBrowserViewViews::SetAutoResizeFlags(uint8_t flags) { auto_resize_flags_ = flags; ResetAutoResizeProportions(); } void NativeBrowserViewViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { // We need to snap the regions to the bounds of the current BrowserView. // For example, if an attached BrowserView is draggable but its bounds are // { x: 200, y: 100, width: 300, height: 300 } // then we need to add 200 to the x-value and 100 to the // y-value of each of the passed regions or it will be incorrectly // assumed that the regions begin in the top left corner as they // would for the main client window. auto const offset = GetBounds().OffsetFromOrigin(); auto snapped_regions = mojo::Clone(regions); for (auto& snapped_region : snapped_regions) { snapped_region->bounds.Offset(offset); } draggable_region_ = DraggableRegionsToSkRegion(snapped_regions); } void NativeBrowserViewViews::SetAutoResizeProportions( const gfx::Size& window_size) { if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) && !auto_horizontal_proportion_set_) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); auto view_bounds = view->bounds(); auto_horizontal_proportion_width_ = static_cast<float>(window_size.width()) / static_cast<float>(view_bounds.width()); auto_horizontal_proportion_left_ = static_cast<float>(window_size.width()) / static_cast<float>(view_bounds.x()); auto_horizontal_proportion_set_ = true; } if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) && !auto_vertical_proportion_set_) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); auto view_bounds = view->bounds(); auto_vertical_proportion_height_ = static_cast<float>(window_size.height()) / static_cast<float>(view_bounds.height()); auto_vertical_proportion_top_ = static_cast<float>(window_size.height()) / static_cast<float>(view_bounds.y()); auto_vertical_proportion_set_ = true; } } void NativeBrowserViewViews::AutoResize(const gfx::Rect& new_window, int width_delta, int height_delta) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); const auto flags = GetAutoResizeFlags(); if (!(flags & kAutoResizeWidth)) { width_delta = 0; } if (!(flags & kAutoResizeHeight)) { height_delta = 0; } if (height_delta || width_delta) { auto new_view_size = view->size(); new_view_size.set_width(new_view_size.width() + width_delta); new_view_size.set_height(new_view_size.height() + height_delta); view->SetSize(new_view_size); } auto new_view_bounds = view->bounds(); if (flags & kAutoResizeHorizontal) { new_view_bounds.set_width(new_window.width() / auto_horizontal_proportion_width_); new_view_bounds.set_x(new_window.width() / auto_horizontal_proportion_left_); } if (flags & kAutoResizeVertical) { new_view_bounds.set_height(new_window.height() / auto_vertical_proportion_height_); new_view_bounds.set_y(new_window.height() / auto_vertical_proportion_top_); } if ((flags & kAutoResizeHorizontal) || (flags & kAutoResizeVertical)) { view->SetBoundsRect(new_view_bounds); } } void NativeBrowserViewViews::ResetAutoResizeProportions() { if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) { auto_horizontal_proportion_set_ = false; } if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) { auto_vertical_proportion_set_ = false; } } void NativeBrowserViewViews::SetBounds(const gfx::Rect& bounds) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); view->SetBoundsRect(bounds); ResetAutoResizeProportions(); } gfx::Rect NativeBrowserViewViews::GetBounds() { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return gfx::Rect(); return iwc_view->GetView()->bounds(); } void NativeBrowserViewViews::RenderViewReady() { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (iwc_view) iwc_view->GetView()->Layout(); } void NativeBrowserViewViews::SetBackgroundColor(SkColor color) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); view->SetBackground(views::CreateSolidBackground(color)); view->SchedulePaint(); } // static NativeBrowserView* NativeBrowserView::Create( InspectableWebContents* inspectable_web_contents) { return new NativeBrowserViewViews(inspectable_web_contents); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,552
[Bug]: -webkit-app-region not recalculated when BrowserView bounds changed
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.3 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior If a BrowserView that contains a draggable region (-webkit-app-region: drag) is moved (has its bounds changed) within a BrowserWindow, the draggable region should effectively move with the BrowserView. ### Actual Behavior The draggable region does not move when the BrowserView does. The previous absolute BrowserWindow region remains draggable, and the new region the BrowserView occupies is not draggable. ### Testcase Gist URL https://gist.github.com/bff9757ccf3613446232a03f08bd8075 ### Additional Information Gist is fairly straightforward, as you move the view down, the original location of the draggable bar is the only draggable region.
https://github.com/electron/electron/issues/34552
https://github.com/electron/electron/pull/34582
d2e539c7d4fb16615164222fd9568ed81d7aacc1
20538c4f34a471677d40ef304e76ae46a3a3c3f1
2022-06-14T18:37:50Z
c++
2022-06-17T10:01:38Z
shell/browser/native_browser_view_views.cc
// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_browser_view_views.h" #include <vector> #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/views/inspectable_web_contents_view_views.h" #include "ui/gfx/geometry/rect.h" #include "ui/views/background.h" #include "ui/views/view.h" namespace electron { NativeBrowserViewViews::NativeBrowserViewViews( InspectableWebContents* inspectable_web_contents) : NativeBrowserView(inspectable_web_contents) {} NativeBrowserViewViews::~NativeBrowserViewViews() = default; void NativeBrowserViewViews::SetAutoResizeFlags(uint8_t flags) { auto_resize_flags_ = flags; ResetAutoResizeProportions(); } void NativeBrowserViewViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { // We need to snap the regions to the bounds of the current BrowserView. // For example, if an attached BrowserView is draggable but its bounds are // { x: 200, y: 100, width: 300, height: 300 } // then we need to add 200 to the x-value and 100 to the // y-value of each of the passed regions or it will be incorrectly // assumed that the regions begin in the top left corner as they // would for the main client window. auto const offset = GetBounds().OffsetFromOrigin(); auto snapped_regions = mojo::Clone(regions); for (auto& snapped_region : snapped_regions) { snapped_region->bounds.Offset(offset); } draggable_region_ = DraggableRegionsToSkRegion(snapped_regions); } void NativeBrowserViewViews::SetAutoResizeProportions( const gfx::Size& window_size) { if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) && !auto_horizontal_proportion_set_) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); auto view_bounds = view->bounds(); auto_horizontal_proportion_width_ = static_cast<float>(window_size.width()) / static_cast<float>(view_bounds.width()); auto_horizontal_proportion_left_ = static_cast<float>(window_size.width()) / static_cast<float>(view_bounds.x()); auto_horizontal_proportion_set_ = true; } if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) && !auto_vertical_proportion_set_) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); auto view_bounds = view->bounds(); auto_vertical_proportion_height_ = static_cast<float>(window_size.height()) / static_cast<float>(view_bounds.height()); auto_vertical_proportion_top_ = static_cast<float>(window_size.height()) / static_cast<float>(view_bounds.y()); auto_vertical_proportion_set_ = true; } } void NativeBrowserViewViews::AutoResize(const gfx::Rect& new_window, int width_delta, int height_delta) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); const auto flags = GetAutoResizeFlags(); if (!(flags & kAutoResizeWidth)) { width_delta = 0; } if (!(flags & kAutoResizeHeight)) { height_delta = 0; } if (height_delta || width_delta) { auto new_view_size = view->size(); new_view_size.set_width(new_view_size.width() + width_delta); new_view_size.set_height(new_view_size.height() + height_delta); view->SetSize(new_view_size); } auto new_view_bounds = view->bounds(); if (flags & kAutoResizeHorizontal) { new_view_bounds.set_width(new_window.width() / auto_horizontal_proportion_width_); new_view_bounds.set_x(new_window.width() / auto_horizontal_proportion_left_); } if (flags & kAutoResizeVertical) { new_view_bounds.set_height(new_window.height() / auto_vertical_proportion_height_); new_view_bounds.set_y(new_window.height() / auto_vertical_proportion_top_); } if ((flags & kAutoResizeHorizontal) || (flags & kAutoResizeVertical)) { view->SetBoundsRect(new_view_bounds); } } void NativeBrowserViewViews::ResetAutoResizeProportions() { if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) { auto_horizontal_proportion_set_ = false; } if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) { auto_vertical_proportion_set_ = false; } } void NativeBrowserViewViews::SetBounds(const gfx::Rect& bounds) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); view->SetBoundsRect(bounds); ResetAutoResizeProportions(); } gfx::Rect NativeBrowserViewViews::GetBounds() { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return gfx::Rect(); return iwc_view->GetView()->bounds(); } void NativeBrowserViewViews::RenderViewReady() { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (iwc_view) iwc_view->GetView()->Layout(); } void NativeBrowserViewViews::SetBackgroundColor(SkColor color) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); view->SetBackground(views::CreateSolidBackground(color)); view->SchedulePaint(); } // static NativeBrowserView* NativeBrowserView::Create( InspectableWebContents* inspectable_web_contents) { return new NativeBrowserViewViews(inspectable_web_contents); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
BUILD.gn
import("//build/config/locales.gni") import("//build/config/ui.gni") import("//build/config/win/manifest.gni") import("//components/os_crypt/features.gni") import("//components/spellcheck/spellcheck_build_features.gni") import("//content/public/app/mac_helpers.gni") import("//extensions/buildflags/buildflags.gni") import("//pdf/features.gni") import("//ppapi/buildflags/buildflags.gni") import("//printing/buildflags/buildflags.gni") import("//testing/test.gni") import("//third_party/ffmpeg/ffmpeg_options.gni") import("//tools/generate_library_loader/generate_library_loader.gni") import("//tools/grit/grit_rule.gni") import("//tools/grit/repack.gni") import("//tools/v8_context_snapshot/v8_context_snapshot.gni") import("//v8/gni/snapshot_toolchain.gni") import("build/asar.gni") import("build/extract_symbols.gni") import("build/npm.gni") import("build/templated_file.gni") import("build/tsc.gni") import("build/webpack/webpack.gni") import("buildflags/buildflags.gni") import("electron_paks.gni") import("filenames.auto.gni") import("filenames.gni") import("filenames.hunspell.gni") import("filenames.libcxx.gni") import("filenames.libcxxabi.gni") if (is_mac) { import("//build/config/mac/rules.gni") import("//third_party/icu/config.gni") import("//ui/gl/features.gni") import("//v8/gni/v8.gni") import("build/rules.gni") assert( mac_deployment_target == "10.13", "Chromium has updated the mac_deployment_target, please update this assert, update the supported versions documentation (docs/tutorial/support.md) and flag this as a breaking change") } if (is_linux) { import("//build/config/linux/pkg_config.gni") import("//tools/generate_stubs/rules.gni") pkg_config("gio_unix") { packages = [ "gio-unix-2.0" ] } pkg_config("libnotify_config") { packages = [ "glib-2.0", "gdk-pixbuf-2.0", ] } generate_library_loader("libnotify_loader") { name = "LibNotifyLoader" output_h = "libnotify_loader.h" output_cc = "libnotify_loader.cc" header = "<libnotify/notify.h>" config = ":libnotify_config" functions = [ "notify_is_initted", "notify_init", "notify_get_server_caps", "notify_get_server_info", "notify_notification_new", "notify_notification_add_action", "notify_notification_set_image_from_pixbuf", "notify_notification_set_timeout", "notify_notification_set_urgency", "notify_notification_set_hint_string", "notify_notification_show", "notify_notification_close", ] } # Generates electron_gtk_stubs.h header which contains # stubs for extracting function ptrs from the gtk library. # Function signatures for which stubs are required should be # declared in electron_gtk.sigs, currently this file contains # signatures for the functions used with native file chooser # implementation. In future, this file can be extended to contain # gtk4 stubs to switch gtk version in runtime. generate_stubs("electron_gtk_stubs") { sigs = [ "shell/browser/ui/electron_gtk.sigs" ] extra_header = "shell/browser/ui/electron_gtk.fragment" output_name = "electron_gtk_stubs" public_deps = [ "//ui/gtk:gtk_config" ] logging_function = "LogNoop()" logging_include = "ui/gtk/log_noop.h" } } declare_args() { use_prebuilt_v8_context_snapshot = false } branding = read_file("shell/app/BRANDING.json", "json") electron_project_name = branding.project_name electron_product_name = branding.product_name electron_mac_bundle_id = branding.mac_bundle_id if (is_mas_build) { assert(is_mac, "It doesn't make sense to build a MAS build on a non-mac platform") } if (enable_pdf_viewer) { assert(enable_pdf, "PDF viewer support requires enable_pdf=true") assert(enable_electron_extensions, "PDF viewer support requires enable_electron_extensions=true") } if (enable_electron_extensions) { assert(enable_extensions, "Chrome extension support requires enable_extensions=true") } config("branding") { defines = [ "ELECTRON_PRODUCT_NAME=\"$electron_product_name\"", "ELECTRON_PROJECT_NAME=\"$electron_project_name\"", ] } config("electron_lib_config") { include_dirs = [ "." ] } # We generate the definitions twice here, once in //electron/electron.d.ts # and once in $target_gen_dir # The one in $target_gen_dir is used for the actual TSC build later one # and the one in //electron/electron.d.ts is used by your IDE (vscode) # for typescript prompting npm_action("build_electron_definitions") { script = "gn-typescript-definitions" args = [ rebase_path("$target_gen_dir/tsc/typings/electron.d.ts") ] inputs = auto_filenames.api_docs + [ "yarn.lock" ] outputs = [ "$target_gen_dir/tsc/typings/electron.d.ts" ] } webpack_build("electron_asar_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.asar_bundle_deps config_file = "//electron/build/webpack/webpack.config.asar.js" out_file = "$target_gen_dir/js2c/asar_bundle.js" } webpack_build("electron_browser_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.browser_bundle_deps config_file = "//electron/build/webpack/webpack.config.browser.js" out_file = "$target_gen_dir/js2c/browser_init.js" } webpack_build("electron_renderer_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.renderer_bundle_deps config_file = "//electron/build/webpack/webpack.config.renderer.js" out_file = "$target_gen_dir/js2c/renderer_init.js" } webpack_build("electron_worker_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.worker_bundle_deps config_file = "//electron/build/webpack/webpack.config.worker.js" out_file = "$target_gen_dir/js2c/worker_init.js" } webpack_build("electron_sandboxed_renderer_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.sandbox_bundle_deps config_file = "//electron/build/webpack/webpack.config.sandboxed_renderer.js" out_file = "$target_gen_dir/js2c/sandbox_bundle.js" } webpack_build("electron_isolated_renderer_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.isolated_bundle_deps config_file = "//electron/build/webpack/webpack.config.isolated_renderer.js" out_file = "$target_gen_dir/js2c/isolated_bundle.js" } action("electron_js2c") { deps = [ ":electron_asar_bundle", ":electron_browser_bundle", ":electron_isolated_renderer_bundle", ":electron_renderer_bundle", ":electron_sandboxed_renderer_bundle", ":electron_worker_bundle", ] sources = [ "$target_gen_dir/js2c/asar_bundle.js", "$target_gen_dir/js2c/browser_init.js", "$target_gen_dir/js2c/isolated_bundle.js", "$target_gen_dir/js2c/renderer_init.js", "$target_gen_dir/js2c/sandbox_bundle.js", "$target_gen_dir/js2c/worker_init.js", ] inputs = sources + [ "//third_party/electron_node/tools/js2c.py" ] outputs = [ "$root_gen_dir/electron_natives.cc" ] script = "build/js2c.py" args = [ rebase_path("//third_party/electron_node") ] + rebase_path(outputs, root_build_dir) + rebase_path(sources, root_build_dir) } action("generate_config_gypi") { outputs = [ "$root_gen_dir/config.gypi" ] script = "script/generate-config-gypi.py" args = rebase_path(outputs) + [ target_cpu ] } target_gen_default_app_js = "$target_gen_dir/js/default_app" typescript_build("default_app_js") { deps = [ ":build_electron_definitions" ] sources = filenames.default_app_ts_sources output_gen_dir = target_gen_default_app_js output_dir_name = "default_app" tsconfig = "tsconfig.default_app.json" } copy("default_app_static") { sources = filenames.default_app_static_sources outputs = [ "$target_gen_default_app_js/{{source}}" ] } copy("default_app_octicon_deps") { sources = filenames.default_app_octicon_sources outputs = [ "$target_gen_default_app_js/electron/default_app/octicon/{{source_file_part}}" ] } asar("default_app_asar") { deps = [ ":default_app_js", ":default_app_octicon_deps", ":default_app_static", ] root = "$target_gen_default_app_js/electron/default_app" sources = get_target_outputs(":default_app_js") + get_target_outputs(":default_app_static") + get_target_outputs(":default_app_octicon_deps") outputs = [ "$root_out_dir/resources/default_app.asar" ] } grit("resources") { source = "electron_resources.grd" outputs = [ "grit/electron_resources.h", "electron_resources.pak", ] # Mojo manifest overlays are generated. grit_flags = [ "-E", "target_gen_dir=" + rebase_path(target_gen_dir, root_build_dir), ] deps = [ ":copy_shell_devtools_discovery_page" ] output_dir = "$target_gen_dir" } copy("copy_shell_devtools_discovery_page") { sources = [ "//content/shell/resources/shell_devtools_discovery_page.html" ] outputs = [ "$target_gen_dir/shell_devtools_discovery_page.html" ] } npm_action("electron_version_args") { script = "generate-version-json" outputs = [ "$target_gen_dir/electron_version.args" ] args = rebase_path(outputs) inputs = [ "ELECTRON_VERSION", "script/generate-version-json.js", ] } templated_file("electron_version_header") { deps = [ ":electron_version_args" ] template = "build/templates/electron_version.tmpl" output = "$target_gen_dir/electron_version.h" args_files = get_target_outputs(":electron_version_args") } action("electron_fuses") { script = "build/fuses/build.py" inputs = [ "build/fuses/fuses.json5" ] outputs = [ "$target_gen_dir/fuses.h", "$target_gen_dir/fuses.cc", ] args = rebase_path(outputs) } action("electron_generate_node_defines") { script = "build/generate_node_defines.py" inputs = [ "//third_party/electron_node/src/tracing/trace_event_common.h", "//third_party/electron_node/src/tracing/trace_event.h", "//third_party/electron_node/src/util.h", ] outputs = [ "$target_gen_dir/push_and_undef_node_defines.h", "$target_gen_dir/pop_node_defines.h", ] args = [ rebase_path(target_gen_dir) ] + rebase_path(inputs) } source_set("electron_lib") { configs += [ "//v8:external_startup_data" ] configs += [ "//third_party/electron_node:node_internals" ] public_configs = [ ":branding", ":electron_lib_config", ] deps = [ ":electron_fuses", ":electron_generate_node_defines", ":electron_js2c", ":electron_version_header", ":resources", "buildflags", "chromium_src:chrome", "chromium_src:chrome_spellchecker", "shell/common/api:mojo", "//base:base_static", "//base/allocator:buildflags", "//chrome:strings", "//chrome/app:command_ids", "//chrome/app/resources:platform_locale_settings", "//components/autofill/core/common:features", "//components/certificate_transparency", "//components/embedder_support:browser_util", "//components/language/core/browser", "//components/net_log", "//components/network_hints/browser", "//components/network_hints/common:mojo_bindings", "//components/network_hints/renderer", "//components/network_session_configurator/common", "//components/omnibox/browser:buildflags", "//components/os_crypt", "//components/pref_registry", "//components/prefs", "//components/security_state/content", "//components/upload_list", "//components/user_prefs", "//components/viz/host", "//components/viz/service", "//content/public/browser", "//content/public/child", "//content/public/gpu", "//content/public/renderer", "//content/public/utility", "//device/bluetooth", "//device/bluetooth/public/cpp", "//gin", "//media/capture/mojom:video_capture", "//media/mojo/mojom", "//net:extras", "//net:net_resources", "//ppapi/host", "//ppapi/proxy", "//ppapi/shared_impl", "//printing/buildflags", "//services/device/public/cpp/geolocation", "//services/device/public/cpp/hid", "//services/device/public/mojom", "//services/proxy_resolver:lib", "//services/video_capture/public/mojom:constants", "//services/viz/privileged/mojom/compositing", "//skia", "//third_party/blink/public:blink", "//third_party/blink/public:blink_devtools_inspector_resources", "//third_party/blink/public/platform/media", "//third_party/boringssl", "//third_party/electron_node:node_lib", "//third_party/inspector_protocol:crdtp", "//third_party/leveldatabase", "//third_party/libyuv", "//third_party/webrtc_overrides:webrtc_component", "//third_party/widevine/cdm:headers", "//third_party/zlib/google:zip", "//ui/base/idle", "//ui/events:dom_keycode_converter", "//ui/gl", "//ui/native_theme", "//ui/shell_dialogs", "//ui/views", "//v8", "//v8:v8_libplatform", ] public_deps = [ "//base", "//base:i18n", "//content/public/app", ] include_dirs = [ ".", "$target_gen_dir", # TODO(nornagon): replace usage of SchemeRegistry by an actually exported # API of blink, then remove this from the include_dirs. "//third_party/blink/renderer", ] defines = [ "V8_DEPRECATION_WARNINGS" ] libs = [] if (is_linux) { defines += [ "GDK_DISABLE_DEPRECATION_WARNINGS" ] } if (!is_mas_build) { deps += [ "//components/crash/core/app", "//components/crash/core/browser", ] } sources = filenames.lib_sources if (is_win) { sources += filenames.lib_sources_win } if (is_mac) { sources += filenames.lib_sources_mac } if (is_posix) { sources += filenames.lib_sources_posix } if (is_linux) { sources += filenames.lib_sources_linux } if (!is_mac) { sources += filenames.lib_sources_views } if (is_component_build) { defines += [ "NODE_SHARED_MODE" ] } if (enable_fake_location_provider) { sources += [ "shell/browser/fake_location_provider.cc", "shell/browser/fake_location_provider.h", ] } if (is_linux) { deps += [ "//components/crash/content/browser", "//ui/gtk:gtk_config", ] } if (is_mac) { deps += [ "//components/remote_cocoa/app_shim", "//components/remote_cocoa/browser", "//content/common:mac_helpers", "//ui/accelerated_widget_mac", ] if (!is_mas_build) { deps += [ "//third_party/crashpad/crashpad/client" ] } frameworks = [ "AVFoundation.framework", "Carbon.framework", "LocalAuthentication.framework", "QuartzCore.framework", "Quartz.framework", "Security.framework", "SecurityInterface.framework", "ServiceManagement.framework", "StoreKit.framework", ] weak_frameworks = [ "QuickLookThumbnailing.framework" ] sources += [ "shell/browser/ui/views/autofill_popup_view.cc", "shell/browser/ui/views/autofill_popup_view.h", ] if (is_mas_build) { sources += [ "shell/browser/api/electron_api_app_mas.mm" ] sources -= [ "shell/browser/auto_updater_mac.mm" ] defines += [ "MAS_BUILD" ] sources -= [ "shell/app/electron_crash_reporter_client.cc", "shell/app/electron_crash_reporter_client.h", "shell/common/crash_keys.cc", "shell/common/crash_keys.h", ] } else { frameworks += [ "Squirrel.framework", "ReactiveObjC.framework", "Mantle.framework", ] deps += [ "//third_party/squirrel.mac:reactiveobjc_framework+link", "//third_party/squirrel.mac:squirrel_framework+link", ] # ReactiveObjC which is used by Squirrel requires using __weak. cflags_objcc = [ "-fobjc-weak" ] } } if (is_linux) { libs = [ "xshmfence" ] deps += [ ":electron_gtk_stubs", ":libnotify_loader", "//build/config/linux/gtk", "//dbus", "//device/bluetooth", "//ui/base/ime/linux", "//ui/events/devices/x11", "//ui/events/platform/x11", "//ui/views/controls/webview", "//ui/views/linux_ui:linux_ui_factory", "//ui/wm", ] if (ozone_platform_x11) { sources += filenames.lib_sources_linux_x11 public_deps += [ "//ui/base/x", "//ui/ozone/platform/x11", ] } configs += [ ":gio_unix" ] defines += [ # Disable warnings for g_settings_list_schemas. "GLIB_DISABLE_DEPRECATION_WARNINGS", ] sources += [ "shell/browser/certificate_manager_model.cc", "shell/browser/certificate_manager_model.h", "shell/browser/ui/gtk/app_indicator_icon.cc", "shell/browser/ui/gtk/app_indicator_icon.h", "shell/browser/ui/gtk/app_indicator_icon_menu.cc", "shell/browser/ui/gtk/app_indicator_icon_menu.h", "shell/browser/ui/gtk/gtk_status_icon.cc", "shell/browser/ui/gtk/gtk_status_icon.h", "shell/browser/ui/gtk/menu_util.cc", "shell/browser/ui/gtk/menu_util.h", "shell/browser/ui/gtk/status_icon.cc", "shell/browser/ui/gtk/status_icon.h", "shell/browser/ui/gtk_util.cc", "shell/browser/ui/gtk_util.h", ] } if (is_win) { libs += [ "dwmapi.lib" ] deps += [ "//components/crash/core/app:crash_export_thunks", "//ui/native_theme:native_theme_browser", "//ui/views/controls/webview", "//ui/wm", "//ui/wm/public", ] public_deps += [ "//sandbox/win:sandbox", "//third_party/crashpad/crashpad/handler", ] } if (enable_plugins) { deps += [ "chromium_src:plugins" ] sources += [ "shell/renderer/pepper_helper.cc", "shell/renderer/pepper_helper.h", ] } if (enable_run_as_node) { sources += [ "shell/app/node_main.cc", "shell/app/node_main.h", ] } if (enable_osr) { sources += [ "shell/browser/osr/osr_host_display_client.cc", "shell/browser/osr/osr_host_display_client.h", "shell/browser/osr/osr_render_widget_host_view.cc", "shell/browser/osr/osr_render_widget_host_view.h", "shell/browser/osr/osr_video_consumer.cc", "shell/browser/osr/osr_video_consumer.h", "shell/browser/osr/osr_view_proxy.cc", "shell/browser/osr/osr_view_proxy.h", "shell/browser/osr/osr_web_contents_view.cc", "shell/browser/osr/osr_web_contents_view.h", ] if (is_mac) { sources += [ "shell/browser/osr/osr_host_display_client_mac.mm", "shell/browser/osr/osr_web_contents_view_mac.mm", ] } deps += [ "//components/viz/service", "//services/viz/public/mojom", "//ui/compositor", ] } if (enable_desktop_capturer) { sources += [ "shell/browser/api/electron_api_desktop_capturer.cc", "shell/browser/api/electron_api_desktop_capturer.h", ] } if (enable_views_api) { sources += [ "shell/browser/api/views/electron_api_image_view.cc", "shell/browser/api/views/electron_api_image_view.h", ] } if (enable_basic_printing) { sources += [ "shell/browser/printing/print_view_manager_electron.cc", "shell/browser/printing/print_view_manager_electron.h", "shell/renderer/printing/print_render_frame_helper_delegate.cc", "shell/renderer/printing/print_render_frame_helper_delegate.h", ] deps += [ "//chrome/services/printing/public/mojom", "//components/printing/common:mojo_interfaces", ] if (is_mac) { deps += [ "//chrome/services/mac_notifications/public/mojom" ] } } if (enable_electron_extensions) { sources += filenames.lib_sources_extensions deps += [ "shell/browser/extensions/api:api_registration", "shell/common/extensions/api", "shell/common/extensions/api:extensions_features", "//chrome/browser/resources:component_extension_resources", "//components/update_client:update_client", "//components/zoom", "//extensions/browser", "//extensions/browser:core_api_provider", "//extensions/browser/updater", "//extensions/common", "//extensions/common:core_api_provider", "//extensions/renderer", ] } if (enable_pdf) { # Printing depends on some //pdf code, so it needs to be built even if the # pdf viewer isn't enabled. deps += [ "//pdf", "//pdf:features", ] } if (enable_pdf_viewer) { deps += [ "//chrome/browser/resources/pdf:resources", "//components/pdf/browser", "//components/pdf/browser:interceptors", "//components/pdf/common", "//components/pdf/renderer", "//pdf", ] sources += [ "shell/browser/electron_pdf_web_contents_helper_client.cc", "shell/browser/electron_pdf_web_contents_helper_client.h", ] } sources += get_target_outputs(":electron_fuses") if (allow_runtime_configurable_key_storage) { defines += [ "ALLOW_RUNTIME_CONFIGURABLE_KEY_STORAGE" ] } } electron_paks("packed_resources") { if (is_mac) { output_dir = "$root_gen_dir/electron_repack" copy_data_to_bundle = true } else { output_dir = root_out_dir } } if (is_mac) { electron_framework_name = "$electron_product_name Framework" electron_helper_name = "$electron_product_name Helper" electron_login_helper_name = "$electron_product_name Login Helper" electron_framework_version = "A" electron_version = read_file("ELECTRON_VERSION", "trim string") mac_xib_bundle_data("electron_xibs") { sources = [ "shell/common/resources/mac/MainMenu.xib" ] } action("fake_v8_context_snapshot_generator") { script = "build/fake_v8_context_snapshot_generator.py" args = [ rebase_path("$root_out_dir/$v8_context_snapshot_filename"), rebase_path("$root_out_dir/fake/$v8_context_snapshot_filename"), ] outputs = [ "$root_out_dir/fake/$v8_context_snapshot_filename" ] } bundle_data("electron_framework_resources") { public_deps = [ ":packed_resources" ] sources = [] if (icu_use_data_file) { sources += [ "$root_out_dir/icudtl.dat" ] public_deps += [ "//third_party/icu:icudata" ] } if (v8_use_external_startup_data) { public_deps += [ "//v8" ] if (use_v8_context_snapshot) { if (use_prebuilt_v8_context_snapshot) { sources += [ "$root_out_dir/fake/$v8_context_snapshot_filename" ] public_deps += [ ":fake_v8_context_snapshot_generator" ] } else { sources += [ "$root_out_dir/$v8_context_snapshot_filename" ] public_deps += [ "//tools/v8_context_snapshot" ] } } else { sources += [ "$root_out_dir/snapshot_blob.bin" ] } } outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ] } if (!is_component_build && is_component_ffmpeg) { bundle_data("electron_framework_libraries") { sources = [] public_deps = [] sources += [ "$root_out_dir/libffmpeg.dylib" ] public_deps += [ "//third_party/ffmpeg:ffmpeg" ] outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ] } } else { group("electron_framework_libraries") { } } if (use_egl) { # Add the ANGLE .dylibs in the Libraries directory of the Framework. bundle_data("electron_angle_binaries") { sources = [ "$root_out_dir/egl_intermediates/libEGL.dylib", "$root_out_dir/egl_intermediates/libGLESv2.dylib", ] outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ] public_deps = [ "//ui/gl:angle_library_copy" ] } # Add the SwiftShader .dylibs in the Libraries directory of the Framework. bundle_data("electron_swiftshader_binaries") { sources = [ "$root_out_dir/vk_intermediates/libvk_swiftshader.dylib", "$root_out_dir/vk_intermediates/vk_swiftshader_icd.json", ] outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ] public_deps = [ "//ui/gl:swiftshader_vk_library_copy" ] } } group("electron_angle_library") { if (use_egl) { deps = [ ":electron_angle_binaries" ] } } group("electron_swiftshader_library") { if (use_egl) { deps = [ ":electron_swiftshader_binaries" ] } } bundle_data("electron_crashpad_helper") { sources = [ "$root_out_dir/chrome_crashpad_handler" ] outputs = [ "{{bundle_contents_dir}}/Helpers/{{source_file_part}}" ] public_deps = [ "//components/crash/core/app:chrome_crashpad_handler" ] if (is_asan) { # crashpad_handler requires the ASan runtime at its @executable_path. sources += [ "$root_out_dir/libclang_rt.asan_osx_dynamic.dylib" ] public_deps += [ "//build/config/sanitizers:copy_asan_runtime" ] } } mac_framework_bundle("electron_framework") { output_name = electron_framework_name framework_version = electron_framework_version framework_contents = [ "Resources", "Libraries", ] if (!is_mas_build) { framework_contents += [ "Helpers" ] } public_deps = [ ":electron_framework_libraries", ":electron_lib", ] deps = [ ":electron_angle_library", ":electron_framework_libraries", ":electron_framework_resources", ":electron_swiftshader_library", ":electron_xibs", ] if (!is_mas_build) { deps += [ ":electron_crashpad_helper" ] } info_plist = "shell/common/resources/mac/Info.plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.framework", "ELECTRON_VERSION=$electron_version", ] include_dirs = [ "." ] sources = filenames.framework_sources frameworks = [] if (enable_osr) { frameworks += [ "IOSurface.framework" ] } ldflags = [ "-Wl,-install_name,@rpath/$output_name.framework/$output_name", "-rpath", "@loader_path/Libraries", # Required for exporting all symbols of libuv. "-Wl,-force_load,obj/third_party/electron_node/deps/uv/libuv.a", ] if (is_component_build) { ldflags += [ "-rpath", "@executable_path/../../../../../..", ] } } template("electron_helper_app") { mac_app_bundle(target_name) { assert(defined(invoker.helper_name_suffix)) output_name = electron_helper_name + invoker.helper_name_suffix deps = [ ":electron_framework+link", "//base/allocator:early_zone_registration_mac", ] if (!is_mas_build) { deps += [ "//sandbox/mac:seatbelt" ] } defines = [ "HELPER_EXECUTABLE" ] sources = [ "shell/app/electron_main_mac.cc", "shell/app/uv_stdio_fix.cc", "shell/app/uv_stdio_fix.h", "shell/common/electron_constants.cc", ] include_dirs = [ "." ] info_plist = "shell/renderer/resources/mac/Info.plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.helper" ] ldflags = [ "-rpath", "@executable_path/../../..", ] if (is_component_build) { ldflags += [ "-rpath", "@executable_path/../../../../../..", ] } } } foreach(helper_params, content_mac_helpers) { _helper_target = helper_params[0] _helper_bundle_id = helper_params[1] _helper_suffix = helper_params[2] electron_helper_app("electron_helper_app_${_helper_target}") { helper_name_suffix = _helper_suffix } } template("stripped_framework") { action(target_name) { assert(defined(invoker.framework)) script = "//electron/build/strip_framework.py" forward_variables_from(invoker, [ "deps" ]) inputs = [ "$root_out_dir/" + invoker.framework ] outputs = [ "$target_out_dir/stripped_frameworks/" + invoker.framework ] args = rebase_path(inputs) + rebase_path(outputs) } } stripped_framework("stripped_mantle_framework") { framework = "Mantle.framework" deps = [ "//third_party/squirrel.mac:mantle_framework" ] } stripped_framework("stripped_reactiveobjc_framework") { framework = "ReactiveObjC.framework" deps = [ "//third_party/squirrel.mac:reactiveobjc_framework" ] } stripped_framework("stripped_squirrel_framework") { framework = "Squirrel.framework" deps = [ "//third_party/squirrel.mac:squirrel_framework" ] } bundle_data("electron_app_framework_bundle_data") { sources = [ "$root_out_dir/$electron_framework_name.framework" ] if (!is_mas_build) { sources += get_target_outputs(":stripped_mantle_framework") + get_target_outputs(":stripped_reactiveobjc_framework") + get_target_outputs(":stripped_squirrel_framework") } outputs = [ "{{bundle_contents_dir}}/Frameworks/{{source_file_part}}" ] public_deps = [ ":electron_framework+link", ":stripped_mantle_framework", ":stripped_reactiveobjc_framework", ":stripped_squirrel_framework", ] foreach(helper_params, content_mac_helpers) { sources += [ "$root_out_dir/${electron_helper_name}${helper_params[2]}.app" ] public_deps += [ ":electron_helper_app_${helper_params[0]}" ] } } mac_app_bundle("electron_login_helper") { output_name = electron_login_helper_name sources = filenames.login_helper_sources include_dirs = [ "." ] frameworks = [ "AppKit.framework" ] info_plist = "shell/app/resources/mac/loginhelper-Info.plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.loginhelper" ] } bundle_data("electron_login_helper_app") { public_deps = [ ":electron_login_helper" ] sources = [ "$root_out_dir/$electron_login_helper_name.app" ] outputs = [ "{{bundle_contents_dir}}/Library/LoginItems/{{source_file_part}}" ] } action("electron_app_lproj_dirs") { outputs = [] foreach(locale, locales_as_apple_outputs) { outputs += [ "$target_gen_dir/app_infoplist_strings/$locale.lproj" ] } script = "build/mac/make_locale_dirs.py" args = rebase_path(outputs) } foreach(locale, locales_as_apple_outputs) { bundle_data("electron_app_strings_${locale}_bundle_data") { sources = [ "$target_gen_dir/app_infoplist_strings/$locale.lproj" ] outputs = [ "{{bundle_resources_dir}}/$locale.lproj" ] public_deps = [ ":electron_app_lproj_dirs" ] } } group("electron_app_strings_bundle_data") { public_deps = [] foreach(locale, locales_as_apple_outputs) { public_deps += [ ":electron_app_strings_${locale}_bundle_data" ] } } bundle_data("electron_app_resources") { public_deps = [ ":default_app_asar", ":electron_app_strings_bundle_data", ] sources = [ "$root_out_dir/resources/default_app.asar", "shell/browser/resources/mac/electron.icns", ] outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ] } asar_hashed_info_plist("electron_app_plist") { keys = [ "DEFAULT_APP_ASAR_HEADER_SHA" ] hash_targets = [ ":default_app_asar_header_hash" ] plist_file = "shell/browser/resources/mac/Info.plist" } mac_app_bundle("electron_app") { output_name = electron_product_name sources = [ "shell/app/electron_main_mac.cc", "shell/app/uv_stdio_fix.cc", "shell/app/uv_stdio_fix.h", ] include_dirs = [ "." ] deps = [ ":electron_app_framework_bundle_data", ":electron_app_plist", ":electron_app_resources", ":electron_fuses", "//base/allocator:early_zone_registration_mac", "//electron/buildflags", ] if (is_mas_build) { deps += [ ":electron_login_helper_app" ] } info_plist_target = ":electron_app_plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id", "ELECTRON_VERSION=$electron_version", ] ldflags = [ "-rpath", "@executable_path/../Frameworks", ] } if (enable_dsyms) { extract_symbols("electron_framework_syms") { binary = "$root_out_dir/$electron_framework_name.framework/Versions/$electron_framework_version/$electron_framework_name" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/$electron_framework_name.dSYM/Contents/Resources/DWARF/$electron_framework_name" deps = [ ":electron_framework" ] } foreach(helper_params, content_mac_helpers) { _helper_target = helper_params[0] _helper_bundle_id = helper_params[1] _helper_suffix = helper_params[2] extract_symbols("electron_helper_syms_${_helper_target}") { binary = "$root_out_dir/$electron_helper_name${_helper_suffix}.app/Contents/MacOS/$electron_helper_name${_helper_suffix}" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/$electron_helper_name${_helper_suffix}.dSYM/Contents/Resources/DWARF/$electron_helper_name${_helper_suffix}" deps = [ ":electron_helper_app_${_helper_target}" ] } } extract_symbols("electron_app_syms") { binary = "$root_out_dir/$electron_product_name.app/Contents/MacOS/$electron_product_name" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/$electron_product_name.dSYM/Contents/Resources/DWARF/$electron_product_name" deps = [ ":electron_app" ] } extract_symbols("egl_syms") { binary = "$root_out_dir/libEGL.dylib" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/libEGL.dylib.dSYM/Contents/Resources/DWARF/libEGL.dylib" deps = [ "//third_party/angle:libEGL" ] } extract_symbols("gles_syms") { binary = "$root_out_dir/libGLESv2.dylib" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/libGLESv2.dylib.dSYM/Contents/Resources/DWARF/libGLESv2.dylib" deps = [ "//third_party/angle:libGLESv2" ] } extract_symbols("crashpad_handler_syms") { binary = "$root_out_dir/chrome_crashpad_handler" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/chrome_crashpad_handler.dSYM/Contents/Resources/DWARF/chrome_crashpad_handler" deps = [ "//components/crash/core/app:chrome_crashpad_handler" ] } group("electron_symbols") { deps = [ ":egl_syms", ":electron_app_syms", ":electron_framework_syms", ":gles_syms", ] if (!is_mas_build) { deps += [ ":crashpad_handler_syms" ] } foreach(helper_params, content_mac_helpers) { _helper_target = helper_params[0] deps += [ ":electron_helper_syms_${_helper_target}" ] } } } else { group("electron_symbols") { } } } else { windows_manifest("electron_app_manifest") { sources = [ "shell/browser/resources/win/disable_window_filtering.manifest", "shell/browser/resources/win/dpi_aware.manifest", as_invoker_manifest, common_controls_manifest, default_compatibility_manifest, ] } executable("electron_app") { output_name = electron_project_name if (is_win) { sources = [ "shell/app/electron_main_win.cc" ] } else if (is_linux) { sources = [ "shell/app/electron_main_linux.cc", "shell/app/uv_stdio_fix.cc", "shell/app/uv_stdio_fix.h", ] } include_dirs = [ "." ] deps = [ ":default_app_asar", ":electron_app_manifest", ":electron_lib", ":packed_resources", "//components/crash/core/app", "//content:sandbox_helper_win", "//electron/buildflags", "//ui/strings", ] data = [] data_deps = [] data += [ "$root_out_dir/resources.pak" ] data += [ "$root_out_dir/chrome_100_percent.pak" ] if (enable_hidpi) { data += [ "$root_out_dir/chrome_200_percent.pak" ] } foreach(locale, platform_pak_locales) { data += [ "$root_out_dir/locales/$locale.pak" ] } if (!is_mac) { data += [ "$root_out_dir/resources/default_app.asar" ] } if (use_v8_context_snapshot) { public_deps = [ "//tools/v8_context_snapshot:v8_context_snapshot" ] } if (is_linux) { data_deps += [ "//components/crash/core/app:chrome_crashpad_handler" ] } if (is_win) { sources += [ # TODO: we should be generating our .rc files more like how chrome does "shell/browser/resources/win/electron.rc", "shell/browser/resources/win/resource.h", ] deps += [ "//components/browser_watcher:browser_watcher_client", "//components/crash/core/app:run_as_crashpad_handler", ] ldflags = [] libs = [ "comctl32.lib", "uiautomationcore.lib", "wtsapi32.lib", ] configs -= [ "//build/config/win:console" ] configs += [ "//build/config/win:windowed", "//build/config/win:delayloads", ] if (current_cpu == "x86") { # Set the initial stack size to 0.5MiB, instead of the 1.5MiB needed by # Chrome's main thread. This saves significant memory on threads (like # those in the Windows thread pool, and others) whose stack size we can # only control through this setting. Because Chrome's main thread needs # a minimum 1.5 MiB stack, the main thread (in 32-bit builds only) uses # fibers to switch to a 1.5 MiB stack before running any other code. ldflags += [ "/STACK:0x80000" ] } else { # Increase the initial stack size. The default is 1MB, this is 8MB. ldflags += [ "/STACK:0x800000" ] } # This is to support renaming of electron.exe. node-gyp has hard-coded # executable names which it will recognise as node. This module definition # file claims that the electron executable is in fact named "node.exe", # which is one of the executable names that node-gyp recognizes. # See https://github.com/nodejs/node-gyp/commit/52ceec3a6d15de3a8f385f43dbe5ecf5456ad07a ldflags += [ "/DEF:" + rebase_path("build/electron.def", root_build_dir) ] inputs = [ "shell/browser/resources/win/electron.ico", "build/electron.def", ] } if (is_linux) { ldflags = [ "-pie", # Required for exporting all symbols of libuv. "-Wl,--whole-archive", "obj/third_party/electron_node/deps/uv/libuv.a", "-Wl,--no-whole-archive", ] if (!is_component_build && is_component_ffmpeg) { configs += [ "//build/config/gcc:rpath_for_built_shared_libraries" ] } if (is_linux) { deps += [ "//sandbox/linux:chrome_sandbox" ] } } } if (is_official_build) { if (is_linux) { _target_executable_suffix = "" _target_shared_library_suffix = ".so" } else if (is_win) { _target_executable_suffix = ".exe" _target_shared_library_suffix = ".dll" } extract_symbols("electron_app_symbols") { binary = "$root_out_dir/$electron_project_name$_target_executable_suffix" symbol_dir = "$root_out_dir/breakpad_symbols" deps = [ ":electron_app" ] } extract_symbols("egl_symbols") { binary = "$root_out_dir/libEGL$_target_shared_library_suffix" symbol_dir = "$root_out_dir/breakpad_symbols" deps = [ "//third_party/angle:libEGL" ] } extract_symbols("gles_symbols") { binary = "$root_out_dir/libGLESv2$_target_shared_library_suffix" symbol_dir = "$root_out_dir/breakpad_symbols" deps = [ "//third_party/angle:libGLESv2" ] } group("electron_symbols") { deps = [ ":egl_symbols", ":electron_app_symbols", ":gles_symbols", ] } } } test("shell_browser_ui_unittests") { sources = [ "//electron/shell/browser/ui/accelerator_util_unittests.cc", "//electron/shell/browser/ui/run_all_unittests.cc", ] configs += [ ":electron_lib_config" ] deps = [ ":electron_lib", "//base", "//base/test:test_support", "//testing/gmock", "//testing/gtest", "//ui/base", "//ui/strings", ] } template("dist_zip") { _runtime_deps_target = "${target_name}__deps" _runtime_deps_file = "$root_out_dir/gen.runtime/" + get_label_info(target_name, "dir") + "/" + get_label_info(target_name, "name") + ".runtime_deps" group(_runtime_deps_target) { forward_variables_from(invoker, [ "deps", "data_deps", "data", "testonly", ]) write_runtime_deps = _runtime_deps_file } action(target_name) { script = "//electron/build/zip.py" deps = [ ":$_runtime_deps_target" ] forward_variables_from(invoker, [ "outputs", "testonly", ]) flatten = false flatten_relative_to = false if (defined(invoker.flatten)) { flatten = invoker.flatten if (defined(invoker.flatten_relative_to)) { flatten_relative_to = invoker.flatten_relative_to } } args = rebase_path(outputs + [ _runtime_deps_file ], root_build_dir) + [ target_cpu, target_os, "$flatten", "$flatten_relative_to", ] } } copy("electron_license") { sources = [ "LICENSE" ] outputs = [ "$root_build_dir/{{source_file_part}}" ] } copy("chromium_licenses") { deps = [ "//components/resources:about_credits" ] sources = [ "$root_gen_dir/components/resources/about_credits.html" ] outputs = [ "$root_build_dir/LICENSES.chromium.html" ] } group("licenses") { data_deps = [ ":chromium_licenses", ":electron_license", ] } copy("electron_version") { sources = [ "ELECTRON_VERSION" ] outputs = [ "$root_build_dir/version" ] } dist_zip("electron_dist_zip") { data_deps = [ ":electron_app", ":electron_version", ":licenses", ] if (is_linux) { data_deps += [ "//sandbox/linux:chrome_sandbox" ] } deps = data_deps outputs = [ "$root_build_dir/dist.zip" ] } dist_zip("electron_ffmpeg_zip") { data_deps = [ "//third_party/ffmpeg" ] deps = data_deps outputs = [ "$root_build_dir/ffmpeg.zip" ] } electron_chromedriver_deps = [ ":licenses", "//chrome/test/chromedriver", "//electron/buildflags", ] group("electron_chromedriver") { testonly = true public_deps = electron_chromedriver_deps } dist_zip("electron_chromedriver_zip") { testonly = true data_deps = electron_chromedriver_deps deps = data_deps outputs = [ "$root_build_dir/chromedriver.zip" ] } mksnapshot_deps = [ ":licenses", "//v8:mksnapshot($v8_snapshot_toolchain)", ] if (use_v8_context_snapshot) { mksnapshot_deps += [ "//tools/v8_context_snapshot:v8_context_snapshot_generator($v8_snapshot_toolchain)" ] } group("electron_mksnapshot") { public_deps = mksnapshot_deps } dist_zip("electron_mksnapshot_zip") { data_deps = mksnapshot_deps deps = data_deps outputs = [ "$root_build_dir/mksnapshot.zip" ] } copy("hunspell_dictionaries") { sources = hunspell_dictionaries + hunspell_licenses outputs = [ "$target_gen_dir/electron_hunspell/{{source_file_part}}" ] } dist_zip("hunspell_dictionaries_zip") { data_deps = [ ":hunspell_dictionaries" ] deps = data_deps flatten = true outputs = [ "$root_build_dir/hunspell_dictionaries.zip" ] } copy("libcxx_headers") { sources = libcxx_headers + libcxx_licenses + [ "//buildtools/third_party/libc++/__config_site" ] outputs = [ "$target_gen_dir/electron_libcxx_include/{{source_root_relative_dir}}/{{source_file_part}}" ] } dist_zip("libcxx_headers_zip") { data_deps = [ ":libcxx_headers" ] deps = data_deps flatten = true flatten_relative_to = rebase_path( "$target_gen_dir/electron_libcxx_include/buildtools/third_party/libc++/trunk", "$root_out_dir") outputs = [ "$root_build_dir/libcxx_headers.zip" ] } copy("libcxxabi_headers") { sources = libcxxabi_headers + libcxxabi_licenses outputs = [ "$target_gen_dir/electron_libcxxabi_include/{{source_root_relative_dir}}/{{source_file_part}}" ] } dist_zip("libcxxabi_headers_zip") { data_deps = [ ":libcxxabi_headers" ] deps = data_deps flatten = true flatten_relative_to = rebase_path( "$target_gen_dir/electron_libcxxabi_include/buildtools/third_party/libc++abi/trunk", "$root_out_dir") outputs = [ "$root_build_dir/libcxxabi_headers.zip" ] } action("libcxx_objects_zip") { deps = [ "//buildtools/third_party/libc++" ] script = "build/zip_libcxx.py" outputs = [ "$root_build_dir/libcxx_objects.zip" ] args = rebase_path(outputs) } group("electron") { public_deps = [ ":electron_app" ] }
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
patches/chromium/make_gtk_getlibgtk_public.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: deepak1556 <[email protected]> Date: Thu, 7 Apr 2022 20:30:16 +0900 Subject: Make gtk::GetLibGtk public Allows embedders to get a handle to the gtk library already loaded in the process. diff --git a/ui/gtk/gtk_compat.cc b/ui/gtk/gtk_compat.cc index b5c7af5bdb93b320f95252d35d2d76bae7f8c445..40b706ed7cde206e98274025148604760b7477f9 100644 --- a/ui/gtk/gtk_compat.cc +++ b/ui/gtk/gtk_compat.cc @@ -86,12 +86,6 @@ void* GetLibGtk4(bool check = true) { return libgtk4; } -void* GetLibGtk() { - if (GtkCheckVersion(4)) - return GetLibGtk4(); - return GetLibGtk3(); -} - bool LoadGtk3() { if (!GetLibGtk3(false)) return false; @@ -134,6 +128,12 @@ gfx::Insets InsetsFromGtkBorder(const GtkBorder& border) { } // namespace +void* GetLibGtk() { + if (GtkCheckVersion(4)) + return GetLibGtk4(); + return GetLibGtk3(); +} + bool LoadGtk() { static bool loaded = LoadGtkImpl(); return loaded; diff --git a/ui/gtk/gtk_compat.h b/ui/gtk/gtk_compat.h index 57e55b9e749b43d327deff449a530e1f435a8e8b..2245974f91be4a691d82f54b55e12e44ae2000c5 100644 --- a/ui/gtk/gtk_compat.h +++ b/ui/gtk/gtk_compat.h @@ -34,6 +34,9 @@ using SkColor = uint32_t; namespace gtk { +// Get handle to the currently loaded gtk library in the process. +void* GetLibGtk(); + // Loads libgtk and related libraries and returns true on success. bool LoadGtk();
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
shell/browser/electron_browser_main_parts.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_main_parts.h" #include <memory> #include <string> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/icon_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/key_storage_config_linux.h" #include "components/os_crypt/os_crypt.h" #include "content/browser/browser_main_loop.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/device_service.h" #include "content/public/browser/first_party_sets_handler.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "media/base/localized_strings.h" #include "services/network/public/cpp/features.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/electron_main_delegate.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/browser.h" #include "shell/browser/browser_process_impl.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_web_ui_controller_factory.h" #include "shell/browser/feature_list.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_helper/trackable_object.h" #include "shell/common/logging.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/idle/idle.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_switches.h" #if defined(USE_AURA) #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/wm/core/wm_state.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "base/threading/thread_task_runner_handle.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h" #include "electron/electron_gtk_stubs.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/gfx/color_utils.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/ozone/public/ozone_platform.h" #include "ui/views/linux_ui/linux_ui.h" #include "ui/views/linux_ui/linux_ui_factory.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/l10n/l10n_util_win.h" #include "ui/display/win/dpi.h" #include "ui/gfx/system_fonts_win.h" #include "ui/strings/grit/app_locale_settings.h" #endif #if BUILDFLAG(IS_MAC) #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "shell/browser/ui/cocoa/views_delegate_mac.h" #else #include "shell/browser/ui/views/electron_views_delegate.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #endif namespace electron { namespace { template <typename T> void Erase(T* container, typename T::iterator iter) { container->erase(iter); } #if BUILDFLAG(IS_WIN) // gfx::Font callbacks void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) { l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override, &font_adjustment->font_scale); font_adjustment->font_scale *= display::win::GetAccessibilityFontScale(); } int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } #endif std::u16string MediaStringProvider(media::MessageId id) { switch (id) { case media::DEFAULT_AUDIO_DEVICE_NAME: return u"Default"; #if BUILDFLAG(IS_WIN) case media::COMMUNICATIONS_AUDIO_DEVICE_NAME: return u"Communications"; #endif default: return std::u16string(); } } #if BUILDFLAG(IS_LINUX) // GTK does not provide a way to check if current theme is dark, so we compare // the text and background luminosity to get a result. // This trick comes from FireFox. void UpdateDarkThemeSetting() { float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel")); float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel")); bool is_dark = fg > bg; // Pass it to NativeUi theme, which is used by the nativeTheme module and most // places in Electron. ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark); // Pass it to Web Theme, to make "prefers-color-scheme" media query work. ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark); } #endif } // namespace #if BUILDFLAG(IS_LINUX) class DarkThemeObserver : public ui::NativeThemeObserver { public: DarkThemeObserver() = default; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override { UpdateDarkThemeSetting(); } }; #endif // static ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr; ElectronBrowserMainParts::ElectronBrowserMainParts() : fake_browser_process_(std::make_unique<BrowserProcessImpl>()), browser_(std::make_unique<Browser>()), node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) { DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts"; self_ = this; } ElectronBrowserMainParts::~ElectronBrowserMainParts() = default; // static ElectronBrowserMainParts* ElectronBrowserMainParts::Get() { DCHECK(self_); return self_; } bool ElectronBrowserMainParts::SetExitCode(int code) { if (!exit_code_) return false; content::BrowserMainLoop::GetInstance()->SetResultCode(code); *exit_code_ = code; return true; } int ElectronBrowserMainParts::GetExitCode() const { return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT); } int ElectronBrowserMainParts::PreEarlyInitialization() { field_trial_list_ = std::make_unique<base::FieldTrialList>(nullptr); #if BUILDFLAG(IS_POSIX) HandleSIGCHLD(); #endif #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::PreEarlyInitialization(); #endif return GetExitCode(); } void ElectronBrowserMainParts::PostEarlyInitialization() { // A workaround was previously needed because there was no ThreadTaskRunner // set. If this check is failing we may need to re-add that workaround DCHECK(base::ThreadTaskRunnerHandle::IsSet()); // The ProxyResolverV8 has setup a complete V8 environment, in order to // avoid conflicts we only initialize our V8 environment after that. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); v8::HandleScope scope(js_env_->isolate()); node_bindings_->Initialize(); // Create the global environment. node::Environment* env = node_bindings_->CreateEnvironment( js_env_->context(), js_env_->platform()); node_env_ = std::make_unique<NodeEnvironment>(env); env->set_trace_sync_io(env->options()->trace_sync_io); // We do not want to crash the main process on unhandled rejections. env->options()->unhandled_rejections = "warn"; // Add Electron extended APIs. electron_bindings_->BindTo(js_env_->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // Wrap the uv loop with global env. node_bindings_->set_uv_env(env); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line // switches at that point. Lets reinitialize it here to pick up the // command-line changes. base::FeatureList::ClearInstanceForTesting(); InitializeFeatureList(); // Initialize field trials. InitializeFieldTrials(); // Reinitialize logging now that the app has had a chance to set the app name // and/or user data directory. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ false); // Initialize after user script environment creation. fake_browser_process_->PostEarlyInitialization(); } int ElectronBrowserMainParts::PreCreateThreads() { #if defined(USE_AURA) screen_ = views::CreateDesktopScreen(); display::Screen::SetScreenInstance(screen_.get()); #endif if (!views::LayoutProvider::Get()) layout_provider_ = std::make_unique<views::LayoutProvider>(); auto* command_line = base::CommandLine::ForCurrentProcess(); std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); #if BUILDFLAG(IS_MAC) // The browser process only wants to support the language Cocoa will use, // so force the app locale to be overridden with that value. This must // happen before the ResourceBundle is loaded if (locale.empty()) l10n_util::OverrideLocaleWithCocoaLocale(); #elif BUILDFLAG(IS_LINUX) // l10n_util::GetApplicationLocaleInternal uses g_get_language_names(), // which keys off of getenv("LC_ALL"). // We must set this env first to make ui::ResourceBundle accept the custom // locale. auto env = base::Environment::Create(); absl::optional<std::string> lc_all; if (!locale.empty()) { std::string str; if (env->GetVar("LC_ALL", &str)) lc_all.emplace(std::move(str)); env->SetVar("LC_ALL", locale.c_str()); } #endif // Load resources bundle according to locale. std::string loaded_locale = LoadResourceBundle(locale); // Initialize the app locale. std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale); ElectronBrowserClient::SetApplicationLocale(app_locale); fake_browser_process_->SetApplicationLocale(app_locale); #if BUILDFLAG(IS_LINUX) // Reset to the original LC_ALL since we should not be changing it. if (!locale.empty()) { if (lc_all) env->SetVar("LC_ALL", *lc_all); else env->UnSetVar("LC_ALL"); } #endif // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); #if BUILDFLAG(IS_MAC) ui::InitIdleMonitor(); #endif fake_browser_process_->PreCreateThreads(); // Notify observers. Browser::Get()->PreCreateThreads(); return 0; } void ElectronBrowserMainParts::PostCreateThreads() { content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); } void ElectronBrowserMainParts::PostDestroyThreads() { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_browser_client_.reset(); extensions::ExtensionsBrowserClient::Set(nullptr); #endif #if BUILDFLAG(IS_LINUX) device::BluetoothAdapterFactory::Shutdown(); bluez::DBusBluezManagerWrapperLinux::Shutdown(); #endif fake_browser_process_->PostDestroyThreads(); } void ElectronBrowserMainParts::ToolkitInitialized() { #if BUILDFLAG(IS_LINUX) auto linux_ui = CreateLinuxUi(); DCHECK(ui::LinuxInputMethodContextFactory::instance()); // Try loading gtk symbols used by Electron. electron::InitializeElectron_gtk(gtk::GetLibGtk()); if (!electron::IsElectron_gtkInitialized()) { electron::UninitializeElectron_gtk(); } // Chromium does not respect GTK dark theme setting, but they may change // in future and this code might be no longer needed. Check the Chromium // issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=998903 UpdateDarkThemeSetting(); // Update the native theme when GTK theme changes. The GetNativeTheme // here returns a NativeThemeGtk, which monitors GTK settings. dark_theme_observer_ = std::make_unique<DarkThemeObserver>(); linux_ui->GetNativeTheme(nullptr)->AddObserver(dark_theme_observer_.get()); views::LinuxUI::SetInstance(std::move(linux_ui)); // Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager // implementation). Start observing them once it's initialized. ui::CursorFactory::GetInstance()->ObserveThemeChanges(); #endif #if defined(USE_AURA) wm_state_ = std::make_unique<wm::WMState>(); #endif #if BUILDFLAG(IS_WIN) gfx::win::SetAdjustFontCallback(&AdjustUIFont); gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize); #endif #if BUILDFLAG(IS_MAC) views_delegate_ = std::make_unique<ViewsDelegateMac>(); #else views_delegate_ = std::make_unique<ViewsDelegate>(); #endif } int ElectronBrowserMainParts::PreMainMessageLoopRun() { // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareEmbedThread(); node_bindings_->StartPolling(); // url::Add*Scheme are not threadsafe, this helps prevent data races. url::LockSchemeRegistries(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_client_ = std::make_unique<ElectronExtensionsClient>(); extensions::ExtensionsClient::Set(extensions_client_.get()); // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient. extensions_browser_client_ = std::make_unique<ElectronExtensionsBrowserClient>(); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt(); extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt(); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckServiceFactory::GetInstance(); #endif content::WebUIControllerFactory::RegisterFactory( ElectronWebUIControllerFactory::GetInstance()); auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) { // --remote-debugging-pipe auto on_disconnect = base::BindOnce([]() { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); })); }); content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler( std::move(on_disconnect)); } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { // --remote-debugging-port DevToolsManagerDelegate::StartHttpHandler(); } #if !BUILDFLAG(IS_MAC) // The corresponding call in macOS is in ElectronApplicationDelegate. Browser::Get()->WillFinishLaunching(); Browser::Get()->DidFinishLaunching(base::DictionaryValue()); #endif // Notify observers that main thread message loop was initialized. Browser::Get()->PreMainMessageLoopRun(); return GetExitCode(); } void ElectronBrowserMainParts::WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) { js_env_->OnMessageLoopCreated(); exit_code_ = content::RESULT_CODE_NORMAL_EXIT; Browser::Get()->SetMainMessageLoopQuitClosure( run_loop->QuitWhenIdleClosure()); } void ElectronBrowserMainParts::PostCreateMainMessageLoop() { #if BUILDFLAG(IS_LINUX) auto shutdown_cb = base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop( std::move(shutdown_cb)); bluez::DBusBluezManagerWrapperLinux::Initialize(); // Set up crypt config. This needs to be done before anything starts the // network service, as the raw encryption key needs to be shared with the // network service for encrypted cookie storage. std::string app_name = electron::Browser::Get()->GetName(); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::unique_ptr<os_crypt::Config> config = std::make_unique<os_crypt::Config>(); // Forward to os_crypt the flag to use a specific password store. config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore); config->product_name = app_name; config->application_name = app_name; config->main_thread_runner = base::ThreadTaskRunnerHandle::Get(); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1 config->should_use_preference = command_line.HasSwitch(::switches::kEnableEncryptionSelection); base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path); OSCrypt::SetConfig(std::move(config)); #endif #if BUILDFLAG(IS_POSIX) // Exit in response to SIGINT, SIGTERM, etc. InstallShutdownSignalHandlers( base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())), content::GetUIThreadTaskRunner({})); #endif } void ElectronBrowserMainParts::PostMainMessageLoopRun() { #if BUILDFLAG(IS_MAC) FreeAppDelegate(); #endif // Shutdown the DownloadManager before destroying Node to prevent // DownloadItem callbacks from crashing. for (auto& iter : ElectronBrowserContext::browser_context_map()) { auto* download_manager = iter.second.get()->GetDownloadManager(); if (download_manager) { download_manager->Shutdown(); } } // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. node_env_->env()->set_trace_sync_io(false); js_env_->OnMessageLoopDestroying(); node::Stop(node_env_->env()); node_env_.reset(); auto default_context_key = ElectronBrowserContext::PartitionKey("", false); std::unique_ptr<ElectronBrowserContext> default_context = std::move( ElectronBrowserContext::browser_context_map()[default_context_key]); ElectronBrowserContext::browser_context_map().clear(); default_context.reset(); fake_browser_process_->PostMainMessageLoopRun(); content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler(); #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun(); #endif } #if !BUILDFLAG(IS_MAC) void ElectronBrowserMainParts::PreCreateMainMessageLoop() { PreCreateMainMessageLoopCommon(); } #endif void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() { #if BUILDFLAG(IS_MAC) InitializeMainNib(); RegisterURLHandler(); #endif media::SetLocalizedStringProvider(MediaStringProvider); #if BUILDFLAG(IS_WIN) auto* local_state = g_browser_process->local_state(); DCHECK(local_state); bool os_crypt_init = OSCrypt::Init(local_state); DCHECK(os_crypt_init); #endif } device::mojom::GeolocationControl* ElectronBrowserMainParts::GetGeolocationControl() { if (!geolocation_control_) { content::GetDeviceService().BindGeolocationControl( geolocation_control_.BindNewPipeAndPassReceiver()); } return geolocation_control_.get(); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserMainParts::GetGeolocationManager() { return geolocation_manager_.get(); } #endif IconManager* ElectronBrowserMainParts::GetIconManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!icon_manager_.get()) icon_manager_ = std::make_unique<IconManager>(); return icon_manager_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
shell/browser/ui/electron_gdk_pixbuf.sigs
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
shell/browser/ui/electron_gtk.fragment
#include <gtk/gtk.h>
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
shell/browser/ui/electron_gtk.sigs
GtkFileChooserNative* gtk_file_chooser_native_new(const gchar* title, GtkWindow* parent, GtkFileChooserAction action, const gchar* accept_label, const gchar* cancel_label); void gtk_native_dialog_set_modal(GtkNativeDialog* self, gboolean modal); void gtk_native_dialog_show(GtkNativeDialog* self); void gtk_native_dialog_hide(GtkNativeDialog* self); gint gtk_native_dialog_run(GtkNativeDialog* self); void gtk_native_dialog_destroy(GtkNativeDialog* self); GType gtk_native_dialog_get_type(void);
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
shell/browser/ui/gtk_util.cc
// Copyright (c) 2019 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/gtk_util.h" #include <gdk/gdk.h> #include <gtk/gtk.h> #include <stdint.h> #include <string> #include "base/no_destructor.h" #include "base/strings/string_number_conversions.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkUnPreMultiply.h" #include "ui/gtk/gtk_compat.h" // nogncheck // The following utilities are pulled from // https://source.chromium.org/chromium/chromium/src/+/main:ui/gtk/select_file_dialog_impl_gtk.cc;l=43-74 namespace gtk_util { namespace { const char* GettextPackage() { static base::NoDestructor<std::string> gettext_package( "gtk" + base::NumberToString(gtk::GtkVersion().components()[0]) + "0"); return gettext_package->c_str(); } const char* GtkGettext(const char* str) { return g_dgettext(GettextPackage(), str); } } // namespace const char* GetCancelLabel() { static const char* cancel = GtkGettext("_Cancel"); return cancel; } const char* GetOpenLabel() { static const char* open = GtkGettext("_Open"); return open; } const char* GetSaveLabel() { static const char* save = GtkGettext("_Save"); return save; } const char* GetOkLabel() { static const char* ok = GtkGettext("_Ok"); return ok; } const char* GetNoLabel() { static const char* no = GtkGettext("_No"); return no; } const char* GetYesLabel() { static const char* yes = GtkGettext("_Yes"); return yes; } GdkPixbuf* GdkPixbufFromSkBitmap(const SkBitmap& bitmap) { if (bitmap.isNull()) return nullptr; int width = bitmap.width(); int height = bitmap.height(); GdkPixbuf* pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, // The only colorspace gtk supports. TRUE, // There is an alpha channel. 8, width, height); // SkBitmaps are premultiplied, we need to unpremultiply them. const int kBytesPerPixel = 4; uint8_t* divided = gdk_pixbuf_get_pixels(pixbuf); for (int y = 0, i = 0; y < height; y++) { for (int x = 0; x < width; x++) { uint32_t pixel = bitmap.getAddr32(0, y)[x]; int alpha = SkColorGetA(pixel); if (alpha != 0 && alpha != 255) { SkColor unmultiplied = SkUnPreMultiply::PMColorToColor(pixel); divided[i + 0] = SkColorGetR(unmultiplied); divided[i + 1] = SkColorGetG(unmultiplied); divided[i + 2] = SkColorGetB(unmultiplied); divided[i + 3] = alpha; } else { divided[i + 0] = SkColorGetR(pixel); divided[i + 1] = SkColorGetG(pixel); divided[i + 2] = SkColorGetB(pixel); divided[i + 3] = alpha; } i += kBytesPerPixel; } } return pixbuf; } } // namespace gtk_util
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
shell/browser/ui/message_box_gtk.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/message_box.h" #include <map> #include "base/callback.h" #include "base/containers/contains.h" #include "base/no_destructor.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_observer.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/gtk_util.h" #include "shell/browser/unresponsive_suppressor.h" #include "ui/base/glib/glib_signal.h" #include "ui/gfx/image/image_skia.h" #include "ui/gtk/gtk_ui.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #if defined(USE_OZONE) #include "ui/base/ui_base_features.h" #endif #define ANSI_FOREGROUND_RED "\x1b[31m" #define ANSI_FOREGROUND_BLACK "\x1b[30m" #define ANSI_TEXT_BOLD "\x1b[1m" #define ANSI_BACKGROUND_GRAY "\x1b[47m" #define ANSI_RESET "\x1b[0m" namespace electron { MessageBoxSettings::MessageBoxSettings() = default; MessageBoxSettings::MessageBoxSettings(const MessageBoxSettings&) = default; MessageBoxSettings::~MessageBoxSettings() = default; namespace { // <ID, messageBox> map std::map<int, GtkWidget*>& GetDialogsMap() { static base::NoDestructor<std::map<int, GtkWidget*>> dialogs; return *dialogs; } class GtkMessageBox : public NativeWindowObserver { public: explicit GtkMessageBox(const MessageBoxSettings& settings) : id_(settings.id), cancel_id_(settings.cancel_id), parent_(static_cast<NativeWindow*>(settings.parent_window)) { // Create dialog. dialog_ = gtk_message_dialog_new(nullptr, // parent static_cast<GtkDialogFlags>(0), // no flags GetMessageType(settings.type), // type GTK_BUTTONS_NONE, // no buttons "%s", settings.message.c_str()); if (id_) GetDialogsMap()[*id_] = dialog_; if (!settings.detail.empty()) gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog_), "%s", settings.detail.c_str()); if (!settings.title.empty()) gtk_window_set_title(GTK_WINDOW(dialog_), settings.title.c_str()); if (!settings.icon.isNull()) { // No easy way to obtain this programmatically, but GTK+'s docs // define GTK_ICON_SIZE_DIALOG to be 48 pixels static constexpr int pixel_width = 48; static constexpr int pixel_height = 48; GdkPixbuf* pixbuf = gtk_util::GdkPixbufFromSkBitmap(*settings.icon.bitmap()); GdkPixbuf* scaled_pixbuf = gdk_pixbuf_scale_simple( pixbuf, pixel_width, pixel_height, GDK_INTERP_BILINEAR); GtkWidget* w = gtk_image_new_from_pixbuf(scaled_pixbuf); gtk_message_dialog_set_image(GTK_MESSAGE_DIALOG(dialog_), w); gtk_widget_show(w); g_clear_pointer(&scaled_pixbuf, g_object_unref); g_clear_pointer(&pixbuf, g_object_unref); } if (!settings.checkbox_label.empty()) { GtkWidget* message_area = gtk_message_dialog_get_message_area(GTK_MESSAGE_DIALOG(dialog_)); GtkWidget* check_button = gtk_check_button_new_with_label(settings.checkbox_label.c_str()); g_signal_connect(check_button, "toggled", G_CALLBACK(OnCheckboxToggledThunk), this); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_button), settings.checkbox_checked); gtk_container_add(GTK_CONTAINER(message_area), check_button); gtk_widget_show(check_button); } // Add buttons. GtkDialog* dialog = GTK_DIALOG(dialog_); if (settings.buttons.size() == 0) { gtk_dialog_add_button(dialog, TranslateToStock(0, "OK"), 0); } else { for (size_t i = 0; i < settings.buttons.size(); ++i) { gtk_dialog_add_button(dialog, TranslateToStock(i, settings.buttons[i]), i); } } gtk_dialog_set_default_response(dialog, settings.default_id); // Parent window. if (parent_) { parent_->AddObserver(this); static_cast<NativeWindowViews*>(parent_)->SetEnabled(false); gtk::SetGtkTransientForAura(dialog_, parent_->GetNativeWindow()); gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE); } } ~GtkMessageBox() override { gtk_widget_destroy(dialog_); if (parent_) { parent_->RemoveObserver(this); static_cast<NativeWindowViews*>(parent_)->SetEnabled(true); } } // disable copy GtkMessageBox(const GtkMessageBox&) = delete; GtkMessageBox& operator=(const GtkMessageBox&) = delete; GtkMessageType GetMessageType(MessageBoxType type) { switch (type) { case MessageBoxType::kInformation: return GTK_MESSAGE_INFO; case MessageBoxType::kWarning: return GTK_MESSAGE_WARNING; case MessageBoxType::kQuestion: return GTK_MESSAGE_QUESTION; case MessageBoxType::kError: return GTK_MESSAGE_ERROR; default: return GTK_MESSAGE_OTHER; } } const char* TranslateToStock(int id, const std::string& text) { const std::string lower = base::ToLowerASCII(text); if (lower == "cancel") return gtk_util::GetCancelLabel(); if (lower == "no") return gtk_util::GetNoLabel(); if (lower == "ok") return gtk_util::GetOkLabel(); if (lower == "yes") return gtk_util::GetYesLabel(); return text.c_str(); } void Show() { gtk_widget_show(dialog_); gtk::GtkUi::GetPlatform()->ShowGtkWindow(GTK_WINDOW(dialog_)); } int RunSynchronous() { Show(); int response = gtk_dialog_run(GTK_DIALOG(dialog_)); return (response < 0) ? cancel_id_ : response; } void RunAsynchronous(MessageBoxCallback callback) { callback_ = std::move(callback); g_signal_connect(dialog_, "delete-event", G_CALLBACK(gtk_widget_hide_on_delete), nullptr); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseDialogThunk), this); Show(); } void OnWindowClosed() override { parent_->RemoveObserver(this); parent_ = nullptr; } CHROMEG_CALLBACK_1(GtkMessageBox, void, OnResponseDialog, GtkWidget*, int); CHROMEG_CALLBACK_0(GtkMessageBox, void, OnCheckboxToggled, GtkWidget*); private: electron::UnresponsiveSuppressor unresponsive_suppressor_; // The id of the dialog. absl::optional<int> id_; // The id to return when the dialog is closed without pressing buttons. int cancel_id_ = 0; bool checkbox_checked_ = false; NativeWindow* parent_; GtkWidget* dialog_; MessageBoxCallback callback_; }; void GtkMessageBox::OnResponseDialog(GtkWidget* widget, int response) { if (id_) GetDialogsMap().erase(*id_); gtk_widget_hide(dialog_); if (response < 0) std::move(callback_).Run(cancel_id_, checkbox_checked_); else std::move(callback_).Run(response, checkbox_checked_); delete this; } void GtkMessageBox::OnCheckboxToggled(GtkWidget* widget) { checkbox_checked_ = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)); } } // namespace int ShowMessageBoxSync(const MessageBoxSettings& settings) { return GtkMessageBox(settings).RunSynchronous(); } void ShowMessageBox(const MessageBoxSettings& settings, MessageBoxCallback callback) { if (settings.id && base::Contains(GetDialogsMap(), *settings.id)) CloseMessageBox(*settings.id); (new GtkMessageBox(settings))->RunAsynchronous(std::move(callback)); } void CloseMessageBox(int id) { auto it = GetDialogsMap().find(id); if (it == GetDialogsMap().end()) { LOG(ERROR) << "CloseMessageBox called with nonexistent ID"; return; } gtk_window_close(GTK_WINDOW(it->second)); } void ShowErrorBox(const std::u16string& title, const std::u16string& content) { if (Browser::Get()->is_ready()) { electron::MessageBoxSettings settings; settings.type = electron::MessageBoxType::kError; settings.buttons = {}; settings.title = "Error"; settings.message = base::UTF16ToUTF8(title); settings.detail = base::UTF16ToUTF8(content); GtkMessageBox(settings).RunSynchronous(); } else { fprintf(stderr, ANSI_TEXT_BOLD ANSI_BACKGROUND_GRAY ANSI_FOREGROUND_RED "%s\n" ANSI_FOREGROUND_BLACK "%s" ANSI_RESET "\n", base::UTF16ToUTF8(title).c_str(), base::UTF16ToUTF8(content).c_str()); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
BUILD.gn
import("//build/config/locales.gni") import("//build/config/ui.gni") import("//build/config/win/manifest.gni") import("//components/os_crypt/features.gni") import("//components/spellcheck/spellcheck_build_features.gni") import("//content/public/app/mac_helpers.gni") import("//extensions/buildflags/buildflags.gni") import("//pdf/features.gni") import("//ppapi/buildflags/buildflags.gni") import("//printing/buildflags/buildflags.gni") import("//testing/test.gni") import("//third_party/ffmpeg/ffmpeg_options.gni") import("//tools/generate_library_loader/generate_library_loader.gni") import("//tools/grit/grit_rule.gni") import("//tools/grit/repack.gni") import("//tools/v8_context_snapshot/v8_context_snapshot.gni") import("//v8/gni/snapshot_toolchain.gni") import("build/asar.gni") import("build/extract_symbols.gni") import("build/npm.gni") import("build/templated_file.gni") import("build/tsc.gni") import("build/webpack/webpack.gni") import("buildflags/buildflags.gni") import("electron_paks.gni") import("filenames.auto.gni") import("filenames.gni") import("filenames.hunspell.gni") import("filenames.libcxx.gni") import("filenames.libcxxabi.gni") if (is_mac) { import("//build/config/mac/rules.gni") import("//third_party/icu/config.gni") import("//ui/gl/features.gni") import("//v8/gni/v8.gni") import("build/rules.gni") assert( mac_deployment_target == "10.13", "Chromium has updated the mac_deployment_target, please update this assert, update the supported versions documentation (docs/tutorial/support.md) and flag this as a breaking change") } if (is_linux) { import("//build/config/linux/pkg_config.gni") import("//tools/generate_stubs/rules.gni") pkg_config("gio_unix") { packages = [ "gio-unix-2.0" ] } pkg_config("libnotify_config") { packages = [ "glib-2.0", "gdk-pixbuf-2.0", ] } generate_library_loader("libnotify_loader") { name = "LibNotifyLoader" output_h = "libnotify_loader.h" output_cc = "libnotify_loader.cc" header = "<libnotify/notify.h>" config = ":libnotify_config" functions = [ "notify_is_initted", "notify_init", "notify_get_server_caps", "notify_get_server_info", "notify_notification_new", "notify_notification_add_action", "notify_notification_set_image_from_pixbuf", "notify_notification_set_timeout", "notify_notification_set_urgency", "notify_notification_set_hint_string", "notify_notification_show", "notify_notification_close", ] } # Generates electron_gtk_stubs.h header which contains # stubs for extracting function ptrs from the gtk library. # Function signatures for which stubs are required should be # declared in electron_gtk.sigs, currently this file contains # signatures for the functions used with native file chooser # implementation. In future, this file can be extended to contain # gtk4 stubs to switch gtk version in runtime. generate_stubs("electron_gtk_stubs") { sigs = [ "shell/browser/ui/electron_gtk.sigs" ] extra_header = "shell/browser/ui/electron_gtk.fragment" output_name = "electron_gtk_stubs" public_deps = [ "//ui/gtk:gtk_config" ] logging_function = "LogNoop()" logging_include = "ui/gtk/log_noop.h" } } declare_args() { use_prebuilt_v8_context_snapshot = false } branding = read_file("shell/app/BRANDING.json", "json") electron_project_name = branding.project_name electron_product_name = branding.product_name electron_mac_bundle_id = branding.mac_bundle_id if (is_mas_build) { assert(is_mac, "It doesn't make sense to build a MAS build on a non-mac platform") } if (enable_pdf_viewer) { assert(enable_pdf, "PDF viewer support requires enable_pdf=true") assert(enable_electron_extensions, "PDF viewer support requires enable_electron_extensions=true") } if (enable_electron_extensions) { assert(enable_extensions, "Chrome extension support requires enable_extensions=true") } config("branding") { defines = [ "ELECTRON_PRODUCT_NAME=\"$electron_product_name\"", "ELECTRON_PROJECT_NAME=\"$electron_project_name\"", ] } config("electron_lib_config") { include_dirs = [ "." ] } # We generate the definitions twice here, once in //electron/electron.d.ts # and once in $target_gen_dir # The one in $target_gen_dir is used for the actual TSC build later one # and the one in //electron/electron.d.ts is used by your IDE (vscode) # for typescript prompting npm_action("build_electron_definitions") { script = "gn-typescript-definitions" args = [ rebase_path("$target_gen_dir/tsc/typings/electron.d.ts") ] inputs = auto_filenames.api_docs + [ "yarn.lock" ] outputs = [ "$target_gen_dir/tsc/typings/electron.d.ts" ] } webpack_build("electron_asar_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.asar_bundle_deps config_file = "//electron/build/webpack/webpack.config.asar.js" out_file = "$target_gen_dir/js2c/asar_bundle.js" } webpack_build("electron_browser_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.browser_bundle_deps config_file = "//electron/build/webpack/webpack.config.browser.js" out_file = "$target_gen_dir/js2c/browser_init.js" } webpack_build("electron_renderer_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.renderer_bundle_deps config_file = "//electron/build/webpack/webpack.config.renderer.js" out_file = "$target_gen_dir/js2c/renderer_init.js" } webpack_build("electron_worker_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.worker_bundle_deps config_file = "//electron/build/webpack/webpack.config.worker.js" out_file = "$target_gen_dir/js2c/worker_init.js" } webpack_build("electron_sandboxed_renderer_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.sandbox_bundle_deps config_file = "//electron/build/webpack/webpack.config.sandboxed_renderer.js" out_file = "$target_gen_dir/js2c/sandbox_bundle.js" } webpack_build("electron_isolated_renderer_bundle") { deps = [ ":build_electron_definitions" ] inputs = auto_filenames.isolated_bundle_deps config_file = "//electron/build/webpack/webpack.config.isolated_renderer.js" out_file = "$target_gen_dir/js2c/isolated_bundle.js" } action("electron_js2c") { deps = [ ":electron_asar_bundle", ":electron_browser_bundle", ":electron_isolated_renderer_bundle", ":electron_renderer_bundle", ":electron_sandboxed_renderer_bundle", ":electron_worker_bundle", ] sources = [ "$target_gen_dir/js2c/asar_bundle.js", "$target_gen_dir/js2c/browser_init.js", "$target_gen_dir/js2c/isolated_bundle.js", "$target_gen_dir/js2c/renderer_init.js", "$target_gen_dir/js2c/sandbox_bundle.js", "$target_gen_dir/js2c/worker_init.js", ] inputs = sources + [ "//third_party/electron_node/tools/js2c.py" ] outputs = [ "$root_gen_dir/electron_natives.cc" ] script = "build/js2c.py" args = [ rebase_path("//third_party/electron_node") ] + rebase_path(outputs, root_build_dir) + rebase_path(sources, root_build_dir) } action("generate_config_gypi") { outputs = [ "$root_gen_dir/config.gypi" ] script = "script/generate-config-gypi.py" args = rebase_path(outputs) + [ target_cpu ] } target_gen_default_app_js = "$target_gen_dir/js/default_app" typescript_build("default_app_js") { deps = [ ":build_electron_definitions" ] sources = filenames.default_app_ts_sources output_gen_dir = target_gen_default_app_js output_dir_name = "default_app" tsconfig = "tsconfig.default_app.json" } copy("default_app_static") { sources = filenames.default_app_static_sources outputs = [ "$target_gen_default_app_js/{{source}}" ] } copy("default_app_octicon_deps") { sources = filenames.default_app_octicon_sources outputs = [ "$target_gen_default_app_js/electron/default_app/octicon/{{source_file_part}}" ] } asar("default_app_asar") { deps = [ ":default_app_js", ":default_app_octicon_deps", ":default_app_static", ] root = "$target_gen_default_app_js/electron/default_app" sources = get_target_outputs(":default_app_js") + get_target_outputs(":default_app_static") + get_target_outputs(":default_app_octicon_deps") outputs = [ "$root_out_dir/resources/default_app.asar" ] } grit("resources") { source = "electron_resources.grd" outputs = [ "grit/electron_resources.h", "electron_resources.pak", ] # Mojo manifest overlays are generated. grit_flags = [ "-E", "target_gen_dir=" + rebase_path(target_gen_dir, root_build_dir), ] deps = [ ":copy_shell_devtools_discovery_page" ] output_dir = "$target_gen_dir" } copy("copy_shell_devtools_discovery_page") { sources = [ "//content/shell/resources/shell_devtools_discovery_page.html" ] outputs = [ "$target_gen_dir/shell_devtools_discovery_page.html" ] } npm_action("electron_version_args") { script = "generate-version-json" outputs = [ "$target_gen_dir/electron_version.args" ] args = rebase_path(outputs) inputs = [ "ELECTRON_VERSION", "script/generate-version-json.js", ] } templated_file("electron_version_header") { deps = [ ":electron_version_args" ] template = "build/templates/electron_version.tmpl" output = "$target_gen_dir/electron_version.h" args_files = get_target_outputs(":electron_version_args") } action("electron_fuses") { script = "build/fuses/build.py" inputs = [ "build/fuses/fuses.json5" ] outputs = [ "$target_gen_dir/fuses.h", "$target_gen_dir/fuses.cc", ] args = rebase_path(outputs) } action("electron_generate_node_defines") { script = "build/generate_node_defines.py" inputs = [ "//third_party/electron_node/src/tracing/trace_event_common.h", "//third_party/electron_node/src/tracing/trace_event.h", "//third_party/electron_node/src/util.h", ] outputs = [ "$target_gen_dir/push_and_undef_node_defines.h", "$target_gen_dir/pop_node_defines.h", ] args = [ rebase_path(target_gen_dir) ] + rebase_path(inputs) } source_set("electron_lib") { configs += [ "//v8:external_startup_data" ] configs += [ "//third_party/electron_node:node_internals" ] public_configs = [ ":branding", ":electron_lib_config", ] deps = [ ":electron_fuses", ":electron_generate_node_defines", ":electron_js2c", ":electron_version_header", ":resources", "buildflags", "chromium_src:chrome", "chromium_src:chrome_spellchecker", "shell/common/api:mojo", "//base:base_static", "//base/allocator:buildflags", "//chrome:strings", "//chrome/app:command_ids", "//chrome/app/resources:platform_locale_settings", "//components/autofill/core/common:features", "//components/certificate_transparency", "//components/embedder_support:browser_util", "//components/language/core/browser", "//components/net_log", "//components/network_hints/browser", "//components/network_hints/common:mojo_bindings", "//components/network_hints/renderer", "//components/network_session_configurator/common", "//components/omnibox/browser:buildflags", "//components/os_crypt", "//components/pref_registry", "//components/prefs", "//components/security_state/content", "//components/upload_list", "//components/user_prefs", "//components/viz/host", "//components/viz/service", "//content/public/browser", "//content/public/child", "//content/public/gpu", "//content/public/renderer", "//content/public/utility", "//device/bluetooth", "//device/bluetooth/public/cpp", "//gin", "//media/capture/mojom:video_capture", "//media/mojo/mojom", "//net:extras", "//net:net_resources", "//ppapi/host", "//ppapi/proxy", "//ppapi/shared_impl", "//printing/buildflags", "//services/device/public/cpp/geolocation", "//services/device/public/cpp/hid", "//services/device/public/mojom", "//services/proxy_resolver:lib", "//services/video_capture/public/mojom:constants", "//services/viz/privileged/mojom/compositing", "//skia", "//third_party/blink/public:blink", "//third_party/blink/public:blink_devtools_inspector_resources", "//third_party/blink/public/platform/media", "//third_party/boringssl", "//third_party/electron_node:node_lib", "//third_party/inspector_protocol:crdtp", "//third_party/leveldatabase", "//third_party/libyuv", "//third_party/webrtc_overrides:webrtc_component", "//third_party/widevine/cdm:headers", "//third_party/zlib/google:zip", "//ui/base/idle", "//ui/events:dom_keycode_converter", "//ui/gl", "//ui/native_theme", "//ui/shell_dialogs", "//ui/views", "//v8", "//v8:v8_libplatform", ] public_deps = [ "//base", "//base:i18n", "//content/public/app", ] include_dirs = [ ".", "$target_gen_dir", # TODO(nornagon): replace usage of SchemeRegistry by an actually exported # API of blink, then remove this from the include_dirs. "//third_party/blink/renderer", ] defines = [ "V8_DEPRECATION_WARNINGS" ] libs = [] if (is_linux) { defines += [ "GDK_DISABLE_DEPRECATION_WARNINGS" ] } if (!is_mas_build) { deps += [ "//components/crash/core/app", "//components/crash/core/browser", ] } sources = filenames.lib_sources if (is_win) { sources += filenames.lib_sources_win } if (is_mac) { sources += filenames.lib_sources_mac } if (is_posix) { sources += filenames.lib_sources_posix } if (is_linux) { sources += filenames.lib_sources_linux } if (!is_mac) { sources += filenames.lib_sources_views } if (is_component_build) { defines += [ "NODE_SHARED_MODE" ] } if (enable_fake_location_provider) { sources += [ "shell/browser/fake_location_provider.cc", "shell/browser/fake_location_provider.h", ] } if (is_linux) { deps += [ "//components/crash/content/browser", "//ui/gtk:gtk_config", ] } if (is_mac) { deps += [ "//components/remote_cocoa/app_shim", "//components/remote_cocoa/browser", "//content/common:mac_helpers", "//ui/accelerated_widget_mac", ] if (!is_mas_build) { deps += [ "//third_party/crashpad/crashpad/client" ] } frameworks = [ "AVFoundation.framework", "Carbon.framework", "LocalAuthentication.framework", "QuartzCore.framework", "Quartz.framework", "Security.framework", "SecurityInterface.framework", "ServiceManagement.framework", "StoreKit.framework", ] weak_frameworks = [ "QuickLookThumbnailing.framework" ] sources += [ "shell/browser/ui/views/autofill_popup_view.cc", "shell/browser/ui/views/autofill_popup_view.h", ] if (is_mas_build) { sources += [ "shell/browser/api/electron_api_app_mas.mm" ] sources -= [ "shell/browser/auto_updater_mac.mm" ] defines += [ "MAS_BUILD" ] sources -= [ "shell/app/electron_crash_reporter_client.cc", "shell/app/electron_crash_reporter_client.h", "shell/common/crash_keys.cc", "shell/common/crash_keys.h", ] } else { frameworks += [ "Squirrel.framework", "ReactiveObjC.framework", "Mantle.framework", ] deps += [ "//third_party/squirrel.mac:reactiveobjc_framework+link", "//third_party/squirrel.mac:squirrel_framework+link", ] # ReactiveObjC which is used by Squirrel requires using __weak. cflags_objcc = [ "-fobjc-weak" ] } } if (is_linux) { libs = [ "xshmfence" ] deps += [ ":electron_gtk_stubs", ":libnotify_loader", "//build/config/linux/gtk", "//dbus", "//device/bluetooth", "//ui/base/ime/linux", "//ui/events/devices/x11", "//ui/events/platform/x11", "//ui/views/controls/webview", "//ui/views/linux_ui:linux_ui_factory", "//ui/wm", ] if (ozone_platform_x11) { sources += filenames.lib_sources_linux_x11 public_deps += [ "//ui/base/x", "//ui/ozone/platform/x11", ] } configs += [ ":gio_unix" ] defines += [ # Disable warnings for g_settings_list_schemas. "GLIB_DISABLE_DEPRECATION_WARNINGS", ] sources += [ "shell/browser/certificate_manager_model.cc", "shell/browser/certificate_manager_model.h", "shell/browser/ui/gtk/app_indicator_icon.cc", "shell/browser/ui/gtk/app_indicator_icon.h", "shell/browser/ui/gtk/app_indicator_icon_menu.cc", "shell/browser/ui/gtk/app_indicator_icon_menu.h", "shell/browser/ui/gtk/gtk_status_icon.cc", "shell/browser/ui/gtk/gtk_status_icon.h", "shell/browser/ui/gtk/menu_util.cc", "shell/browser/ui/gtk/menu_util.h", "shell/browser/ui/gtk/status_icon.cc", "shell/browser/ui/gtk/status_icon.h", "shell/browser/ui/gtk_util.cc", "shell/browser/ui/gtk_util.h", ] } if (is_win) { libs += [ "dwmapi.lib" ] deps += [ "//components/crash/core/app:crash_export_thunks", "//ui/native_theme:native_theme_browser", "//ui/views/controls/webview", "//ui/wm", "//ui/wm/public", ] public_deps += [ "//sandbox/win:sandbox", "//third_party/crashpad/crashpad/handler", ] } if (enable_plugins) { deps += [ "chromium_src:plugins" ] sources += [ "shell/renderer/pepper_helper.cc", "shell/renderer/pepper_helper.h", ] } if (enable_run_as_node) { sources += [ "shell/app/node_main.cc", "shell/app/node_main.h", ] } if (enable_osr) { sources += [ "shell/browser/osr/osr_host_display_client.cc", "shell/browser/osr/osr_host_display_client.h", "shell/browser/osr/osr_render_widget_host_view.cc", "shell/browser/osr/osr_render_widget_host_view.h", "shell/browser/osr/osr_video_consumer.cc", "shell/browser/osr/osr_video_consumer.h", "shell/browser/osr/osr_view_proxy.cc", "shell/browser/osr/osr_view_proxy.h", "shell/browser/osr/osr_web_contents_view.cc", "shell/browser/osr/osr_web_contents_view.h", ] if (is_mac) { sources += [ "shell/browser/osr/osr_host_display_client_mac.mm", "shell/browser/osr/osr_web_contents_view_mac.mm", ] } deps += [ "//components/viz/service", "//services/viz/public/mojom", "//ui/compositor", ] } if (enable_desktop_capturer) { sources += [ "shell/browser/api/electron_api_desktop_capturer.cc", "shell/browser/api/electron_api_desktop_capturer.h", ] } if (enable_views_api) { sources += [ "shell/browser/api/views/electron_api_image_view.cc", "shell/browser/api/views/electron_api_image_view.h", ] } if (enable_basic_printing) { sources += [ "shell/browser/printing/print_view_manager_electron.cc", "shell/browser/printing/print_view_manager_electron.h", "shell/renderer/printing/print_render_frame_helper_delegate.cc", "shell/renderer/printing/print_render_frame_helper_delegate.h", ] deps += [ "//chrome/services/printing/public/mojom", "//components/printing/common:mojo_interfaces", ] if (is_mac) { deps += [ "//chrome/services/mac_notifications/public/mojom" ] } } if (enable_electron_extensions) { sources += filenames.lib_sources_extensions deps += [ "shell/browser/extensions/api:api_registration", "shell/common/extensions/api", "shell/common/extensions/api:extensions_features", "//chrome/browser/resources:component_extension_resources", "//components/update_client:update_client", "//components/zoom", "//extensions/browser", "//extensions/browser:core_api_provider", "//extensions/browser/updater", "//extensions/common", "//extensions/common:core_api_provider", "//extensions/renderer", ] } if (enable_pdf) { # Printing depends on some //pdf code, so it needs to be built even if the # pdf viewer isn't enabled. deps += [ "//pdf", "//pdf:features", ] } if (enable_pdf_viewer) { deps += [ "//chrome/browser/resources/pdf:resources", "//components/pdf/browser", "//components/pdf/browser:interceptors", "//components/pdf/common", "//components/pdf/renderer", "//pdf", ] sources += [ "shell/browser/electron_pdf_web_contents_helper_client.cc", "shell/browser/electron_pdf_web_contents_helper_client.h", ] } sources += get_target_outputs(":electron_fuses") if (allow_runtime_configurable_key_storage) { defines += [ "ALLOW_RUNTIME_CONFIGURABLE_KEY_STORAGE" ] } } electron_paks("packed_resources") { if (is_mac) { output_dir = "$root_gen_dir/electron_repack" copy_data_to_bundle = true } else { output_dir = root_out_dir } } if (is_mac) { electron_framework_name = "$electron_product_name Framework" electron_helper_name = "$electron_product_name Helper" electron_login_helper_name = "$electron_product_name Login Helper" electron_framework_version = "A" electron_version = read_file("ELECTRON_VERSION", "trim string") mac_xib_bundle_data("electron_xibs") { sources = [ "shell/common/resources/mac/MainMenu.xib" ] } action("fake_v8_context_snapshot_generator") { script = "build/fake_v8_context_snapshot_generator.py" args = [ rebase_path("$root_out_dir/$v8_context_snapshot_filename"), rebase_path("$root_out_dir/fake/$v8_context_snapshot_filename"), ] outputs = [ "$root_out_dir/fake/$v8_context_snapshot_filename" ] } bundle_data("electron_framework_resources") { public_deps = [ ":packed_resources" ] sources = [] if (icu_use_data_file) { sources += [ "$root_out_dir/icudtl.dat" ] public_deps += [ "//third_party/icu:icudata" ] } if (v8_use_external_startup_data) { public_deps += [ "//v8" ] if (use_v8_context_snapshot) { if (use_prebuilt_v8_context_snapshot) { sources += [ "$root_out_dir/fake/$v8_context_snapshot_filename" ] public_deps += [ ":fake_v8_context_snapshot_generator" ] } else { sources += [ "$root_out_dir/$v8_context_snapshot_filename" ] public_deps += [ "//tools/v8_context_snapshot" ] } } else { sources += [ "$root_out_dir/snapshot_blob.bin" ] } } outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ] } if (!is_component_build && is_component_ffmpeg) { bundle_data("electron_framework_libraries") { sources = [] public_deps = [] sources += [ "$root_out_dir/libffmpeg.dylib" ] public_deps += [ "//third_party/ffmpeg:ffmpeg" ] outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ] } } else { group("electron_framework_libraries") { } } if (use_egl) { # Add the ANGLE .dylibs in the Libraries directory of the Framework. bundle_data("electron_angle_binaries") { sources = [ "$root_out_dir/egl_intermediates/libEGL.dylib", "$root_out_dir/egl_intermediates/libGLESv2.dylib", ] outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ] public_deps = [ "//ui/gl:angle_library_copy" ] } # Add the SwiftShader .dylibs in the Libraries directory of the Framework. bundle_data("electron_swiftshader_binaries") { sources = [ "$root_out_dir/vk_intermediates/libvk_swiftshader.dylib", "$root_out_dir/vk_intermediates/vk_swiftshader_icd.json", ] outputs = [ "{{bundle_contents_dir}}/Libraries/{{source_file_part}}" ] public_deps = [ "//ui/gl:swiftshader_vk_library_copy" ] } } group("electron_angle_library") { if (use_egl) { deps = [ ":electron_angle_binaries" ] } } group("electron_swiftshader_library") { if (use_egl) { deps = [ ":electron_swiftshader_binaries" ] } } bundle_data("electron_crashpad_helper") { sources = [ "$root_out_dir/chrome_crashpad_handler" ] outputs = [ "{{bundle_contents_dir}}/Helpers/{{source_file_part}}" ] public_deps = [ "//components/crash/core/app:chrome_crashpad_handler" ] if (is_asan) { # crashpad_handler requires the ASan runtime at its @executable_path. sources += [ "$root_out_dir/libclang_rt.asan_osx_dynamic.dylib" ] public_deps += [ "//build/config/sanitizers:copy_asan_runtime" ] } } mac_framework_bundle("electron_framework") { output_name = electron_framework_name framework_version = electron_framework_version framework_contents = [ "Resources", "Libraries", ] if (!is_mas_build) { framework_contents += [ "Helpers" ] } public_deps = [ ":electron_framework_libraries", ":electron_lib", ] deps = [ ":electron_angle_library", ":electron_framework_libraries", ":electron_framework_resources", ":electron_swiftshader_library", ":electron_xibs", ] if (!is_mas_build) { deps += [ ":electron_crashpad_helper" ] } info_plist = "shell/common/resources/mac/Info.plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.framework", "ELECTRON_VERSION=$electron_version", ] include_dirs = [ "." ] sources = filenames.framework_sources frameworks = [] if (enable_osr) { frameworks += [ "IOSurface.framework" ] } ldflags = [ "-Wl,-install_name,@rpath/$output_name.framework/$output_name", "-rpath", "@loader_path/Libraries", # Required for exporting all symbols of libuv. "-Wl,-force_load,obj/third_party/electron_node/deps/uv/libuv.a", ] if (is_component_build) { ldflags += [ "-rpath", "@executable_path/../../../../../..", ] } } template("electron_helper_app") { mac_app_bundle(target_name) { assert(defined(invoker.helper_name_suffix)) output_name = electron_helper_name + invoker.helper_name_suffix deps = [ ":electron_framework+link", "//base/allocator:early_zone_registration_mac", ] if (!is_mas_build) { deps += [ "//sandbox/mac:seatbelt" ] } defines = [ "HELPER_EXECUTABLE" ] sources = [ "shell/app/electron_main_mac.cc", "shell/app/uv_stdio_fix.cc", "shell/app/uv_stdio_fix.h", "shell/common/electron_constants.cc", ] include_dirs = [ "." ] info_plist = "shell/renderer/resources/mac/Info.plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.helper" ] ldflags = [ "-rpath", "@executable_path/../../..", ] if (is_component_build) { ldflags += [ "-rpath", "@executable_path/../../../../../..", ] } } } foreach(helper_params, content_mac_helpers) { _helper_target = helper_params[0] _helper_bundle_id = helper_params[1] _helper_suffix = helper_params[2] electron_helper_app("electron_helper_app_${_helper_target}") { helper_name_suffix = _helper_suffix } } template("stripped_framework") { action(target_name) { assert(defined(invoker.framework)) script = "//electron/build/strip_framework.py" forward_variables_from(invoker, [ "deps" ]) inputs = [ "$root_out_dir/" + invoker.framework ] outputs = [ "$target_out_dir/stripped_frameworks/" + invoker.framework ] args = rebase_path(inputs) + rebase_path(outputs) } } stripped_framework("stripped_mantle_framework") { framework = "Mantle.framework" deps = [ "//third_party/squirrel.mac:mantle_framework" ] } stripped_framework("stripped_reactiveobjc_framework") { framework = "ReactiveObjC.framework" deps = [ "//third_party/squirrel.mac:reactiveobjc_framework" ] } stripped_framework("stripped_squirrel_framework") { framework = "Squirrel.framework" deps = [ "//third_party/squirrel.mac:squirrel_framework" ] } bundle_data("electron_app_framework_bundle_data") { sources = [ "$root_out_dir/$electron_framework_name.framework" ] if (!is_mas_build) { sources += get_target_outputs(":stripped_mantle_framework") + get_target_outputs(":stripped_reactiveobjc_framework") + get_target_outputs(":stripped_squirrel_framework") } outputs = [ "{{bundle_contents_dir}}/Frameworks/{{source_file_part}}" ] public_deps = [ ":electron_framework+link", ":stripped_mantle_framework", ":stripped_reactiveobjc_framework", ":stripped_squirrel_framework", ] foreach(helper_params, content_mac_helpers) { sources += [ "$root_out_dir/${electron_helper_name}${helper_params[2]}.app" ] public_deps += [ ":electron_helper_app_${helper_params[0]}" ] } } mac_app_bundle("electron_login_helper") { output_name = electron_login_helper_name sources = filenames.login_helper_sources include_dirs = [ "." ] frameworks = [ "AppKit.framework" ] info_plist = "shell/app/resources/mac/loginhelper-Info.plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id.loginhelper" ] } bundle_data("electron_login_helper_app") { public_deps = [ ":electron_login_helper" ] sources = [ "$root_out_dir/$electron_login_helper_name.app" ] outputs = [ "{{bundle_contents_dir}}/Library/LoginItems/{{source_file_part}}" ] } action("electron_app_lproj_dirs") { outputs = [] foreach(locale, locales_as_apple_outputs) { outputs += [ "$target_gen_dir/app_infoplist_strings/$locale.lproj" ] } script = "build/mac/make_locale_dirs.py" args = rebase_path(outputs) } foreach(locale, locales_as_apple_outputs) { bundle_data("electron_app_strings_${locale}_bundle_data") { sources = [ "$target_gen_dir/app_infoplist_strings/$locale.lproj" ] outputs = [ "{{bundle_resources_dir}}/$locale.lproj" ] public_deps = [ ":electron_app_lproj_dirs" ] } } group("electron_app_strings_bundle_data") { public_deps = [] foreach(locale, locales_as_apple_outputs) { public_deps += [ ":electron_app_strings_${locale}_bundle_data" ] } } bundle_data("electron_app_resources") { public_deps = [ ":default_app_asar", ":electron_app_strings_bundle_data", ] sources = [ "$root_out_dir/resources/default_app.asar", "shell/browser/resources/mac/electron.icns", ] outputs = [ "{{bundle_resources_dir}}/{{source_file_part}}" ] } asar_hashed_info_plist("electron_app_plist") { keys = [ "DEFAULT_APP_ASAR_HEADER_SHA" ] hash_targets = [ ":default_app_asar_header_hash" ] plist_file = "shell/browser/resources/mac/Info.plist" } mac_app_bundle("electron_app") { output_name = electron_product_name sources = [ "shell/app/electron_main_mac.cc", "shell/app/uv_stdio_fix.cc", "shell/app/uv_stdio_fix.h", ] include_dirs = [ "." ] deps = [ ":electron_app_framework_bundle_data", ":electron_app_plist", ":electron_app_resources", ":electron_fuses", "//base/allocator:early_zone_registration_mac", "//electron/buildflags", ] if (is_mas_build) { deps += [ ":electron_login_helper_app" ] } info_plist_target = ":electron_app_plist" extra_substitutions = [ "ELECTRON_BUNDLE_ID=$electron_mac_bundle_id", "ELECTRON_VERSION=$electron_version", ] ldflags = [ "-rpath", "@executable_path/../Frameworks", ] } if (enable_dsyms) { extract_symbols("electron_framework_syms") { binary = "$root_out_dir/$electron_framework_name.framework/Versions/$electron_framework_version/$electron_framework_name" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/$electron_framework_name.dSYM/Contents/Resources/DWARF/$electron_framework_name" deps = [ ":electron_framework" ] } foreach(helper_params, content_mac_helpers) { _helper_target = helper_params[0] _helper_bundle_id = helper_params[1] _helper_suffix = helper_params[2] extract_symbols("electron_helper_syms_${_helper_target}") { binary = "$root_out_dir/$electron_helper_name${_helper_suffix}.app/Contents/MacOS/$electron_helper_name${_helper_suffix}" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/$electron_helper_name${_helper_suffix}.dSYM/Contents/Resources/DWARF/$electron_helper_name${_helper_suffix}" deps = [ ":electron_helper_app_${_helper_target}" ] } } extract_symbols("electron_app_syms") { binary = "$root_out_dir/$electron_product_name.app/Contents/MacOS/$electron_product_name" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/$electron_product_name.dSYM/Contents/Resources/DWARF/$electron_product_name" deps = [ ":electron_app" ] } extract_symbols("egl_syms") { binary = "$root_out_dir/libEGL.dylib" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/libEGL.dylib.dSYM/Contents/Resources/DWARF/libEGL.dylib" deps = [ "//third_party/angle:libEGL" ] } extract_symbols("gles_syms") { binary = "$root_out_dir/libGLESv2.dylib" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/libGLESv2.dylib.dSYM/Contents/Resources/DWARF/libGLESv2.dylib" deps = [ "//third_party/angle:libGLESv2" ] } extract_symbols("crashpad_handler_syms") { binary = "$root_out_dir/chrome_crashpad_handler" symbol_dir = "$root_out_dir/breakpad_symbols" dsym_file = "$root_out_dir/chrome_crashpad_handler.dSYM/Contents/Resources/DWARF/chrome_crashpad_handler" deps = [ "//components/crash/core/app:chrome_crashpad_handler" ] } group("electron_symbols") { deps = [ ":egl_syms", ":electron_app_syms", ":electron_framework_syms", ":gles_syms", ] if (!is_mas_build) { deps += [ ":crashpad_handler_syms" ] } foreach(helper_params, content_mac_helpers) { _helper_target = helper_params[0] deps += [ ":electron_helper_syms_${_helper_target}" ] } } } else { group("electron_symbols") { } } } else { windows_manifest("electron_app_manifest") { sources = [ "shell/browser/resources/win/disable_window_filtering.manifest", "shell/browser/resources/win/dpi_aware.manifest", as_invoker_manifest, common_controls_manifest, default_compatibility_manifest, ] } executable("electron_app") { output_name = electron_project_name if (is_win) { sources = [ "shell/app/electron_main_win.cc" ] } else if (is_linux) { sources = [ "shell/app/electron_main_linux.cc", "shell/app/uv_stdio_fix.cc", "shell/app/uv_stdio_fix.h", ] } include_dirs = [ "." ] deps = [ ":default_app_asar", ":electron_app_manifest", ":electron_lib", ":packed_resources", "//components/crash/core/app", "//content:sandbox_helper_win", "//electron/buildflags", "//ui/strings", ] data = [] data_deps = [] data += [ "$root_out_dir/resources.pak" ] data += [ "$root_out_dir/chrome_100_percent.pak" ] if (enable_hidpi) { data += [ "$root_out_dir/chrome_200_percent.pak" ] } foreach(locale, platform_pak_locales) { data += [ "$root_out_dir/locales/$locale.pak" ] } if (!is_mac) { data += [ "$root_out_dir/resources/default_app.asar" ] } if (use_v8_context_snapshot) { public_deps = [ "//tools/v8_context_snapshot:v8_context_snapshot" ] } if (is_linux) { data_deps += [ "//components/crash/core/app:chrome_crashpad_handler" ] } if (is_win) { sources += [ # TODO: we should be generating our .rc files more like how chrome does "shell/browser/resources/win/electron.rc", "shell/browser/resources/win/resource.h", ] deps += [ "//components/browser_watcher:browser_watcher_client", "//components/crash/core/app:run_as_crashpad_handler", ] ldflags = [] libs = [ "comctl32.lib", "uiautomationcore.lib", "wtsapi32.lib", ] configs -= [ "//build/config/win:console" ] configs += [ "//build/config/win:windowed", "//build/config/win:delayloads", ] if (current_cpu == "x86") { # Set the initial stack size to 0.5MiB, instead of the 1.5MiB needed by # Chrome's main thread. This saves significant memory on threads (like # those in the Windows thread pool, and others) whose stack size we can # only control through this setting. Because Chrome's main thread needs # a minimum 1.5 MiB stack, the main thread (in 32-bit builds only) uses # fibers to switch to a 1.5 MiB stack before running any other code. ldflags += [ "/STACK:0x80000" ] } else { # Increase the initial stack size. The default is 1MB, this is 8MB. ldflags += [ "/STACK:0x800000" ] } # This is to support renaming of electron.exe. node-gyp has hard-coded # executable names which it will recognise as node. This module definition # file claims that the electron executable is in fact named "node.exe", # which is one of the executable names that node-gyp recognizes. # See https://github.com/nodejs/node-gyp/commit/52ceec3a6d15de3a8f385f43dbe5ecf5456ad07a ldflags += [ "/DEF:" + rebase_path("build/electron.def", root_build_dir) ] inputs = [ "shell/browser/resources/win/electron.ico", "build/electron.def", ] } if (is_linux) { ldflags = [ "-pie", # Required for exporting all symbols of libuv. "-Wl,--whole-archive", "obj/third_party/electron_node/deps/uv/libuv.a", "-Wl,--no-whole-archive", ] if (!is_component_build && is_component_ffmpeg) { configs += [ "//build/config/gcc:rpath_for_built_shared_libraries" ] } if (is_linux) { deps += [ "//sandbox/linux:chrome_sandbox" ] } } } if (is_official_build) { if (is_linux) { _target_executable_suffix = "" _target_shared_library_suffix = ".so" } else if (is_win) { _target_executable_suffix = ".exe" _target_shared_library_suffix = ".dll" } extract_symbols("electron_app_symbols") { binary = "$root_out_dir/$electron_project_name$_target_executable_suffix" symbol_dir = "$root_out_dir/breakpad_symbols" deps = [ ":electron_app" ] } extract_symbols("egl_symbols") { binary = "$root_out_dir/libEGL$_target_shared_library_suffix" symbol_dir = "$root_out_dir/breakpad_symbols" deps = [ "//third_party/angle:libEGL" ] } extract_symbols("gles_symbols") { binary = "$root_out_dir/libGLESv2$_target_shared_library_suffix" symbol_dir = "$root_out_dir/breakpad_symbols" deps = [ "//third_party/angle:libGLESv2" ] } group("electron_symbols") { deps = [ ":egl_symbols", ":electron_app_symbols", ":gles_symbols", ] } } } test("shell_browser_ui_unittests") { sources = [ "//electron/shell/browser/ui/accelerator_util_unittests.cc", "//electron/shell/browser/ui/run_all_unittests.cc", ] configs += [ ":electron_lib_config" ] deps = [ ":electron_lib", "//base", "//base/test:test_support", "//testing/gmock", "//testing/gtest", "//ui/base", "//ui/strings", ] } template("dist_zip") { _runtime_deps_target = "${target_name}__deps" _runtime_deps_file = "$root_out_dir/gen.runtime/" + get_label_info(target_name, "dir") + "/" + get_label_info(target_name, "name") + ".runtime_deps" group(_runtime_deps_target) { forward_variables_from(invoker, [ "deps", "data_deps", "data", "testonly", ]) write_runtime_deps = _runtime_deps_file } action(target_name) { script = "//electron/build/zip.py" deps = [ ":$_runtime_deps_target" ] forward_variables_from(invoker, [ "outputs", "testonly", ]) flatten = false flatten_relative_to = false if (defined(invoker.flatten)) { flatten = invoker.flatten if (defined(invoker.flatten_relative_to)) { flatten_relative_to = invoker.flatten_relative_to } } args = rebase_path(outputs + [ _runtime_deps_file ], root_build_dir) + [ target_cpu, target_os, "$flatten", "$flatten_relative_to", ] } } copy("electron_license") { sources = [ "LICENSE" ] outputs = [ "$root_build_dir/{{source_file_part}}" ] } copy("chromium_licenses") { deps = [ "//components/resources:about_credits" ] sources = [ "$root_gen_dir/components/resources/about_credits.html" ] outputs = [ "$root_build_dir/LICENSES.chromium.html" ] } group("licenses") { data_deps = [ ":chromium_licenses", ":electron_license", ] } copy("electron_version") { sources = [ "ELECTRON_VERSION" ] outputs = [ "$root_build_dir/version" ] } dist_zip("electron_dist_zip") { data_deps = [ ":electron_app", ":electron_version", ":licenses", ] if (is_linux) { data_deps += [ "//sandbox/linux:chrome_sandbox" ] } deps = data_deps outputs = [ "$root_build_dir/dist.zip" ] } dist_zip("electron_ffmpeg_zip") { data_deps = [ "//third_party/ffmpeg" ] deps = data_deps outputs = [ "$root_build_dir/ffmpeg.zip" ] } electron_chromedriver_deps = [ ":licenses", "//chrome/test/chromedriver", "//electron/buildflags", ] group("electron_chromedriver") { testonly = true public_deps = electron_chromedriver_deps } dist_zip("electron_chromedriver_zip") { testonly = true data_deps = electron_chromedriver_deps deps = data_deps outputs = [ "$root_build_dir/chromedriver.zip" ] } mksnapshot_deps = [ ":licenses", "//v8:mksnapshot($v8_snapshot_toolchain)", ] if (use_v8_context_snapshot) { mksnapshot_deps += [ "//tools/v8_context_snapshot:v8_context_snapshot_generator($v8_snapshot_toolchain)" ] } group("electron_mksnapshot") { public_deps = mksnapshot_deps } dist_zip("electron_mksnapshot_zip") { data_deps = mksnapshot_deps deps = data_deps outputs = [ "$root_build_dir/mksnapshot.zip" ] } copy("hunspell_dictionaries") { sources = hunspell_dictionaries + hunspell_licenses outputs = [ "$target_gen_dir/electron_hunspell/{{source_file_part}}" ] } dist_zip("hunspell_dictionaries_zip") { data_deps = [ ":hunspell_dictionaries" ] deps = data_deps flatten = true outputs = [ "$root_build_dir/hunspell_dictionaries.zip" ] } copy("libcxx_headers") { sources = libcxx_headers + libcxx_licenses + [ "//buildtools/third_party/libc++/__config_site" ] outputs = [ "$target_gen_dir/electron_libcxx_include/{{source_root_relative_dir}}/{{source_file_part}}" ] } dist_zip("libcxx_headers_zip") { data_deps = [ ":libcxx_headers" ] deps = data_deps flatten = true flatten_relative_to = rebase_path( "$target_gen_dir/electron_libcxx_include/buildtools/third_party/libc++/trunk", "$root_out_dir") outputs = [ "$root_build_dir/libcxx_headers.zip" ] } copy("libcxxabi_headers") { sources = libcxxabi_headers + libcxxabi_licenses outputs = [ "$target_gen_dir/electron_libcxxabi_include/{{source_root_relative_dir}}/{{source_file_part}}" ] } dist_zip("libcxxabi_headers_zip") { data_deps = [ ":libcxxabi_headers" ] deps = data_deps flatten = true flatten_relative_to = rebase_path( "$target_gen_dir/electron_libcxxabi_include/buildtools/third_party/libc++abi/trunk", "$root_out_dir") outputs = [ "$root_build_dir/libcxxabi_headers.zip" ] } action("libcxx_objects_zip") { deps = [ "//buildtools/third_party/libc++" ] script = "build/zip_libcxx.py" outputs = [ "$root_build_dir/libcxx_objects.zip" ] args = rebase_path(outputs) } group("electron") { public_deps = [ ":electron_app" ] }
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
patches/chromium/make_gtk_getlibgtk_public.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: deepak1556 <[email protected]> Date: Thu, 7 Apr 2022 20:30:16 +0900 Subject: Make gtk::GetLibGtk public Allows embedders to get a handle to the gtk library already loaded in the process. diff --git a/ui/gtk/gtk_compat.cc b/ui/gtk/gtk_compat.cc index b5c7af5bdb93b320f95252d35d2d76bae7f8c445..40b706ed7cde206e98274025148604760b7477f9 100644 --- a/ui/gtk/gtk_compat.cc +++ b/ui/gtk/gtk_compat.cc @@ -86,12 +86,6 @@ void* GetLibGtk4(bool check = true) { return libgtk4; } -void* GetLibGtk() { - if (GtkCheckVersion(4)) - return GetLibGtk4(); - return GetLibGtk3(); -} - bool LoadGtk3() { if (!GetLibGtk3(false)) return false; @@ -134,6 +128,12 @@ gfx::Insets InsetsFromGtkBorder(const GtkBorder& border) { } // namespace +void* GetLibGtk() { + if (GtkCheckVersion(4)) + return GetLibGtk4(); + return GetLibGtk3(); +} + bool LoadGtk() { static bool loaded = LoadGtkImpl(); return loaded; diff --git a/ui/gtk/gtk_compat.h b/ui/gtk/gtk_compat.h index 57e55b9e749b43d327deff449a530e1f435a8e8b..2245974f91be4a691d82f54b55e12e44ae2000c5 100644 --- a/ui/gtk/gtk_compat.h +++ b/ui/gtk/gtk_compat.h @@ -34,6 +34,9 @@ using SkColor = uint32_t; namespace gtk { +// Get handle to the currently loaded gtk library in the process. +void* GetLibGtk(); + // Loads libgtk and related libraries and returns true on success. bool LoadGtk();
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
shell/browser/electron_browser_main_parts.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_main_parts.h" #include <memory> #include <string> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/icon_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/key_storage_config_linux.h" #include "components/os_crypt/os_crypt.h" #include "content/browser/browser_main_loop.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/device_service.h" #include "content/public/browser/first_party_sets_handler.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "media/base/localized_strings.h" #include "services/network/public/cpp/features.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/electron_main_delegate.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/browser.h" #include "shell/browser/browser_process_impl.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_web_ui_controller_factory.h" #include "shell/browser/feature_list.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_helper/trackable_object.h" #include "shell/common/logging.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/idle/idle.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_switches.h" #if defined(USE_AURA) #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/wm/core/wm_state.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "base/threading/thread_task_runner_handle.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h" #include "electron/electron_gtk_stubs.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/gfx/color_utils.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/ozone/public/ozone_platform.h" #include "ui/views/linux_ui/linux_ui.h" #include "ui/views/linux_ui/linux_ui_factory.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/l10n/l10n_util_win.h" #include "ui/display/win/dpi.h" #include "ui/gfx/system_fonts_win.h" #include "ui/strings/grit/app_locale_settings.h" #endif #if BUILDFLAG(IS_MAC) #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "shell/browser/ui/cocoa/views_delegate_mac.h" #else #include "shell/browser/ui/views/electron_views_delegate.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #endif namespace electron { namespace { template <typename T> void Erase(T* container, typename T::iterator iter) { container->erase(iter); } #if BUILDFLAG(IS_WIN) // gfx::Font callbacks void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) { l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override, &font_adjustment->font_scale); font_adjustment->font_scale *= display::win::GetAccessibilityFontScale(); } int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } #endif std::u16string MediaStringProvider(media::MessageId id) { switch (id) { case media::DEFAULT_AUDIO_DEVICE_NAME: return u"Default"; #if BUILDFLAG(IS_WIN) case media::COMMUNICATIONS_AUDIO_DEVICE_NAME: return u"Communications"; #endif default: return std::u16string(); } } #if BUILDFLAG(IS_LINUX) // GTK does not provide a way to check if current theme is dark, so we compare // the text and background luminosity to get a result. // This trick comes from FireFox. void UpdateDarkThemeSetting() { float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel")); float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel")); bool is_dark = fg > bg; // Pass it to NativeUi theme, which is used by the nativeTheme module and most // places in Electron. ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark); // Pass it to Web Theme, to make "prefers-color-scheme" media query work. ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark); } #endif } // namespace #if BUILDFLAG(IS_LINUX) class DarkThemeObserver : public ui::NativeThemeObserver { public: DarkThemeObserver() = default; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override { UpdateDarkThemeSetting(); } }; #endif // static ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr; ElectronBrowserMainParts::ElectronBrowserMainParts() : fake_browser_process_(std::make_unique<BrowserProcessImpl>()), browser_(std::make_unique<Browser>()), node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) { DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts"; self_ = this; } ElectronBrowserMainParts::~ElectronBrowserMainParts() = default; // static ElectronBrowserMainParts* ElectronBrowserMainParts::Get() { DCHECK(self_); return self_; } bool ElectronBrowserMainParts::SetExitCode(int code) { if (!exit_code_) return false; content::BrowserMainLoop::GetInstance()->SetResultCode(code); *exit_code_ = code; return true; } int ElectronBrowserMainParts::GetExitCode() const { return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT); } int ElectronBrowserMainParts::PreEarlyInitialization() { field_trial_list_ = std::make_unique<base::FieldTrialList>(nullptr); #if BUILDFLAG(IS_POSIX) HandleSIGCHLD(); #endif #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::PreEarlyInitialization(); #endif return GetExitCode(); } void ElectronBrowserMainParts::PostEarlyInitialization() { // A workaround was previously needed because there was no ThreadTaskRunner // set. If this check is failing we may need to re-add that workaround DCHECK(base::ThreadTaskRunnerHandle::IsSet()); // The ProxyResolverV8 has setup a complete V8 environment, in order to // avoid conflicts we only initialize our V8 environment after that. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); v8::HandleScope scope(js_env_->isolate()); node_bindings_->Initialize(); // Create the global environment. node::Environment* env = node_bindings_->CreateEnvironment( js_env_->context(), js_env_->platform()); node_env_ = std::make_unique<NodeEnvironment>(env); env->set_trace_sync_io(env->options()->trace_sync_io); // We do not want to crash the main process on unhandled rejections. env->options()->unhandled_rejections = "warn"; // Add Electron extended APIs. electron_bindings_->BindTo(js_env_->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // Wrap the uv loop with global env. node_bindings_->set_uv_env(env); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line // switches at that point. Lets reinitialize it here to pick up the // command-line changes. base::FeatureList::ClearInstanceForTesting(); InitializeFeatureList(); // Initialize field trials. InitializeFieldTrials(); // Reinitialize logging now that the app has had a chance to set the app name // and/or user data directory. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ false); // Initialize after user script environment creation. fake_browser_process_->PostEarlyInitialization(); } int ElectronBrowserMainParts::PreCreateThreads() { #if defined(USE_AURA) screen_ = views::CreateDesktopScreen(); display::Screen::SetScreenInstance(screen_.get()); #endif if (!views::LayoutProvider::Get()) layout_provider_ = std::make_unique<views::LayoutProvider>(); auto* command_line = base::CommandLine::ForCurrentProcess(); std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); #if BUILDFLAG(IS_MAC) // The browser process only wants to support the language Cocoa will use, // so force the app locale to be overridden with that value. This must // happen before the ResourceBundle is loaded if (locale.empty()) l10n_util::OverrideLocaleWithCocoaLocale(); #elif BUILDFLAG(IS_LINUX) // l10n_util::GetApplicationLocaleInternal uses g_get_language_names(), // which keys off of getenv("LC_ALL"). // We must set this env first to make ui::ResourceBundle accept the custom // locale. auto env = base::Environment::Create(); absl::optional<std::string> lc_all; if (!locale.empty()) { std::string str; if (env->GetVar("LC_ALL", &str)) lc_all.emplace(std::move(str)); env->SetVar("LC_ALL", locale.c_str()); } #endif // Load resources bundle according to locale. std::string loaded_locale = LoadResourceBundle(locale); // Initialize the app locale. std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale); ElectronBrowserClient::SetApplicationLocale(app_locale); fake_browser_process_->SetApplicationLocale(app_locale); #if BUILDFLAG(IS_LINUX) // Reset to the original LC_ALL since we should not be changing it. if (!locale.empty()) { if (lc_all) env->SetVar("LC_ALL", *lc_all); else env->UnSetVar("LC_ALL"); } #endif // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); #if BUILDFLAG(IS_MAC) ui::InitIdleMonitor(); #endif fake_browser_process_->PreCreateThreads(); // Notify observers. Browser::Get()->PreCreateThreads(); return 0; } void ElectronBrowserMainParts::PostCreateThreads() { content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); } void ElectronBrowserMainParts::PostDestroyThreads() { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_browser_client_.reset(); extensions::ExtensionsBrowserClient::Set(nullptr); #endif #if BUILDFLAG(IS_LINUX) device::BluetoothAdapterFactory::Shutdown(); bluez::DBusBluezManagerWrapperLinux::Shutdown(); #endif fake_browser_process_->PostDestroyThreads(); } void ElectronBrowserMainParts::ToolkitInitialized() { #if BUILDFLAG(IS_LINUX) auto linux_ui = CreateLinuxUi(); DCHECK(ui::LinuxInputMethodContextFactory::instance()); // Try loading gtk symbols used by Electron. electron::InitializeElectron_gtk(gtk::GetLibGtk()); if (!electron::IsElectron_gtkInitialized()) { electron::UninitializeElectron_gtk(); } // Chromium does not respect GTK dark theme setting, but they may change // in future and this code might be no longer needed. Check the Chromium // issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=998903 UpdateDarkThemeSetting(); // Update the native theme when GTK theme changes. The GetNativeTheme // here returns a NativeThemeGtk, which monitors GTK settings. dark_theme_observer_ = std::make_unique<DarkThemeObserver>(); linux_ui->GetNativeTheme(nullptr)->AddObserver(dark_theme_observer_.get()); views::LinuxUI::SetInstance(std::move(linux_ui)); // Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager // implementation). Start observing them once it's initialized. ui::CursorFactory::GetInstance()->ObserveThemeChanges(); #endif #if defined(USE_AURA) wm_state_ = std::make_unique<wm::WMState>(); #endif #if BUILDFLAG(IS_WIN) gfx::win::SetAdjustFontCallback(&AdjustUIFont); gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize); #endif #if BUILDFLAG(IS_MAC) views_delegate_ = std::make_unique<ViewsDelegateMac>(); #else views_delegate_ = std::make_unique<ViewsDelegate>(); #endif } int ElectronBrowserMainParts::PreMainMessageLoopRun() { // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareEmbedThread(); node_bindings_->StartPolling(); // url::Add*Scheme are not threadsafe, this helps prevent data races. url::LockSchemeRegistries(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_client_ = std::make_unique<ElectronExtensionsClient>(); extensions::ExtensionsClient::Set(extensions_client_.get()); // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient. extensions_browser_client_ = std::make_unique<ElectronExtensionsBrowserClient>(); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt(); extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt(); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckServiceFactory::GetInstance(); #endif content::WebUIControllerFactory::RegisterFactory( ElectronWebUIControllerFactory::GetInstance()); auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) { // --remote-debugging-pipe auto on_disconnect = base::BindOnce([]() { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); })); }); content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler( std::move(on_disconnect)); } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { // --remote-debugging-port DevToolsManagerDelegate::StartHttpHandler(); } #if !BUILDFLAG(IS_MAC) // The corresponding call in macOS is in ElectronApplicationDelegate. Browser::Get()->WillFinishLaunching(); Browser::Get()->DidFinishLaunching(base::DictionaryValue()); #endif // Notify observers that main thread message loop was initialized. Browser::Get()->PreMainMessageLoopRun(); return GetExitCode(); } void ElectronBrowserMainParts::WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) { js_env_->OnMessageLoopCreated(); exit_code_ = content::RESULT_CODE_NORMAL_EXIT; Browser::Get()->SetMainMessageLoopQuitClosure( run_loop->QuitWhenIdleClosure()); } void ElectronBrowserMainParts::PostCreateMainMessageLoop() { #if BUILDFLAG(IS_LINUX) auto shutdown_cb = base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop( std::move(shutdown_cb)); bluez::DBusBluezManagerWrapperLinux::Initialize(); // Set up crypt config. This needs to be done before anything starts the // network service, as the raw encryption key needs to be shared with the // network service for encrypted cookie storage. std::string app_name = electron::Browser::Get()->GetName(); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::unique_ptr<os_crypt::Config> config = std::make_unique<os_crypt::Config>(); // Forward to os_crypt the flag to use a specific password store. config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore); config->product_name = app_name; config->application_name = app_name; config->main_thread_runner = base::ThreadTaskRunnerHandle::Get(); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1 config->should_use_preference = command_line.HasSwitch(::switches::kEnableEncryptionSelection); base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path); OSCrypt::SetConfig(std::move(config)); #endif #if BUILDFLAG(IS_POSIX) // Exit in response to SIGINT, SIGTERM, etc. InstallShutdownSignalHandlers( base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())), content::GetUIThreadTaskRunner({})); #endif } void ElectronBrowserMainParts::PostMainMessageLoopRun() { #if BUILDFLAG(IS_MAC) FreeAppDelegate(); #endif // Shutdown the DownloadManager before destroying Node to prevent // DownloadItem callbacks from crashing. for (auto& iter : ElectronBrowserContext::browser_context_map()) { auto* download_manager = iter.second.get()->GetDownloadManager(); if (download_manager) { download_manager->Shutdown(); } } // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. node_env_->env()->set_trace_sync_io(false); js_env_->OnMessageLoopDestroying(); node::Stop(node_env_->env()); node_env_.reset(); auto default_context_key = ElectronBrowserContext::PartitionKey("", false); std::unique_ptr<ElectronBrowserContext> default_context = std::move( ElectronBrowserContext::browser_context_map()[default_context_key]); ElectronBrowserContext::browser_context_map().clear(); default_context.reset(); fake_browser_process_->PostMainMessageLoopRun(); content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler(); #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun(); #endif } #if !BUILDFLAG(IS_MAC) void ElectronBrowserMainParts::PreCreateMainMessageLoop() { PreCreateMainMessageLoopCommon(); } #endif void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() { #if BUILDFLAG(IS_MAC) InitializeMainNib(); RegisterURLHandler(); #endif media::SetLocalizedStringProvider(MediaStringProvider); #if BUILDFLAG(IS_WIN) auto* local_state = g_browser_process->local_state(); DCHECK(local_state); bool os_crypt_init = OSCrypt::Init(local_state); DCHECK(os_crypt_init); #endif } device::mojom::GeolocationControl* ElectronBrowserMainParts::GetGeolocationControl() { if (!geolocation_control_) { content::GetDeviceService().BindGeolocationControl( geolocation_control_.BindNewPipeAndPassReceiver()); } return geolocation_control_.get(); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserMainParts::GetGeolocationManager() { return geolocation_manager_.get(); } #endif IconManager* ElectronBrowserMainParts::GetIconManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!icon_manager_.get()) icon_manager_ = std::make_unique<IconManager>(); return icon_manager_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
shell/browser/ui/electron_gdk_pixbuf.sigs
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
shell/browser/ui/electron_gtk.fragment
#include <gtk/gtk.h>
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
shell/browser/ui/electron_gtk.sigs
GtkFileChooserNative* gtk_file_chooser_native_new(const gchar* title, GtkWindow* parent, GtkFileChooserAction action, const gchar* accept_label, const gchar* cancel_label); void gtk_native_dialog_set_modal(GtkNativeDialog* self, gboolean modal); void gtk_native_dialog_show(GtkNativeDialog* self); void gtk_native_dialog_hide(GtkNativeDialog* self); gint gtk_native_dialog_run(GtkNativeDialog* self); void gtk_native_dialog_destroy(GtkNativeDialog* self); GType gtk_native_dialog_get_type(void);
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
shell/browser/ui/gtk_util.cc
// Copyright (c) 2019 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/gtk_util.h" #include <gdk/gdk.h> #include <gtk/gtk.h> #include <stdint.h> #include <string> #include "base/no_destructor.h" #include "base/strings/string_number_conversions.h" #include "third_party/skia/include/core/SkBitmap.h" #include "third_party/skia/include/core/SkColor.h" #include "third_party/skia/include/core/SkUnPreMultiply.h" #include "ui/gtk/gtk_compat.h" // nogncheck // The following utilities are pulled from // https://source.chromium.org/chromium/chromium/src/+/main:ui/gtk/select_file_dialog_impl_gtk.cc;l=43-74 namespace gtk_util { namespace { const char* GettextPackage() { static base::NoDestructor<std::string> gettext_package( "gtk" + base::NumberToString(gtk::GtkVersion().components()[0]) + "0"); return gettext_package->c_str(); } const char* GtkGettext(const char* str) { return g_dgettext(GettextPackage(), str); } } // namespace const char* GetCancelLabel() { static const char* cancel = GtkGettext("_Cancel"); return cancel; } const char* GetOpenLabel() { static const char* open = GtkGettext("_Open"); return open; } const char* GetSaveLabel() { static const char* save = GtkGettext("_Save"); return save; } const char* GetOkLabel() { static const char* ok = GtkGettext("_Ok"); return ok; } const char* GetNoLabel() { static const char* no = GtkGettext("_No"); return no; } const char* GetYesLabel() { static const char* yes = GtkGettext("_Yes"); return yes; } GdkPixbuf* GdkPixbufFromSkBitmap(const SkBitmap& bitmap) { if (bitmap.isNull()) return nullptr; int width = bitmap.width(); int height = bitmap.height(); GdkPixbuf* pixbuf = gdk_pixbuf_new(GDK_COLORSPACE_RGB, // The only colorspace gtk supports. TRUE, // There is an alpha channel. 8, width, height); // SkBitmaps are premultiplied, we need to unpremultiply them. const int kBytesPerPixel = 4; uint8_t* divided = gdk_pixbuf_get_pixels(pixbuf); for (int y = 0, i = 0; y < height; y++) { for (int x = 0; x < width; x++) { uint32_t pixel = bitmap.getAddr32(0, y)[x]; int alpha = SkColorGetA(pixel); if (alpha != 0 && alpha != 255) { SkColor unmultiplied = SkUnPreMultiply::PMColorToColor(pixel); divided[i + 0] = SkColorGetR(unmultiplied); divided[i + 1] = SkColorGetG(unmultiplied); divided[i + 2] = SkColorGetB(unmultiplied); divided[i + 3] = alpha; } else { divided[i + 0] = SkColorGetR(pixel); divided[i + 1] = SkColorGetG(pixel); divided[i + 2] = SkColorGetB(pixel); divided[i + 3] = alpha; } i += kBytesPerPixel; } } return pixbuf; } } // namespace gtk_util
closed
electron/electron
https://github.com/electron/electron
34,060
[Bug]: libgdk-pixbuf library is not dynamically linked
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.x.y ### What operating system are you using? Ubuntu ### Operating System Version Xubuntu 20.04, Ubuntu 16.04 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior While porting over Chromium's script to generate dependencies for Debian packages in VS Code (https://github.com/microsoft/vscode/issues/13089), I noticed that libgdk-pixbuf is statically linked rather than dynamically linked. An issue is that the exact name of the library changed over time, so sometimes it is libgdk-pixbuf-2.0-0, and other times it is libgdk-pixbuf2.0-0. Therefore, Electron should look up the library at runtime. ### Actual Behavior Using the Electron sysroot when searching for Debian dependencies, it seems libgdk-pixbuf-2.0-0 is statically linked: https://github.com/microsoft/vscode/pull/147335/files#diff-b84879f8920b8ee14b70af14c40c90a255472a38795104384f64db32f1c7505dR56 I verified in a separate CI run that the dependency is indeed contributed by Electron, and not by other shared libraries that VS Code uses. ### Testcase Gist URL _No response_ ### Additional Information Since libgdk is responsible for rendering menus and file dialogs, I think we should log a message and crash the program if the dependency cannot be found during runtime. CC @deepak1556
https://github.com/electron/electron/issues/34060
https://github.com/electron/electron/pull/34077
b3ec0a801a3c3ad0b789854df830bd3573d8174a
999a225edb6454d4940264ee51d99cd65fa1c2e2
2022-05-03T23:25:08Z
c++
2022-06-20T00:42:30Z
shell/browser/ui/message_box_gtk.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/ui/message_box.h" #include <map> #include "base/callback.h" #include "base/containers/contains.h" #include "base/no_destructor.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_observer.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/gtk_util.h" #include "shell/browser/unresponsive_suppressor.h" #include "ui/base/glib/glib_signal.h" #include "ui/gfx/image/image_skia.h" #include "ui/gtk/gtk_ui.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #if defined(USE_OZONE) #include "ui/base/ui_base_features.h" #endif #define ANSI_FOREGROUND_RED "\x1b[31m" #define ANSI_FOREGROUND_BLACK "\x1b[30m" #define ANSI_TEXT_BOLD "\x1b[1m" #define ANSI_BACKGROUND_GRAY "\x1b[47m" #define ANSI_RESET "\x1b[0m" namespace electron { MessageBoxSettings::MessageBoxSettings() = default; MessageBoxSettings::MessageBoxSettings(const MessageBoxSettings&) = default; MessageBoxSettings::~MessageBoxSettings() = default; namespace { // <ID, messageBox> map std::map<int, GtkWidget*>& GetDialogsMap() { static base::NoDestructor<std::map<int, GtkWidget*>> dialogs; return *dialogs; } class GtkMessageBox : public NativeWindowObserver { public: explicit GtkMessageBox(const MessageBoxSettings& settings) : id_(settings.id), cancel_id_(settings.cancel_id), parent_(static_cast<NativeWindow*>(settings.parent_window)) { // Create dialog. dialog_ = gtk_message_dialog_new(nullptr, // parent static_cast<GtkDialogFlags>(0), // no flags GetMessageType(settings.type), // type GTK_BUTTONS_NONE, // no buttons "%s", settings.message.c_str()); if (id_) GetDialogsMap()[*id_] = dialog_; if (!settings.detail.empty()) gtk_message_dialog_format_secondary_text(GTK_MESSAGE_DIALOG(dialog_), "%s", settings.detail.c_str()); if (!settings.title.empty()) gtk_window_set_title(GTK_WINDOW(dialog_), settings.title.c_str()); if (!settings.icon.isNull()) { // No easy way to obtain this programmatically, but GTK+'s docs // define GTK_ICON_SIZE_DIALOG to be 48 pixels static constexpr int pixel_width = 48; static constexpr int pixel_height = 48; GdkPixbuf* pixbuf = gtk_util::GdkPixbufFromSkBitmap(*settings.icon.bitmap()); GdkPixbuf* scaled_pixbuf = gdk_pixbuf_scale_simple( pixbuf, pixel_width, pixel_height, GDK_INTERP_BILINEAR); GtkWidget* w = gtk_image_new_from_pixbuf(scaled_pixbuf); gtk_message_dialog_set_image(GTK_MESSAGE_DIALOG(dialog_), w); gtk_widget_show(w); g_clear_pointer(&scaled_pixbuf, g_object_unref); g_clear_pointer(&pixbuf, g_object_unref); } if (!settings.checkbox_label.empty()) { GtkWidget* message_area = gtk_message_dialog_get_message_area(GTK_MESSAGE_DIALOG(dialog_)); GtkWidget* check_button = gtk_check_button_new_with_label(settings.checkbox_label.c_str()); g_signal_connect(check_button, "toggled", G_CALLBACK(OnCheckboxToggledThunk), this); gtk_toggle_button_set_active(GTK_TOGGLE_BUTTON(check_button), settings.checkbox_checked); gtk_container_add(GTK_CONTAINER(message_area), check_button); gtk_widget_show(check_button); } // Add buttons. GtkDialog* dialog = GTK_DIALOG(dialog_); if (settings.buttons.size() == 0) { gtk_dialog_add_button(dialog, TranslateToStock(0, "OK"), 0); } else { for (size_t i = 0; i < settings.buttons.size(); ++i) { gtk_dialog_add_button(dialog, TranslateToStock(i, settings.buttons[i]), i); } } gtk_dialog_set_default_response(dialog, settings.default_id); // Parent window. if (parent_) { parent_->AddObserver(this); static_cast<NativeWindowViews*>(parent_)->SetEnabled(false); gtk::SetGtkTransientForAura(dialog_, parent_->GetNativeWindow()); gtk_window_set_modal(GTK_WINDOW(dialog_), TRUE); } } ~GtkMessageBox() override { gtk_widget_destroy(dialog_); if (parent_) { parent_->RemoveObserver(this); static_cast<NativeWindowViews*>(parent_)->SetEnabled(true); } } // disable copy GtkMessageBox(const GtkMessageBox&) = delete; GtkMessageBox& operator=(const GtkMessageBox&) = delete; GtkMessageType GetMessageType(MessageBoxType type) { switch (type) { case MessageBoxType::kInformation: return GTK_MESSAGE_INFO; case MessageBoxType::kWarning: return GTK_MESSAGE_WARNING; case MessageBoxType::kQuestion: return GTK_MESSAGE_QUESTION; case MessageBoxType::kError: return GTK_MESSAGE_ERROR; default: return GTK_MESSAGE_OTHER; } } const char* TranslateToStock(int id, const std::string& text) { const std::string lower = base::ToLowerASCII(text); if (lower == "cancel") return gtk_util::GetCancelLabel(); if (lower == "no") return gtk_util::GetNoLabel(); if (lower == "ok") return gtk_util::GetOkLabel(); if (lower == "yes") return gtk_util::GetYesLabel(); return text.c_str(); } void Show() { gtk_widget_show(dialog_); gtk::GtkUi::GetPlatform()->ShowGtkWindow(GTK_WINDOW(dialog_)); } int RunSynchronous() { Show(); int response = gtk_dialog_run(GTK_DIALOG(dialog_)); return (response < 0) ? cancel_id_ : response; } void RunAsynchronous(MessageBoxCallback callback) { callback_ = std::move(callback); g_signal_connect(dialog_, "delete-event", G_CALLBACK(gtk_widget_hide_on_delete), nullptr); g_signal_connect(dialog_, "response", G_CALLBACK(OnResponseDialogThunk), this); Show(); } void OnWindowClosed() override { parent_->RemoveObserver(this); parent_ = nullptr; } CHROMEG_CALLBACK_1(GtkMessageBox, void, OnResponseDialog, GtkWidget*, int); CHROMEG_CALLBACK_0(GtkMessageBox, void, OnCheckboxToggled, GtkWidget*); private: electron::UnresponsiveSuppressor unresponsive_suppressor_; // The id of the dialog. absl::optional<int> id_; // The id to return when the dialog is closed without pressing buttons. int cancel_id_ = 0; bool checkbox_checked_ = false; NativeWindow* parent_; GtkWidget* dialog_; MessageBoxCallback callback_; }; void GtkMessageBox::OnResponseDialog(GtkWidget* widget, int response) { if (id_) GetDialogsMap().erase(*id_); gtk_widget_hide(dialog_); if (response < 0) std::move(callback_).Run(cancel_id_, checkbox_checked_); else std::move(callback_).Run(response, checkbox_checked_); delete this; } void GtkMessageBox::OnCheckboxToggled(GtkWidget* widget) { checkbox_checked_ = gtk_toggle_button_get_active(GTK_TOGGLE_BUTTON(widget)); } } // namespace int ShowMessageBoxSync(const MessageBoxSettings& settings) { return GtkMessageBox(settings).RunSynchronous(); } void ShowMessageBox(const MessageBoxSettings& settings, MessageBoxCallback callback) { if (settings.id && base::Contains(GetDialogsMap(), *settings.id)) CloseMessageBox(*settings.id); (new GtkMessageBox(settings))->RunAsynchronous(std::move(callback)); } void CloseMessageBox(int id) { auto it = GetDialogsMap().find(id); if (it == GetDialogsMap().end()) { LOG(ERROR) << "CloseMessageBox called with nonexistent ID"; return; } gtk_window_close(GTK_WINDOW(it->second)); } void ShowErrorBox(const std::u16string& title, const std::u16string& content) { if (Browser::Get()->is_ready()) { electron::MessageBoxSettings settings; settings.type = electron::MessageBoxType::kError; settings.buttons = {}; settings.title = "Error"; settings.message = base::UTF16ToUTF8(title); settings.detail = base::UTF16ToUTF8(content); GtkMessageBox(settings).RunSynchronous(); } else { fprintf(stderr, ANSI_TEXT_BOLD ANSI_BACKGROUND_GRAY ANSI_FOREGROUND_RED "%s\n" ANSI_FOREGROUND_BLACK "%s" ANSI_RESET "\n", base::UTF16ToUTF8(title).c_str(), base::UTF16ToUTF8(content).c_str()); } } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,321
[Bug]: `crashReporter.start` blocks main process takes more than 600ms on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.4 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 18.2.4 ### Expected Behavior Expect `crashReporter.start` to return quickly. It takes only 33ms in `Electron@11` with the same code on the same machine. ### Actual Behavior It seems that #33072 does not the same question. `crashReporter.start` takes a long time while `spawn` returns quickly, and seriously delay the app startup. ```javascript /** [email protected], [email protected] */ console.time('crashReporter') crashReporter.start({ submitURL: 'https://your-domain.com/url-to-submit' }) console.timeEnd('crashReporter') // => crashReporter: 762.32ms console.time('spawn') child_process.spawn('ls') console.timeEnd('spawn') // => spawn: 3.836ms ``` ```javascript /** [email protected], [email protected] */ console.time('crashReporter') crashReporter.start({ submitURL: 'https://your-domain.com/url-to-submit' }) console.timeEnd('crashReporter') // => crashReporter: 32.330ms console.time('spawn') child_process.spawn('ls') console.timeEnd('spawn') // => spawn: 6.081ms ``` ### Testcase Gist URL https://gist.github.com/cupools/9336a79b76ef5da2b61105a63c796824 ### Additional Information _No response_
https://github.com/electron/electron/issues/34321
https://github.com/electron/electron/pull/34609
bf4efb693b571addc1b3ce8ed78288abdc9967a0
ec98e95b8ac48a313cd8acb1c723829e40b108df
2022-05-23T14:15:58Z
c++
2022-06-20T04:31:29Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch v8_context_snapshot_generator.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch chore_expose_v8_initialization_isolate_callbacks.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch
closed
electron/electron
https://github.com/electron/electron
34,321
[Bug]: `crashReporter.start` blocks main process takes more than 600ms on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.4 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 18.2.4 ### Expected Behavior Expect `crashReporter.start` to return quickly. It takes only 33ms in `Electron@11` with the same code on the same machine. ### Actual Behavior It seems that #33072 does not the same question. `crashReporter.start` takes a long time while `spawn` returns quickly, and seriously delay the app startup. ```javascript /** [email protected], [email protected] */ console.time('crashReporter') crashReporter.start({ submitURL: 'https://your-domain.com/url-to-submit' }) console.timeEnd('crashReporter') // => crashReporter: 762.32ms console.time('spawn') child_process.spawn('ls') console.timeEnd('spawn') // => spawn: 3.836ms ``` ```javascript /** [email protected], [email protected] */ console.time('crashReporter') crashReporter.start({ submitURL: 'https://your-domain.com/url-to-submit' }) console.timeEnd('crashReporter') // => crashReporter: 32.330ms console.time('spawn') child_process.spawn('ls') console.timeEnd('spawn') // => spawn: 6.081ms ``` ### Testcase Gist URL https://gist.github.com/cupools/9336a79b76ef5da2b61105a63c796824 ### Additional Information _No response_
https://github.com/electron/electron/issues/34321
https://github.com/electron/electron/pull/34609
bf4efb693b571addc1b3ce8ed78288abdc9967a0
ec98e95b8ac48a313cd8acb1c723829e40b108df
2022-05-23T14:15:58Z
c++
2022-06-20T04:31:29Z
patches/chromium/posix_replace_doubleforkandexec_with_forkandspawn.patch
closed
electron/electron
https://github.com/electron/electron
34,321
[Bug]: `crashReporter.start` blocks main process takes more than 600ms on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.4 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 18.2.4 ### Expected Behavior Expect `crashReporter.start` to return quickly. It takes only 33ms in `Electron@11` with the same code on the same machine. ### Actual Behavior It seems that #33072 does not the same question. `crashReporter.start` takes a long time while `spawn` returns quickly, and seriously delay the app startup. ```javascript /** [email protected], [email protected] */ console.time('crashReporter') crashReporter.start({ submitURL: 'https://your-domain.com/url-to-submit' }) console.timeEnd('crashReporter') // => crashReporter: 762.32ms console.time('spawn') child_process.spawn('ls') console.timeEnd('spawn') // => spawn: 3.836ms ``` ```javascript /** [email protected], [email protected] */ console.time('crashReporter') crashReporter.start({ submitURL: 'https://your-domain.com/url-to-submit' }) console.timeEnd('crashReporter') // => crashReporter: 32.330ms console.time('spawn') child_process.spawn('ls') console.timeEnd('spawn') // => spawn: 6.081ms ``` ### Testcase Gist URL https://gist.github.com/cupools/9336a79b76ef5da2b61105a63c796824 ### Additional Information _No response_
https://github.com/electron/electron/issues/34321
https://github.com/electron/electron/pull/34609
bf4efb693b571addc1b3ce8ed78288abdc9967a0
ec98e95b8ac48a313cd8acb1c723829e40b108df
2022-05-23T14:15:58Z
c++
2022-06-20T04:31:29Z
patches/chromium/.patches
build_gn.patch dcheck.patch accelerator.patch blink_file_path.patch blink_local_frame.patch can_create_window.patch disable_hidden.patch dom_storage_limits.patch render_widget_host_view_base.patch render_widget_host_view_mac.patch webview_cross_drag.patch gin_enable_disable_v8_platform.patch disable-redraw-lock.patch enable_reset_aspect_ratio.patch v8_context_snapshot_generator.patch boringssl_build_gn.patch pepper_plugin_support.patch gtk_visibility.patch sysroot.patch resource_file_conflict.patch scroll_bounce_flag.patch mas_blink_no_private_api.patch mas_no_private_api.patch mas-cgdisplayusesforcetogray.patch mas_disable_remote_layer.patch mas_disable_remote_accessibility.patch mas_disable_custom_window_frame.patch mas_avoid_usage_of_private_macos_apis.patch mas_use_public_apis_to_determine_if_a_font_is_a_system_font.patch chrome_key_systems.patch add_didinstallconditionalfeatures.patch desktop_media_list.patch proxy_config_monitor.patch gritsettings_resource_ids.patch isolate_holder.patch notification_provenance.patch dump_syms.patch command-ismediakey.patch printing.patch support_mixed_sandbox_with_zygote.patch unsandboxed_ppapi_processes_skip_zygote.patch build_add_electron_tracing_category.patch worker_context_will_destroy.patch frame_host_manager.patch crashpad_pid_check.patch network_service_allow_remote_certificate_verification_logic.patch disable_color_correct_rendering.patch add_contentgpuclient_precreatemessageloop_callback.patch picture-in-picture.patch disable_compositor_recycling.patch allow_new_privileges_in_unsandboxed_child_processes.patch expose_setuseragent_on_networkcontext.patch feat_add_set_theme_source_to_allow_apps_to.patch add_webmessageportconverter_entangleandinjectmessageportchannel.patch ignore_rc_check.patch remove_usage_of_incognito_apis_in_the_spellchecker.patch allow_disabling_blink_scheduler_throttling_per_renderview.patch hack_plugin_response_interceptor_to_point_to_electron.patch feat_add_support_for_overriding_the_base_spellchecker_download_url.patch feat_enable_offscreen_rendering_with_viz_compositor.patch gpu_notify_when_dxdiag_request_fails.patch feat_allow_embedders_to_add_observers_on_created_hunspell.patch feat_add_onclose_to_messageport.patch allow_in-process_windows_to_have_different_web_prefs.patch refactor_expose_cursor_changes_to_the_webcontentsobserver.patch crash_allow_setting_more_options.patch breakpad_treat_node_processes_as_browser_processes.patch upload_list_add_loadsync_method.patch breakpad_allow_getting_string_values_for_crash_keys.patch crash_allow_disabling_compression_on_linux.patch allow_setting_secondary_label_via_simplemenumodel.patch feat_add_streaming-protocol_registry_to_multibuffer_data_source.patch fix_patch_out_profile_refs_in_accessibility_ui.patch skip_atk_toolchain_check.patch worker_feat_add_hook_to_notify_script_ready.patch chore_provide_iswebcontentscreationoverridden_with_full_params.patch fix_properly_honor_printing_page_ranges.patch chore_expose_v8_initialization_isolate_callbacks.patch export_gin_v8platform_pageallocator_for_usage_outside_of_the_gin.patch fix_export_zlib_symbols.patch don_t_use_potentially_null_getwebframe_-_view_when_get_blink.patch web_contents.patch webview_fullscreen.patch disable_unload_metrics.patch fix_add_check_for_sandbox_then_result.patch extend_apply_webpreferences.patch build_libc_as_static_library.patch build_do_not_depend_on_packed_resource_integrity.patch refactor_restore_base_adaptcallbackforrepeating.patch hack_to_allow_gclient_sync_with_host_os_mac_on_linux_in_ci.patch don_t_run_pcscan_notifythreadcreated_if_pcscan_is_disabled.patch logging_win32_only_create_a_console_if_logging_to_stderr.patch fix_media_key_usage_with_globalshortcuts.patch feat_expose_raw_response_headers_from_urlloader.patch chore_do_not_use_chrome_windows_in_cryptotoken_webrequestsender.patch process_singleton.patch fix_expose_decrementcapturercount_in_web_contents_impl.patch add_ui_scopedcliboardwriter_writeunsaferawdata.patch feat_add_data_parameter_to_processsingleton.patch load_v8_snapshot_in_browser_process.patch fix_adapt_exclusive_access_for_electron_needs.patch fix_aspect_ratio_with_max_size.patch fix_dont_delete_SerialPortManager_on_main_thread.patch fix_crash_when_saving_edited_pdf_files.patch port_autofill_colors_to_the_color_pipeline.patch build_disable_partition_alloc_on_mac.patch fix_non-client_mouse_tracking_and_message_bubbling_on_windows.patch build_make_libcxx_abi_unstable_false_for_electron.patch introduce_ozoneplatform_electron_can_call_x11_property.patch make_gtk_getlibgtk_public.patch build_disable_print_content_analysis.patch custom_protocols_plzserviceworker.patch feat_filter_out_non-shareable_windows_in_the_current_application_in.patch
closed
electron/electron
https://github.com/electron/electron
34,321
[Bug]: `crashReporter.start` blocks main process takes more than 600ms on macOS
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.4 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3.1 ### What arch are you using? x64 ### Last Known Working Electron version 18.2.4 ### Expected Behavior Expect `crashReporter.start` to return quickly. It takes only 33ms in `Electron@11` with the same code on the same machine. ### Actual Behavior It seems that #33072 does not the same question. `crashReporter.start` takes a long time while `spawn` returns quickly, and seriously delay the app startup. ```javascript /** [email protected], [email protected] */ console.time('crashReporter') crashReporter.start({ submitURL: 'https://your-domain.com/url-to-submit' }) console.timeEnd('crashReporter') // => crashReporter: 762.32ms console.time('spawn') child_process.spawn('ls') console.timeEnd('spawn') // => spawn: 3.836ms ``` ```javascript /** [email protected], [email protected] */ console.time('crashReporter') crashReporter.start({ submitURL: 'https://your-domain.com/url-to-submit' }) console.timeEnd('crashReporter') // => crashReporter: 32.330ms console.time('spawn') child_process.spawn('ls') console.timeEnd('spawn') // => spawn: 6.081ms ``` ### Testcase Gist URL https://gist.github.com/cupools/9336a79b76ef5da2b61105a63c796824 ### Additional Information _No response_
https://github.com/electron/electron/issues/34321
https://github.com/electron/electron/pull/34609
bf4efb693b571addc1b3ce8ed78288abdc9967a0
ec98e95b8ac48a313cd8acb1c723829e40b108df
2022-05-23T14:15:58Z
c++
2022-06-20T04:31:29Z
patches/chromium/posix_replace_doubleforkandexec_with_forkandspawn.patch
closed
electron/electron
https://github.com/electron/electron
34,580
[Bug]: BrowserView doesn't always repaint after call to `setBounds`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version v19.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior BrowserView should repaint when bounds are changed. ### Actual Behavior BrowserView does not consistently repaint when bounds are changed. ### Testcase Gist URL https://gist.github.com/de7bb5f18826338729e03441da70e102 ### Additional Information _No response_
https://github.com/electron/electron/issues/34580
https://github.com/electron/electron/pull/34581
ec98e95b8ac48a313cd8acb1c723829e40b108df
e2f42e5d994a27f461e503b72934e3e4111ce29f
2022-06-15T18:34:44Z
c++
2022-06-20T04:31:53Z
shell/browser/native_browser_view_views.cc
// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_browser_view_views.h" #include <vector> #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/views/inspectable_web_contents_view_views.h" #include "ui/gfx/geometry/rect.h" #include "ui/views/background.h" #include "ui/views/view.h" namespace electron { NativeBrowserViewViews::NativeBrowserViewViews( InspectableWebContents* inspectable_web_contents) : NativeBrowserView(inspectable_web_contents) {} NativeBrowserViewViews::~NativeBrowserViewViews() = default; void NativeBrowserViewViews::SetAutoResizeFlags(uint8_t flags) { auto_resize_flags_ = flags; ResetAutoResizeProportions(); } void NativeBrowserViewViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { if (&draggable_regions_ != &regions) draggable_regions_ = mojo::Clone(regions); // We need to snap the regions to the bounds of the current BrowserView. // For example, if an attached BrowserView is draggable but its bounds are // { x: 200, y: 100, width: 300, height: 300 } // then we need to add 200 to the x-value and 100 to the // y-value of each of the passed regions or it will be incorrectly // assumed that the regions begin in the top left corner as they // would for the main client window. auto const offset = GetBounds().OffsetFromOrigin(); for (auto& snapped_region : draggable_regions_) { snapped_region->bounds.Offset(offset); } draggable_region_ = DraggableRegionsToSkRegion(draggable_regions_); } void NativeBrowserViewViews::SetAutoResizeProportions( const gfx::Size& window_size) { if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) && !auto_horizontal_proportion_set_) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); auto view_bounds = view->bounds(); auto_horizontal_proportion_width_ = static_cast<float>(window_size.width()) / static_cast<float>(view_bounds.width()); auto_horizontal_proportion_left_ = static_cast<float>(window_size.width()) / static_cast<float>(view_bounds.x()); auto_horizontal_proportion_set_ = true; } if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) && !auto_vertical_proportion_set_) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); auto view_bounds = view->bounds(); auto_vertical_proportion_height_ = static_cast<float>(window_size.height()) / static_cast<float>(view_bounds.height()); auto_vertical_proportion_top_ = static_cast<float>(window_size.height()) / static_cast<float>(view_bounds.y()); auto_vertical_proportion_set_ = true; } } void NativeBrowserViewViews::AutoResize(const gfx::Rect& new_window, int width_delta, int height_delta) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); const auto flags = GetAutoResizeFlags(); if (!(flags & kAutoResizeWidth)) { width_delta = 0; } if (!(flags & kAutoResizeHeight)) { height_delta = 0; } if (height_delta || width_delta) { auto new_view_size = view->size(); new_view_size.set_width(new_view_size.width() + width_delta); new_view_size.set_height(new_view_size.height() + height_delta); view->SetSize(new_view_size); } auto new_view_bounds = view->bounds(); if (flags & kAutoResizeHorizontal) { new_view_bounds.set_width(new_window.width() / auto_horizontal_proportion_width_); new_view_bounds.set_x(new_window.width() / auto_horizontal_proportion_left_); } if (flags & kAutoResizeVertical) { new_view_bounds.set_height(new_window.height() / auto_vertical_proportion_height_); new_view_bounds.set_y(new_window.height() / auto_vertical_proportion_top_); } if ((flags & kAutoResizeHorizontal) || (flags & kAutoResizeVertical)) { view->SetBoundsRect(new_view_bounds); } } void NativeBrowserViewViews::ResetAutoResizeProportions() { if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) { auto_horizontal_proportion_set_ = false; } if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) { auto_vertical_proportion_set_ = false; } } void NativeBrowserViewViews::SetBounds(const gfx::Rect& bounds) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); view->SetBoundsRect(bounds); ResetAutoResizeProportions(); // Ensure draggable regions are properly updated to reflect new bounds. UpdateDraggableRegions(draggable_regions_); } gfx::Rect NativeBrowserViewViews::GetBounds() { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return gfx::Rect(); return iwc_view->GetView()->bounds(); } void NativeBrowserViewViews::RenderViewReady() { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (iwc_view) iwc_view->GetView()->Layout(); } void NativeBrowserViewViews::SetBackgroundColor(SkColor color) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); view->SetBackground(views::CreateSolidBackground(color)); view->SchedulePaint(); } // static NativeBrowserView* NativeBrowserView::Create( InspectableWebContents* inspectable_web_contents) { return new NativeBrowserViewViews(inspectable_web_contents); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,580
[Bug]: BrowserView doesn't always repaint after call to `setBounds`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version v19.0.0 ### What operating system are you using? Windows ### Operating System Version Windows 10 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior BrowserView should repaint when bounds are changed. ### Actual Behavior BrowserView does not consistently repaint when bounds are changed. ### Testcase Gist URL https://gist.github.com/de7bb5f18826338729e03441da70e102 ### Additional Information _No response_
https://github.com/electron/electron/issues/34580
https://github.com/electron/electron/pull/34581
ec98e95b8ac48a313cd8acb1c723829e40b108df
e2f42e5d994a27f461e503b72934e3e4111ce29f
2022-06-15T18:34:44Z
c++
2022-06-20T04:31:53Z
shell/browser/native_browser_view_views.cc
// Copyright (c) 2017 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_browser_view_views.h" #include <vector> #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/views/inspectable_web_contents_view_views.h" #include "ui/gfx/geometry/rect.h" #include "ui/views/background.h" #include "ui/views/view.h" namespace electron { NativeBrowserViewViews::NativeBrowserViewViews( InspectableWebContents* inspectable_web_contents) : NativeBrowserView(inspectable_web_contents) {} NativeBrowserViewViews::~NativeBrowserViewViews() = default; void NativeBrowserViewViews::SetAutoResizeFlags(uint8_t flags) { auto_resize_flags_ = flags; ResetAutoResizeProportions(); } void NativeBrowserViewViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { if (&draggable_regions_ != &regions) draggable_regions_ = mojo::Clone(regions); // We need to snap the regions to the bounds of the current BrowserView. // For example, if an attached BrowserView is draggable but its bounds are // { x: 200, y: 100, width: 300, height: 300 } // then we need to add 200 to the x-value and 100 to the // y-value of each of the passed regions or it will be incorrectly // assumed that the regions begin in the top left corner as they // would for the main client window. auto const offset = GetBounds().OffsetFromOrigin(); for (auto& snapped_region : draggable_regions_) { snapped_region->bounds.Offset(offset); } draggable_region_ = DraggableRegionsToSkRegion(draggable_regions_); } void NativeBrowserViewViews::SetAutoResizeProportions( const gfx::Size& window_size) { if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) && !auto_horizontal_proportion_set_) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); auto view_bounds = view->bounds(); auto_horizontal_proportion_width_ = static_cast<float>(window_size.width()) / static_cast<float>(view_bounds.width()); auto_horizontal_proportion_left_ = static_cast<float>(window_size.width()) / static_cast<float>(view_bounds.x()); auto_horizontal_proportion_set_ = true; } if ((auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) && !auto_vertical_proportion_set_) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); auto view_bounds = view->bounds(); auto_vertical_proportion_height_ = static_cast<float>(window_size.height()) / static_cast<float>(view_bounds.height()); auto_vertical_proportion_top_ = static_cast<float>(window_size.height()) / static_cast<float>(view_bounds.y()); auto_vertical_proportion_set_ = true; } } void NativeBrowserViewViews::AutoResize(const gfx::Rect& new_window, int width_delta, int height_delta) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); const auto flags = GetAutoResizeFlags(); if (!(flags & kAutoResizeWidth)) { width_delta = 0; } if (!(flags & kAutoResizeHeight)) { height_delta = 0; } if (height_delta || width_delta) { auto new_view_size = view->size(); new_view_size.set_width(new_view_size.width() + width_delta); new_view_size.set_height(new_view_size.height() + height_delta); view->SetSize(new_view_size); } auto new_view_bounds = view->bounds(); if (flags & kAutoResizeHorizontal) { new_view_bounds.set_width(new_window.width() / auto_horizontal_proportion_width_); new_view_bounds.set_x(new_window.width() / auto_horizontal_proportion_left_); } if (flags & kAutoResizeVertical) { new_view_bounds.set_height(new_window.height() / auto_vertical_proportion_height_); new_view_bounds.set_y(new_window.height() / auto_vertical_proportion_top_); } if ((flags & kAutoResizeHorizontal) || (flags & kAutoResizeVertical)) { view->SetBoundsRect(new_view_bounds); } } void NativeBrowserViewViews::ResetAutoResizeProportions() { if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeHorizontal) { auto_horizontal_proportion_set_ = false; } if (auto_resize_flags_ & AutoResizeFlags::kAutoResizeVertical) { auto_vertical_proportion_set_ = false; } } void NativeBrowserViewViews::SetBounds(const gfx::Rect& bounds) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); view->SetBoundsRect(bounds); ResetAutoResizeProportions(); // Ensure draggable regions are properly updated to reflect new bounds. UpdateDraggableRegions(draggable_regions_); } gfx::Rect NativeBrowserViewViews::GetBounds() { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return gfx::Rect(); return iwc_view->GetView()->bounds(); } void NativeBrowserViewViews::RenderViewReady() { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (iwc_view) iwc_view->GetView()->Layout(); } void NativeBrowserViewViews::SetBackgroundColor(SkColor color) { InspectableWebContentsView* iwc_view = GetInspectableWebContentsView(); if (!iwc_view) return; auto* view = iwc_view->GetView(); view->SetBackground(views::CreateSolidBackground(color)); view->SchedulePaint(); } // static NativeBrowserView* NativeBrowserView::Create( InspectableWebContents* inspectable_web_contents) { return new NativeBrowserViewViews(inspectable_web_contents); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,385
[Bug]: BrowserView holds onto media keys in Windows 10 when media is being played from BrowserView
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 16.0.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H2 ### What arch are you using? x64 ### Last Known Working Electron version Unknown ### Expected Behavior 1. Open an Electron application with a BrowserView that contains an embedded YouTube video 2. Press play on the video 3. Pause the video using the Play/Pause media key 4. Switch to another media playing application (eg. Spotify) 5. Press Play/Pause The media from Spotify should start playing ### Actual Behavior The media from the Electron application will play instead. It will always hold onto these keys until the application is closed. ### Testcase Gist URL https://gist.github.com/devinbinnie/92cf5efde8617cbd2a8a478c0397edac ### Additional Information First reproduces on Electron v14.
https://github.com/electron/electron/issues/32385
https://github.com/electron/electron/pull/34594
e2f42e5d994a27f461e503b72934e3e4111ce29f
6e9466f96b48fce7ca98cf308a9c6700ee90733a
2022-01-07T20:26:34Z
c++
2022-06-20T10:40:10Z
patches/chromium/fix_media_key_usage_with_globalshortcuts.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Mon, 16 Aug 2021 17:55:32 +0200 Subject: fix: media key usage with globalShortcuts This patch enables media keys to work properly with Electron's globalShortcut module. Chromium's default usage of RemoteCommandCenterDelegate on macOS falls down into MPRemoteCommandCenter, which makes it such that an app will not receive remote control events until it begins playing audio. This runs counter to the design of globalShortcuts, and so we need to instead use `ui::MediaKeysListener`. diff --git a/chrome/browser/extensions/global_shortcut_listener.cc b/chrome/browser/extensions/global_shortcut_listener.cc index bc009606d01469125052e68a9cdc82aaa697c764..ff18043cb07d748a49adea9874517fb29e3e7f9f 100644 --- a/chrome/browser/extensions/global_shortcut_listener.cc +++ b/chrome/browser/extensions/global_shortcut_listener.cc @@ -7,6 +7,7 @@ #include "base/check.h" #include "base/notreached.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/media_keys_listener_manager.h" #include "ui/base/accelerators/accelerator.h" using content::BrowserThread; @@ -66,6 +67,22 @@ void GlobalShortcutListener::UnregisterAccelerator( StopListening(); } +// static +void GlobalShortcutListener::SetShouldUseInternalMediaKeyHandling(bool should_use) { + if (content::MediaKeysListenerManager:: + IsMediaKeysListenerManagerEnabled()) { + content::MediaKeysListenerManager* media_keys_listener_manager = + content::MediaKeysListenerManager::GetInstance(); + DCHECK(media_keys_listener_manager); + + if (should_use) { + media_keys_listener_manager->EnableInternalMediaKeyHandling(); + } else { + media_keys_listener_manager->DisableInternalMediaKeyHandling(); + } + } +} + void GlobalShortcutListener::UnregisterAccelerators(Observer* observer) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (IsShortcutHandlingSuspended()) diff --git a/chrome/browser/extensions/global_shortcut_listener.h b/chrome/browser/extensions/global_shortcut_listener.h index ad366d0fd4c3a637d75a102ab56984f0d01bfc04..d63eb133fd4bab1ea309bb8c742acf88d97d779e 100644 --- a/chrome/browser/extensions/global_shortcut_listener.h +++ b/chrome/browser/extensions/global_shortcut_listener.h @@ -33,6 +33,8 @@ class GlobalShortcutListener { static GlobalShortcutListener* GetInstance(); + static void SetShouldUseInternalMediaKeyHandling(bool should_use); + // Register an observer for when a certain |accelerator| is struck. Returns // true if register successfully, or false if 1) the specificied |accelerator| // has been registered by another caller or other native applications, or diff --git a/content/browser/media/media_keys_listener_manager_impl.cc b/content/browser/media/media_keys_listener_manager_impl.cc index b954f8dde00d4f5257223c464e9145a6bef48900..b58999f295586a61bcc2648488a8b28f15d80a7e 100644 --- a/content/browser/media/media_keys_listener_manager_impl.cc +++ b/content/browser/media/media_keys_listener_manager_impl.cc @@ -56,7 +56,12 @@ bool MediaKeysListenerManagerImpl::StartWatchingMediaKey( CanActiveMediaSessionControllerReceiveEvents(); // Tell the underlying MediaKeysListener to listen for the key. - if (should_start_watching && media_keys_listener_ && + if ( +#if BUILDFLAG(IS_MAC) + !media_key_handling_enabled_ && +#endif // BUILDFLAG(IS_MAC) + should_start_watching && + media_keys_listener_ && !media_keys_listener_->StartWatchingMediaKey(key_code)) { return false; } @@ -239,18 +244,18 @@ void MediaKeysListenerManagerImpl::StartListeningForMediaKeysIfNecessary() { #endif if (system_media_controls_) { + // This is required for proper functioning of MediaMetadata. system_media_controls_->AddObserver(this); system_media_controls_notifier_ = std::make_unique<SystemMediaControlsNotifier>( system_media_controls_.get()); - } else { - // If we can't access system media controls, then directly listen for media - // key keypresses instead. - media_keys_listener_ = ui::MediaKeysListener::Create( - this, ui::MediaKeysListener::Scope::kGlobal); - DCHECK(media_keys_listener_); } + // Directly listen for media key keypresses when using GlobalShortcuts. + media_keys_listener_ = ui::MediaKeysListener::Create( + this, ui::MediaKeysListener::Scope::kGlobal); + DCHECK(media_keys_listener_); + EnsureAuxiliaryServices(); }
closed
electron/electron
https://github.com/electron/electron
32,385
[Bug]: BrowserView holds onto media keys in Windows 10 when media is being played from BrowserView
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 16.0.1 ### What operating system are you using? Windows ### Operating System Version Windows 10 21H2 ### What arch are you using? x64 ### Last Known Working Electron version Unknown ### Expected Behavior 1. Open an Electron application with a BrowserView that contains an embedded YouTube video 2. Press play on the video 3. Pause the video using the Play/Pause media key 4. Switch to another media playing application (eg. Spotify) 5. Press Play/Pause The media from Spotify should start playing ### Actual Behavior The media from the Electron application will play instead. It will always hold onto these keys until the application is closed. ### Testcase Gist URL https://gist.github.com/devinbinnie/92cf5efde8617cbd2a8a478c0397edac ### Additional Information First reproduces on Electron v14.
https://github.com/electron/electron/issues/32385
https://github.com/electron/electron/pull/34594
e2f42e5d994a27f461e503b72934e3e4111ce29f
6e9466f96b48fce7ca98cf308a9c6700ee90733a
2022-01-07T20:26:34Z
c++
2022-06-20T10:40:10Z
patches/chromium/fix_media_key_usage_with_globalshortcuts.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Mon, 16 Aug 2021 17:55:32 +0200 Subject: fix: media key usage with globalShortcuts This patch enables media keys to work properly with Electron's globalShortcut module. Chromium's default usage of RemoteCommandCenterDelegate on macOS falls down into MPRemoteCommandCenter, which makes it such that an app will not receive remote control events until it begins playing audio. This runs counter to the design of globalShortcuts, and so we need to instead use `ui::MediaKeysListener`. diff --git a/chrome/browser/extensions/global_shortcut_listener.cc b/chrome/browser/extensions/global_shortcut_listener.cc index bc009606d01469125052e68a9cdc82aaa697c764..ff18043cb07d748a49adea9874517fb29e3e7f9f 100644 --- a/chrome/browser/extensions/global_shortcut_listener.cc +++ b/chrome/browser/extensions/global_shortcut_listener.cc @@ -7,6 +7,7 @@ #include "base/check.h" #include "base/notreached.h" #include "content/public/browser/browser_thread.h" +#include "content/public/browser/media_keys_listener_manager.h" #include "ui/base/accelerators/accelerator.h" using content::BrowserThread; @@ -66,6 +67,22 @@ void GlobalShortcutListener::UnregisterAccelerator( StopListening(); } +// static +void GlobalShortcutListener::SetShouldUseInternalMediaKeyHandling(bool should_use) { + if (content::MediaKeysListenerManager:: + IsMediaKeysListenerManagerEnabled()) { + content::MediaKeysListenerManager* media_keys_listener_manager = + content::MediaKeysListenerManager::GetInstance(); + DCHECK(media_keys_listener_manager); + + if (should_use) { + media_keys_listener_manager->EnableInternalMediaKeyHandling(); + } else { + media_keys_listener_manager->DisableInternalMediaKeyHandling(); + } + } +} + void GlobalShortcutListener::UnregisterAccelerators(Observer* observer) { CHECK(BrowserThread::CurrentlyOn(BrowserThread::UI)); if (IsShortcutHandlingSuspended()) diff --git a/chrome/browser/extensions/global_shortcut_listener.h b/chrome/browser/extensions/global_shortcut_listener.h index ad366d0fd4c3a637d75a102ab56984f0d01bfc04..d63eb133fd4bab1ea309bb8c742acf88d97d779e 100644 --- a/chrome/browser/extensions/global_shortcut_listener.h +++ b/chrome/browser/extensions/global_shortcut_listener.h @@ -33,6 +33,8 @@ class GlobalShortcutListener { static GlobalShortcutListener* GetInstance(); + static void SetShouldUseInternalMediaKeyHandling(bool should_use); + // Register an observer for when a certain |accelerator| is struck. Returns // true if register successfully, or false if 1) the specificied |accelerator| // has been registered by another caller or other native applications, or diff --git a/content/browser/media/media_keys_listener_manager_impl.cc b/content/browser/media/media_keys_listener_manager_impl.cc index b954f8dde00d4f5257223c464e9145a6bef48900..b58999f295586a61bcc2648488a8b28f15d80a7e 100644 --- a/content/browser/media/media_keys_listener_manager_impl.cc +++ b/content/browser/media/media_keys_listener_manager_impl.cc @@ -56,7 +56,12 @@ bool MediaKeysListenerManagerImpl::StartWatchingMediaKey( CanActiveMediaSessionControllerReceiveEvents(); // Tell the underlying MediaKeysListener to listen for the key. - if (should_start_watching && media_keys_listener_ && + if ( +#if BUILDFLAG(IS_MAC) + !media_key_handling_enabled_ && +#endif // BUILDFLAG(IS_MAC) + should_start_watching && + media_keys_listener_ && !media_keys_listener_->StartWatchingMediaKey(key_code)) { return false; } @@ -239,18 +244,18 @@ void MediaKeysListenerManagerImpl::StartListeningForMediaKeysIfNecessary() { #endif if (system_media_controls_) { + // This is required for proper functioning of MediaMetadata. system_media_controls_->AddObserver(this); system_media_controls_notifier_ = std::make_unique<SystemMediaControlsNotifier>( system_media_controls_.get()); - } else { - // If we can't access system media controls, then directly listen for media - // key keypresses instead. - media_keys_listener_ = ui::MediaKeysListener::Create( - this, ui::MediaKeysListener::Scope::kGlobal); - DCHECK(media_keys_listener_); } + // Directly listen for media key keypresses when using GlobalShortcuts. + media_keys_listener_ = ui::MediaKeysListener::Create( + this, ui::MediaKeysListener::Scope::kGlobal); + DCHECK(media_keys_listener_); + EnsureAuxiliaryServices(); }
closed
electron/electron
https://github.com/electron/electron
34,603
[Bug]: Deprecated dragging API
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.7 ### What operating system are you using? macOS ### Operating System Version Mac os 10.14 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Remove the deprecation of Dragging API ### Actual Behavior After update to mac os 10.14, I am using this code to drag multiple files ``` event.sender.startDrag({ // Fallback for files parameter file: iconPaths[0], // The paths to the files being dragged. (files will override file field) files: iconPaths, // Preview of the drag and drop file icon: nativeImage.createFromBuffer(iconPreview), }) ``` But when dragging multiple files, I see this alert on the console ``` Dragging multiple files using the deprecated NSFilenamesPboardType and dragging API. Please update to the NSDraggingSession API. ``` After investigate, seems like mac os now recomends to use URL format instead of file paths. more info here https://developer.apple.com/documentation/macos-release-notes/appkit-release-notes-for-macos-10_14 Drag and Drop If you’re using certain deprecated APIs in apps linked on macOS 10.14, you’ll see two kinds of exceptions being thrown. If you encounter an exception about dragging multiple files using the deprecated [NSFilenamesPboardType](https://developer.apple.com/documentation/appkit/nsfilenamespboardtype) and dragging API, adopt the following APIs depending on your usage: [drag(_:at:offset:event:pasteboard:source:slideBack:)](https://developer.apple.com/documentation/appkit/nswindow/1419224-drag): Adopt [NSDraggingSession](https://developer.apple.com/documentation/appkit/nsdraggingsession) and use [URL](https://developer.apple.com/documentation/foundation/url) instances instead of string file paths. [tableView:writeRows:toPasteboard:](https://developer.apple.com/documentation/objectivec/nsobject/1539424-tableview) or [tableView(_:writeRowsWith:to:)](https://developer.apple.com/documentation/appkit/nstableviewdatasource/1525370-tableview): Adopt [tableView(_:pasteboardWriterForRow:)](https://developer.apple.com/documentation/appkit/nstableviewdatasource/1535294-tableview) and return [URL](https://developer.apple.com/documentation/foundation/url) instances or nil if the row shouldn’t be dragged. [collectionView(_:writeItemsAt:to:)](https://developer.apple.com/documentation/appkit/nscollectionviewdelegate/1528182-collectionview): Adopt [collectionView(_:pasteboardWriterForItemAt:)](https://developer.apple.com/documentation/appkit/nscollectionviewdelegate/1527290-collectionview) and return [URL](https://developer.apple.com/documentation/foundation/url) instances or nil if the row shouldn’t be dragged. If you encounter an exception noting that “there must be 1 draggingItem per pasteboardItem,” you need to ensure that the number of pasteboard items you add is the same as the number of drag items you’re using. The same exception occurs if you use the deprecated drag and drop API. Update your drag and drop code to [NSDraggingSession](https://developer.apple.com/documentation/appkit/nsdraggingsession) or [collectionView(_:pasteboardWriterForItemAt:)](https://developer.apple.com/documentation/appkit/nscollectionviewdelegate/1528257-collectionview) to avoid the exception in that case. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34603
https://github.com/electron/electron/pull/34615
d341610d64eb1220a3e923475c29dce1b4835ae7
8e45f43f1835d317742577f0ec23c5786d8ce4fd
2022-06-17T00:02:26Z
c++
2022-06-20T13:17:53Z
shell/browser/ui/drag_util_mac.mm
// Copyright (c) 2016 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #import <Cocoa/Cocoa.h> #include <vector> #include "base/files/file_path.h" #include "base/strings/sys_string_conversions.h" #include "shell/browser/ui/drag_util.h" namespace electron { namespace { // Write information about the file being dragged to the pasteboard. void AddFilesToPasteboard(NSPasteboard* pasteboard, const std::vector<base::FilePath>& files) { NSMutableArray* fileList = [NSMutableArray array]; for (const base::FilePath& file : files) [fileList addObject:base::SysUTF8ToNSString(file.value())]; [pasteboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType] owner:nil]; [pasteboard setPropertyList:fileList forType:NSFilenamesPboardType]; } } // namespace void DragFileItems(const std::vector<base::FilePath>& files, const gfx::Image& icon, gfx::NativeView view) { NSPasteboard* pasteboard = [NSPasteboard pasteboardWithName:NSPasteboardNameDrag]; AddFilesToPasteboard(pasteboard, files); // Synthesize a drag event, since we don't have access to the actual event // that initiated a drag (possibly consumed by the Web UI, for example). NSWindow* window = [view.GetNativeNSView() window]; NSPoint position = [window mouseLocationOutsideOfEventStream]; NSTimeInterval eventTime = [[NSApp currentEvent] timestamp]; NSEvent* dragEvent = [NSEvent mouseEventWithType:NSEventTypeLeftMouseDragged location:position modifierFlags:NSEventMaskLeftMouseDragged timestamp:eventTime windowNumber:[window windowNumber] context:nil eventNumber:0 clickCount:1 pressure:1.0]; // Run the drag operation. [window dragImage:icon.ToNSImage() at:position offset:NSZeroSize event:dragEvent pasteboard:pasteboard source:view.GetNativeNSView() slideBack:YES]; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,603
[Bug]: Deprecated dragging API
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 17.4.7 ### What operating system are you using? macOS ### Operating System Version Mac os 10.14 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Remove the deprecation of Dragging API ### Actual Behavior After update to mac os 10.14, I am using this code to drag multiple files ``` event.sender.startDrag({ // Fallback for files parameter file: iconPaths[0], // The paths to the files being dragged. (files will override file field) files: iconPaths, // Preview of the drag and drop file icon: nativeImage.createFromBuffer(iconPreview), }) ``` But when dragging multiple files, I see this alert on the console ``` Dragging multiple files using the deprecated NSFilenamesPboardType and dragging API. Please update to the NSDraggingSession API. ``` After investigate, seems like mac os now recomends to use URL format instead of file paths. more info here https://developer.apple.com/documentation/macos-release-notes/appkit-release-notes-for-macos-10_14 Drag and Drop If you’re using certain deprecated APIs in apps linked on macOS 10.14, you’ll see two kinds of exceptions being thrown. If you encounter an exception about dragging multiple files using the deprecated [NSFilenamesPboardType](https://developer.apple.com/documentation/appkit/nsfilenamespboardtype) and dragging API, adopt the following APIs depending on your usage: [drag(_:at:offset:event:pasteboard:source:slideBack:)](https://developer.apple.com/documentation/appkit/nswindow/1419224-drag): Adopt [NSDraggingSession](https://developer.apple.com/documentation/appkit/nsdraggingsession) and use [URL](https://developer.apple.com/documentation/foundation/url) instances instead of string file paths. [tableView:writeRows:toPasteboard:](https://developer.apple.com/documentation/objectivec/nsobject/1539424-tableview) or [tableView(_:writeRowsWith:to:)](https://developer.apple.com/documentation/appkit/nstableviewdatasource/1525370-tableview): Adopt [tableView(_:pasteboardWriterForRow:)](https://developer.apple.com/documentation/appkit/nstableviewdatasource/1535294-tableview) and return [URL](https://developer.apple.com/documentation/foundation/url) instances or nil if the row shouldn’t be dragged. [collectionView(_:writeItemsAt:to:)](https://developer.apple.com/documentation/appkit/nscollectionviewdelegate/1528182-collectionview): Adopt [collectionView(_:pasteboardWriterForItemAt:)](https://developer.apple.com/documentation/appkit/nscollectionviewdelegate/1527290-collectionview) and return [URL](https://developer.apple.com/documentation/foundation/url) instances or nil if the row shouldn’t be dragged. If you encounter an exception noting that “there must be 1 draggingItem per pasteboardItem,” you need to ensure that the number of pasteboard items you add is the same as the number of drag items you’re using. The same exception occurs if you use the deprecated drag and drop API. Update your drag and drop code to [NSDraggingSession](https://developer.apple.com/documentation/appkit/nsdraggingsession) or [collectionView(_:pasteboardWriterForItemAt:)](https://developer.apple.com/documentation/appkit/nscollectionviewdelegate/1528257-collectionview) to avoid the exception in that case. ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34603
https://github.com/electron/electron/pull/34615
d341610d64eb1220a3e923475c29dce1b4835ae7
8e45f43f1835d317742577f0ec23c5786d8ce4fd
2022-06-17T00:02:26Z
c++
2022-06-20T13:17:53Z
shell/browser/ui/drag_util_mac.mm
// Copyright (c) 2016 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #import <Cocoa/Cocoa.h> #include <vector> #include "base/files/file_path.h" #include "base/strings/sys_string_conversions.h" #include "shell/browser/ui/drag_util.h" namespace electron { namespace { // Write information about the file being dragged to the pasteboard. void AddFilesToPasteboard(NSPasteboard* pasteboard, const std::vector<base::FilePath>& files) { NSMutableArray* fileList = [NSMutableArray array]; for (const base::FilePath& file : files) [fileList addObject:base::SysUTF8ToNSString(file.value())]; [pasteboard declareTypes:[NSArray arrayWithObject:NSFilenamesPboardType] owner:nil]; [pasteboard setPropertyList:fileList forType:NSFilenamesPboardType]; } } // namespace void DragFileItems(const std::vector<base::FilePath>& files, const gfx::Image& icon, gfx::NativeView view) { NSPasteboard* pasteboard = [NSPasteboard pasteboardWithName:NSPasteboardNameDrag]; AddFilesToPasteboard(pasteboard, files); // Synthesize a drag event, since we don't have access to the actual event // that initiated a drag (possibly consumed by the Web UI, for example). NSWindow* window = [view.GetNativeNSView() window]; NSPoint position = [window mouseLocationOutsideOfEventStream]; NSTimeInterval eventTime = [[NSApp currentEvent] timestamp]; NSEvent* dragEvent = [NSEvent mouseEventWithType:NSEventTypeLeftMouseDragged location:position modifierFlags:NSEventMaskLeftMouseDragged timestamp:eventTime windowNumber:[window windowNumber] context:nil eventNumber:0 clickCount:1 pressure:1.0]; // Run the drag operation. [window dragImage:icon.ToNSImage() at:position offset:NSZeroSize event:dragEvent pasteboard:pasteboard source:view.GetNativeNSView() slideBack:YES]; } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,507
[Bug]: Traffic light display cannot be changed after certain operations
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.4 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior If after doing `window.setWindowButtonVisibility(false)` to fullscreen and back, the traffic light display can still be configurable. ### Actual Behavior If after doing `window.setWindowButtonVisibility(false)` to fullscreen and then back, the traffic light display will not be able to be configured. ### Testcase Gist URL https://gist.github.com/ci7lus/d33c403d8d7fd4de69ca59befdd0b6a7 ### Additional Information Repro: https://github.com/vivid-lapin/electron-button-fullscreen-repro https://user-images.githubusercontent.com/7887955/173172634-b7c51c7f-b44f-4f98-93cf-143576a1d726.mp4
https://github.com/electron/electron/issues/34507
https://github.com/electron/electron/pull/34530
f3f327823e577c5869b78c806f99644e9dabfb29
530a022b0548eb50acde87b5d18b5cff8eb7bbca
2022-06-11T04:36:24Z
c++
2022-06-21T07:35:53Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" // This view would inform Chromium to resize the hosted views::View. // // The overridden methods should behave the same with BridgedContentView. @interface ElectronAdaptedContentView : NSView { @private views::NativeWidgetMacNSWindowHost* bridge_host_; } @end @implementation ElectronAdaptedContentView - (id)initWithShell:(electron::NativeWindowMac*)shell { if ((self = [self init])) { bridge_host_ = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell->GetNativeWindow()); } return self; } - (void)viewDidMoveToWindow { // When this view is added to a window, AppKit calls setFrameSize before it is // added to the window, so the behavior in setFrameSize is not triggered. NSWindow* window = [self window]; if (window) [self setFrameSize:NSZeroSize]; } - (void)setFrameSize:(NSSize)newSize { // The size passed in here does not always use // -[NSWindow contentRectForFrameRect]. The following ensures that the // contentView for a frameless window can extend over the titlebar of the new // window containing it, since AppKit requires a titlebar to give frameless // windows correct shadows and rounded corners. NSWindow* window = [self window]; if (window && [window contentView] == self) { newSize = [window contentRectForFrameRect:[window frame]].size; // Ensure that the window geometry be updated on the host side before the // view size is updated. bridge_host_->GetInProcessNSWindowBridge()->UpdateWindowGeometry(); } [super setFrameSize:newSize]; // The OnViewSizeChanged is marked private in derived class. static_cast<remote_cocoa::mojom::NativeWidgetNSWindowHost*>(bridge_host_) ->OnViewSizeChanged(gfx::Size(newSize.width, newSize.height)); } @end // This view always takes the size of its superview. It is intended to be used // as a NSWindow's contentView. It is needed because NSWindow's implementation // explicitly resizes the contentView at inopportune times. @interface FullSizeContentView : NSView @end @implementation FullSizeContentView // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. - (void)setFrameSize:(NSSize)size { if ([self superview]) size = [[self superview] bounds].size; [super setFrameSize:size]; } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. - (void)viewDidMoveToSuperview { [self setFrame:[[self superview] bounds]]; } @end @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorBarStyle) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // Removing NSWindowStyleMaskTitled removes window title, which removes // rounded corners of window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = 0; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_.reset(); }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]); [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]); [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; // Use an NSEvent monitor to listen for the wheel event. BOOL __block began = NO; wheel_event_monitor_ = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskScrollWheel handler:^(NSEvent* event) { if ([[event window] windowNumber] != [window_ windowNumber]) return event; if (!began && (([event phase] == NSEventPhaseMayBegin) || ([event phase] == NSEventPhaseBegan))) { this->NotifyWindowScrollTouchBegin(); began = YES; } else if (began && (([event phase] == NSEventPhaseEnded) || ([event phase] == NSEventPhaseCancelled))) { this->NotifyWindowScrollTouchEnd(); began = NO; } return event; }]; // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { SetHasDeferredWindowClose(true); return; } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. SetEnabled(true); [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Retain the child window before closing it. If the last reference to the // NSWindow goes away inside -[NSWindow close], then bad stuff can happen. // See e.g. http://crbug.com/616701. base::scoped_nsobject<NSWindow> child_window(window_, base::scoped_policy::RETAIN); [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. SetEnabled(true); if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // Hide all children of the current window before hiding the window. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm // expects this when window visibility changes. if ([window_ childWindows]) { for (NSWindow* child in [window_ childWindows]) { [child orderOut:nil]; } } // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; // For a window to be visible, it must be visible to the user in the // foreground of the app, which means that it should not be minimized or // occluded return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { [window_ beginSheet:window_ completionHandler:^(NSModalResponse returnCode) { NSLog(@"modal enabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::SetFullScreen(bool fullscreen) { // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::ENTERING : FullScreenTransitionState::EXITING; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; [window_ orderWindow:NSWindowAbove relativeTo:id.id]; return true; } void NativeWindowMac::MoveTop() { [window_ orderWindow:NSWindowAbove relativeTo:0]; } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::NONE; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [window_ flushWindow]; [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; SetFullScreen(true); } else if (!kiosk && is_kiosk_) { [NSApp setPresentationOptions:kiosk_options_]; is_kiosk_ = false; SetFullScreen(false); } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=372?q=kWindowCaptureMacV2&ss=chromium // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[[NSImageView alloc] init] autorelease]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[[ElectronProgressBar alloc] initWithFrame:frame] autorelease]; [progress_indicator setStyle:NSProgressIndicatorBarStyle]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to functionally // mimic app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { ProcessSerialNumber psn = {0, kCurrentProcess}; if (visibleOnFullScreen) { [window_ setCanHide:NO]; TransformProcessType(&psn, kProcessTransformToUIElementApplication); } else { [window_ setCanHide:YES]; TransformProcessType(&psn, kProcessTransformToForegroundApplication); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } std::string dep_warn = " has been deprecated and removed as of macOS 10.15."; node::Environment* env = node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); NSVisualEffectMaterial vibrancyType{}; if (type == "appearance-based") { EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialAppearanceBased; } else if (type == "light") { EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialLight; } else if (type == "dark") { EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialDark; } else if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "medium-light") { EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialMediumLight; } else if (type == "ultra-dark") { EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialUltraDark; } if (@available(macOS 10.14, *)) { if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]] autorelease]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; // The visibility of window buttons are managed by |buttons_proxy_| if the // style is customButtonsOnHover. if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) [buttons_proxy_ setVisible:visible]; else InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetTrafficLightPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetTrafficLightPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_.reset([[ElectronTouchBar alloc] initWithDelegate:window_delegate_.get() window:this settings:std::move(items)]); [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_.reset([[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]); [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); if (wheel_event_monitor_) { [NSEvent removeMonitor:wheel_event_monitor_]; wheel_event_monitor_ = nil; } } void NativeWindowMac::OverrideNSWindowContentView() { // When using `views::Widget` to hold WebContents, Chromium would use // `BridgedContentView` as content view, which does not support draggable // regions. In order to make draggable regions work, we have to replace the // content view with a simple NSView. if (has_frame()) { container_view_.reset( [[ElectronAdaptedContentView alloc] initWithShell:this]); } else { container_view_.reset([[FullSizeContentView alloc] init]); [container_view_ setFrame:[[[window_ contentView] superview] bounds]]; } [container_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [window_ setContentView:container_view_]; AddContentViewLayers(); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]); [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } if (!has_frame()) { // In OSX 10.10, adding subviews to the root view for the NSView hierarchy // produces warnings. To eliminate the warnings, we resize the contentView // to fill the window, and add subviews to that. // http://crbug.com/380412 if (!original_set_frame_size) { Class cl = [[window_ contentView] class]; original_set_frame_size = class_replaceMethod( cl, @selector(setFrameSize:), (IMP)SetFrameSize, "v@:{_NSSize=ff}"); original_view_did_move_to_superview = class_replaceMethod(cl, @selector(viewDidMoveToSuperview), (IMP)ViewDidMoveToSuperview, "v@:"); [[window_ contentView] viewDidMoveToWindow]; } } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) { if (is_modal()) return; NativeWindow::SetParentWindow(parent); // Do not remove/add if we are already properly attached. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. if ([window_ parentWindow]) [[window_ parentWindow] removeChildWindow:window_]; // Set new parent window. // Note that this method will force the window to become visible. if (parent && attach) { // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [parent->GetNativeWindow().GetNativeNSWindow() addChildWindow:window_ ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,507
[Bug]: Traffic light display cannot be changed after certain operations
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.4 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior If after doing `window.setWindowButtonVisibility(false)` to fullscreen and back, the traffic light display can still be configurable. ### Actual Behavior If after doing `window.setWindowButtonVisibility(false)` to fullscreen and then back, the traffic light display will not be able to be configured. ### Testcase Gist URL https://gist.github.com/ci7lus/d33c403d8d7fd4de69ca59befdd0b6a7 ### Additional Information Repro: https://github.com/vivid-lapin/electron-button-fullscreen-repro https://user-images.githubusercontent.com/7887955/173172634-b7c51c7f-b44f-4f98-93cf-143576a1d726.mp4
https://github.com/electron/electron/issues/34507
https://github.com/electron/electron/pull/34530
f3f327823e577c5869b78c806f99644e9dabfb29
530a022b0548eb50acde87b5d18b5cff8eb7bbca
2022-06-11T04:36:24Z
c++
2022-06-21T07:35:53Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as http from 'http'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { areColorsSimilar, captureScreen, CHROMA_COLOR_HEX, getPixelColor } from './screen-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = emittedOnce(w, 'maximize'); const shown = emittedOnce(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await delay(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = emittedOnce(w, 'blur'); const isShown = emittedOnce(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = emittedOnce(w, 'focus'); const isShown = emittedOnce(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { await emittedOnce(w, 'focus', () => w.show()); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.webContents.incrementCapturerCount(); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); it('should increase the capturer count', () => { const w = new BrowserWindow({ show: false }); w.webContents.incrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.true(); w.webContents.decrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.false(); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | childProcess.ChildProcess | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath], { stdio: 'inherit' }); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = emittedOnce(w, 'hide'); let shown = emittedOnce(w, 'show'); const maximize = emittedOnce(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = emittedOnce(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await delay(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await delay(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: CHROMA_COLOR_HEX, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html')); await emittedOnce(foregroundWindow, 'ready-to-show'); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true(); expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: CHROMA_COLOR_HEX }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
34,507
[Bug]: Traffic light display cannot be changed after certain operations
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.4 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior If after doing `window.setWindowButtonVisibility(false)` to fullscreen and back, the traffic light display can still be configurable. ### Actual Behavior If after doing `window.setWindowButtonVisibility(false)` to fullscreen and then back, the traffic light display will not be able to be configured. ### Testcase Gist URL https://gist.github.com/ci7lus/d33c403d8d7fd4de69ca59befdd0b6a7 ### Additional Information Repro: https://github.com/vivid-lapin/electron-button-fullscreen-repro https://user-images.githubusercontent.com/7887955/173172634-b7c51c7f-b44f-4f98-93cf-143576a1d726.mp4
https://github.com/electron/electron/issues/34507
https://github.com/electron/electron/pull/34530
f3f327823e577c5869b78c806f99644e9dabfb29
530a022b0548eb50acde87b5d18b5cff8eb7bbca
2022-06-11T04:36:24Z
c++
2022-06-21T07:35:53Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" // This view would inform Chromium to resize the hosted views::View. // // The overridden methods should behave the same with BridgedContentView. @interface ElectronAdaptedContentView : NSView { @private views::NativeWidgetMacNSWindowHost* bridge_host_; } @end @implementation ElectronAdaptedContentView - (id)initWithShell:(electron::NativeWindowMac*)shell { if ((self = [self init])) { bridge_host_ = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell->GetNativeWindow()); } return self; } - (void)viewDidMoveToWindow { // When this view is added to a window, AppKit calls setFrameSize before it is // added to the window, so the behavior in setFrameSize is not triggered. NSWindow* window = [self window]; if (window) [self setFrameSize:NSZeroSize]; } - (void)setFrameSize:(NSSize)newSize { // The size passed in here does not always use // -[NSWindow contentRectForFrameRect]. The following ensures that the // contentView for a frameless window can extend over the titlebar of the new // window containing it, since AppKit requires a titlebar to give frameless // windows correct shadows and rounded corners. NSWindow* window = [self window]; if (window && [window contentView] == self) { newSize = [window contentRectForFrameRect:[window frame]].size; // Ensure that the window geometry be updated on the host side before the // view size is updated. bridge_host_->GetInProcessNSWindowBridge()->UpdateWindowGeometry(); } [super setFrameSize:newSize]; // The OnViewSizeChanged is marked private in derived class. static_cast<remote_cocoa::mojom::NativeWidgetNSWindowHost*>(bridge_host_) ->OnViewSizeChanged(gfx::Size(newSize.width, newSize.height)); } @end // This view always takes the size of its superview. It is intended to be used // as a NSWindow's contentView. It is needed because NSWindow's implementation // explicitly resizes the contentView at inopportune times. @interface FullSizeContentView : NSView @end @implementation FullSizeContentView // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. - (void)setFrameSize:(NSSize)size { if ([self superview]) size = [[self superview] bounds].size; [super setFrameSize:size]; } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. - (void)viewDidMoveToSuperview { [self setFrame:[[self superview] bounds]]; } @end @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorBarStyle) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // Removing NSWindowStyleMaskTitled removes window title, which removes // rounded corners of window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = 0; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_.reset(); }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]); [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]); [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; // Use an NSEvent monitor to listen for the wheel event. BOOL __block began = NO; wheel_event_monitor_ = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskScrollWheel handler:^(NSEvent* event) { if ([[event window] windowNumber] != [window_ windowNumber]) return event; if (!began && (([event phase] == NSEventPhaseMayBegin) || ([event phase] == NSEventPhaseBegan))) { this->NotifyWindowScrollTouchBegin(); began = YES; } else if (began && (([event phase] == NSEventPhaseEnded) || ([event phase] == NSEventPhaseCancelled))) { this->NotifyWindowScrollTouchEnd(); began = NO; } return event; }]; // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { SetHasDeferredWindowClose(true); return; } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. SetEnabled(true); [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Retain the child window before closing it. If the last reference to the // NSWindow goes away inside -[NSWindow close], then bad stuff can happen. // See e.g. http://crbug.com/616701. base::scoped_nsobject<NSWindow> child_window(window_, base::scoped_policy::RETAIN); [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. SetEnabled(true); if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // Hide all children of the current window before hiding the window. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm // expects this when window visibility changes. if ([window_ childWindows]) { for (NSWindow* child in [window_ childWindows]) { [child orderOut:nil]; } } // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; // For a window to be visible, it must be visible to the user in the // foreground of the app, which means that it should not be minimized or // occluded return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { [window_ beginSheet:window_ completionHandler:^(NSModalResponse returnCode) { NSLog(@"modal enabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::SetFullScreen(bool fullscreen) { // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::ENTERING : FullScreenTransitionState::EXITING; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; [window_ orderWindow:NSWindowAbove relativeTo:id.id]; return true; } void NativeWindowMac::MoveTop() { [window_ orderWindow:NSWindowAbove relativeTo:0]; } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::NONE; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [window_ flushWindow]; [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; SetFullScreen(true); } else if (!kiosk && is_kiosk_) { [NSApp setPresentationOptions:kiosk_options_]; is_kiosk_ = false; SetFullScreen(false); } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=372?q=kWindowCaptureMacV2&ss=chromium // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[[NSImageView alloc] init] autorelease]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[[ElectronProgressBar alloc] initWithFrame:frame] autorelease]; [progress_indicator setStyle:NSProgressIndicatorBarStyle]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to functionally // mimic app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { ProcessSerialNumber psn = {0, kCurrentProcess}; if (visibleOnFullScreen) { [window_ setCanHide:NO]; TransformProcessType(&psn, kProcessTransformToUIElementApplication); } else { [window_ setCanHide:YES]; TransformProcessType(&psn, kProcessTransformToForegroundApplication); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } std::string dep_warn = " has been deprecated and removed as of macOS 10.15."; node::Environment* env = node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); NSVisualEffectMaterial vibrancyType{}; if (type == "appearance-based") { EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialAppearanceBased; } else if (type == "light") { EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialLight; } else if (type == "dark") { EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialDark; } else if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "medium-light") { EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialMediumLight; } else if (type == "ultra-dark") { EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialUltraDark; } if (@available(macOS 10.14, *)) { if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]] autorelease]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; // The visibility of window buttons are managed by |buttons_proxy_| if the // style is customButtonsOnHover. if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) [buttons_proxy_ setVisible:visible]; else InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetTrafficLightPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetTrafficLightPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_.reset([[ElectronTouchBar alloc] initWithDelegate:window_delegate_.get() window:this settings:std::move(items)]); [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_.reset([[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]); [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); if (wheel_event_monitor_) { [NSEvent removeMonitor:wheel_event_monitor_]; wheel_event_monitor_ = nil; } } void NativeWindowMac::OverrideNSWindowContentView() { // When using `views::Widget` to hold WebContents, Chromium would use // `BridgedContentView` as content view, which does not support draggable // regions. In order to make draggable regions work, we have to replace the // content view with a simple NSView. if (has_frame()) { container_view_.reset( [[ElectronAdaptedContentView alloc] initWithShell:this]); } else { container_view_.reset([[FullSizeContentView alloc] init]); [container_view_ setFrame:[[[window_ contentView] superview] bounds]]; } [container_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [window_ setContentView:container_view_]; AddContentViewLayers(); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]); [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } if (!has_frame()) { // In OSX 10.10, adding subviews to the root view for the NSView hierarchy // produces warnings. To eliminate the warnings, we resize the contentView // to fill the window, and add subviews to that. // http://crbug.com/380412 if (!original_set_frame_size) { Class cl = [[window_ contentView] class]; original_set_frame_size = class_replaceMethod( cl, @selector(setFrameSize:), (IMP)SetFrameSize, "v@:{_NSSize=ff}"); original_view_did_move_to_superview = class_replaceMethod(cl, @selector(viewDidMoveToSuperview), (IMP)ViewDidMoveToSuperview, "v@:"); [[window_ contentView] viewDidMoveToWindow]; } } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) { if (is_modal()) return; NativeWindow::SetParentWindow(parent); // Do not remove/add if we are already properly attached. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. if ([window_ parentWindow]) [[window_ parentWindow] removeChildWindow:window_]; // Set new parent window. // Note that this method will force the window to become visible. if (parent && attach) { // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [parent->GetNativeWindow().GetNativeNSWindow() addChildWindow:window_ ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,507
[Bug]: Traffic light display cannot be changed after certain operations
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.4 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior If after doing `window.setWindowButtonVisibility(false)` to fullscreen and back, the traffic light display can still be configurable. ### Actual Behavior If after doing `window.setWindowButtonVisibility(false)` to fullscreen and then back, the traffic light display will not be able to be configured. ### Testcase Gist URL https://gist.github.com/ci7lus/d33c403d8d7fd4de69ca59befdd0b6a7 ### Additional Information Repro: https://github.com/vivid-lapin/electron-button-fullscreen-repro https://user-images.githubusercontent.com/7887955/173172634-b7c51c7f-b44f-4f98-93cf-143576a1d726.mp4
https://github.com/electron/electron/issues/34507
https://github.com/electron/electron/pull/34530
f3f327823e577c5869b78c806f99644e9dabfb29
530a022b0548eb50acde87b5d18b5cff8eb7bbca
2022-06-11T04:36:24Z
c++
2022-06-21T07:35:53Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as http from 'http'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { areColorsSimilar, captureScreen, CHROMA_COLOR_HEX, getPixelColor } from './screen-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = emittedOnce(w, 'maximize'); const shown = emittedOnce(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await delay(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = emittedOnce(w, 'blur'); const isShown = emittedOnce(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = emittedOnce(w, 'focus'); const isShown = emittedOnce(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { await emittedOnce(w, 'focus', () => w.show()); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = Object.assign(fullBounds, boundsUpdate); expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'resize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.webContents.incrementCapturerCount(); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); it('should increase the capturer count', () => { const w = new BrowserWindow({ show: false }); w.webContents.incrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.true(); w.webContents.decrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.false(); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | childProcess.ChildProcess | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); it('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath], { stdio: 'inherit' }); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = emittedOnce(w, 'hide'); let shown = emittedOnce(w, 'show'); const maximize = emittedOnce(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = emittedOnce(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await delay(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await delay(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: CHROMA_COLOR_HEX, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html')); await emittedOnce(foregroundWindow, 'ready-to-show'); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true(); expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: CHROMA_COLOR_HEX }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
32,285
[Bug]: The title bar overlay is not updated to fit the settings of the window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 16.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 11 21H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior If a window has the `maximizable` property set to `false`, the built-in title bar overlay should be updated and the maximise button should be disabled. And if a window has the `minimizable` property set to `false`, the built-in title bar overlay should be updated and the minimise button should be disabled. ### Actual Behavior These buttons are still active on the windows that have these properties set to `false`. ![image](https://user-images.githubusercontent.com/72353925/147394733-edffab52-5fea-483d-a62a-840596810551.png) Main Window (the first one): maximizable -> true minimizable -> true Editor Window (the second one): maximizable -> true minimizable -> true Custom Alert Window (the third one): maximizable -> false minimizable -> true About Window (the fourth one): maximizable -> false minimizable -> false ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32285
https://github.com/electron/electron/pull/34677
106aa0e9228250015eef99eaa9063bafa9fc187b
3b881e4a132742b30e2f7a61203c1bfec5b81364
2021-12-25T22:35:51Z
c++
2022-06-23T17:08:32Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // TODO(ckerr): remove in Electron v20.0.0 // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; return; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) SetWMSpecState(static_cast<x11::Window>(GetAcceleratedWidget()), skip, x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,285
[Bug]: The title bar overlay is not updated to fit the settings of the window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 16.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 11 21H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior If a window has the `maximizable` property set to `false`, the built-in title bar overlay should be updated and the maximise button should be disabled. And if a window has the `minimizable` property set to `false`, the built-in title bar overlay should be updated and the minimise button should be disabled. ### Actual Behavior These buttons are still active on the windows that have these properties set to `false`. ![image](https://user-images.githubusercontent.com/72353925/147394733-edffab52-5fea-483d-a62a-840596810551.png) Main Window (the first one): maximizable -> true minimizable -> true Editor Window (the second one): maximizable -> true minimizable -> true Custom Alert Window (the third one): maximizable -> false minimizable -> true About Window (the fourth one): maximizable -> false minimizable -> false ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32285
https://github.com/electron/electron/pull/34677
106aa0e9228250015eef99eaa9063bafa9fc187b
3b881e4a132742b30e2f7a61203c1bfec5b81364
2021-12-25T22:35:51Z
c++
2022-06-23T17:08:32Z
shell/browser/ui/views/win_caption_button_container.cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Modified from // chrome/browser/ui/views/frame/glass_browser_caption_button_container.cc #include "shell/browser/ui/views/win_caption_button_container.h" #include <memory> #include <utility> #include "shell/browser/ui/views/win_caption_button.h" #include "shell/browser/ui/views/win_frame_view.h" #include "ui/base/l10n/l10n_util.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/view_class_properties.h" namespace electron { namespace { std::unique_ptr<WinCaptionButton> CreateCaptionButton( views::Button::PressedCallback callback, WinFrameView* frame_view, ViewID button_type, int accessible_name_resource_id) { return std::make_unique<WinCaptionButton>( std::move(callback), frame_view, button_type, l10n_util::GetStringUTF16(accessible_name_resource_id)); } bool HitTestCaptionButton(WinCaptionButton* button, const gfx::Point& point) { return button && button->GetVisible() && button->bounds().Contains(point); } } // anonymous namespace WinCaptionButtonContainer::WinCaptionButtonContainer(WinFrameView* frame_view) : frame_view_(frame_view), minimize_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::Minimize, base::Unretained(frame_view_->frame())), frame_view_, VIEW_ID_MINIMIZE_BUTTON, IDS_APP_ACCNAME_MINIMIZE))), maximize_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::Maximize, base::Unretained(frame_view_->frame())), frame_view_, VIEW_ID_MAXIMIZE_BUTTON, IDS_APP_ACCNAME_MAXIMIZE))), restore_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::Restore, base::Unretained(frame_view_->frame())), frame_view_, VIEW_ID_RESTORE_BUTTON, IDS_APP_ACCNAME_RESTORE))), close_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::CloseWithReason, base::Unretained(frame_view_->frame()), views::Widget::ClosedReason::kCloseButtonClicked), frame_view_, VIEW_ID_CLOSE_BUTTON, IDS_APP_ACCNAME_CLOSE))) { // Layout is horizontal, with buttons placed at the trailing end of the view. // This allows the container to expand to become a faux titlebar/drag handle. auto* const layout = SetLayoutManager(std::make_unique<views::FlexLayout>()); layout->SetOrientation(views::LayoutOrientation::kHorizontal) .SetMainAxisAlignment(views::LayoutAlignment::kEnd) .SetCrossAxisAlignment(views::LayoutAlignment::kStart) .SetDefault( views::kFlexBehaviorKey, views::FlexSpecification(views::LayoutOrientation::kHorizontal, views::MinimumFlexSizeRule::kPreferred, views::MaximumFlexSizeRule::kPreferred, /* adjust_width_for_height */ false, views::MinimumFlexSizeRule::kScaleToZero)); } WinCaptionButtonContainer::~WinCaptionButtonContainer() {} int WinCaptionButtonContainer::NonClientHitTest(const gfx::Point& point) const { DCHECK(HitTestPoint(point)) << "should only be called with a point inside this view's bounds"; if (HitTestCaptionButton(minimize_button_, point)) { return HTMINBUTTON; } if (HitTestCaptionButton(maximize_button_, point)) { return HTMAXBUTTON; } if (HitTestCaptionButton(restore_button_, point)) { return HTMAXBUTTON; } if (HitTestCaptionButton(close_button_, point)) { return HTCLOSE; } return HTCAPTION; } gfx::Size WinCaptionButtonContainer::GetButtonSize() const { // Close button size is set the same as all the buttons return close_button_->GetSize(); } void WinCaptionButtonContainer::SetButtonSize(gfx::Size size) { minimize_button_->SetSize(size); maximize_button_->SetSize(size); restore_button_->SetSize(size); close_button_->SetSize(size); } void WinCaptionButtonContainer::ResetWindowControls() { minimize_button_->SetState(views::Button::STATE_NORMAL); maximize_button_->SetState(views::Button::STATE_NORMAL); restore_button_->SetState(views::Button::STATE_NORMAL); close_button_->SetState(views::Button::STATE_NORMAL); InvalidateLayout(); } void WinCaptionButtonContainer::AddedToWidget() { views::Widget* const widget = GetWidget(); DCHECK(!widget_observation_.IsObserving()); widget_observation_.Observe(widget); UpdateButtons(); if (frame_view_->window()->IsWindowControlsOverlayEnabled()) { SetPaintToLayer(); } } void WinCaptionButtonContainer::RemovedFromWidget() { DCHECK(widget_observation_.IsObserving()); widget_observation_.Reset(); } void WinCaptionButtonContainer::OnWidgetBoundsChanged( views::Widget* widget, const gfx::Rect& new_bounds) { UpdateButtons(); } void WinCaptionButtonContainer::UpdateButtons() { const bool is_maximized = frame_view_->frame()->IsMaximized(); restore_button_->SetVisible(is_maximized); maximize_button_->SetVisible(!is_maximized); // In touch mode, windows cannot be taken out of fullscreen or tiled mode, so // the maximize/restore button should be disabled. const bool is_touch = ui::TouchUiController::Get()->touch_ui(); restore_button_->SetEnabled(!is_touch); maximize_button_->SetEnabled(!is_touch); InvalidateLayout(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,285
[Bug]: The title bar overlay is not updated to fit the settings of the window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 16.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 11 21H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior If a window has the `maximizable` property set to `false`, the built-in title bar overlay should be updated and the maximise button should be disabled. And if a window has the `minimizable` property set to `false`, the built-in title bar overlay should be updated and the minimise button should be disabled. ### Actual Behavior These buttons are still active on the windows that have these properties set to `false`. ![image](https://user-images.githubusercontent.com/72353925/147394733-edffab52-5fea-483d-a62a-840596810551.png) Main Window (the first one): maximizable -> true minimizable -> true Editor Window (the second one): maximizable -> true minimizable -> true Custom Alert Window (the third one): maximizable -> false minimizable -> true About Window (the fourth one): maximizable -> false minimizable -> false ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32285
https://github.com/electron/electron/pull/34677
106aa0e9228250015eef99eaa9063bafa9fc187b
3b881e4a132742b30e2f7a61203c1bfec5b81364
2021-12-25T22:35:51Z
c++
2022-06-23T17:08:32Z
shell/browser/ui/views/win_caption_button_container.h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Modified from // chrome/browser/ui/views/frame/glass_browser_caption_button_container.h #ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_ #define ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_ #include "base/scoped_observation.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/base/pointer/touch_ui_controller.h" #include "ui/views/controls/button/button.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" namespace electron { class WinFrameView; class WinCaptionButton; // Provides a container for Windows 10 caption buttons that can be moved between // frame and browser window as needed. When extended horizontally, becomes a // grab bar for moving the window. class WinCaptionButtonContainer : public views::View, public views::WidgetObserver { public: explicit WinCaptionButtonContainer(WinFrameView* frame_view); ~WinCaptionButtonContainer() override; // Tests to see if the specified |point| (which is expressed in this view's // coordinates and which must be within this view's bounds) is within one of // the caption buttons. Returns one of HitTestCompat enum defined in // ui/base/hit_test.h, HTCAPTION if the area hit would be part of the window's // drag handle, and HTNOWHERE otherwise. // See also ClientView::NonClientHitTest. int NonClientHitTest(const gfx::Point& point) const; gfx::Size GetButtonSize() const; void SetButtonSize(gfx::Size size); private: // views::View: void AddedToWidget() override; void RemovedFromWidget() override; // views::WidgetObserver: void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& new_bounds) override; void ResetWindowControls(); // Sets caption button visibility and enabled state based on window state. // Only one of maximize or restore button should ever be visible at the same // time, and both are disabled in tablet UI mode. void UpdateButtons(); WinFrameView* const frame_view_; WinCaptionButton* const minimize_button_; WinCaptionButton* const maximize_button_; WinCaptionButton* const restore_button_; WinCaptionButton* const close_button_; base::ScopedObservation<views::Widget, views::WidgetObserver> widget_observation_{this}; base::CallbackListSubscription subscription_ = ui::TouchUiController::Get()->RegisterCallback( base::BindRepeating(&WinCaptionButtonContainer::UpdateButtons, base::Unretained(this))); }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_
closed
electron/electron
https://github.com/electron/electron
32,285
[Bug]: The title bar overlay is not updated to fit the settings of the window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 16.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 11 21H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior If a window has the `maximizable` property set to `false`, the built-in title bar overlay should be updated and the maximise button should be disabled. And if a window has the `minimizable` property set to `false`, the built-in title bar overlay should be updated and the minimise button should be disabled. ### Actual Behavior These buttons are still active on the windows that have these properties set to `false`. ![image](https://user-images.githubusercontent.com/72353925/147394733-edffab52-5fea-483d-a62a-840596810551.png) Main Window (the first one): maximizable -> true minimizable -> true Editor Window (the second one): maximizable -> true minimizable -> true Custom Alert Window (the third one): maximizable -> false minimizable -> true About Window (the fourth one): maximizable -> false minimizable -> false ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32285
https://github.com/electron/electron/pull/34677
106aa0e9228250015eef99eaa9063bafa9fc187b
3b881e4a132742b30e2f7a61203c1bfec5b81364
2021-12-25T22:35:51Z
c++
2022-06-23T17:08:32Z
shell/browser/ui/views/win_frame_view.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. // // Portions of this file are sourced from // chrome/browser/ui/views/frame/glass_browser_frame_view.h, // Copyright (c) 2012 The Chromium Authors, // which is governed by a BSD-style license #ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_FRAME_VIEW_H_ #define ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_FRAME_VIEW_H_ #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/win_caption_button.h" namespace electron { class WinFrameView : public FramelessView { public: static const char kViewClassName[]; WinFrameView(); ~WinFrameView() override; void Init(NativeWindowViews* window, views::Widget* frame) override; // Alpha to use for features in the titlebar (the window title and caption // buttons) when the window is inactive. They are opaque when active. static constexpr SkAlpha kInactiveTitlebarFeatureAlpha = 0x66; SkColor GetReadableFeatureColor(SkColor background_color); // Tells the NonClientView to invalidate the WinFrameView's caption buttons. void InvalidateCaptionButtons(); // views::NonClientFrameView: gfx::Rect GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const override; int NonClientHitTest(const gfx::Point& point) override; // views::View: const char* GetClassName() const override; NativeWindowViews* window() const { return window_; } views::Widget* frame() const { return frame_; } bool IsMaximized() const; bool ShouldCustomDrawSystemTitlebar() const; // Visual height of the titlebar when the window is maximized (i.e. excluding // the area above the top of the screen). int TitlebarMaximizedVisualHeight() const; protected: // views::View: void Layout() override; private: friend class WinCaptionButtonContainer; int FrameBorderThickness() const; // views::ViewTargeterDelegate: views::View* TargetForRect(views::View* root, const gfx::Rect& rect) override; // Returns the thickness of the window border for the top edge of the frame, // which is sometimes different than FrameBorderThickness(). Does not include // the titlebar/tabstrip area. If |restored| is true, this is calculated as if // the window was restored, regardless of its current state. int FrameTopBorderThickness(bool restored) const; int FrameTopBorderThicknessPx(bool restored) const; // Returns the height of the titlebar for popups or other browser types that // don't have tabs. int TitlebarHeight(int custom_height) const; // Returns the y coordinate for the top of the frame, which in maximized mode // is the top of the screen and in restored mode is 1 pixel below the top of // the window to leave room for the visual border that Windows draws. int WindowTopY() const; void LayoutCaptionButtons(); void LayoutWindowControlsOverlay(); // The container holding the caption buttons (minimize, maximize, close, etc.) // May be null if the caption button container is destroyed before the frame // view. Always check for validity before using! WinCaptionButtonContainer* caption_button_container_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_FRAME_VIEW_H_
closed
electron/electron
https://github.com/electron/electron
32,285
[Bug]: The title bar overlay is not updated to fit the settings of the window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 16.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 11 21H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior If a window has the `maximizable` property set to `false`, the built-in title bar overlay should be updated and the maximise button should be disabled. And if a window has the `minimizable` property set to `false`, the built-in title bar overlay should be updated and the minimise button should be disabled. ### Actual Behavior These buttons are still active on the windows that have these properties set to `false`. ![image](https://user-images.githubusercontent.com/72353925/147394733-edffab52-5fea-483d-a62a-840596810551.png) Main Window (the first one): maximizable -> true minimizable -> true Editor Window (the second one): maximizable -> true minimizable -> true Custom Alert Window (the third one): maximizable -> false minimizable -> true About Window (the fourth one): maximizable -> false minimizable -> false ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32285
https://github.com/electron/electron/pull/34677
106aa0e9228250015eef99eaa9063bafa9fc187b
3b881e4a132742b30e2f7a61203c1bfec5b81364
2021-12-25T22:35:51Z
c++
2022-06-23T17:08:32Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // TODO(ckerr): remove in Electron v20.0.0 // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; return; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) SetWMSpecState(static_cast<x11::Window>(GetAcceleratedWidget()), skip, x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,285
[Bug]: The title bar overlay is not updated to fit the settings of the window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 16.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 11 21H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior If a window has the `maximizable` property set to `false`, the built-in title bar overlay should be updated and the maximise button should be disabled. And if a window has the `minimizable` property set to `false`, the built-in title bar overlay should be updated and the minimise button should be disabled. ### Actual Behavior These buttons are still active on the windows that have these properties set to `false`. ![image](https://user-images.githubusercontent.com/72353925/147394733-edffab52-5fea-483d-a62a-840596810551.png) Main Window (the first one): maximizable -> true minimizable -> true Editor Window (the second one): maximizable -> true minimizable -> true Custom Alert Window (the third one): maximizable -> false minimizable -> true About Window (the fourth one): maximizable -> false minimizable -> false ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32285
https://github.com/electron/electron/pull/34677
106aa0e9228250015eef99eaa9063bafa9fc187b
3b881e4a132742b30e2f7a61203c1bfec5b81364
2021-12-25T22:35:51Z
c++
2022-06-23T17:08:32Z
shell/browser/ui/views/win_caption_button_container.cc
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Modified from // chrome/browser/ui/views/frame/glass_browser_caption_button_container.cc #include "shell/browser/ui/views/win_caption_button_container.h" #include <memory> #include <utility> #include "shell/browser/ui/views/win_caption_button.h" #include "shell/browser/ui/views/win_frame_view.h" #include "ui/base/l10n/l10n_util.h" #include "ui/strings/grit/ui_strings.h" #include "ui/views/layout/flex_layout.h" #include "ui/views/view_class_properties.h" namespace electron { namespace { std::unique_ptr<WinCaptionButton> CreateCaptionButton( views::Button::PressedCallback callback, WinFrameView* frame_view, ViewID button_type, int accessible_name_resource_id) { return std::make_unique<WinCaptionButton>( std::move(callback), frame_view, button_type, l10n_util::GetStringUTF16(accessible_name_resource_id)); } bool HitTestCaptionButton(WinCaptionButton* button, const gfx::Point& point) { return button && button->GetVisible() && button->bounds().Contains(point); } } // anonymous namespace WinCaptionButtonContainer::WinCaptionButtonContainer(WinFrameView* frame_view) : frame_view_(frame_view), minimize_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::Minimize, base::Unretained(frame_view_->frame())), frame_view_, VIEW_ID_MINIMIZE_BUTTON, IDS_APP_ACCNAME_MINIMIZE))), maximize_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::Maximize, base::Unretained(frame_view_->frame())), frame_view_, VIEW_ID_MAXIMIZE_BUTTON, IDS_APP_ACCNAME_MAXIMIZE))), restore_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::Restore, base::Unretained(frame_view_->frame())), frame_view_, VIEW_ID_RESTORE_BUTTON, IDS_APP_ACCNAME_RESTORE))), close_button_(AddChildView(CreateCaptionButton( base::BindRepeating(&views::Widget::CloseWithReason, base::Unretained(frame_view_->frame()), views::Widget::ClosedReason::kCloseButtonClicked), frame_view_, VIEW_ID_CLOSE_BUTTON, IDS_APP_ACCNAME_CLOSE))) { // Layout is horizontal, with buttons placed at the trailing end of the view. // This allows the container to expand to become a faux titlebar/drag handle. auto* const layout = SetLayoutManager(std::make_unique<views::FlexLayout>()); layout->SetOrientation(views::LayoutOrientation::kHorizontal) .SetMainAxisAlignment(views::LayoutAlignment::kEnd) .SetCrossAxisAlignment(views::LayoutAlignment::kStart) .SetDefault( views::kFlexBehaviorKey, views::FlexSpecification(views::LayoutOrientation::kHorizontal, views::MinimumFlexSizeRule::kPreferred, views::MaximumFlexSizeRule::kPreferred, /* adjust_width_for_height */ false, views::MinimumFlexSizeRule::kScaleToZero)); } WinCaptionButtonContainer::~WinCaptionButtonContainer() {} int WinCaptionButtonContainer::NonClientHitTest(const gfx::Point& point) const { DCHECK(HitTestPoint(point)) << "should only be called with a point inside this view's bounds"; if (HitTestCaptionButton(minimize_button_, point)) { return HTMINBUTTON; } if (HitTestCaptionButton(maximize_button_, point)) { return HTMAXBUTTON; } if (HitTestCaptionButton(restore_button_, point)) { return HTMAXBUTTON; } if (HitTestCaptionButton(close_button_, point)) { return HTCLOSE; } return HTCAPTION; } gfx::Size WinCaptionButtonContainer::GetButtonSize() const { // Close button size is set the same as all the buttons return close_button_->GetSize(); } void WinCaptionButtonContainer::SetButtonSize(gfx::Size size) { minimize_button_->SetSize(size); maximize_button_->SetSize(size); restore_button_->SetSize(size); close_button_->SetSize(size); } void WinCaptionButtonContainer::ResetWindowControls() { minimize_button_->SetState(views::Button::STATE_NORMAL); maximize_button_->SetState(views::Button::STATE_NORMAL); restore_button_->SetState(views::Button::STATE_NORMAL); close_button_->SetState(views::Button::STATE_NORMAL); InvalidateLayout(); } void WinCaptionButtonContainer::AddedToWidget() { views::Widget* const widget = GetWidget(); DCHECK(!widget_observation_.IsObserving()); widget_observation_.Observe(widget); UpdateButtons(); if (frame_view_->window()->IsWindowControlsOverlayEnabled()) { SetPaintToLayer(); } } void WinCaptionButtonContainer::RemovedFromWidget() { DCHECK(widget_observation_.IsObserving()); widget_observation_.Reset(); } void WinCaptionButtonContainer::OnWidgetBoundsChanged( views::Widget* widget, const gfx::Rect& new_bounds) { UpdateButtons(); } void WinCaptionButtonContainer::UpdateButtons() { const bool is_maximized = frame_view_->frame()->IsMaximized(); restore_button_->SetVisible(is_maximized); maximize_button_->SetVisible(!is_maximized); // In touch mode, windows cannot be taken out of fullscreen or tiled mode, so // the maximize/restore button should be disabled. const bool is_touch = ui::TouchUiController::Get()->touch_ui(); restore_button_->SetEnabled(!is_touch); maximize_button_->SetEnabled(!is_touch); InvalidateLayout(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,285
[Bug]: The title bar overlay is not updated to fit the settings of the window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 16.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 11 21H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior If a window has the `maximizable` property set to `false`, the built-in title bar overlay should be updated and the maximise button should be disabled. And if a window has the `minimizable` property set to `false`, the built-in title bar overlay should be updated and the minimise button should be disabled. ### Actual Behavior These buttons are still active on the windows that have these properties set to `false`. ![image](https://user-images.githubusercontent.com/72353925/147394733-edffab52-5fea-483d-a62a-840596810551.png) Main Window (the first one): maximizable -> true minimizable -> true Editor Window (the second one): maximizable -> true minimizable -> true Custom Alert Window (the third one): maximizable -> false minimizable -> true About Window (the fourth one): maximizable -> false minimizable -> false ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32285
https://github.com/electron/electron/pull/34677
106aa0e9228250015eef99eaa9063bafa9fc187b
3b881e4a132742b30e2f7a61203c1bfec5b81364
2021-12-25T22:35:51Z
c++
2022-06-23T17:08:32Z
shell/browser/ui/views/win_caption_button_container.h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Modified from // chrome/browser/ui/views/frame/glass_browser_caption_button_container.h #ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_ #define ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_ #include "base/scoped_observation.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/base/pointer/touch_ui_controller.h" #include "ui/views/controls/button/button.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" namespace electron { class WinFrameView; class WinCaptionButton; // Provides a container for Windows 10 caption buttons that can be moved between // frame and browser window as needed. When extended horizontally, becomes a // grab bar for moving the window. class WinCaptionButtonContainer : public views::View, public views::WidgetObserver { public: explicit WinCaptionButtonContainer(WinFrameView* frame_view); ~WinCaptionButtonContainer() override; // Tests to see if the specified |point| (which is expressed in this view's // coordinates and which must be within this view's bounds) is within one of // the caption buttons. Returns one of HitTestCompat enum defined in // ui/base/hit_test.h, HTCAPTION if the area hit would be part of the window's // drag handle, and HTNOWHERE otherwise. // See also ClientView::NonClientHitTest. int NonClientHitTest(const gfx::Point& point) const; gfx::Size GetButtonSize() const; void SetButtonSize(gfx::Size size); private: // views::View: void AddedToWidget() override; void RemovedFromWidget() override; // views::WidgetObserver: void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& new_bounds) override; void ResetWindowControls(); // Sets caption button visibility and enabled state based on window state. // Only one of maximize or restore button should ever be visible at the same // time, and both are disabled in tablet UI mode. void UpdateButtons(); WinFrameView* const frame_view_; WinCaptionButton* const minimize_button_; WinCaptionButton* const maximize_button_; WinCaptionButton* const restore_button_; WinCaptionButton* const close_button_; base::ScopedObservation<views::Widget, views::WidgetObserver> widget_observation_{this}; base::CallbackListSubscription subscription_ = ui::TouchUiController::Get()->RegisterCallback( base::BindRepeating(&WinCaptionButtonContainer::UpdateButtons, base::Unretained(this))); }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_
closed
electron/electron
https://github.com/electron/electron
32,285
[Bug]: The title bar overlay is not updated to fit the settings of the window
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version 16.0.5 ### What operating system are you using? Windows ### Operating System Version Windows 11 21H2 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior If a window has the `maximizable` property set to `false`, the built-in title bar overlay should be updated and the maximise button should be disabled. And if a window has the `minimizable` property set to `false`, the built-in title bar overlay should be updated and the minimise button should be disabled. ### Actual Behavior These buttons are still active on the windows that have these properties set to `false`. ![image](https://user-images.githubusercontent.com/72353925/147394733-edffab52-5fea-483d-a62a-840596810551.png) Main Window (the first one): maximizable -> true minimizable -> true Editor Window (the second one): maximizable -> true minimizable -> true Custom Alert Window (the third one): maximizable -> false minimizable -> true About Window (the fourth one): maximizable -> false minimizable -> false ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/32285
https://github.com/electron/electron/pull/34677
106aa0e9228250015eef99eaa9063bafa9fc187b
3b881e4a132742b30e2f7a61203c1bfec5b81364
2021-12-25T22:35:51Z
c++
2022-06-23T17:08:32Z
shell/browser/ui/views/win_frame_view.h
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. // // Portions of this file are sourced from // chrome/browser/ui/views/frame/glass_browser_frame_view.h, // Copyright (c) 2012 The Chromium Authors, // which is governed by a BSD-style license #ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_FRAME_VIEW_H_ #define ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_FRAME_VIEW_H_ #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/win_caption_button.h" namespace electron { class WinFrameView : public FramelessView { public: static const char kViewClassName[]; WinFrameView(); ~WinFrameView() override; void Init(NativeWindowViews* window, views::Widget* frame) override; // Alpha to use for features in the titlebar (the window title and caption // buttons) when the window is inactive. They are opaque when active. static constexpr SkAlpha kInactiveTitlebarFeatureAlpha = 0x66; SkColor GetReadableFeatureColor(SkColor background_color); // Tells the NonClientView to invalidate the WinFrameView's caption buttons. void InvalidateCaptionButtons(); // views::NonClientFrameView: gfx::Rect GetWindowBoundsForClientBounds( const gfx::Rect& client_bounds) const override; int NonClientHitTest(const gfx::Point& point) override; // views::View: const char* GetClassName() const override; NativeWindowViews* window() const { return window_; } views::Widget* frame() const { return frame_; } bool IsMaximized() const; bool ShouldCustomDrawSystemTitlebar() const; // Visual height of the titlebar when the window is maximized (i.e. excluding // the area above the top of the screen). int TitlebarMaximizedVisualHeight() const; protected: // views::View: void Layout() override; private: friend class WinCaptionButtonContainer; int FrameBorderThickness() const; // views::ViewTargeterDelegate: views::View* TargetForRect(views::View* root, const gfx::Rect& rect) override; // Returns the thickness of the window border for the top edge of the frame, // which is sometimes different than FrameBorderThickness(). Does not include // the titlebar/tabstrip area. If |restored| is true, this is calculated as if // the window was restored, regardless of its current state. int FrameTopBorderThickness(bool restored) const; int FrameTopBorderThicknessPx(bool restored) const; // Returns the height of the titlebar for popups or other browser types that // don't have tabs. int TitlebarHeight(int custom_height) const; // Returns the y coordinate for the top of the frame, which in maximized mode // is the top of the screen and in restored mode is 1 pixel below the top of // the window to leave room for the visual border that Windows draws. int WindowTopY() const; void LayoutCaptionButtons(); void LayoutWindowControlsOverlay(); // The container holding the caption buttons (minimize, maximize, close, etc.) // May be null if the caption button container is destroyed before the frame // view. Always check for validity before using! WinCaptionButtonContainer* caption_button_container_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_FRAME_VIEW_H_
closed
electron/electron
https://github.com/electron/electron
34,750
[Bug]: Datalist rendering on macOS broken
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19, 20 ### What operating system are you using? macOS ### Operating System Version Monterey 12.4 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.0-alpha.3 ### Expected Behavior Datalist is rendered below associated input, and words are not cut off ### Actual Behavior From Electron 19.0.0-alpha.4 on, the words are cut off at the bottom. This issue isnt present in 19.0.0-alpha.3, though the datalist overlay is still rendered in the wrong place (it seems due to it being rendered based on the offset from the webFrame, but placed on top of the webContents.) <img width="806" alt="Screenshot 2022-06-27 at 13 17 10" src="https://user-images.githubusercontent.com/41970/175929574-0a19832d-90e4-476b-8ab4-584e121015fc.png"> ### Testcase Gist URL https://gist.github.com/1525a4d39d33bc46eb033af6ebcf51c1 ### Additional Information The Gist loads a codepen with a datalist ( https://codepen.io/leorapirap/pen/ZBrBMx ) If you open that in chrome regular, or electron 18, the datalist dropdown looks good.
https://github.com/electron/electron/issues/34750
https://github.com/electron/electron/pull/34759
6257e0c348ed3e30b8b7799475adeb6019138f95
35ff95d3c71849ac97ced178a2330b9d4651f250
2022-06-27T11:16:42Z
c++
2022-06-29T08:14:03Z
shell/browser/ui/views/autofill_popup_view.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "shell/browser/ui/views/autofill_popup_view.h" #include <memory> #include <utility> #include "base/bind.h" #include "base/i18n/rtl.h" #include "cc/paint/skia_paint_canvas.h" #include "content/public/browser/render_view_host.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/base/dragdrop/drag_drop_types.h" #include "ui/color/color_provider.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/text_utils.h" #include "ui/views/border.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/widget/widget.h" namespace electron { void AutofillPopupChildView::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ax::mojom::Role::kMenuItem; node_data->SetName(suggestion_); } AutofillPopupView::AutofillPopupView(AutofillPopup* popup, views::Widget* parent_widget) : popup_(popup), parent_widget_(parent_widget) { CreateChildViews(); SetFocusBehavior(FocusBehavior::ALWAYS); set_drag_controller(this); } AutofillPopupView::~AutofillPopupView() { if (popup_) { auto* host = popup_->frame_host_->GetRenderViewHost()->GetWidget(); host->RemoveKeyPressEventCallback(keypress_callback_); popup_->view_ = nullptr; popup_ = nullptr; } RemoveObserver(); #if BUILDFLAG(ENABLE_OSR) if (view_proxy_.get()) { view_proxy_->ResetView(); } #endif if (GetWidget()) { GetWidget()->Close(); } } void AutofillPopupView::Show() { bool visible = parent_widget_->IsVisible(); #if BUILDFLAG(ENABLE_OSR) visible = visible || view_proxy_; #endif if (!popup_ || !visible || parent_widget_->IsClosed()) return; const bool initialize_widget = !GetWidget(); if (initialize_widget) { parent_widget_->AddObserver(this); // The widget is destroyed by the corresponding NativeWidget, so we use // a weak pointer to hold the reference and don't have to worry about // deletion. auto* widget = new views::Widget; views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP); params.delegate = this; params.parent = parent_widget_->GetNativeView(); params.z_order = ui::ZOrderLevel::kFloatingUIElement; widget->Init(std::move(params)); // No animation for popup appearance (too distracting). widget->SetVisibilityAnimationTransition(views::Widget::ANIMATE_HIDE); show_time_ = base::Time::Now(); } SetBorder(views::CreateSolidBorder( kPopupBorderThickness, GetColorProvider()->GetColor(ui::kColorUnfocusedBorder))); DoUpdateBoundsAndRedrawPopup(); GetWidget()->Show(); if (initialize_widget) views::WidgetFocusManager::GetInstance()->AddFocusChangeListener(this); keypress_callback_ = base::BindRepeating( &AutofillPopupView::HandleKeyPressEvent, base::Unretained(this)); auto* host = popup_->frame_host_->GetRenderViewHost()->GetWidget(); host->AddKeyPressEventCallback(keypress_callback_); NotifyAccessibilityEvent(ax::mojom::Event::kMenuStart, true); } void AutofillPopupView::Hide() { if (popup_) { auto* host = popup_->frame_host_->GetRenderViewHost()->GetWidget(); host->RemoveKeyPressEventCallback(keypress_callback_); popup_ = nullptr; } RemoveObserver(); NotifyAccessibilityEvent(ax::mojom::Event::kMenuEnd, true); if (GetWidget()) { GetWidget()->Close(); } } void AutofillPopupView::OnSuggestionsChanged() { if (!popup_) return; CreateChildViews(); if (popup_->GetLineCount() == 0) { popup_->Hide(); return; } DoUpdateBoundsAndRedrawPopup(); } void AutofillPopupView::WriteDragDataForView(views::View*, const gfx::Point&, ui::OSExchangeData*) {} int AutofillPopupView::GetDragOperationsForView(views::View*, const gfx::Point&) { return ui::DragDropTypes::DRAG_NONE; } bool AutofillPopupView::CanStartDragForView(views::View*, const gfx::Point&, const gfx::Point&) { return false; } void AutofillPopupView::OnSelectedRowChanged( absl::optional<int> previous_row_selection, absl::optional<int> current_row_selection) { SchedulePaint(); if (current_row_selection) { int selected = current_row_selection.value_or(-1); if (selected == -1 || static_cast<size_t>(selected) >= children().size()) return; children().at(selected)->NotifyAccessibilityEvent( ax::mojom::Event::kSelection, true); } } void AutofillPopupView::DrawAutofillEntry(gfx::Canvas* canvas, int index, const gfx::Rect& entry_rect) { if (!popup_) return; canvas->FillRect(entry_rect, GetColorProvider()->GetColor( popup_->GetBackgroundColorIDForRow(index))); const bool is_rtl = base::i18n::IsRTL(); const int text_align = is_rtl ? gfx::Canvas::TEXT_ALIGN_RIGHT : gfx::Canvas::TEXT_ALIGN_LEFT; gfx::Rect value_rect = entry_rect; value_rect.Inset(gfx::Insets::VH(kEndPadding, 0)); int x_align_left = value_rect.x(); const int value_width = gfx::GetStringWidth( popup_->GetValueAt(index), popup_->GetValueFontListForRow(index)); int value_x_align_left = x_align_left; value_x_align_left = is_rtl ? value_rect.right() - value_width : value_rect.x(); canvas->DrawStringRectWithFlags( popup_->GetValueAt(index), popup_->GetValueFontListForRow(index), GetColorProvider()->GetColor(ui::kColorResultsTableNormalText), gfx::Rect(value_x_align_left, value_rect.y(), value_width, value_rect.height()), text_align); // Draw the label text, if one exists. if (!popup_->GetLabelAt(index).empty()) { const int label_width = gfx::GetStringWidth( popup_->GetLabelAt(index), popup_->GetLabelFontListForRow(index)); int label_x_align_left = x_align_left; label_x_align_left = is_rtl ? value_rect.x() : value_rect.right() - label_width; canvas->DrawStringRectWithFlags( popup_->GetLabelAt(index), popup_->GetLabelFontListForRow(index), GetColorProvider()->GetColor(ui::kColorResultsTableDimmedText), gfx::Rect(label_x_align_left, entry_rect.y(), label_width, entry_rect.height()), text_align); } } void AutofillPopupView::CreateChildViews() { if (!popup_) return; RemoveAllChildViews(); for (int i = 0; i < popup_->GetLineCount(); ++i) { auto* child_view = new AutofillPopupChildView(popup_->GetValueAt(i)); child_view->set_drag_controller(this); AddChildView(child_view); } } void AutofillPopupView::DoUpdateBoundsAndRedrawPopup() { if (!popup_) return; GetWidget()->SetBounds(popup_->popup_bounds_); #if BUILDFLAG(ENABLE_OSR) if (view_proxy_.get()) { view_proxy_->SetBounds(popup_->popup_bounds_in_view()); } #endif SchedulePaint(); } void AutofillPopupView::OnPaint(gfx::Canvas* canvas) { if (!popup_ || static_cast<size_t>(popup_->GetLineCount()) != children().size()) return; gfx::Canvas* draw_canvas = canvas; SkBitmap bitmap; #if BUILDFLAG(ENABLE_OSR) std::unique_ptr<cc::SkiaPaintCanvas> paint_canvas; if (view_proxy_.get()) { bitmap.allocN32Pixels(popup_->popup_bounds_in_view().width(), popup_->popup_bounds_in_view().height(), true); paint_canvas = std::make_unique<cc::SkiaPaintCanvas>(bitmap); draw_canvas = new gfx::Canvas(paint_canvas.get(), 1.0); } #endif draw_canvas->DrawColor( GetColorProvider()->GetColor(ui::kColorResultsTableNormalBackground)); OnPaintBorder(draw_canvas); for (int i = 0; i < popup_->GetLineCount(); ++i) { gfx::Rect line_rect = popup_->GetRowBounds(i); DrawAutofillEntry(draw_canvas, i, line_rect); } #if BUILDFLAG(ENABLE_OSR) if (view_proxy_.get()) { view_proxy_->SetBounds(popup_->popup_bounds_in_view()); view_proxy_->SetBitmap(bitmap); } #endif } void AutofillPopupView::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ax::mojom::Role::kMenu; node_data->SetName("Autofill Menu"); } void AutofillPopupView::OnMouseCaptureLost() { ClearSelection(); } bool AutofillPopupView::OnMouseDragged(const ui::MouseEvent& event) { if (HitTestPoint(event.location())) { SetSelection(event.location()); // We must return true in order to get future OnMouseDragged and // OnMouseReleased events. return true; } // If we move off of the popup, we lose the selection. ClearSelection(); return false; } void AutofillPopupView::OnMouseExited(const ui::MouseEvent& event) { // Pressing return causes the cursor to hide, which will generate an // OnMouseExited event. Pressing return should activate the current selection // via AcceleratorPressed, so we need to let that run first. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&AutofillPopupView::ClearSelection, weak_ptr_factory_.GetWeakPtr())); } void AutofillPopupView::OnMouseMoved(const ui::MouseEvent& event) { // A synthesized mouse move will be sent when the popup is first shown. // Don't preview a suggestion if the mouse happens to be hovering there. #if BUILDFLAG(IS_WIN) if (base::Time::Now() - show_time_ <= base::Milliseconds(50)) return; #else if (event.flags() & ui::EF_IS_SYNTHESIZED) return; #endif if (HitTestPoint(event.location())) SetSelection(event.location()); else ClearSelection(); } bool AutofillPopupView::OnMousePressed(const ui::MouseEvent& event) { return event.GetClickCount() == 1; } void AutofillPopupView::OnMouseReleased(const ui::MouseEvent& event) { // We only care about the left click. if (event.IsOnlyLeftMouseButton() && HitTestPoint(event.location())) AcceptSelection(event.location()); } void AutofillPopupView::OnGestureEvent(ui::GestureEvent* event) { switch (event->type()) { case ui::ET_GESTURE_TAP_DOWN: case ui::ET_GESTURE_SCROLL_BEGIN: case ui::ET_GESTURE_SCROLL_UPDATE: if (HitTestPoint(event->location())) SetSelection(event->location()); else ClearSelection(); break; case ui::ET_GESTURE_TAP: case ui::ET_GESTURE_SCROLL_END: if (HitTestPoint(event->location())) AcceptSelection(event->location()); else ClearSelection(); break; case ui::ET_GESTURE_TAP_CANCEL: case ui::ET_SCROLL_FLING_START: ClearSelection(); break; default: return; } event->SetHandled(); } bool AutofillPopupView::AcceleratorPressed(const ui::Accelerator& accelerator) { if (accelerator.modifiers() != ui::EF_NONE) return false; if (accelerator.key_code() == ui::VKEY_ESCAPE) { if (popup_) popup_->Hide(); return true; } if (accelerator.key_code() == ui::VKEY_RETURN) return AcceptSelectedLine(); return false; } bool AutofillPopupView::HandleKeyPressEvent( const content::NativeWebKeyboardEvent& event) { if (!popup_) return false; switch (event.windows_key_code) { case ui::VKEY_UP: SelectPreviousLine(); return true; case ui::VKEY_DOWN: SelectNextLine(); return true; case ui::VKEY_PRIOR: // Page up. SetSelectedLine(0); return true; case ui::VKEY_NEXT: // Page down. SetSelectedLine(popup_->GetLineCount() - 1); return true; case ui::VKEY_ESCAPE: popup_->Hide(); return true; case ui::VKEY_TAB: // A tab press should cause the selected line to be accepted, but still // return false so the tab key press propagates and changes the cursor // location. AcceptSelectedLine(); return false; case ui::VKEY_RETURN: return AcceptSelectedLine(); default: return false; } } void AutofillPopupView::OnNativeFocusChanged(gfx::NativeView focused_now) { if (GetWidget() && GetWidget()->GetNativeView() != focused_now && popup_) popup_->Hide(); } void AutofillPopupView::OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& new_bounds) { if (widget != parent_widget_) return; if (popup_) popup_->Hide(); } void AutofillPopupView::AcceptSuggestion(int index) { if (!popup_) return; popup_->AcceptSuggestion(index); popup_->Hide(); } bool AutofillPopupView::AcceptSelectedLine() { if (!selected_line_ || selected_line_.value() >= popup_->GetLineCount()) return false; AcceptSuggestion(selected_line_.value()); return true; } void AutofillPopupView::AcceptSelection(const gfx::Point& point) { if (!popup_) return; SetSelectedLine(popup_->LineFromY(point.y())); AcceptSelectedLine(); } void AutofillPopupView::SetSelectedLine(absl::optional<int> selected_line) { if (!popup_) return; if (selected_line_ == selected_line) return; if (selected_line && selected_line.value() >= popup_->GetLineCount()) return; auto previous_selected_line(selected_line_); selected_line_ = selected_line; OnSelectedRowChanged(previous_selected_line, selected_line_); } void AutofillPopupView::SetSelection(const gfx::Point& point) { if (!popup_) return; SetSelectedLine(popup_->LineFromY(point.y())); } void AutofillPopupView::SelectNextLine() { if (!popup_) return; int new_selected_line = selected_line_ ? *selected_line_ + 1 : 0; if (new_selected_line >= popup_->GetLineCount()) new_selected_line = 0; SetSelectedLine(new_selected_line); } void AutofillPopupView::SelectPreviousLine() { if (!popup_) return; int new_selected_line = selected_line_.value_or(0) - 1; if (new_selected_line < 0) new_selected_line = popup_->GetLineCount() - 1; SetSelectedLine(new_selected_line); } void AutofillPopupView::ClearSelection() { SetSelectedLine(absl::nullopt); } void AutofillPopupView::RemoveObserver() { parent_widget_->RemoveObserver(this); views::WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(this); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,750
[Bug]: Datalist rendering on macOS broken
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19, 20 ### What operating system are you using? macOS ### Operating System Version Monterey 12.4 ### What arch are you using? x64 ### Last Known Working Electron version 19.0.0-alpha.3 ### Expected Behavior Datalist is rendered below associated input, and words are not cut off ### Actual Behavior From Electron 19.0.0-alpha.4 on, the words are cut off at the bottom. This issue isnt present in 19.0.0-alpha.3, though the datalist overlay is still rendered in the wrong place (it seems due to it being rendered based on the offset from the webFrame, but placed on top of the webContents.) <img width="806" alt="Screenshot 2022-06-27 at 13 17 10" src="https://user-images.githubusercontent.com/41970/175929574-0a19832d-90e4-476b-8ab4-584e121015fc.png"> ### Testcase Gist URL https://gist.github.com/1525a4d39d33bc46eb033af6ebcf51c1 ### Additional Information The Gist loads a codepen with a datalist ( https://codepen.io/leorapirap/pen/ZBrBMx ) If you open that in chrome regular, or electron 18, the datalist dropdown looks good.
https://github.com/electron/electron/issues/34750
https://github.com/electron/electron/pull/34759
6257e0c348ed3e30b8b7799475adeb6019138f95
35ff95d3c71849ac97ced178a2330b9d4651f250
2022-06-27T11:16:42Z
c++
2022-06-29T08:14:03Z
shell/browser/ui/views/autofill_popup_view.cc
// Copyright (c) 2012 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. #include "shell/browser/ui/views/autofill_popup_view.h" #include <memory> #include <utility> #include "base/bind.h" #include "base/i18n/rtl.h" #include "cc/paint/skia_paint_canvas.h" #include "content/public/browser/render_view_host.h" #include "ui/accessibility/ax_enums.mojom.h" #include "ui/base/dragdrop/drag_drop_types.h" #include "ui/color/color_provider.h" #include "ui/events/keycodes/keyboard_codes.h" #include "ui/gfx/canvas.h" #include "ui/gfx/geometry/point.h" #include "ui/gfx/geometry/rect.h" #include "ui/gfx/text_utils.h" #include "ui/views/border.h" #include "ui/views/focus/focus_manager.h" #include "ui/views/widget/widget.h" namespace electron { void AutofillPopupChildView::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ax::mojom::Role::kMenuItem; node_data->SetName(suggestion_); } AutofillPopupView::AutofillPopupView(AutofillPopup* popup, views::Widget* parent_widget) : popup_(popup), parent_widget_(parent_widget) { CreateChildViews(); SetFocusBehavior(FocusBehavior::ALWAYS); set_drag_controller(this); } AutofillPopupView::~AutofillPopupView() { if (popup_) { auto* host = popup_->frame_host_->GetRenderViewHost()->GetWidget(); host->RemoveKeyPressEventCallback(keypress_callback_); popup_->view_ = nullptr; popup_ = nullptr; } RemoveObserver(); #if BUILDFLAG(ENABLE_OSR) if (view_proxy_.get()) { view_proxy_->ResetView(); } #endif if (GetWidget()) { GetWidget()->Close(); } } void AutofillPopupView::Show() { bool visible = parent_widget_->IsVisible(); #if BUILDFLAG(ENABLE_OSR) visible = visible || view_proxy_; #endif if (!popup_ || !visible || parent_widget_->IsClosed()) return; const bool initialize_widget = !GetWidget(); if (initialize_widget) { parent_widget_->AddObserver(this); // The widget is destroyed by the corresponding NativeWidget, so we use // a weak pointer to hold the reference and don't have to worry about // deletion. auto* widget = new views::Widget; views::Widget::InitParams params(views::Widget::InitParams::TYPE_POPUP); params.delegate = this; params.parent = parent_widget_->GetNativeView(); params.z_order = ui::ZOrderLevel::kFloatingUIElement; widget->Init(std::move(params)); // No animation for popup appearance (too distracting). widget->SetVisibilityAnimationTransition(views::Widget::ANIMATE_HIDE); show_time_ = base::Time::Now(); } SetBorder(views::CreateSolidBorder( kPopupBorderThickness, GetColorProvider()->GetColor(ui::kColorUnfocusedBorder))); DoUpdateBoundsAndRedrawPopup(); GetWidget()->Show(); if (initialize_widget) views::WidgetFocusManager::GetInstance()->AddFocusChangeListener(this); keypress_callback_ = base::BindRepeating( &AutofillPopupView::HandleKeyPressEvent, base::Unretained(this)); auto* host = popup_->frame_host_->GetRenderViewHost()->GetWidget(); host->AddKeyPressEventCallback(keypress_callback_); NotifyAccessibilityEvent(ax::mojom::Event::kMenuStart, true); } void AutofillPopupView::Hide() { if (popup_) { auto* host = popup_->frame_host_->GetRenderViewHost()->GetWidget(); host->RemoveKeyPressEventCallback(keypress_callback_); popup_ = nullptr; } RemoveObserver(); NotifyAccessibilityEvent(ax::mojom::Event::kMenuEnd, true); if (GetWidget()) { GetWidget()->Close(); } } void AutofillPopupView::OnSuggestionsChanged() { if (!popup_) return; CreateChildViews(); if (popup_->GetLineCount() == 0) { popup_->Hide(); return; } DoUpdateBoundsAndRedrawPopup(); } void AutofillPopupView::WriteDragDataForView(views::View*, const gfx::Point&, ui::OSExchangeData*) {} int AutofillPopupView::GetDragOperationsForView(views::View*, const gfx::Point&) { return ui::DragDropTypes::DRAG_NONE; } bool AutofillPopupView::CanStartDragForView(views::View*, const gfx::Point&, const gfx::Point&) { return false; } void AutofillPopupView::OnSelectedRowChanged( absl::optional<int> previous_row_selection, absl::optional<int> current_row_selection) { SchedulePaint(); if (current_row_selection) { int selected = current_row_selection.value_or(-1); if (selected == -1 || static_cast<size_t>(selected) >= children().size()) return; children().at(selected)->NotifyAccessibilityEvent( ax::mojom::Event::kSelection, true); } } void AutofillPopupView::DrawAutofillEntry(gfx::Canvas* canvas, int index, const gfx::Rect& entry_rect) { if (!popup_) return; canvas->FillRect(entry_rect, GetColorProvider()->GetColor( popup_->GetBackgroundColorIDForRow(index))); const bool is_rtl = base::i18n::IsRTL(); const int text_align = is_rtl ? gfx::Canvas::TEXT_ALIGN_RIGHT : gfx::Canvas::TEXT_ALIGN_LEFT; gfx::Rect value_rect = entry_rect; value_rect.Inset(gfx::Insets::VH(kEndPadding, 0)); int x_align_left = value_rect.x(); const int value_width = gfx::GetStringWidth( popup_->GetValueAt(index), popup_->GetValueFontListForRow(index)); int value_x_align_left = x_align_left; value_x_align_left = is_rtl ? value_rect.right() - value_width : value_rect.x(); canvas->DrawStringRectWithFlags( popup_->GetValueAt(index), popup_->GetValueFontListForRow(index), GetColorProvider()->GetColor(ui::kColorResultsTableNormalText), gfx::Rect(value_x_align_left, value_rect.y(), value_width, value_rect.height()), text_align); // Draw the label text, if one exists. if (!popup_->GetLabelAt(index).empty()) { const int label_width = gfx::GetStringWidth( popup_->GetLabelAt(index), popup_->GetLabelFontListForRow(index)); int label_x_align_left = x_align_left; label_x_align_left = is_rtl ? value_rect.x() : value_rect.right() - label_width; canvas->DrawStringRectWithFlags( popup_->GetLabelAt(index), popup_->GetLabelFontListForRow(index), GetColorProvider()->GetColor(ui::kColorResultsTableDimmedText), gfx::Rect(label_x_align_left, entry_rect.y(), label_width, entry_rect.height()), text_align); } } void AutofillPopupView::CreateChildViews() { if (!popup_) return; RemoveAllChildViews(); for (int i = 0; i < popup_->GetLineCount(); ++i) { auto* child_view = new AutofillPopupChildView(popup_->GetValueAt(i)); child_view->set_drag_controller(this); AddChildView(child_view); } } void AutofillPopupView::DoUpdateBoundsAndRedrawPopup() { if (!popup_) return; GetWidget()->SetBounds(popup_->popup_bounds_); #if BUILDFLAG(ENABLE_OSR) if (view_proxy_.get()) { view_proxy_->SetBounds(popup_->popup_bounds_in_view()); } #endif SchedulePaint(); } void AutofillPopupView::OnPaint(gfx::Canvas* canvas) { if (!popup_ || static_cast<size_t>(popup_->GetLineCount()) != children().size()) return; gfx::Canvas* draw_canvas = canvas; SkBitmap bitmap; #if BUILDFLAG(ENABLE_OSR) std::unique_ptr<cc::SkiaPaintCanvas> paint_canvas; if (view_proxy_.get()) { bitmap.allocN32Pixels(popup_->popup_bounds_in_view().width(), popup_->popup_bounds_in_view().height(), true); paint_canvas = std::make_unique<cc::SkiaPaintCanvas>(bitmap); draw_canvas = new gfx::Canvas(paint_canvas.get(), 1.0); } #endif draw_canvas->DrawColor( GetColorProvider()->GetColor(ui::kColorResultsTableNormalBackground)); OnPaintBorder(draw_canvas); for (int i = 0; i < popup_->GetLineCount(); ++i) { gfx::Rect line_rect = popup_->GetRowBounds(i); DrawAutofillEntry(draw_canvas, i, line_rect); } #if BUILDFLAG(ENABLE_OSR) if (view_proxy_.get()) { view_proxy_->SetBounds(popup_->popup_bounds_in_view()); view_proxy_->SetBitmap(bitmap); } #endif } void AutofillPopupView::GetAccessibleNodeData(ui::AXNodeData* node_data) { node_data->role = ax::mojom::Role::kMenu; node_data->SetName("Autofill Menu"); } void AutofillPopupView::OnMouseCaptureLost() { ClearSelection(); } bool AutofillPopupView::OnMouseDragged(const ui::MouseEvent& event) { if (HitTestPoint(event.location())) { SetSelection(event.location()); // We must return true in order to get future OnMouseDragged and // OnMouseReleased events. return true; } // If we move off of the popup, we lose the selection. ClearSelection(); return false; } void AutofillPopupView::OnMouseExited(const ui::MouseEvent& event) { // Pressing return causes the cursor to hide, which will generate an // OnMouseExited event. Pressing return should activate the current selection // via AcceleratorPressed, so we need to let that run first. base::ThreadTaskRunnerHandle::Get()->PostTask( FROM_HERE, base::BindOnce(&AutofillPopupView::ClearSelection, weak_ptr_factory_.GetWeakPtr())); } void AutofillPopupView::OnMouseMoved(const ui::MouseEvent& event) { // A synthesized mouse move will be sent when the popup is first shown. // Don't preview a suggestion if the mouse happens to be hovering there. #if BUILDFLAG(IS_WIN) if (base::Time::Now() - show_time_ <= base::Milliseconds(50)) return; #else if (event.flags() & ui::EF_IS_SYNTHESIZED) return; #endif if (HitTestPoint(event.location())) SetSelection(event.location()); else ClearSelection(); } bool AutofillPopupView::OnMousePressed(const ui::MouseEvent& event) { return event.GetClickCount() == 1; } void AutofillPopupView::OnMouseReleased(const ui::MouseEvent& event) { // We only care about the left click. if (event.IsOnlyLeftMouseButton() && HitTestPoint(event.location())) AcceptSelection(event.location()); } void AutofillPopupView::OnGestureEvent(ui::GestureEvent* event) { switch (event->type()) { case ui::ET_GESTURE_TAP_DOWN: case ui::ET_GESTURE_SCROLL_BEGIN: case ui::ET_GESTURE_SCROLL_UPDATE: if (HitTestPoint(event->location())) SetSelection(event->location()); else ClearSelection(); break; case ui::ET_GESTURE_TAP: case ui::ET_GESTURE_SCROLL_END: if (HitTestPoint(event->location())) AcceptSelection(event->location()); else ClearSelection(); break; case ui::ET_GESTURE_TAP_CANCEL: case ui::ET_SCROLL_FLING_START: ClearSelection(); break; default: return; } event->SetHandled(); } bool AutofillPopupView::AcceleratorPressed(const ui::Accelerator& accelerator) { if (accelerator.modifiers() != ui::EF_NONE) return false; if (accelerator.key_code() == ui::VKEY_ESCAPE) { if (popup_) popup_->Hide(); return true; } if (accelerator.key_code() == ui::VKEY_RETURN) return AcceptSelectedLine(); return false; } bool AutofillPopupView::HandleKeyPressEvent( const content::NativeWebKeyboardEvent& event) { if (!popup_) return false; switch (event.windows_key_code) { case ui::VKEY_UP: SelectPreviousLine(); return true; case ui::VKEY_DOWN: SelectNextLine(); return true; case ui::VKEY_PRIOR: // Page up. SetSelectedLine(0); return true; case ui::VKEY_NEXT: // Page down. SetSelectedLine(popup_->GetLineCount() - 1); return true; case ui::VKEY_ESCAPE: popup_->Hide(); return true; case ui::VKEY_TAB: // A tab press should cause the selected line to be accepted, but still // return false so the tab key press propagates and changes the cursor // location. AcceptSelectedLine(); return false; case ui::VKEY_RETURN: return AcceptSelectedLine(); default: return false; } } void AutofillPopupView::OnNativeFocusChanged(gfx::NativeView focused_now) { if (GetWidget() && GetWidget()->GetNativeView() != focused_now && popup_) popup_->Hide(); } void AutofillPopupView::OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& new_bounds) { if (widget != parent_widget_) return; if (popup_) popup_->Hide(); } void AutofillPopupView::AcceptSuggestion(int index) { if (!popup_) return; popup_->AcceptSuggestion(index); popup_->Hide(); } bool AutofillPopupView::AcceptSelectedLine() { if (!selected_line_ || selected_line_.value() >= popup_->GetLineCount()) return false; AcceptSuggestion(selected_line_.value()); return true; } void AutofillPopupView::AcceptSelection(const gfx::Point& point) { if (!popup_) return; SetSelectedLine(popup_->LineFromY(point.y())); AcceptSelectedLine(); } void AutofillPopupView::SetSelectedLine(absl::optional<int> selected_line) { if (!popup_) return; if (selected_line_ == selected_line) return; if (selected_line && selected_line.value() >= popup_->GetLineCount()) return; auto previous_selected_line(selected_line_); selected_line_ = selected_line; OnSelectedRowChanged(previous_selected_line, selected_line_); } void AutofillPopupView::SetSelection(const gfx::Point& point) { if (!popup_) return; SetSelectedLine(popup_->LineFromY(point.y())); } void AutofillPopupView::SelectNextLine() { if (!popup_) return; int new_selected_line = selected_line_ ? *selected_line_ + 1 : 0; if (new_selected_line >= popup_->GetLineCount()) new_selected_line = 0; SetSelectedLine(new_selected_line); } void AutofillPopupView::SelectPreviousLine() { if (!popup_) return; int new_selected_line = selected_line_.value_or(0) - 1; if (new_selected_line < 0) new_selected_line = popup_->GetLineCount() - 1; SetSelectedLine(new_selected_line); } void AutofillPopupView::ClearSelection() { SetSelectedLine(absl::nullopt); } void AutofillPopupView::RemoveObserver() { parent_widget_->RemoveObserver(this); views::WidgetFocusManager::GetInstance()->RemoveFocusChangeListener(this); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
31,634
[Bug]: crypto.hkdf "Deriving bits failed"
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version v15.3.0 ### What operating system are you using? macOS ### Operating System Version Darwin C02CX0K5MD6V 20.6.0 Darwin Kernel Version 20.6.0: Mon Aug 30 06:12:21 PDT 2021; root:xnu-7195.141.6~3/RELEASE_X86_64 x86_64 ### What arch are you using? x64 ### Last Known Working Electron version none ### Expected Behavior `crypto.hkdf` and `crypto.hkdfSync` work as documented[^1] [^1]: https://nodejs.org/api/crypto.html#cryptohkdfdigest-ikm-salt-info-keylen-callback ### Actual Behavior ``` crypto.hkdfSync('sha256', 'foo', '', '', 32) // Uncaught Error: Deriving bits failed // at Object.hkdfSync (node:internal/crypto/hkdf:140:35) crypto.hkdf('sha256', 'foo', '', '', 32, console.log) // [Error: Deriving bits failed] ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/31634
https://github.com/electron/electron/pull/34767
35ff95d3c71849ac97ced178a2330b9d4651f250
ad2b1fee59c2e4352b0c5664f72c0067a2ef4d7f
2021-10-29T09:01:40Z
c++
2022-06-29T12:53:57Z
patches/node/fix_crypto_tests_to_run_with_bssl.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Jeremy Rose <[email protected]> Date: Tue, 9 Feb 2021 12:34:46 -0800 Subject: fix crypto tests to run with bssl This fixes some crypto tests so that they pass when compiled with BoringSSL. This should be upstreamed in some form, though it may need to be tweaked before it's acceptable to upstream, as this patch comments out a couple of tests that upstream probably cares about. diff --git a/test/parallel/test-crypto-async-sign-verify.js b/test/parallel/test-crypto-async-sign-verify.js index 4e3c32fdcd23fbe3e74bd5e624b739d224689f33..19d65aae7fa8ec9f9b907733ead17a208ed47909 100644 --- a/test/parallel/test-crypto-async-sign-verify.js +++ b/test/parallel/test-crypto-async-sign-verify.js @@ -88,6 +88,7 @@ test('rsa_public.pem', 'rsa_private.pem', 'sha256', false, // ED25519 test('ed25519_public.pem', 'ed25519_private.pem', undefined, true); // ED448 +/* test('ed448_public.pem', 'ed448_private.pem', undefined, true); // ECDSA w/ der signature encoding @@ -109,6 +110,7 @@ test('dsa_public.pem', 'dsa_private.pem', 'sha256', // DSA w/ ieee-p1363 signature encoding test('dsa_public.pem', 'dsa_private.pem', 'sha256', false, { dsaEncoding: 'ieee-p1363' }); +*/ // Test Parallel Execution w/ KeyObject is threadsafe in openssl3 { diff --git a/test/parallel/test-crypto-authenticated.js b/test/parallel/test-crypto-authenticated.js index 3749895769ffc9947143aee9aeb126628262bc84..f769fc37dbd81d5a0219236921e0bcb0de416463 100644 --- a/test/parallel/test-crypto-authenticated.js +++ b/test/parallel/test-crypto-authenticated.js @@ -50,7 +50,9 @@ const errMessages = { const ciphers = crypto.getCiphers(); const expectedWarnings = common.hasFipsCrypto ? - [] : [ + [] : !ciphers.includes('aes-192-ccm') ? [ + ['Use Cipheriv for counter mode of aes-192-gcm'], + ] : [ ['Use Cipheriv for counter mode of aes-192-gcm'], ['Use Cipheriv for counter mode of aes-192-ccm'], ['Use Cipheriv for counter mode of aes-192-ccm'], @@ -319,7 +321,9 @@ for (const test of TEST_CASES) { // Test that create(De|C)ipher(iv)? throws if the mode is CCM and an invalid // authentication tag length has been specified. -{ +if (!ciphers.includes('aes-256-ccm')) { + common.printSkipMessage(`unsupported aes-256-ccm test`); +} else { for (const authTagLength of [-1, true, false, NaN, 5.5]) { assert.throws(() => { crypto.createCipheriv('aes-256-ccm', @@ -407,6 +411,10 @@ for (const test of TEST_CASES) { // authentication tag has been specified. { for (const mode of ['ccm', 'ocb']) { + if (!ciphers.includes(`aes-256-${mode}`)) { + common.printSkipMessage(`unsupported aes-256-${mode} test`); + continue; + } assert.throws(() => { crypto.createCipheriv(`aes-256-${mode}`, 'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8', @@ -441,7 +449,9 @@ for (const test of TEST_CASES) { } // Test that setAAD throws if an invalid plaintext length has been specified. -{ +if (!ciphers.includes('aes-256-ccm')) { + common.printSkipMessage(`unsupported aes-256-ccm test`); +} else { const cipher = crypto.createCipheriv('aes-256-ccm', 'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8', 'qkuZpJWCewa6S', @@ -462,7 +472,9 @@ for (const test of TEST_CASES) { } // Test that setAAD and update throw if the plaintext is too long. -{ +if (!ciphers.includes('aes-256-ccm')) { + common.printSkipMessage(`unsupported aes-256-ccm test`); +} else { for (const ivLength of [13, 12]) { const maxMessageSize = (1 << (8 * (15 - ivLength))) - 1; const key = 'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8'; @@ -493,7 +505,9 @@ for (const test of TEST_CASES) { // Test that setAAD throws if the mode is CCM and the plaintext length has not // been specified. -{ +if (!ciphers.includes('aes-256-ccm')) { + common.printSkipMessage(`unsupported aes-256-ccm test`); +} else { assert.throws(() => { const cipher = crypto.createCipheriv('aes-256-ccm', 'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8', @@ -518,7 +532,9 @@ for (const test of TEST_CASES) { } // Test that final() throws in CCM mode when no authentication tag is provided. -{ +if (!ciphers.includes('aes-128-ccm')) { + common.printSkipMessage(`unsupported aes-256-ccm test`); +} else { if (!common.hasFipsCrypto) { const key = Buffer.from('1ed2233fa2223ef5d7df08546049406c', 'hex'); const iv = Buffer.from('7305220bca40d4c90e1791e9', 'hex'); @@ -550,7 +566,9 @@ for (const test of TEST_CASES) { } // Test that an IV length of 11 does not overflow max_message_size_. -{ +if (!ciphers.includes('aes-128-ccm')) { + common.printSkipMessage(`unsupported aes-128-ccm test`); +} else { const key = 'x'.repeat(16); const iv = Buffer.from('112233445566778899aabb', 'hex'); const options = { authTagLength: 8 }; @@ -567,6 +585,10 @@ for (const test of TEST_CASES) { const iv = Buffer.from('0123456789ab', 'utf8'); for (const mode of ['gcm', 'ocb']) { + if (!ciphers.includes(`aes-128-${mode}`)) { + common.printSkipMessage(`unsupported aes-128-${mode} test`); + continue; + } for (const authTagLength of mode === 'gcm' ? [undefined, 8] : [8]) { const cipher = crypto.createCipheriv(`aes-128-${mode}`, key, iv, { authTagLength @@ -601,6 +623,10 @@ for (const test of TEST_CASES) { const opts = { authTagLength: 8 }; for (const mode of ['gcm', 'ccm', 'ocb']) { + if (!ciphers.includes(`aes-128-${mode}`)) { + common.printSkipMessage(`unsupported aes-128-${mode} test`); + continue; + } const cipher = crypto.createCipheriv(`aes-128-${mode}`, key, iv, opts); const ciphertext = Buffer.concat([cipher.update(plain), cipher.final()]); const tag = cipher.getAuthTag(); @@ -623,7 +649,9 @@ for (const test of TEST_CASES) { // Test chacha20-poly1305 rejects invalid IV lengths of 13, 14, 15, and 16 (a // length of 17 or greater was already rejected). // - https://www.openssl.org/news/secadv/20190306.txt -{ +if (!ciphers.includes('chacha20-poly1305')) { + common.printSkipMessage(`unsupported chacha20-poly1305 test`); +} else { // Valid extracted from TEST_CASES, check that it detects IV tampering. const valid = { algo: 'chacha20-poly1305', @@ -669,6 +697,9 @@ for (const test of TEST_CASES) { { // CCM cipher without data should not crash, see https://github.com/nodejs/node/issues/38035. + common.printSkipMessage(`unsupported aes-128-ccm test`); + return; + const algo = 'aes-128-ccm'; const key = Buffer.alloc(16); const iv = Buffer.alloc(12); diff --git a/test/parallel/test-crypto-binary-default.js b/test/parallel/test-crypto-binary-default.js index 3bbca5b0da395b94c04da7bb7c55b107e41367d8..af62558c4f23aa82804e0077da7b7f3a86cfac60 100644 --- a/test/parallel/test-crypto-binary-default.js +++ b/test/parallel/test-crypto-binary-default.js @@ -51,15 +51,15 @@ tls.createSecureContext({ pfx: certPfx, passphrase: 'sample' }); assert.throws(function() { tls.createSecureContext({ pfx: certPfx }); -}, /^Error: mac verify failure$/); +}, /^Error: (mac verify failure|INCORRECT_PASSWORD)$/); assert.throws(function() { tls.createSecureContext({ pfx: certPfx, passphrase: 'test' }); -}, /^Error: mac verify failure$/); +}, /^Error: (mac verify failure|INCORRECT_PASSWORD)$/); assert.throws(function() { tls.createSecureContext({ pfx: 'sample', passphrase: 'test' }); -}, /^Error: not enough data$/); +}, /^Error: (not enough data|BAD_PKCS12_DATA)$/); // Test HMAC { @@ -462,7 +462,7 @@ assert.throws(function() { function testCipher1(key) { // Test encryption and decryption const plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; - const cipher = crypto.createCipher('aes192', key); + const cipher = crypto.createCipher('aes-192-cbc', key); // Encrypt plaintext which is in utf8 format // to a ciphertext which will be in hex @@ -470,7 +470,7 @@ function testCipher1(key) { // Only use binary or hex, not base64. ciph += cipher.final('hex'); - const decipher = crypto.createDecipher('aes192', key); + const decipher = crypto.createDecipher('aes-192-cbc', key); let txt = decipher.update(ciph, 'hex', 'utf8'); txt += decipher.final('utf8'); @@ -485,14 +485,14 @@ function testCipher2(key) { '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'jAfaFg**'; - const cipher = crypto.createCipher('aes256', key); + const cipher = crypto.createCipher('aes-256-cbc', key); // Encrypt plaintext which is in utf8 format // to a ciphertext which will be in Base64 let ciph = cipher.update(plaintext, 'utf8', 'base64'); ciph += cipher.final('base64'); - const decipher = crypto.createDecipher('aes256', key); + const decipher = crypto.createDecipher('aes-256-cbc', key); let txt = decipher.update(ciph, 'base64', 'utf8'); txt += decipher.final('utf8'); @@ -537,6 +537,10 @@ function testCipher4(key, iv) { function testCipher5(key, iv) { + if (!crypto.getCiphers().includes('id-aes128-wrap')) { + common.printSkipMessage(`unsupported id-aes128-wrap test`); + return; + } // Test encryption and decryption with explicit key with aes128-wrap const plaintext = '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + @@ -662,6 +666,8 @@ assert.throws( } +/* NB: BoringSSL does not support using DSA through the EVP API. + * https://boringssl.googlesource.com/boringssl/+/a2278d4d2cabe73f6663e3299ea7808edfa306b9/PORTING.md#dsa-s // // Test DSA signing and verification // @@ -682,6 +688,7 @@ assert.throws( assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); } +*/ // diff --git a/test/parallel/test-crypto-certificate.js b/test/parallel/test-crypto-certificate.js index 4a5f1f149fe6c739f7f1d2ee17df6e61a942d621..b3287f428ce6b3fde11d449c601a57ff5e3843f9 100644 --- a/test/parallel/test-crypto-certificate.js +++ b/test/parallel/test-crypto-certificate.js @@ -40,8 +40,10 @@ function copyArrayBuffer(buf) { } function checkMethods(certificate) { - + /* spkacValid has a md5 based signature which is not allowed in boringssl + https://boringssl.googlesource.com/boringssl/+/33d7e32ce40c04e8f1b99c05964956fda187819f assert.strictEqual(certificate.verifySpkac(spkacValid), true); + */ assert.strictEqual(certificate.verifySpkac(spkacFail), false); assert.strictEqual( @@ -56,10 +58,12 @@ function checkMethods(certificate) { ); assert.strictEqual(certificate.exportChallenge(spkacFail), ''); + /* spkacValid has a md5 based signature which is not allowed in boringssl const ab = copyArrayBuffer(spkacValid); assert.strictEqual(certificate.verifySpkac(ab), true); assert.strictEqual(certificate.verifySpkac(new Uint8Array(ab)), true); assert.strictEqual(certificate.verifySpkac(new DataView(ab)), true); + */ } { diff --git a/test/parallel/test-crypto-cipher-decipher.js b/test/parallel/test-crypto-cipher-decipher.js index 35514afbea92562a81c163b1e4d918b4ab609f71..13098e1acf12c309f2ed6f6143a2c2eeb8a2763d 100644 --- a/test/parallel/test-crypto-cipher-decipher.js +++ b/test/parallel/test-crypto-cipher-decipher.js @@ -22,7 +22,7 @@ common.expectWarning({ function testCipher1(key) { // Test encryption and decryption const plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; - const cipher = crypto.createCipher('aes192', key); + const cipher = crypto.createCipher('aes-192-cbc', key); // Encrypt plaintext which is in utf8 format // to a ciphertext which will be in hex @@ -30,7 +30,7 @@ function testCipher1(key) { // Only use binary or hex, not base64. ciph += cipher.final('hex'); - const decipher = crypto.createDecipher('aes192', key); + const decipher = crypto.createDecipher('aes-192-cbc', key); let txt = decipher.update(ciph, 'hex', 'utf8'); txt += decipher.final('utf8'); @@ -40,11 +40,11 @@ function testCipher1(key) { // NB: In real life, it's not guaranteed that you can get all of it // in a single read() like this. But in this case, we know it's // quite small, so there's no harm. - const cStream = crypto.createCipher('aes192', key); + const cStream = crypto.createCipher('aes-192-cbc', key); cStream.end(plaintext); ciph = cStream.read(); - const dStream = crypto.createDecipher('aes192', key); + const dStream = crypto.createDecipher('aes-192-cbc', key); dStream.end(ciph); txt = dStream.read().toString('utf8'); @@ -59,14 +59,14 @@ function testCipher2(key) { '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'jAfaFg**'; - const cipher = crypto.createCipher('aes256', key); + const cipher = crypto.createCipher('aes-256-cbc', key); // Encrypt plaintext which is in utf8 format to a ciphertext which will be in // Base64. let ciph = cipher.update(plaintext, 'utf8', 'base64'); ciph += cipher.final('base64'); - const decipher = crypto.createDecipher('aes256', key); + const decipher = crypto.createDecipher('aes-256-cbc', key); let txt = decipher.update(ciph, 'base64', 'utf8'); txt += decipher.final('utf8'); @@ -170,7 +170,7 @@ testCipher2(Buffer.from('0123456789abcdef')); // Regression test for https://github.com/nodejs/node-v0.x-archive/issues/5482: // string to Cipher#update() should not assert. { - const c = crypto.createCipher('aes192', '0123456789abcdef'); + const c = crypto.createCipher('aes-192-cbc', '0123456789abcdef'); c.update('update'); c.final(); } @@ -178,15 +178,15 @@ testCipher2(Buffer.from('0123456789abcdef')); // https://github.com/nodejs/node-v0.x-archive/issues/5655 regression tests, // 'utf-8' and 'utf8' are identical. { - let c = crypto.createCipher('aes192', '0123456789abcdef'); + let c = crypto.createCipher('aes-192-cbc', '0123456789abcdef'); c.update('update', ''); // Defaults to "utf8". c.final('utf-8'); // Should not throw. - c = crypto.createCipher('aes192', '0123456789abcdef'); + c = crypto.createCipher('aes-192-cbc', '0123456789abcdef'); c.update('update', 'utf8'); c.final('utf-8'); // Should not throw. - c = crypto.createCipher('aes192', '0123456789abcdef'); + c = crypto.createCipher('aes-192-cbc', '0123456789abcdef'); c.update('update', 'utf-8'); c.final('utf8'); // Should not throw. } @@ -195,23 +195,23 @@ testCipher2(Buffer.from('0123456789abcdef')); { const key = '0123456789abcdef'; const plaintext = 'Top secret!!!'; - const c = crypto.createCipher('aes192', key); + const c = crypto.createCipher('aes-192-cbc', key); let ciph = c.update(plaintext, 'utf16le', 'base64'); ciph += c.final('base64'); - let decipher = crypto.createDecipher('aes192', key); + let decipher = crypto.createDecipher('aes-192-cbc', key); let txt; txt = decipher.update(ciph, 'base64', 'ucs2'); txt += decipher.final('ucs2'); assert.strictEqual(txt, plaintext); - decipher = crypto.createDecipher('aes192', key); + decipher = crypto.createDecipher('aes-192-cbc', key); txt = decipher.update(ciph, 'base64', 'ucs-2'); txt += decipher.final('ucs-2'); assert.strictEqual(txt, plaintext); - decipher = crypto.createDecipher('aes192', key); + decipher = crypto.createDecipher('aes-192-cbc', key); txt = decipher.update(ciph, 'base64', 'utf-16le'); txt += decipher.final('utf-16le'); assert.strictEqual(txt, plaintext); diff --git a/test/parallel/test-crypto-cipheriv-decipheriv.js b/test/parallel/test-crypto-cipheriv-decipheriv.js index 87f3641fb188bd322e7c256e9548c6af85dc9a14..1e803bc33ba4642065bf1897c56f65fc92bd2a50 100644 --- a/test/parallel/test-crypto-cipheriv-decipheriv.js +++ b/test/parallel/test-crypto-cipheriv-decipheriv.js @@ -60,6 +60,10 @@ function testCipher2(key, iv) { function testCipher3(key, iv) { + if (!crypto.getCiphers().includes('id-aes128-wrap')) { + common.printSkipMessage(`unsupported id-aes128-wrap test`); + return; + } // Test encryption and decryption with explicit key and iv. // AES Key Wrap test vector comes from RFC3394 const plaintext = Buffer.from('00112233445566778899AABBCCDDEEFF', 'hex'); diff --git a/test/parallel/test-crypto-classes.js b/test/parallel/test-crypto-classes.js index dd073274aef765e8f1e403aa2c8baf9694b521cb..fc6339e040debe61ecc61a3eb5b26823b102f1ff 100644 --- a/test/parallel/test-crypto-classes.js +++ b/test/parallel/test-crypto-classes.js @@ -22,8 +22,8 @@ const TEST_CASES = { }; if (!common.hasFipsCrypto) { - TEST_CASES.Cipher = ['aes192', 'secret']; - TEST_CASES.Decipher = ['aes192', 'secret']; + TEST_CASES.Cipher = ['aes-192-cbc', 'secret']; + TEST_CASES.Decipher = ['aes-192-cbc', 'secret']; TEST_CASES.DiffieHellman = [common.hasOpenSSL3 ? 1024 : 256]; } diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js index 18721fcf289e5545408e309db050a2ff0f4b0140..e5235e0a5fbd68416b4a9480818901b411ed91bd 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -49,7 +49,7 @@ for (const bits of [-1, 0, 1]) { assert.throws(() => crypto.createDiffieHellman(bits), { code: 'ERR_OSSL_BN_BITS_TOO_SMALL', name: 'Error', - message: /bits too small/, + message: /bits too small|BITS_TOO_SMALL/, }); } } @@ -65,7 +65,7 @@ for (const g of [-1, 1]) { const ex = { code: 'ERR_OSSL_DH_BAD_GENERATOR', name: 'Error', - message: /bad generator/, + message: /bad generator|BAD_GENERATOR/, }; assert.throws(() => crypto.createDiffieHellman('abcdef', g), ex); assert.throws(() => crypto.createDiffieHellman('abcdef', 'hex', g), ex); @@ -79,7 +79,7 @@ for (const g of [Buffer.from([]), const ex = { code: 'ERR_OSSL_DH_BAD_GENERATOR', name: 'Error', - message: /bad generator/, + message: /bad generator|BAD_GENERATOR/, }; assert.throws(() => crypto.createDiffieHellman('abcdef', g), ex); assert.throws(() => crypto.createDiffieHellman('abcdef', 'hex', g), ex); @@ -133,18 +133,17 @@ assert.strictEqual(secret1, secret4); let wrongBlockLength; if (common.hasOpenSSL3) { wrongBlockLength = { - message: 'error:1C80006B:Provider routines::wrong final block length', - code: 'ERR_OSSL_WRONG_FINAL_BLOCK_LENGTH', - library: 'Provider routines', - reason: 'wrong final block length' + message: /error:1C80006B:Provider routines::wrong final block length|error:1e00007b:Cipher functions:OPENSSL_internal:WRONG_FINAL_BLOCK_LENGTH/, + code: /ERR_OSSL_(EVP_)?WRONG_FINAL_BLOCK_LENGTH/, + library: /digital envelope routines|Cipher functions/, + reason: /wrong final block length|WRONG_FINAL_BLOCK_LENGTH/ }; } else { wrongBlockLength = { - message: 'error:0606506D:digital envelope' + - ' routines:EVP_DecryptFinal_ex:wrong final block length', - code: 'ERR_OSSL_EVP_WRONG_FINAL_BLOCK_LENGTH', - library: 'digital envelope routines', - reason: 'wrong final block length' + message: /error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length|error:1e00007b:Cipher functions:OPENSSL_internal:WRONG_FINAL_BLOCK_LENGTH/, + code: /ERR_OSSL_(EVP_)?WRONG_FINAL_BLOCK_LENGTH/, + library: /digital envelope routines|Cipher functions/, + reason: /wrong final block length|WRONG_FINAL_BLOCK_LENGTH/ }; } diff --git a/test/parallel/test-crypto-getcipherinfo.js b/test/parallel/test-crypto-getcipherinfo.js index 98d2a52eceac4bc564fd2878f77b50c336a67a66..bcb2de6e354c26816000f2400d9c1d46de01888a 100644 --- a/test/parallel/test-crypto-getcipherinfo.js +++ b/test/parallel/test-crypto-getcipherinfo.js @@ -62,9 +62,13 @@ assert(getCipherInfo('aes-128-cbc', { ivLength: 16 })); assert(!getCipherInfo('aes-128-ccm', { ivLength: 1 })); assert(!getCipherInfo('aes-128-ccm', { ivLength: 14 })); +/* for (let n = 7; n <= 13; n++) assert(getCipherInfo('aes-128-ccm', { ivLength: n })); +*/ assert(!getCipherInfo('aes-128-ocb', { ivLength: 16 })); +/* for (let n = 1; n < 16; n++) assert(getCipherInfo('aes-128-ocb', { ivLength: n })); +*/ \ No newline at end of file diff --git a/test/parallel/test-crypto-hash-stream-pipe.js b/test/parallel/test-crypto-hash-stream-pipe.js index d22281abbd5c3cab3aaa3ac494301fa6b4a8a968..5f0c6a4aed2e868a1a1049212edf218791cd6868 100644 --- a/test/parallel/test-crypto-hash-stream-pipe.js +++ b/test/parallel/test-crypto-hash-stream-pipe.js @@ -30,11 +30,11 @@ const crypto = require('crypto'); const stream = require('stream'); const s = new stream.PassThrough(); -const h = crypto.createHash('sha3-512'); -const expect = '36a38a2a35e698974d4e5791a3f05b05' + - '198235381e864f91a0e8cd6a26b677ec' + - 'dcde8e2b069bd7355fabd68abd6fc801' + - '19659f25e92f8efc961ee3a7c815c758'; +const h = crypto.createHash('sha512'); +const expect = 'fba055c6fd0c5b6645407749ed7a8b41' + + 'b8f629f2163c3ca3701d864adabda1f8' + + '93c37bf82b22fdd151ba8e357f611da4' + + '88a74b6a5525dd9b69554c6ce5138ad7'; s.pipe(h).on('data', common.mustCall(function(c) { assert.strictEqual(c, expect); diff --git a/test/parallel/test-crypto-hash.js b/test/parallel/test-crypto-hash.js index af2146982c7a3bf7bd7527f44e4b17a3b605026e..f6b91f675cfea367c608892dee078b565814f2dd 100644 --- a/test/parallel/test-crypto-hash.js +++ b/test/parallel/test-crypto-hash.js @@ -182,6 +182,7 @@ assert.throws( // Test XOF hash functions and the outputLength option. { + /* // Default outputLengths. assert.strictEqual(crypto.createHash('shake128').digest('hex'), '7f9c2ba4e88f827d616045507605853e'); @@ -236,6 +237,7 @@ assert.throws( assert.strictEqual(superLongHash.length, 2 * 1024 * 1024); assert.ok(superLongHash.endsWith('193414035ddba77bf7bba97981e656ec')); assert.ok(superLongHash.startsWith('a2a28dbc49cfd6e5d6ceea3d03e77748')); + */ // Non-XOF hash functions should accept valid outputLength options as well. assert.strictEqual(crypto.createHash('sha224', { outputLength: 28 }) diff --git a/test/parallel/test-crypto-padding.js b/test/parallel/test-crypto-padding.js index f1f14b472997e76bb4100edb1c6cf4fc24d1074d..5057e3f9bc5bb78aceffa5e79530f8ceed84e6f7 100644 --- a/test/parallel/test-crypto-padding.js +++ b/test/parallel/test-crypto-padding.js @@ -87,10 +87,9 @@ assert.throws(function() { code: 'ERR_OSSL_WRONG_FINAL_BLOCK_LENGTH', reason: 'wrong final block length', } : { - message: 'error:0607F08A:digital envelope routines:EVP_EncryptFinal_ex:' + - 'data not multiple of block length', - code: 'ERR_OSSL_EVP_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH', - reason: 'data not multiple of block length', + message: /error:0607F08A:digital envelope routines:EVP_EncryptFinal_ex:data not multiple of block length|error:1e00006a:Cipher functions:OPENSSL_internal:DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH/, + code: /ERR_OSSL(_EVP)?_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH/, + reason: /data not multiple of block length|DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH/, } ); @@ -114,10 +113,9 @@ assert.throws(function() { reason: 'bad decrypt', code: 'ERR_OSSL_BAD_DECRYPT', } : { - message: 'error:06065064:digital envelope routines:EVP_DecryptFinal_ex:' + - 'bad decrypt', - reason: 'bad decrypt', - code: 'ERR_OSSL_EVP_BAD_DECRYPT', + message: /error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt|error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT/, + reason: /bad decrypt|BAD_DECRYPT/, + code: /ERR_OSSL(_EVP)?_BAD_DECRYPT/, }); // No-pad encrypted string should return the same: diff --git a/test/parallel/test-crypto-private-decrypt-gh32240.js b/test/parallel/test-crypto-private-decrypt-gh32240.js index 1785f5eef3d202976666081d09850ed744d83446..e88227a215ba4f7fa196f7642ae694a57d55b3ca 100644 --- a/test/parallel/test-crypto-private-decrypt-gh32240.js +++ b/test/parallel/test-crypto-private-decrypt-gh32240.js @@ -24,7 +24,7 @@ const pkeyEncrypted = pair.privateKey.export({ type: 'pkcs1', format: 'pem', - cipher: 'aes128', + cipher: 'aes-128-cbc', passphrase: 'secret', }); diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index 9afcb38616dafd6da1ab7b5843d68f4f796ca9a6..00d3381056a5a40c549f06d74c130149ba4abc8c 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -28,12 +28,11 @@ const dsaPkcs8KeyPem = fixtures.readKey('dsa_private_pkcs8.pem'); const ec = new TextEncoder(); const openssl1DecryptError = { - message: 'error:06065064:digital envelope routines:EVP_DecryptFinal_ex:' + - 'bad decrypt', - code: 'ERR_OSSL_EVP_BAD_DECRYPT', - reason: 'bad decrypt', - function: 'EVP_DecryptFinal_ex', - library: 'digital envelope routines', + message: /error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt|error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT/, + code: /ERR_OSSL(_EVP)?_BAD_DECRYPT/, + reason: /bad decrypt|BAD_DECRYPT/, + function: /EVP_DecryptFinal_ex|OPENSSL_internal/, + library: /digital envelope routines|Cipher functions/, }; const decryptError = common.hasOpenSSL3 ? @@ -397,7 +396,7 @@ assert.throws(() => { assert.strictEqual(verify2.verify(publicKey, signature, 'hex'), true); } - +/* // // Test DSA signing and verification // @@ -472,3 +471,4 @@ const input = 'I AM THE WALRUS'; assert.strictEqual(verify.verify(dsaPubPem, signature, 'hex'), true); } +*/ diff --git a/test/parallel/test-crypto-sign-verify.js b/test/parallel/test-crypto-sign-verify.js index b2c14b1efcd68bd20e9c946106f1ab5fb58627c5..eef0bfe638b641c68fdadd95226a74df044921cb 100644 --- a/test/parallel/test-crypto-sign-verify.js +++ b/test/parallel/test-crypto-sign-verify.js @@ -29,6 +29,7 @@ const keySize = 2048; 'instance when called without `new`'); } +/* // Test handling of exceptional conditions { const library = { @@ -69,6 +70,7 @@ const keySize = 2048; delete Object.prototype.opensslErrorStack; } +*/ assert.throws( () => crypto.createVerify('SHA256').verify({ @@ -342,15 +344,17 @@ assert.throws( padding: crypto.constants.RSA_PKCS1_OAEP_PADDING }); }, common.hasOpenSSL3 ? { - code: 'ERR_OSSL_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE', - message: /illegal or unsupported padding mode/, + code: /^ERR_OSSL_(RSA|EVP)_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE$/, + message: /illegal or unsupported padding mode|ILLEGAL_OR_UNSUPPORTED_PADDING_MODE/, } : { - code: 'ERR_OSSL_RSA_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE', - message: /illegal or unsupported padding mode/, + code: /^ERR_OSSL_(RSA|EVP)_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE$/, + message: /illegal or unsupported padding mode|ILLEGAL_OR_UNSUPPORTED_PADDING_MODE/, + /* opensslErrorStack: [ 'error:06089093:digital envelope routines:EVP_PKEY_CTX_ctrl:' + 'command not supported', ], + */ }); } @@ -420,10 +424,12 @@ assert.throws( public: fixtures.readKey('ed25519_public.pem', 'ascii'), algo: null, sigLen: 64 }, + /* { private: fixtures.readKey('ed448_private.pem', 'ascii'), public: fixtures.readKey('ed448_public.pem', 'ascii'), algo: null, sigLen: 114 }, + */ { private: fixtures.readKey('rsa_private_2048.pem', 'ascii'), public: fixtures.readKey('rsa_public_2048.pem', 'ascii'), algo: 'sha1', @@ -494,7 +500,7 @@ assert.throws( { const data = Buffer.from('Hello world'); - const keys = [['ec-key.pem', 64], ['dsa_private_1025.pem', 40]]; + const keys = [['ec-key.pem', 64]/*, ['dsa_private_1025.pem', 40]*/]; for (const [file, length] of keys) { const privKey = fixtures.readKey(file); diff --git a/test/parallel/test-crypto-stream.js b/test/parallel/test-crypto-stream.js index 008ab129f0e019c659eecf5a76b7eb412c947fe3..6688f5d916f50e1e4fcfff1619c8634a3233f820 100644 --- a/test/parallel/test-crypto-stream.js +++ b/test/parallel/test-crypto-stream.js @@ -76,10 +76,10 @@ cipher.pipe(decipher) library: 'Provider routines', reason: 'bad decrypt', } : { - message: /bad decrypt/, - function: 'EVP_DecryptFinal_ex', - library: 'digital envelope routines', - reason: 'bad decrypt', + message: /bad decrypt|BAD_DECRYPT/, + function: /EVP_DecryptFinal_ex|OPENSSL_internal/, + library: /digital envelope routines|Cipher functions/, + reason: /bad decrypt|BAD_DECRYPT/, })); cipher.end('Papaya!'); // Should not cause an unhandled exception. diff --git a/test/parallel/test-crypto-x509.js b/test/parallel/test-crypto-x509.js index d1782359277dc52d7a60830a6dd958544d610e6b..4c781f062bc505b860b821773070551f4cd80067 100644 --- a/test/parallel/test-crypto-x509.js +++ b/test/parallel/test-crypto-x509.js @@ -110,7 +110,7 @@ const der = Buffer.from( 'A3:06:C5:CE:43:C1:7F:2D:7E:5F:44:A5:EE:A3:CB:97:05:A3:E3:68' ); assert.strictEqual(x509.keyUsage, undefined); - assert.strictEqual(x509.serialNumber, 'ECC9B856270DA9A8'); + assert.match(x509.serialNumber, /ECC9B856270DA9A8/i); assert.deepStrictEqual(x509.raw, der); @@ -196,6 +196,12 @@ const der = Buffer.from( }); mc.port2.postMessage(x509); + const modulusOSSL = 'EF5440701637E28ABB038E5641F828D834C342A9D25EDBB86A2BF' + + '6FBD809CB8E037A98B71708E001242E4DEB54C6164885F599DD87' + + 'A23215745955BE20417E33C4D0D1B80C9DA3DE419A2607195D2FB' + + '75657B0BBFB5EB7D0BBA5122D1B6964C7B570D50B8EC001EEB68D' + + 'FB584437508F3129928D673B30A3E0BF4F50609E6371'; + // Verify that legacy encoding works const legacyObjectCheck = { subject: 'C=US\n' + @@ -219,11 +225,7 @@ const der = Buffer.from( 'CA Issuers - URI:http://ca.nodejs.org/ca.cert' : 'OCSP - URI:http://ocsp.nodejs.org/\n' + 'CA Issuers - URI:http://ca.nodejs.org/ca.cert\n', - modulus: 'EF5440701637E28ABB038E5641F828D834C342A9D25EDBB86A2BF' + - '6FBD809CB8E037A98B71708E001242E4DEB54C6164885F599DD87' + - 'A23215745955BE20417E33C4D0D1B80C9DA3DE419A2607195D2FB' + - '75657B0BBFB5EB7D0BBA5122D1B6964C7B570D50B8EC001EEB68D' + - 'FB584437508F3129928D673B30A3E0BF4F50609E6371', + modulusPattern: new RegExp(modulusOSSL, 'i'), bits: 1024, exponent: '0x10001', valid_from: 'Nov 16 18:42:21 2018 GMT', @@ -237,7 +239,7 @@ const der = Buffer.from( 'D0:39:97:54:B6:D0:B4:46:5B:DE:13:5B:68:86:B6:F2:A8:' + '95:22:D5:6E:8B:35:DA:89:29:CA:A3:06:C5:CE:43:C1:7F:' + '2D:7E:5F:44:A5:EE:A3:CB:97:05:A3:E3:68', - serialNumber: 'ECC9B856270DA9A8' + serialNumberPattern: /ECC9B856270DA9A8/i }; const legacyObject = x509.toLegacyObject(); @@ -246,7 +248,7 @@ const der = Buffer.from( assert.strictEqual(legacyObject.subject, legacyObjectCheck.subject); assert.strictEqual(legacyObject.issuer, legacyObjectCheck.issuer); assert.strictEqual(legacyObject.infoAccess, legacyObjectCheck.infoAccess); - assert.strictEqual(legacyObject.modulus, legacyObjectCheck.modulus); + assert.match(legacyObject.modulus, legacyObjectCheck.modulusPattern); assert.strictEqual(legacyObject.bits, legacyObjectCheck.bits); assert.strictEqual(legacyObject.exponent, legacyObjectCheck.exponent); assert.strictEqual(legacyObject.valid_from, legacyObjectCheck.valid_from); @@ -255,7 +257,5 @@ const der = Buffer.from( assert.strictEqual( legacyObject.fingerprint256, legacyObjectCheck.fingerprint256); - assert.strictEqual( - legacyObject.serialNumber, - legacyObjectCheck.serialNumber); + assert.match(legacyObject.serialNumber, legacyObjectCheck.serialNumberPattern); } diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js index a8ceb169de2b3de73f062083c42292babc673e73..a3bb574d0e5dc85b4ba3fb0b3bd8782fbb8c8700 100644 --- a/test/parallel/test-crypto.js +++ b/test/parallel/test-crypto.js @@ -67,7 +67,7 @@ assert.throws(() => { // Throws general Error, so there is no opensslErrorStack property. return err instanceof Error && err.name === 'Error' && - /^Error: mac verify failure$/.test(err) && + (/^Error: (mac verify failure|INCORRECT_PASSWORD)$/.test(err)) && !('opensslErrorStack' in err); }); @@ -77,7 +77,7 @@ assert.throws(() => { // Throws general Error, so there is no opensslErrorStack property. return err instanceof Error && err.name === 'Error' && - /^Error: mac verify failure$/.test(err) && + (/^Error: (mac verify failure|INCORRECT_PASSWORD)$/.test(err)) && !('opensslErrorStack' in err); }); @@ -87,7 +87,7 @@ assert.throws(() => { // Throws general Error, so there is no opensslErrorStack property. return err instanceof Error && err.name === 'Error' && - /^Error: not enough data$/.test(err) && + /^Error: (not enough data|BAD_PKCS12_DATA)$/.test(err) && !('opensslErrorStack' in err); }); @@ -150,8 +150,6 @@ assert(crypto.getHashes().includes('sha1')); assert(crypto.getHashes().includes('sha256')); assert(!crypto.getHashes().includes('SHA1')); assert(!crypto.getHashes().includes('SHA256')); -assert(crypto.getHashes().includes('RSA-SHA1')); -assert(!crypto.getHashes().includes('rsa-sha1')); validateList(crypto.getHashes()); // Make sure all of the hashes are supported by OpenSSL for (const algo of crypto.getHashes()) @@ -188,7 +186,7 @@ const encodingError = { // hex input that's not a power of two should throw, not assert in C++ land. ['createCipher', 'createDecipher'].forEach((funcName) => { assert.throws( - () => crypto[funcName]('aes192', 'test').update('0', 'hex'), + () => crypto[funcName]('aes-192-cbc', 'test').update('0', 'hex'), (error) => { assert.ok(!('opensslErrorStack' in error)); if (common.hasFipsCrypto) { @@ -240,15 +238,15 @@ assert.throws(() => { library: 'rsa routines', } : { name: 'Error', - message: /routines:RSA_sign:digest too big for rsa key$/, - library: 'rsa routines', - function: 'RSA_sign', - reason: 'digest too big for rsa key', + message: /routines:RSA_sign:digest too big for rsa key$|routines:OPENSSL_internal:DIGEST_TOO_BIG_FOR_RSA_KEY$/, + library: /rsa routines|RSA routines/, + function: /RSA_sign|OPENSSL_internal/, + reason: /digest too big for rsa key|DIGEST_TOO_BIG_FOR_RSA_KEY/, code: 'ERR_OSSL_RSA_DIGEST_TOO_BIG_FOR_RSA_KEY' }); return true; }); - +/* if (!common.hasOpenSSL3) { assert.throws(() => { // The correct header inside `rsa_private_pkcs8_bad.pem` should have been @@ -276,7 +274,7 @@ if (!common.hasOpenSSL3) { return true; }); } - +*/ // Make sure memory isn't released before being returned console.log(crypto.randomBytes(16)); diff --git a/test/parallel/test-https-agent-additional-options.js b/test/parallel/test-https-agent-additional-options.js index 543ee176fb6af38874fee9f14be76f3fdda11060..fef9f1bc2f9fc6c220cf47847e86e03882b51b1d 100644 --- a/test/parallel/test-https-agent-additional-options.js +++ b/test/parallel/test-https-agent-additional-options.js @@ -13,7 +13,7 @@ const options = { cert: fixtures.readKey('agent1-cert.pem'), ca: fixtures.readKey('ca1-cert.pem'), minVersion: 'TLSv1.1', - ciphers: 'ALL@SECLEVEL=0' + // ciphers: 'ALL@SECLEVEL=0' }; const server = https.Server(options, (req, res) => { @@ -28,7 +28,7 @@ function getBaseOptions(port) { ca: options.ca, rejectUnauthorized: true, servername: 'agent1', - ciphers: 'ALL@SECLEVEL=0' + // ciphers: 'ALL@SECLEVEL=0' }; } diff --git a/test/parallel/test-https-agent-session-eviction.js b/test/parallel/test-https-agent-session-eviction.js index 940c43cc40bf15e51df177ee30ecc69ffbeec296..e95743a91a3c709c7d2c10dc80b3f75b7d988027 100644 --- a/test/parallel/test-https-agent-session-eviction.js +++ b/test/parallel/test-https-agent-session-eviction.js @@ -14,7 +14,7 @@ const options = { key: readKey('agent1-key.pem'), cert: readKey('agent1-cert.pem'), secureOptions: SSL_OP_NO_TICKET, - ciphers: 'RSA@SECLEVEL=0' + // ciphers: 'RSA@SECLEVEL=0' }; // Create TLS1.2 server diff --git a/test/parallel/test-tls-getcertificate-x509.js b/test/parallel/test-tls-getcertificate-x509.js index 5be788f67931131256f7fb0ab802cb0edee58173..0969e417c239b7300f53f6c4434318bc8fe579fe 100644 --- a/test/parallel/test-tls-getcertificate-x509.js +++ b/test/parallel/test-tls-getcertificate-x509.js @@ -20,9 +20,7 @@ const server = tls.createServer(options, function(cleartext) { server.once('secureConnection', common.mustCall(function(socket) { const cert = socket.getX509Certificate(); assert(cert instanceof X509Certificate); - assert.strictEqual( - cert.serialNumber, - 'D0082F458B6EFBE8'); + assert.match(cert.serialNumber, /D0082F458B6EFBE8/i) })); server.listen(0, common.mustCall(function() { @@ -33,10 +31,7 @@ server.listen(0, common.mustCall(function() { const peerCert = socket.getPeerX509Certificate(); assert(peerCert.issuerCertificate instanceof X509Certificate); assert.strictEqual(peerCert.issuerCertificate.issuerCertificate, undefined); - assert.strictEqual( - peerCert.issuerCertificate.serialNumber, - 'ECC9B856270DA9A7' - ); + assert.match(peerCert.issuerCertificate.serialNumber, /ECC9B856270DA9A7/i); server.close(); })); socket.end('Hello'); diff --git a/test/parallel/test-tls-getprotocol.js b/test/parallel/test-tls-getprotocol.js index 02c683c71c8775e84d5d125a4f05560b8206677d..4c6dd20ca0a8d0acdf9f8d1b7153087de9305196 100644 --- a/test/parallel/test-tls-getprotocol.js +++ b/test/parallel/test-tls-getprotocol.js @@ -18,7 +18,7 @@ const clientConfigs = [ const serverConfig = { secureProtocol: 'TLS_method', - ciphers: 'RSA@SECLEVEL=0', + // ciphers: 'RSA@SECLEVEL=0', key: fixtures.readKey('agent2-key.pem'), cert: fixtures.readKey('agent2-cert.pem') }; diff --git a/test/parallel/test-tls-write-error.js b/test/parallel/test-tls-write-error.js index b06f2fa2c53ea72f9a66f0d002dd9281d0259a0f..864fffeebfad75d95416fd47efdea7f222c507a2 100644 --- a/test/parallel/test-tls-write-error.js +++ b/test/parallel/test-tls-write-error.js @@ -17,7 +17,7 @@ const server_cert = fixtures.readKey('agent1-cert.pem'); const opts = { key: server_key, cert: server_cert, - ciphers: 'ALL@SECLEVEL=0' + // ciphers: 'ALL@SECLEVEL=0' }; const server = https.createServer(opts, (req, res) => { diff --git a/test/parallel/test-webcrypto-derivebits.js b/test/parallel/test-webcrypto-derivebits.js index 95c38f454fbb939c9f74f25ec946d0c8e94e4c41..882c01fd812f5ed880fa3482ede92695ad505ff3 100644 --- a/test/parallel/test-webcrypto-derivebits.js +++ b/test/parallel/test-webcrypto-derivebits.js @@ -39,6 +39,7 @@ const { internalBinding } = require('internal/test/binding'); test('P-521').then(common.mustCall()); } +/* // Test HKDF bit derivation { async function test(pass, info, salt, hash, length, expected) { @@ -70,6 +71,7 @@ const { internalBinding } = require('internal/test/binding'); tests.then(common.mustCall()); } +*/ // Test PBKDF2 bit derivation { diff --git a/test/parallel/test-webcrypto-derivekey.js b/test/parallel/test-webcrypto-derivekey.js index ee48a61f4ac8f5e8e4cec96eb03d75cb1c45f56a..5108bbf7499f29bafffda76f3c5270aae0271b44 100644 --- a/test/parallel/test-webcrypto-derivekey.js +++ b/test/parallel/test-webcrypto-derivekey.js @@ -48,6 +48,7 @@ const { internalBinding } = require('internal/test/binding'); test('P-521').then(common.mustCall()); } +/* // Test HKDF bit derivation { async function test(pass, info, salt, hash, expected) { @@ -84,6 +85,7 @@ const { internalBinding } = require('internal/test/binding'); tests.then(common.mustCall()); } +*/ // Test PBKDF2 bit derivation { diff --git a/test/parallel/test-webcrypto-encrypt-decrypt-rsa.js b/test/parallel/test-webcrypto-encrypt-decrypt-rsa.js index 151eebd36c9765df086a020ba42920b2442b1b77..efe97ff2499cba909ac5500d827364fa389a0469 100644 --- a/test/parallel/test-webcrypto-encrypt-decrypt-rsa.js +++ b/test/parallel/test-webcrypto-encrypt-decrypt-rsa.js @@ -127,7 +127,7 @@ async function testEncryptionLongPlaintext({ algorithm, return assert.rejects( subtle.encrypt(algorithm, publicKey, newplaintext), { - message: /data too large/ + message: /data too large|DATA_TOO_LARGE_FOR_KEY_SIZE/ }); } diff --git a/test/parallel/test-webcrypto-export-import-rsa.js b/test/parallel/test-webcrypto-export-import-rsa.js index ab7aa77394ac9989514b7a184900092bd6753996..b0104ac45867a923a8c651e01e8c6975a62f7c61 100644 --- a/test/parallel/test-webcrypto-export-import-rsa.js +++ b/test/parallel/test-webcrypto-export-import-rsa.js @@ -481,6 +481,7 @@ const testVectors = [ await Promise.all(variations); })().then(common.mustCall()); +/* { const publicPem = fixtures.readKey('rsa_pss_public_2048.pem', 'ascii'); const privatePem = fixtures.readKey('rsa_pss_private_2048.pem', 'ascii'); @@ -522,6 +523,7 @@ const testVectors = [ assert.strictEqual(jwk.alg, 'PS256'); })().then(common.mustCall()); } +*/ { const ecPublic = crypto.createPublicKey( diff --git a/test/parallel/test-webcrypto-wrap-unwrap.js b/test/parallel/test-webcrypto-wrap-unwrap.js index 1094845c73e14313860ad476fb7baba2a11b5af4..51972b4b34b191ac59145889dbf2da5c0d407dbe 100644 --- a/test/parallel/test-webcrypto-wrap-unwrap.js +++ b/test/parallel/test-webcrypto-wrap-unwrap.js @@ -18,14 +18,15 @@ const kWrappingData = { wrap: { label: new Uint8Array(8) }, pair: true }, - 'AES-CTR': { + 'AES-CBC': { generate: { length: 128 }, - wrap: { counter: new Uint8Array(16), length: 64 }, + wrap: { iv: new Uint8Array(16) }, pair: false }, - 'AES-CBC': { + /* + 'AES-CTR': { generate: { length: 128 }, - wrap: { iv: new Uint8Array(16) }, + wrap: { counter: new Uint8Array(16), length: 64 }, pair: false }, 'AES-GCM': { @@ -42,6 +43,7 @@ const kWrappingData = { wrap: { }, pair: false } + */ }; function generateWrappingKeys() { diff --git a/test/parallel/test-x509-escaping.js b/test/parallel/test-x509-escaping.js index 99418e4c0bf21c26d5ba0ad9d617419abc625593..fc129b26ea13895353d6ede26bb2d91695c94ba4 100644 --- a/test/parallel/test-x509-escaping.js +++ b/test/parallel/test-x509-escaping.js @@ -425,11 +425,11 @@ const { hasOpenSSL3 } = common; assert.strictEqual(certX509.subjectAltName, 'DNS:evil.example.com'); // The newer X509Certificate API allows customizing this behavior: - assert.strictEqual(certX509.checkHost(servername), servername); + assert.strictEqual(certX509.checkHost(servername), undefined); assert.strictEqual(certX509.checkHost(servername, { subject: 'default' }), undefined); assert.strictEqual(certX509.checkHost(servername, { subject: 'always' }), - servername); + undefined); assert.strictEqual(certX509.checkHost(servername, { subject: 'never' }), undefined); @@ -464,11 +464,11 @@ const { hasOpenSSL3 } = common; assert.strictEqual(certX509.subjectAltName, 'IP Address:1.2.3.4'); // The newer X509Certificate API allows customizing this behavior: - assert.strictEqual(certX509.checkHost(servername), servername); + assert.strictEqual(certX509.checkHost(servername), undefined); assert.strictEqual(certX509.checkHost(servername, { subject: 'default' }), - servername); + undefined); assert.strictEqual(certX509.checkHost(servername, { subject: 'always' }), - servername); + undefined); assert.strictEqual(certX509.checkHost(servername, { subject: 'never' }), undefined);
closed
electron/electron
https://github.com/electron/electron
31,634
[Bug]: crypto.hkdf "Deriving bits failed"
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version v15.3.0 ### What operating system are you using? macOS ### Operating System Version Darwin C02CX0K5MD6V 20.6.0 Darwin Kernel Version 20.6.0: Mon Aug 30 06:12:21 PDT 2021; root:xnu-7195.141.6~3/RELEASE_X86_64 x86_64 ### What arch are you using? x64 ### Last Known Working Electron version none ### Expected Behavior `crypto.hkdf` and `crypto.hkdfSync` work as documented[^1] [^1]: https://nodejs.org/api/crypto.html#cryptohkdfdigest-ikm-salt-info-keylen-callback ### Actual Behavior ``` crypto.hkdfSync('sha256', 'foo', '', '', 32) // Uncaught Error: Deriving bits failed // at Object.hkdfSync (node:internal/crypto/hkdf:140:35) crypto.hkdf('sha256', 'foo', '', '', 32, console.log) // [Error: Deriving bits failed] ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/31634
https://github.com/electron/electron/pull/34767
35ff95d3c71849ac97ced178a2330b9d4651f250
ad2b1fee59c2e4352b0c5664f72c0067a2ef4d7f
2021-10-29T09:01:40Z
c++
2022-06-29T12:53:57Z
patches/node/fix_handle_boringssl_and_openssl_incompatibilities.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Wed, 12 Feb 2020 15:08:04 -0800 Subject: fix: handle BoringSSL and OpenSSL incompatibilities This patch corrects for imcompatibilities between OpenSSL, which Node.js uses, and BoringSSL which Electron uses via Chromium. Each incompatibility typically has ~2 paths forward: * Upstream a shim or adapted implementation to BoringSSL * Alter Node.js functionality to something which both libraries can handle. Where possible, we should seek to make this patch as minimal as possible. Upstreams: - https://github.com/nodejs/node/pull/39054 - https://github.com/nodejs/node/pull/39138 - https://github.com/nodejs/node/pull/39136 diff --git a/src/crypto/crypto_common.cc b/src/crypto/crypto_common.cc index a5aa39c23c1708ac27564a1a77a9f05fc07791e2..630a3400e74f20b1dbee17027c7dbe8688fed4b2 100644 --- a/src/crypto/crypto_common.cc +++ b/src/crypto/crypto_common.cc @@ -162,7 +162,7 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) { const unsigned char* buf; size_t len; size_t rem; - +#ifndef OPENSSL_IS_BORINGSSL if (!SSL_client_hello_get0_ext( ssl.get(), TLSEXT_TYPE_application_layer_protocol_negotiation, @@ -175,13 +175,15 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) { len = (buf[0] << 8) | buf[1]; if (len + 2 != rem) return nullptr; return reinterpret_cast<const char*>(buf + 3); +#endif + return nullptr; } const char* GetClientHelloServerName(const SSLPointer& ssl) { const unsigned char* buf; size_t len; size_t rem; - +#ifndef OPENSSL_IS_BORINGSSL if (!SSL_client_hello_get0_ext( ssl.get(), TLSEXT_TYPE_server_name, @@ -203,6 +205,8 @@ const char* GetClientHelloServerName(const SSLPointer& ssl) { if (len + 2 > rem) return nullptr; return reinterpret_cast<const char*>(buf + 5); +#endif + return nullptr; } const char* GetServerName(SSL* ssl) { @@ -210,7 +214,10 @@ const char* GetServerName(SSL* ssl) { } bool SetGroups(SecureContext* sc, const char* groups) { +#ifndef OPENSSL_IS_BORINGSSL return SSL_CTX_set1_groups_list(**sc, groups) == 1; +#endif + return SSL_CTX_set1_curves_list(**sc, groups) == 1; } const char* X509ErrorCode(long err) { // NOLINT(runtime/int) @@ -1101,14 +1108,14 @@ MaybeLocal<Array> GetClientHelloCiphers( Environment* env, const SSLPointer& ssl) { EscapableHandleScope scope(env->isolate()); - const unsigned char* buf; - size_t len = SSL_client_hello_get0_ciphers(ssl.get(), &buf); + // const unsigned char* buf = nullptr; + size_t len = 0; // SSL_client_hello_get0_ciphers(ssl.get(), &buf); size_t count = len / 2; MaybeStackBuffer<Local<Value>, 16> ciphers(count); int j = 0; for (size_t n = 0; n < len; n += 2) { - const SSL_CIPHER* cipher = SSL_CIPHER_find(ssl.get(), buf); - buf += 2; + const SSL_CIPHER* cipher = nullptr; // SSL_CIPHER_find(ssl.get(), buf); + // buf += 2; Local<Object> obj = Object::New(env->isolate()); if (!Set(env->context(), obj, diff --git a/src/crypto/crypto_dh.cc b/src/crypto/crypto_dh.cc index b6ef5e5b1e004e663fbfd2578b82644cb53051e0..1d48ea6d022304b1e6a4f703fea790437edcc876 100644 --- a/src/crypto/crypto_dh.cc +++ b/src/crypto/crypto_dh.cc @@ -143,13 +143,11 @@ void DiffieHellman::MemoryInfo(MemoryTracker* tracker) const { bool DiffieHellman::Init(const char* p, int p_len, int g) { dh_.reset(DH_new()); if (p_len <= 0) { - ERR_put_error(ERR_LIB_BN, BN_F_BN_GENERATE_PRIME_EX, - BN_R_BITS_TOO_SMALL, __FILE__, __LINE__); + OPENSSL_PUT_ERROR(BN, BN_R_BITS_TOO_SMALL); return false; } if (g <= 1) { - ERR_put_error(ERR_LIB_DH, DH_F_DH_BUILTIN_GENPARAMS, - DH_R_BAD_GENERATOR, __FILE__, __LINE__); + OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR); return false; } BIGNUM* bn_p = @@ -167,21 +165,18 @@ bool DiffieHellman::Init(const char* p, int p_len, int g) { bool DiffieHellman::Init(const char* p, int p_len, const char* g, int g_len) { dh_.reset(DH_new()); if (p_len <= 0) { - ERR_put_error(ERR_LIB_BN, BN_F_BN_GENERATE_PRIME_EX, - BN_R_BITS_TOO_SMALL, __FILE__, __LINE__); + OPENSSL_PUT_ERROR(BN, BN_R_BITS_TOO_SMALL); return false; } if (g_len <= 0) { - ERR_put_error(ERR_LIB_DH, DH_F_DH_BUILTIN_GENPARAMS, - DH_R_BAD_GENERATOR, __FILE__, __LINE__); + OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR); return false; } BIGNUM* bn_g = BN_bin2bn(reinterpret_cast<const unsigned char*>(g), g_len, nullptr); if (BN_is_zero(bn_g) || BN_is_one(bn_g)) { BN_free(bn_g); - ERR_put_error(ERR_LIB_DH, DH_F_DH_BUILTIN_GENPARAMS, - DH_R_BAD_GENERATOR, __FILE__, __LINE__); + OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR); return false; } BIGNUM* bn_p = @@ -501,16 +496,20 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) { if (!BN_set_word(bn_g.get(), params->params.generator) || !DH_set0_pqg(dh.get(), prime, nullptr, bn_g.get())) return EVPKeyCtxPointer(); - +#ifndef OPENSSL_IS_BORINGSSL params->params.prime_fixed_value.release(); bn_g.release(); key_params = EVPKeyPointer(EVP_PKEY_new()); CHECK(key_params); EVP_PKEY_assign_DH(key_params.get(), dh.release()); +#else + return EVPKeyCtxPointer(); +#endif } else { EVPKeyCtxPointer param_ctx(EVP_PKEY_CTX_new_id(EVP_PKEY_DH, nullptr)); EVP_PKEY* raw_params = nullptr; +#ifndef OPENSSL_IS_BORINGSSL if (!param_ctx || EVP_PKEY_paramgen_init(param_ctx.get()) <= 0 || EVP_PKEY_CTX_set_dh_paramgen_prime_len( @@ -522,8 +521,10 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) { EVP_PKEY_paramgen(param_ctx.get(), &raw_params) <= 0) { return EVPKeyCtxPointer(); } - key_params = EVPKeyPointer(raw_params); +#else + return EVPKeyCtxPointer(); +#endif } EVPKeyCtxPointer ctx(EVP_PKEY_CTX_new(key_params.get(), nullptr)); diff --git a/src/crypto/crypto_dsa.cc b/src/crypto/crypto_dsa.cc index c7894baf00ee9ce4684f4c752f1c7c9b98163741..655895dbff8b88daa53c7b40a5feca42a461b689 100644 --- a/src/crypto/crypto_dsa.cc +++ b/src/crypto/crypto_dsa.cc @@ -29,7 +29,7 @@ namespace crypto { EVPKeyCtxPointer DsaKeyGenTraits::Setup(DsaKeyPairGenConfig* params) { EVPKeyCtxPointer param_ctx(EVP_PKEY_CTX_new_id(EVP_PKEY_DSA, nullptr)); EVP_PKEY* raw_params = nullptr; - +#ifndef OPENSSL_IS_BORINGSSL if (!param_ctx || EVP_PKEY_paramgen_init(param_ctx.get()) <= 0 || EVP_PKEY_CTX_set_dsa_paramgen_bits( @@ -49,7 +49,9 @@ EVPKeyCtxPointer DsaKeyGenTraits::Setup(DsaKeyPairGenConfig* params) { return EVPKeyCtxPointer(); } } - +#else + return EVPKeyCtxPointer(); +#endif if (EVP_PKEY_paramgen(param_ctx.get(), &raw_params) <= 0) return EVPKeyCtxPointer(); diff --git a/src/crypto/crypto_hkdf.cc b/src/crypto/crypto_hkdf.cc index 0aa96ada47abe4b66fb616c665101278bbe0afb6..1e9a4863c5faea5f6b275483ca16f3a6e8dac25b 100644 --- a/src/crypto/crypto_hkdf.cc +++ b/src/crypto/crypto_hkdf.cc @@ -101,6 +101,7 @@ bool HKDFTraits::DeriveBits( Environment* env, const HKDFConfig& params, ByteSource* out) { +#ifndef OPENSSL_IS_BORINGSSL EVPKeyCtxPointer ctx = EVPKeyCtxPointer(EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, nullptr)); if (!ctx || @@ -132,6 +133,9 @@ bool HKDFTraits::DeriveBits( *out = std::move(buf); return true; +#else + return false; +#endif } void HKDFConfig::MemoryInfo(MemoryTracker* tracker) const { diff --git a/src/crypto/crypto_random.cc b/src/crypto/crypto_random.cc index fc88deb460314c2620d842ec30141bcd13109d60..c097ccfcffb1158317ba09e7c4beb725ccbab74f 100644 --- a/src/crypto/crypto_random.cc +++ b/src/crypto/crypto_random.cc @@ -150,7 +150,7 @@ Maybe<bool> RandomPrimeTraits::AdditionalConfig( params->bits = bits; params->safe = safe; - params->prime.reset(BN_secure_new()); + params->prime.reset(BN_new()); if (!params->prime) { THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime"); return Nothing<bool>(); diff --git a/src/crypto/crypto_rsa.cc b/src/crypto/crypto_rsa.cc index ae4550e9fde8120c35409e495d5b763a95546509..188a7efe76df2a1aa2eb2746f4d748361bba4fb4 100644 --- a/src/crypto/crypto_rsa.cc +++ b/src/crypto/crypto_rsa.cc @@ -621,10 +621,11 @@ Maybe<bool> GetRsaKeyDetail( } if (params->saltLength != nullptr) { - if (ASN1_INTEGER_get_int64(&salt_length, params->saltLength) != 1) { - ThrowCryptoError(env, ERR_get_error(), "ASN1_INTEGER_get_in64 error"); - return Nothing<bool>(); - } + // TODO(codebytere): Upstream a shim to BoringSSL? + // if (ASN1_INTEGER_get_int64(&salt_length, params->saltLength) != 1) { + // ThrowCryptoError(env, ERR_get_error(), "ASN1_INTEGER_get_in64 error"); + // return Nothing<bool>(); + // } } if (target diff --git a/src/crypto/crypto_util.cc b/src/crypto/crypto_util.cc index e1ef170a9f17634d218492a2ce888c3a4365e097..8dffad89c80e0906780d1b26ba9a65ba1e76ce0a 100644 --- a/src/crypto/crypto_util.cc +++ b/src/crypto/crypto_util.cc @@ -508,24 +508,14 @@ Maybe<bool> Decorate(Environment* env, Local<Object> obj, V(BIO) \ V(PKCS7) \ V(X509V3) \ - V(PKCS12) \ V(RAND) \ - V(DSO) \ V(ENGINE) \ V(OCSP) \ V(UI) \ V(COMP) \ V(ECDSA) \ V(ECDH) \ - V(OSSL_STORE) \ - V(FIPS) \ - V(CMS) \ - V(TS) \ V(HMAC) \ - V(CT) \ - V(ASYNC) \ - V(KDF) \ - V(SM2) \ V(USER) \ #define V(name) case ERR_LIB_##name: lib = #name "_"; break; @@ -684,7 +674,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { CHECK(args[0]->IsUint32()); Environment* env = Environment::GetCurrent(args); uint32_t len = args[0].As<Uint32>()->Value(); - char* data = static_cast<char*>(OPENSSL_secure_malloc(len)); + char* data = static_cast<char*>(OPENSSL_malloc(len)); if (data == nullptr) { // There's no memory available for the allocation. // Return nothing. @@ -696,7 +686,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { data, len, [](void* data, size_t len, void* deleter_data) { - OPENSSL_secure_clear_free(data, len); + OPENSSL_clear_free(data, len); }, data); Local<ArrayBuffer> buffer = ArrayBuffer::New(env->isolate(), store); @@ -704,10 +694,12 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { } void SecureHeapUsed(const FunctionCallbackInfo<Value>& args) { +#ifndef OPENSSL_IS_BORINGSSL Environment* env = Environment::GetCurrent(args); if (CRYPTO_secure_malloc_initialized()) args.GetReturnValue().Set( BigInt::New(env->isolate(), CRYPTO_secure_used())); +#endif } } // namespace diff --git a/src/crypto/crypto_util.h b/src/crypto/crypto_util.h index c431159e6f77f8c86844bcadb86012b056d03372..0ce3a8f219a2952f660ff72a6ce36ee109add649 100644 --- a/src/crypto/crypto_util.h +++ b/src/crypto/crypto_util.h @@ -16,7 +16,9 @@ #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/ec.h> +#ifndef OPENSSL_IS_BORINGSSL #include <openssl/kdf.h> +#endif #include <openssl/rsa.h> #include <openssl/dsa.h> #include <openssl/ssl.h> diff --git a/src/node_metadata.h b/src/node_metadata.h index 4486d5af2c1622c7c8f44401dc3ebb986d8e3c2e..db1769f1b3f1617ed8dbbea57b5e324183b42be2 100644 --- a/src/node_metadata.h +++ b/src/node_metadata.h @@ -6,7 +6,7 @@ #include <string> #include "node_version.h" -#if HAVE_OPENSSL +#if 0 #include <openssl/crypto.h> #endif // HAVE_OPENSSL
closed
electron/electron
https://github.com/electron/electron
31,634
[Bug]: crypto.hkdf "Deriving bits failed"
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version v15.3.0 ### What operating system are you using? macOS ### Operating System Version Darwin C02CX0K5MD6V 20.6.0 Darwin Kernel Version 20.6.0: Mon Aug 30 06:12:21 PDT 2021; root:xnu-7195.141.6~3/RELEASE_X86_64 x86_64 ### What arch are you using? x64 ### Last Known Working Electron version none ### Expected Behavior `crypto.hkdf` and `crypto.hkdfSync` work as documented[^1] [^1]: https://nodejs.org/api/crypto.html#cryptohkdfdigest-ikm-salt-info-keylen-callback ### Actual Behavior ``` crypto.hkdfSync('sha256', 'foo', '', '', 32) // Uncaught Error: Deriving bits failed // at Object.hkdfSync (node:internal/crypto/hkdf:140:35) crypto.hkdf('sha256', 'foo', '', '', 32, console.log) // [Error: Deriving bits failed] ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/31634
https://github.com/electron/electron/pull/34767
35ff95d3c71849ac97ced178a2330b9d4651f250
ad2b1fee59c2e4352b0c5664f72c0067a2ef4d7f
2021-10-29T09:01:40Z
c++
2022-06-29T12:53:57Z
patches/node/support_v8_sandboxed_pointers.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Jeremy Rose <[email protected]> Date: Tue, 21 Jun 2022 10:04:21 -0700 Subject: support V8 sandboxed pointers This refactors several allocators to allocate within the V8 memory cage, allowing them to be compatible with the V8_SANDBOXED_POINTERS feature. diff --git a/lib/internal/bootstrap/pre_execution.js b/lib/internal/bootstrap/pre_execution.js index 4c459b58b5a048d9d8a4f15f4011e7cce68089f4..6fb4c8d4567aee5b313ad621ea42699a196f18c7 100644 --- a/lib/internal/bootstrap/pre_execution.js +++ b/lib/internal/bootstrap/pre_execution.js @@ -14,7 +14,6 @@ const { getOptionValue, getEmbedderOptions, } = require('internal/options'); -const { reconnectZeroFillToggle } = require('internal/buffer'); const { defineOperation, emitExperimentalWarning, @@ -26,10 +25,6 @@ const { ERR_MANIFEST_ASSERT_INTEGRITY } = require('internal/errors').codes; const assert = require('internal/assert'); function prepareMainThreadExecution(expandArgv1 = false) { - // TODO(joyeecheung): this is also necessary for workers when they deserialize - // this toggle from the snapshot. - reconnectZeroFillToggle(); - // Patch the process object with legacy properties and normalizations patchProcessObject(expandArgv1); setupTraceCategoryState(); diff --git a/lib/internal/buffer.js b/lib/internal/buffer.js index bd38cf48a7fc6e8d61d8f11fa15c34aee182cbe3..1aa071cdc071dcdaf5c3b4bed0d3d76e5871731d 100644 --- a/lib/internal/buffer.js +++ b/lib/internal/buffer.js @@ -30,7 +30,7 @@ const { hexWrite, ucs2Write, utf8Write, - getZeroFillToggle + setZeroFillToggle } = internalBinding('buffer'); const { untransferable_object_private_symbol, @@ -1055,24 +1055,15 @@ function markAsUntransferable(obj) { // in C++. // |zeroFill| can be undefined when running inside an isolate where we // do not own the ArrayBuffer allocator. Zero fill is always on in that case. -let zeroFill = getZeroFillToggle(); function createUnsafeBuffer(size) { - zeroFill[0] = 0; + setZeroFillToggle(false); try { return new FastBuffer(size); } finally { - zeroFill[0] = 1; + setZeroFillToggle(true) } } -// The connection between the JS land zero fill toggle and the -// C++ one in the NodeArrayBufferAllocator gets lost if the toggle -// is deserialized from the snapshot, because V8 owns the underlying -// memory of this toggle. This resets the connection. -function reconnectZeroFillToggle() { - zeroFill = getZeroFillToggle(); -} - module.exports = { FastBuffer, addBufferPrototypeMethods, @@ -1080,5 +1071,4 @@ module.exports = { createUnsafeBuffer, readUInt16BE, readUInt32BE, - reconnectZeroFillToggle }; diff --git a/src/api/environment.cc b/src/api/environment.cc index 2abf5994405e8da2a04d1b23b75ccd3658398474..024d612a04d83583b397549589d994e32cf0107f 100644 --- a/src/api/environment.cc +++ b/src/api/environment.cc @@ -83,16 +83,16 @@ MaybeLocal<Value> PrepareStackTraceCallback(Local<Context> context, void* NodeArrayBufferAllocator::Allocate(size_t size) { void* ret; if (zero_fill_field_ || per_process::cli_options->zero_fill_all_buffers) - ret = UncheckedCalloc(size); + ret = allocator_->Allocate(size); else - ret = UncheckedMalloc(size); + ret = allocator_->AllocateUninitialized(size); if (LIKELY(ret != nullptr)) total_mem_usage_.fetch_add(size, std::memory_order_relaxed); return ret; } void* NodeArrayBufferAllocator::AllocateUninitialized(size_t size) { - void* ret = node::UncheckedMalloc(size); + void* ret = allocator_->AllocateUninitialized(size); if (LIKELY(ret != nullptr)) total_mem_usage_.fetch_add(size, std::memory_order_relaxed); return ret; @@ -100,7 +100,7 @@ void* NodeArrayBufferAllocator::AllocateUninitialized(size_t size) { void* NodeArrayBufferAllocator::Reallocate( void* data, size_t old_size, size_t size) { - void* ret = UncheckedRealloc<char>(static_cast<char*>(data), size); + void* ret = allocator_->Reallocate(data, old_size, size); if (LIKELY(ret != nullptr) || UNLIKELY(size == 0)) total_mem_usage_.fetch_add(size - old_size, std::memory_order_relaxed); return ret; @@ -108,7 +108,7 @@ void* NodeArrayBufferAllocator::Reallocate( void NodeArrayBufferAllocator::Free(void* data, size_t size) { total_mem_usage_.fetch_sub(size, std::memory_order_relaxed); - free(data); + allocator_->Free(data, size); } DebuggingArrayBufferAllocator::~DebuggingArrayBufferAllocator() { diff --git a/src/crypto/crypto_util.cc b/src/crypto/crypto_util.cc index 8dffad89c80e0906780d1b26ba9a65ba1e76ce0a..45bc99ce75248794e95b2dcb0101c28152e2bfd0 100644 --- a/src/crypto/crypto_util.cc +++ b/src/crypto/crypto_util.cc @@ -318,10 +318,35 @@ ByteSource& ByteSource::operator=(ByteSource&& other) noexcept { return *this; } -std::unique_ptr<BackingStore> ByteSource::ReleaseToBackingStore() { +std::unique_ptr<BackingStore> ByteSource::ReleaseToBackingStore(Environment* env) { // It's ok for allocated_data_ to be nullptr but // only if size_ is zero. CHECK_IMPLIES(size_ > 0, allocated_data_ != nullptr); +#if defined(V8_SANDBOXED_POINTERS) + // When V8 sandboxed pointers are enabled, we have to copy into the memory + // cage. We still want to ensure we erase the data on free though, so + // provide a custom deleter that calls OPENSSL_cleanse. + if (!size()) + return ArrayBuffer::NewBackingStore(env->isolate(), 0); + std::unique_ptr<ArrayBuffer::Allocator> allocator(ArrayBuffer::Allocator::NewDefaultAllocator()); + void* v8_data = allocator->Allocate(size()); + CHECK(v8_data); + memcpy(v8_data, allocated_data_, size()); + OPENSSL_clear_free(allocated_data_, size()); + std::unique_ptr<BackingStore> ptr = ArrayBuffer::NewBackingStore( + v8_data, + size(), + [](void* data, size_t length, void*) { + OPENSSL_cleanse(data, length); + std::unique_ptr<ArrayBuffer::Allocator> allocator(ArrayBuffer::Allocator::NewDefaultAllocator()); + allocator->Free(data, length); + }, nullptr); + CHECK(ptr); + allocated_data_ = nullptr; + data_ = nullptr; + size_ = 0; + return ptr; +#else std::unique_ptr<BackingStore> ptr = ArrayBuffer::NewBackingStore( allocated_data_, size(), @@ -333,10 +358,11 @@ std::unique_ptr<BackingStore> ByteSource::ReleaseToBackingStore() { data_ = nullptr; size_ = 0; return ptr; +#endif // defined(V8_SANDBOXED_POINTERS) } Local<ArrayBuffer> ByteSource::ToArrayBuffer(Environment* env) { - std::unique_ptr<BackingStore> store = ReleaseToBackingStore(); + std::unique_ptr<BackingStore> store = ReleaseToBackingStore(env); return ArrayBuffer::New(env->isolate(), std::move(store)); } @@ -665,6 +691,16 @@ CryptoJobMode GetCryptoJobMode(v8::Local<v8::Value> args) { } namespace { +#if defined(V8_SANDBOXED_POINTERS) +// When V8 sandboxed pointers are enabled, the secure heap cannot be used as +// all ArrayBuffers must be allocated inside the V8 memory cage. +void SecureBuffer(const FunctionCallbackInfo<Value>& args) { + CHECK(args[0]->IsUint32()); + uint32_t len = args[0].As<Uint32>()->Value(); + Local<ArrayBuffer> buffer = ArrayBuffer::New(args.GetIsolate(), len); + args.GetReturnValue().Set(Uint8Array::New(buffer, 0, len)); +} +#else // SecureBuffer uses openssl to allocate a Uint8Array using // OPENSSL_secure_malloc. Because we do not yet actually // make use of secure heap, this has the same semantics as @@ -692,6 +728,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { Local<ArrayBuffer> buffer = ArrayBuffer::New(env->isolate(), store); args.GetReturnValue().Set(Uint8Array::New(buffer, 0, len)); } +#endif // defined(V8_SANDBOXED_POINTERS) void SecureHeapUsed(const FunctionCallbackInfo<Value>& args) { #ifndef OPENSSL_IS_BORINGSSL diff --git a/src/crypto/crypto_util.h b/src/crypto/crypto_util.h index 0ce3a8f219a2952f660ff72a6ce36ee109add649..06e9eb72e4ea60db4c63d08b24b80a1e6c4f3eaf 100644 --- a/src/crypto/crypto_util.h +++ b/src/crypto/crypto_util.h @@ -257,7 +257,7 @@ class ByteSource { // Creates a v8::BackingStore that takes over responsibility for // any allocated data. The ByteSource will be reset with size = 0 // after being called. - std::unique_ptr<v8::BackingStore> ReleaseToBackingStore(); + std::unique_ptr<v8::BackingStore> ReleaseToBackingStore(Environment* env); v8::Local<v8::ArrayBuffer> ToArrayBuffer(Environment* env); diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 215bd8003aabe17e43ac780c723cfe971b437eae..eb00eb6f592e20f3c17a529f30b09673774eb1c1 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -1175,33 +1175,14 @@ void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) { env->set_buffer_prototype_object(proto); } -void GetZeroFillToggle(const FunctionCallbackInfo<Value>& args) { +void SetZeroFillToggle(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); NodeArrayBufferAllocator* allocator = env->isolate_data()->node_allocator(); Local<ArrayBuffer> ab; - // It can be a nullptr when running inside an isolate where we - // do not own the ArrayBuffer allocator. - if (allocator == nullptr) { - // Create a dummy Uint32Array - the JS land can only toggle the C++ land - // setting when the allocator uses our toggle. With this the toggle in JS - // land results in no-ops. - ab = ArrayBuffer::New(env->isolate(), sizeof(uint32_t)); - } else { + if (allocator != nullptr) { uint32_t* zero_fill_field = allocator->zero_fill_field(); - std::unique_ptr<BackingStore> backing = - ArrayBuffer::NewBackingStore(zero_fill_field, - sizeof(*zero_fill_field), - [](void*, size_t, void*) {}, - nullptr); - ab = ArrayBuffer::New(env->isolate(), std::move(backing)); + *zero_fill_field = args[0]->BooleanValue(env->isolate()); } - - ab->SetPrivate( - env->context(), - env->untransferable_object_private_symbol(), - True(env->isolate())).Check(); - - args.GetReturnValue().Set(Uint32Array::New(ab, 0, 1)); } void DetachArrayBuffer(const FunctionCallbackInfo<Value>& args) { @@ -1310,7 +1291,7 @@ void Initialize(Local<Object> target, env->SetMethod(target, "ucs2Write", StringWrite<UCS2>); env->SetMethod(target, "utf8Write", StringWrite<UTF8>); - env->SetMethod(target, "getZeroFillToggle", GetZeroFillToggle); + env->SetMethod(target, "setZeroFillToggle", SetZeroFillToggle); } } // anonymous namespace @@ -1350,7 +1331,7 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) { registry->Register(StringWrite<HEX>); registry->Register(StringWrite<UCS2>); registry->Register(StringWrite<UTF8>); - registry->Register(GetZeroFillToggle); + registry->Register(SetZeroFillToggle); registry->Register(DetachArrayBuffer); registry->Register(CopyArrayBuffer); diff --git a/src/node_i18n.cc b/src/node_i18n.cc index c537a247f55ff070da1988fc8b7309b5692b5c18..59bfb597849cd5a94800d6c83b238ef77245243e 100644 --- a/src/node_i18n.cc +++ b/src/node_i18n.cc @@ -104,7 +104,7 @@ namespace { template <typename T> MaybeLocal<Object> ToBufferEndian(Environment* env, MaybeStackBuffer<T>* buf) { - MaybeLocal<Object> ret = Buffer::New(env, buf); + MaybeLocal<Object> ret = Buffer::Copy(env, reinterpret_cast<char*>(buf->out()), buf->length() * sizeof(T)); if (ret.IsEmpty()) return ret; diff --git a/src/node_internals.h b/src/node_internals.h index d37be23cd63e82d4040777bd0e17ed449ec0b15b..0b66996f11c66800a7e21ee84fa101450b856227 100644 --- a/src/node_internals.h +++ b/src/node_internals.h @@ -118,6 +118,8 @@ class NodeArrayBufferAllocator : public ArrayBufferAllocator { private: uint32_t zero_fill_field_ = 1; // Boolean but exposed as uint32 to JS land. std::atomic<size_t> total_mem_usage_ {0}; + + std::unique_ptr<v8::ArrayBuffer::Allocator> allocator_{v8::ArrayBuffer::Allocator::NewDefaultAllocator()}; }; class DebuggingArrayBufferAllocator final : public NodeArrayBufferAllocator { diff --git a/src/node_serdes.cc b/src/node_serdes.cc index f6f0034bc24d09e3ad65491c7d6be0b9c9db1581..92d5020f293c98c81d3891a82f7320629bf9f926 100644 --- a/src/node_serdes.cc +++ b/src/node_serdes.cc @@ -29,6 +29,11 @@ using v8::ValueSerializer; namespace serdes { +v8::ArrayBuffer::Allocator* GetAllocator() { + static v8::ArrayBuffer::Allocator* allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); + return allocator; +}; + class SerializerContext : public BaseObject, public ValueSerializer::Delegate { public: @@ -37,10 +42,15 @@ class SerializerContext : public BaseObject, ~SerializerContext() override = default; + // v8::ValueSerializer::Delegate void ThrowDataCloneError(Local<String> message) override; Maybe<bool> WriteHostObject(Isolate* isolate, Local<Object> object) override; Maybe<uint32_t> GetSharedArrayBufferId( Isolate* isolate, Local<SharedArrayBuffer> shared_array_buffer) override; + void* ReallocateBufferMemory(void* old_buffer, + size_t old_length, + size_t* new_length) override; + void FreeBufferMemory(void* buffer) override; static void SetTreatArrayBufferViewsAsHostObjects( const FunctionCallbackInfo<Value>& args); @@ -61,6 +71,7 @@ class SerializerContext : public BaseObject, private: ValueSerializer serializer_; + size_t last_length_ = 0; }; class DeserializerContext : public BaseObject, @@ -144,6 +155,24 @@ Maybe<uint32_t> SerializerContext::GetSharedArrayBufferId( return id.ToLocalChecked()->Uint32Value(env()->context()); } +void* SerializerContext::ReallocateBufferMemory(void* old_buffer, + size_t requested_size, + size_t* new_length) { + *new_length = std::max(static_cast<size_t>(4096), requested_size); + if (old_buffer) { + void* ret = GetAllocator()->Reallocate(old_buffer, last_length_, *new_length); + last_length_ = *new_length; + return ret; + } else { + last_length_ = *new_length; + return GetAllocator()->Allocate(*new_length); + } +} + +void SerializerContext::FreeBufferMemory(void* buffer) { + GetAllocator()->Free(buffer, last_length_); +} + Maybe<bool> SerializerContext::WriteHostObject(Isolate* isolate, Local<Object> input) { MaybeLocal<Value> ret; @@ -211,7 +240,12 @@ void SerializerContext::ReleaseBuffer(const FunctionCallbackInfo<Value>& args) { std::pair<uint8_t*, size_t> ret = ctx->serializer_.Release(); auto buf = Buffer::New(ctx->env(), reinterpret_cast<char*>(ret.first), - ret.second); + ret.second, + [](char* data, void* hint){ + if (data) + GetAllocator()->Free(data, reinterpret_cast<size_t>(hint)); + }, + reinterpret_cast<void*>(ctx->last_length_)); if (!buf.IsEmpty()) { args.GetReturnValue().Set(buf.ToLocalChecked());
closed
electron/electron
https://github.com/electron/electron
31,634
[Bug]: crypto.hkdf "Deriving bits failed"
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version v15.3.0 ### What operating system are you using? macOS ### Operating System Version Darwin C02CX0K5MD6V 20.6.0 Darwin Kernel Version 20.6.0: Mon Aug 30 06:12:21 PDT 2021; root:xnu-7195.141.6~3/RELEASE_X86_64 x86_64 ### What arch are you using? x64 ### Last Known Working Electron version none ### Expected Behavior `crypto.hkdf` and `crypto.hkdfSync` work as documented[^1] [^1]: https://nodejs.org/api/crypto.html#cryptohkdfdigest-ikm-salt-info-keylen-callback ### Actual Behavior ``` crypto.hkdfSync('sha256', 'foo', '', '', 32) // Uncaught Error: Deriving bits failed // at Object.hkdfSync (node:internal/crypto/hkdf:140:35) crypto.hkdf('sha256', 'foo', '', '', 32, console.log) // [Error: Deriving bits failed] ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/31634
https://github.com/electron/electron/pull/34767
35ff95d3c71849ac97ced178a2330b9d4651f250
ad2b1fee59c2e4352b0c5664f72c0067a2ef4d7f
2021-10-29T09:01:40Z
c++
2022-06-29T12:53:57Z
script/node-disabled-tests.json
[ "abort/test-abort-backtrace", "async-hooks/test-crypto-pbkdf2", "async-hooks/test-crypto-randomBytes", "parallel/test-bootstrap-modules", "parallel/test-child-process-fork-exec-path", "parallel/test-cli-node-print-help", "parallel/test-cluster-bind-privileged-port", "parallel/test-cluster-shared-handle-bind-privileged-port", "parallel/test-code-cache", "parallel/test-crypto-aes-wrap", "parallel/test-crypto-authenticated-stream", "parallel/test-crypto-des3-wrap", "parallel/test-crypto-dh-stateless", "parallel/test-crypto-ecb", "parallel/test-crypto-engine", "parallel/test-crypto-fips", "parallel/test-crypto-hkdf.js", "parallel/test-crypto-keygen", "parallel/test-crypto-keygen-deprecation", "parallel/test-crypto-key-objects", "parallel/test-crypto-padding-aes256", "parallel/test-crypto-secure-heap", "parallel/test-fs-utimes-y2K38", "parallel/test-heapsnapshot-near-heap-limit-worker.js", "parallel/test-http2-clean-output", "parallel/test-https-agent-session-reuse", "parallel/test-https-options-boolean-check", "parallel/test-icu-minimum-version", "parallel/test-inspector-multisession-ws", "parallel/test-inspector-port-zero-cluster", "parallel/test-inspector-tracing-domain", "parallel/test-module-loading-globalpaths", "parallel/test-module-version", "parallel/test-openssl-ca-options", "parallel/test-process-env-allowed-flags-are-documented", "parallel/test-process-versions", "parallel/test-repl", "parallel/test-repl-underscore", "parallel/test-stdout-close-catch", "parallel/test-tls-cert-chains-concat", "parallel/test-tls-cert-chains-in-ca", "parallel/test-tls-cli-max-version-1.2", "parallel/test-tls-cli-max-version-1.3", "parallel/test-tls-cli-min-version-1.1", "parallel/test-tls-cli-min-version-1.2", "parallel/test-tls-cli-min-version-1.3", "parallel/test-tls-client-auth", "parallel/test-tls-client-getephemeralkeyinfo", "parallel/test-tls-client-mindhsize", "parallel/test-tls-client-reject", "parallel/test-tls-client-renegotiation-13", "parallel/test-tls-cnnic-whitelist", "parallel/test-tls-disable-renegotiation", "parallel/test-tls-empty-sni-context", "parallel/test-tls-env-bad-extra-ca", "parallel/test-tls-env-extra-ca", "parallel/test-tls-finished", "parallel/test-tls-generic-stream", "parallel/test-tls-getcipher", "parallel/test-tls-handshake-error", "parallel/test-tls-handshake-exception", "parallel/test-tls-hello-parser-failure", "parallel/test-tls-honorcipherorder", "parallel/test-tls-junk-closes-server", "parallel/test-tls-junk-server", "parallel/test-tls-key-mismatch", "parallel/test-tls-max-send-fragment", "parallel/test-tls-min-max-version", "parallel/test-tls-multi-key", "parallel/test-tls-multi-pfx", "parallel/test-tls-no-cert-required", "parallel/test-tls-options-boolean-check", "parallel/test-tls-passphrase", "parallel/test-tls-peer-certificate", "parallel/test-tls-pfx-authorizationerror", "parallel/test-tls-psk-circuit", "parallel/test-tls-root-certificates", "parallel/test-tls-server-failed-handshake-emits-clienterror", "parallel/test-tls-set-ciphers", "parallel/test-tls-set-ciphers-error", "parallel/test-tls-set-sigalgs", "parallel/test-tls-socket-allow-half-open-option", "parallel/test-tls-socket-failed-handshake-emits-error", "parallel/test-tls-ticket", "parallel/test-tls-ticket-cluster", "parallel/test-trace-events-all", "parallel/test-trace-events-async-hooks", "parallel/test-trace-events-binding", "parallel/test-trace-events-bootstrap", "parallel/test-trace-events-category-used", "parallel/test-trace-events-console", "parallel/test-trace-events-dynamic-enable", "parallel/test-trace-events-dynamic-enable-workers-disabled", "parallel/test-trace-events-environment", "parallel/test-trace-events-file-pattern", "parallel/test-trace-events-fs-sync", "parallel/test-trace-events-metadata", "parallel/test-trace-events-none", "parallel/test-trace-events-perf", "parallel/test-trace-events-process-exit", "parallel/test-trace-events-promises", "parallel/test-trace-events-v8", "parallel/test-trace-events-vm", "parallel/test-trace-events-worker-metadata", "parallel/test-v8-untrusted-code-mitigations", "parallel/test-webcrypto-derivebits-hkdf", "parallel/test-webcrypto-derivebits-node-dh", "parallel/test-webcrypto-ed25519-ed448", "parallel/test-webcrypto-encrypt-decrypt", "parallel/test-webcrypto-encrypt-decrypt-aes", "parallel/test-webcrypto-encrypt-decrypt-rsa", "parallel/test-webcrypto-keygen", "parallel/test-webcrypto-rsa-pss-params", "parallel/test-webcrypto-sign-verify-node-dsa", "parallel/test-webcrypto-x25519-x448", "parallel/test-worker-debug", "parallel/test-worker-stdio", "parallel/test-zlib-unused-weak", "report/test-report-fatal-error", "report/test-report-getreport", "report/test-report-signal", "report/test-report-uncaught-exception", "report/test-report-uncaught-exception-compat", "report/test-report-uv-handles", "report/test-report-worker", "report/test-report-writereport", "sequential/test-cpu-prof-kill", "sequential/test-diagnostic-dir-cpu-prof", "sequential/test-cpu-prof-drained.js", "sequential/test-tls-connect", "wpt/test-webcrypto" ]
closed
electron/electron
https://github.com/electron/electron
31,634
[Bug]: crypto.hkdf "Deriving bits failed"
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version v15.3.0 ### What operating system are you using? macOS ### Operating System Version Darwin C02CX0K5MD6V 20.6.0 Darwin Kernel Version 20.6.0: Mon Aug 30 06:12:21 PDT 2021; root:xnu-7195.141.6~3/RELEASE_X86_64 x86_64 ### What arch are you using? x64 ### Last Known Working Electron version none ### Expected Behavior `crypto.hkdf` and `crypto.hkdfSync` work as documented[^1] [^1]: https://nodejs.org/api/crypto.html#cryptohkdfdigest-ikm-salt-info-keylen-callback ### Actual Behavior ``` crypto.hkdfSync('sha256', 'foo', '', '', 32) // Uncaught Error: Deriving bits failed // at Object.hkdfSync (node:internal/crypto/hkdf:140:35) crypto.hkdf('sha256', 'foo', '', '', 32, console.log) // [Error: Deriving bits failed] ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/31634
https://github.com/electron/electron/pull/34767
35ff95d3c71849ac97ced178a2330b9d4651f250
ad2b1fee59c2e4352b0c5664f72c0067a2ef4d7f
2021-10-29T09:01:40Z
c++
2022-06-29T12:53:57Z
patches/node/fix_crypto_tests_to_run_with_bssl.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Jeremy Rose <[email protected]> Date: Tue, 9 Feb 2021 12:34:46 -0800 Subject: fix crypto tests to run with bssl This fixes some crypto tests so that they pass when compiled with BoringSSL. This should be upstreamed in some form, though it may need to be tweaked before it's acceptable to upstream, as this patch comments out a couple of tests that upstream probably cares about. diff --git a/test/parallel/test-crypto-async-sign-verify.js b/test/parallel/test-crypto-async-sign-verify.js index 4e3c32fdcd23fbe3e74bd5e624b739d224689f33..19d65aae7fa8ec9f9b907733ead17a208ed47909 100644 --- a/test/parallel/test-crypto-async-sign-verify.js +++ b/test/parallel/test-crypto-async-sign-verify.js @@ -88,6 +88,7 @@ test('rsa_public.pem', 'rsa_private.pem', 'sha256', false, // ED25519 test('ed25519_public.pem', 'ed25519_private.pem', undefined, true); // ED448 +/* test('ed448_public.pem', 'ed448_private.pem', undefined, true); // ECDSA w/ der signature encoding @@ -109,6 +110,7 @@ test('dsa_public.pem', 'dsa_private.pem', 'sha256', // DSA w/ ieee-p1363 signature encoding test('dsa_public.pem', 'dsa_private.pem', 'sha256', false, { dsaEncoding: 'ieee-p1363' }); +*/ // Test Parallel Execution w/ KeyObject is threadsafe in openssl3 { diff --git a/test/parallel/test-crypto-authenticated.js b/test/parallel/test-crypto-authenticated.js index 3749895769ffc9947143aee9aeb126628262bc84..f769fc37dbd81d5a0219236921e0bcb0de416463 100644 --- a/test/parallel/test-crypto-authenticated.js +++ b/test/parallel/test-crypto-authenticated.js @@ -50,7 +50,9 @@ const errMessages = { const ciphers = crypto.getCiphers(); const expectedWarnings = common.hasFipsCrypto ? - [] : [ + [] : !ciphers.includes('aes-192-ccm') ? [ + ['Use Cipheriv for counter mode of aes-192-gcm'], + ] : [ ['Use Cipheriv for counter mode of aes-192-gcm'], ['Use Cipheriv for counter mode of aes-192-ccm'], ['Use Cipheriv for counter mode of aes-192-ccm'], @@ -319,7 +321,9 @@ for (const test of TEST_CASES) { // Test that create(De|C)ipher(iv)? throws if the mode is CCM and an invalid // authentication tag length has been specified. -{ +if (!ciphers.includes('aes-256-ccm')) { + common.printSkipMessage(`unsupported aes-256-ccm test`); +} else { for (const authTagLength of [-1, true, false, NaN, 5.5]) { assert.throws(() => { crypto.createCipheriv('aes-256-ccm', @@ -407,6 +411,10 @@ for (const test of TEST_CASES) { // authentication tag has been specified. { for (const mode of ['ccm', 'ocb']) { + if (!ciphers.includes(`aes-256-${mode}`)) { + common.printSkipMessage(`unsupported aes-256-${mode} test`); + continue; + } assert.throws(() => { crypto.createCipheriv(`aes-256-${mode}`, 'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8', @@ -441,7 +449,9 @@ for (const test of TEST_CASES) { } // Test that setAAD throws if an invalid plaintext length has been specified. -{ +if (!ciphers.includes('aes-256-ccm')) { + common.printSkipMessage(`unsupported aes-256-ccm test`); +} else { const cipher = crypto.createCipheriv('aes-256-ccm', 'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8', 'qkuZpJWCewa6S', @@ -462,7 +472,9 @@ for (const test of TEST_CASES) { } // Test that setAAD and update throw if the plaintext is too long. -{ +if (!ciphers.includes('aes-256-ccm')) { + common.printSkipMessage(`unsupported aes-256-ccm test`); +} else { for (const ivLength of [13, 12]) { const maxMessageSize = (1 << (8 * (15 - ivLength))) - 1; const key = 'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8'; @@ -493,7 +505,9 @@ for (const test of TEST_CASES) { // Test that setAAD throws if the mode is CCM and the plaintext length has not // been specified. -{ +if (!ciphers.includes('aes-256-ccm')) { + common.printSkipMessage(`unsupported aes-256-ccm test`); +} else { assert.throws(() => { const cipher = crypto.createCipheriv('aes-256-ccm', 'FxLKsqdmv0E9xrQhp0b1ZgI0K7JFZJM8', @@ -518,7 +532,9 @@ for (const test of TEST_CASES) { } // Test that final() throws in CCM mode when no authentication tag is provided. -{ +if (!ciphers.includes('aes-128-ccm')) { + common.printSkipMessage(`unsupported aes-256-ccm test`); +} else { if (!common.hasFipsCrypto) { const key = Buffer.from('1ed2233fa2223ef5d7df08546049406c', 'hex'); const iv = Buffer.from('7305220bca40d4c90e1791e9', 'hex'); @@ -550,7 +566,9 @@ for (const test of TEST_CASES) { } // Test that an IV length of 11 does not overflow max_message_size_. -{ +if (!ciphers.includes('aes-128-ccm')) { + common.printSkipMessage(`unsupported aes-128-ccm test`); +} else { const key = 'x'.repeat(16); const iv = Buffer.from('112233445566778899aabb', 'hex'); const options = { authTagLength: 8 }; @@ -567,6 +585,10 @@ for (const test of TEST_CASES) { const iv = Buffer.from('0123456789ab', 'utf8'); for (const mode of ['gcm', 'ocb']) { + if (!ciphers.includes(`aes-128-${mode}`)) { + common.printSkipMessage(`unsupported aes-128-${mode} test`); + continue; + } for (const authTagLength of mode === 'gcm' ? [undefined, 8] : [8]) { const cipher = crypto.createCipheriv(`aes-128-${mode}`, key, iv, { authTagLength @@ -601,6 +623,10 @@ for (const test of TEST_CASES) { const opts = { authTagLength: 8 }; for (const mode of ['gcm', 'ccm', 'ocb']) { + if (!ciphers.includes(`aes-128-${mode}`)) { + common.printSkipMessage(`unsupported aes-128-${mode} test`); + continue; + } const cipher = crypto.createCipheriv(`aes-128-${mode}`, key, iv, opts); const ciphertext = Buffer.concat([cipher.update(plain), cipher.final()]); const tag = cipher.getAuthTag(); @@ -623,7 +649,9 @@ for (const test of TEST_CASES) { // Test chacha20-poly1305 rejects invalid IV lengths of 13, 14, 15, and 16 (a // length of 17 or greater was already rejected). // - https://www.openssl.org/news/secadv/20190306.txt -{ +if (!ciphers.includes('chacha20-poly1305')) { + common.printSkipMessage(`unsupported chacha20-poly1305 test`); +} else { // Valid extracted from TEST_CASES, check that it detects IV tampering. const valid = { algo: 'chacha20-poly1305', @@ -669,6 +697,9 @@ for (const test of TEST_CASES) { { // CCM cipher without data should not crash, see https://github.com/nodejs/node/issues/38035. + common.printSkipMessage(`unsupported aes-128-ccm test`); + return; + const algo = 'aes-128-ccm'; const key = Buffer.alloc(16); const iv = Buffer.alloc(12); diff --git a/test/parallel/test-crypto-binary-default.js b/test/parallel/test-crypto-binary-default.js index 3bbca5b0da395b94c04da7bb7c55b107e41367d8..af62558c4f23aa82804e0077da7b7f3a86cfac60 100644 --- a/test/parallel/test-crypto-binary-default.js +++ b/test/parallel/test-crypto-binary-default.js @@ -51,15 +51,15 @@ tls.createSecureContext({ pfx: certPfx, passphrase: 'sample' }); assert.throws(function() { tls.createSecureContext({ pfx: certPfx }); -}, /^Error: mac verify failure$/); +}, /^Error: (mac verify failure|INCORRECT_PASSWORD)$/); assert.throws(function() { tls.createSecureContext({ pfx: certPfx, passphrase: 'test' }); -}, /^Error: mac verify failure$/); +}, /^Error: (mac verify failure|INCORRECT_PASSWORD)$/); assert.throws(function() { tls.createSecureContext({ pfx: 'sample', passphrase: 'test' }); -}, /^Error: not enough data$/); +}, /^Error: (not enough data|BAD_PKCS12_DATA)$/); // Test HMAC { @@ -462,7 +462,7 @@ assert.throws(function() { function testCipher1(key) { // Test encryption and decryption const plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; - const cipher = crypto.createCipher('aes192', key); + const cipher = crypto.createCipher('aes-192-cbc', key); // Encrypt plaintext which is in utf8 format // to a ciphertext which will be in hex @@ -470,7 +470,7 @@ function testCipher1(key) { // Only use binary or hex, not base64. ciph += cipher.final('hex'); - const decipher = crypto.createDecipher('aes192', key); + const decipher = crypto.createDecipher('aes-192-cbc', key); let txt = decipher.update(ciph, 'hex', 'utf8'); txt += decipher.final('utf8'); @@ -485,14 +485,14 @@ function testCipher2(key) { '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'jAfaFg**'; - const cipher = crypto.createCipher('aes256', key); + const cipher = crypto.createCipher('aes-256-cbc', key); // Encrypt plaintext which is in utf8 format // to a ciphertext which will be in Base64 let ciph = cipher.update(plaintext, 'utf8', 'base64'); ciph += cipher.final('base64'); - const decipher = crypto.createDecipher('aes256', key); + const decipher = crypto.createDecipher('aes-256-cbc', key); let txt = decipher.update(ciph, 'base64', 'utf8'); txt += decipher.final('utf8'); @@ -537,6 +537,10 @@ function testCipher4(key, iv) { function testCipher5(key, iv) { + if (!crypto.getCiphers().includes('id-aes128-wrap')) { + common.printSkipMessage(`unsupported id-aes128-wrap test`); + return; + } // Test encryption and decryption with explicit key with aes128-wrap const plaintext = '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + @@ -662,6 +666,8 @@ assert.throws( } +/* NB: BoringSSL does not support using DSA through the EVP API. + * https://boringssl.googlesource.com/boringssl/+/a2278d4d2cabe73f6663e3299ea7808edfa306b9/PORTING.md#dsa-s // // Test DSA signing and verification // @@ -682,6 +688,7 @@ assert.throws( assert.strictEqual(verify.verify(publicKey, signature, 'hex'), true); } +*/ // diff --git a/test/parallel/test-crypto-certificate.js b/test/parallel/test-crypto-certificate.js index 4a5f1f149fe6c739f7f1d2ee17df6e61a942d621..b3287f428ce6b3fde11d449c601a57ff5e3843f9 100644 --- a/test/parallel/test-crypto-certificate.js +++ b/test/parallel/test-crypto-certificate.js @@ -40,8 +40,10 @@ function copyArrayBuffer(buf) { } function checkMethods(certificate) { - + /* spkacValid has a md5 based signature which is not allowed in boringssl + https://boringssl.googlesource.com/boringssl/+/33d7e32ce40c04e8f1b99c05964956fda187819f assert.strictEqual(certificate.verifySpkac(spkacValid), true); + */ assert.strictEqual(certificate.verifySpkac(spkacFail), false); assert.strictEqual( @@ -56,10 +58,12 @@ function checkMethods(certificate) { ); assert.strictEqual(certificate.exportChallenge(spkacFail), ''); + /* spkacValid has a md5 based signature which is not allowed in boringssl const ab = copyArrayBuffer(spkacValid); assert.strictEqual(certificate.verifySpkac(ab), true); assert.strictEqual(certificate.verifySpkac(new Uint8Array(ab)), true); assert.strictEqual(certificate.verifySpkac(new DataView(ab)), true); + */ } { diff --git a/test/parallel/test-crypto-cipher-decipher.js b/test/parallel/test-crypto-cipher-decipher.js index 35514afbea92562a81c163b1e4d918b4ab609f71..13098e1acf12c309f2ed6f6143a2c2eeb8a2763d 100644 --- a/test/parallel/test-crypto-cipher-decipher.js +++ b/test/parallel/test-crypto-cipher-decipher.js @@ -22,7 +22,7 @@ common.expectWarning({ function testCipher1(key) { // Test encryption and decryption const plaintext = 'Keep this a secret? No! Tell everyone about node.js!'; - const cipher = crypto.createCipher('aes192', key); + const cipher = crypto.createCipher('aes-192-cbc', key); // Encrypt plaintext which is in utf8 format // to a ciphertext which will be in hex @@ -30,7 +30,7 @@ function testCipher1(key) { // Only use binary or hex, not base64. ciph += cipher.final('hex'); - const decipher = crypto.createDecipher('aes192', key); + const decipher = crypto.createDecipher('aes-192-cbc', key); let txt = decipher.update(ciph, 'hex', 'utf8'); txt += decipher.final('utf8'); @@ -40,11 +40,11 @@ function testCipher1(key) { // NB: In real life, it's not guaranteed that you can get all of it // in a single read() like this. But in this case, we know it's // quite small, so there's no harm. - const cStream = crypto.createCipher('aes192', key); + const cStream = crypto.createCipher('aes-192-cbc', key); cStream.end(plaintext); ciph = cStream.read(); - const dStream = crypto.createDecipher('aes192', key); + const dStream = crypto.createDecipher('aes-192-cbc', key); dStream.end(ciph); txt = dStream.read().toString('utf8'); @@ -59,14 +59,14 @@ function testCipher2(key) { '32|RmVZZkFUVmpRRkp0TmJaUm56ZU9qcnJkaXNNWVNpTTU*|iXmckfRWZBGWWELw' + 'eCBsThSsfUHLeRe0KCsK8ooHgxie0zOINpXxfZi/oNG7uq9JWFVCk70gfzQH8ZUJ' + 'jAfaFg**'; - const cipher = crypto.createCipher('aes256', key); + const cipher = crypto.createCipher('aes-256-cbc', key); // Encrypt plaintext which is in utf8 format to a ciphertext which will be in // Base64. let ciph = cipher.update(plaintext, 'utf8', 'base64'); ciph += cipher.final('base64'); - const decipher = crypto.createDecipher('aes256', key); + const decipher = crypto.createDecipher('aes-256-cbc', key); let txt = decipher.update(ciph, 'base64', 'utf8'); txt += decipher.final('utf8'); @@ -170,7 +170,7 @@ testCipher2(Buffer.from('0123456789abcdef')); // Regression test for https://github.com/nodejs/node-v0.x-archive/issues/5482: // string to Cipher#update() should not assert. { - const c = crypto.createCipher('aes192', '0123456789abcdef'); + const c = crypto.createCipher('aes-192-cbc', '0123456789abcdef'); c.update('update'); c.final(); } @@ -178,15 +178,15 @@ testCipher2(Buffer.from('0123456789abcdef')); // https://github.com/nodejs/node-v0.x-archive/issues/5655 regression tests, // 'utf-8' and 'utf8' are identical. { - let c = crypto.createCipher('aes192', '0123456789abcdef'); + let c = crypto.createCipher('aes-192-cbc', '0123456789abcdef'); c.update('update', ''); // Defaults to "utf8". c.final('utf-8'); // Should not throw. - c = crypto.createCipher('aes192', '0123456789abcdef'); + c = crypto.createCipher('aes-192-cbc', '0123456789abcdef'); c.update('update', 'utf8'); c.final('utf-8'); // Should not throw. - c = crypto.createCipher('aes192', '0123456789abcdef'); + c = crypto.createCipher('aes-192-cbc', '0123456789abcdef'); c.update('update', 'utf-8'); c.final('utf8'); // Should not throw. } @@ -195,23 +195,23 @@ testCipher2(Buffer.from('0123456789abcdef')); { const key = '0123456789abcdef'; const plaintext = 'Top secret!!!'; - const c = crypto.createCipher('aes192', key); + const c = crypto.createCipher('aes-192-cbc', key); let ciph = c.update(plaintext, 'utf16le', 'base64'); ciph += c.final('base64'); - let decipher = crypto.createDecipher('aes192', key); + let decipher = crypto.createDecipher('aes-192-cbc', key); let txt; txt = decipher.update(ciph, 'base64', 'ucs2'); txt += decipher.final('ucs2'); assert.strictEqual(txt, plaintext); - decipher = crypto.createDecipher('aes192', key); + decipher = crypto.createDecipher('aes-192-cbc', key); txt = decipher.update(ciph, 'base64', 'ucs-2'); txt += decipher.final('ucs-2'); assert.strictEqual(txt, plaintext); - decipher = crypto.createDecipher('aes192', key); + decipher = crypto.createDecipher('aes-192-cbc', key); txt = decipher.update(ciph, 'base64', 'utf-16le'); txt += decipher.final('utf-16le'); assert.strictEqual(txt, plaintext); diff --git a/test/parallel/test-crypto-cipheriv-decipheriv.js b/test/parallel/test-crypto-cipheriv-decipheriv.js index 87f3641fb188bd322e7c256e9548c6af85dc9a14..1e803bc33ba4642065bf1897c56f65fc92bd2a50 100644 --- a/test/parallel/test-crypto-cipheriv-decipheriv.js +++ b/test/parallel/test-crypto-cipheriv-decipheriv.js @@ -60,6 +60,10 @@ function testCipher2(key, iv) { function testCipher3(key, iv) { + if (!crypto.getCiphers().includes('id-aes128-wrap')) { + common.printSkipMessage(`unsupported id-aes128-wrap test`); + return; + } // Test encryption and decryption with explicit key and iv. // AES Key Wrap test vector comes from RFC3394 const plaintext = Buffer.from('00112233445566778899AABBCCDDEEFF', 'hex'); diff --git a/test/parallel/test-crypto-classes.js b/test/parallel/test-crypto-classes.js index dd073274aef765e8f1e403aa2c8baf9694b521cb..fc6339e040debe61ecc61a3eb5b26823b102f1ff 100644 --- a/test/parallel/test-crypto-classes.js +++ b/test/parallel/test-crypto-classes.js @@ -22,8 +22,8 @@ const TEST_CASES = { }; if (!common.hasFipsCrypto) { - TEST_CASES.Cipher = ['aes192', 'secret']; - TEST_CASES.Decipher = ['aes192', 'secret']; + TEST_CASES.Cipher = ['aes-192-cbc', 'secret']; + TEST_CASES.Decipher = ['aes-192-cbc', 'secret']; TEST_CASES.DiffieHellman = [common.hasOpenSSL3 ? 1024 : 256]; } diff --git a/test/parallel/test-crypto-dh.js b/test/parallel/test-crypto-dh.js index 18721fcf289e5545408e309db050a2ff0f4b0140..e5235e0a5fbd68416b4a9480818901b411ed91bd 100644 --- a/test/parallel/test-crypto-dh.js +++ b/test/parallel/test-crypto-dh.js @@ -49,7 +49,7 @@ for (const bits of [-1, 0, 1]) { assert.throws(() => crypto.createDiffieHellman(bits), { code: 'ERR_OSSL_BN_BITS_TOO_SMALL', name: 'Error', - message: /bits too small/, + message: /bits too small|BITS_TOO_SMALL/, }); } } @@ -65,7 +65,7 @@ for (const g of [-1, 1]) { const ex = { code: 'ERR_OSSL_DH_BAD_GENERATOR', name: 'Error', - message: /bad generator/, + message: /bad generator|BAD_GENERATOR/, }; assert.throws(() => crypto.createDiffieHellman('abcdef', g), ex); assert.throws(() => crypto.createDiffieHellman('abcdef', 'hex', g), ex); @@ -79,7 +79,7 @@ for (const g of [Buffer.from([]), const ex = { code: 'ERR_OSSL_DH_BAD_GENERATOR', name: 'Error', - message: /bad generator/, + message: /bad generator|BAD_GENERATOR/, }; assert.throws(() => crypto.createDiffieHellman('abcdef', g), ex); assert.throws(() => crypto.createDiffieHellman('abcdef', 'hex', g), ex); @@ -133,18 +133,17 @@ assert.strictEqual(secret1, secret4); let wrongBlockLength; if (common.hasOpenSSL3) { wrongBlockLength = { - message: 'error:1C80006B:Provider routines::wrong final block length', - code: 'ERR_OSSL_WRONG_FINAL_BLOCK_LENGTH', - library: 'Provider routines', - reason: 'wrong final block length' + message: /error:1C80006B:Provider routines::wrong final block length|error:1e00007b:Cipher functions:OPENSSL_internal:WRONG_FINAL_BLOCK_LENGTH/, + code: /ERR_OSSL_(EVP_)?WRONG_FINAL_BLOCK_LENGTH/, + library: /digital envelope routines|Cipher functions/, + reason: /wrong final block length|WRONG_FINAL_BLOCK_LENGTH/ }; } else { wrongBlockLength = { - message: 'error:0606506D:digital envelope' + - ' routines:EVP_DecryptFinal_ex:wrong final block length', - code: 'ERR_OSSL_EVP_WRONG_FINAL_BLOCK_LENGTH', - library: 'digital envelope routines', - reason: 'wrong final block length' + message: /error:0606506D:digital envelope routines:EVP_DecryptFinal_ex:wrong final block length|error:1e00007b:Cipher functions:OPENSSL_internal:WRONG_FINAL_BLOCK_LENGTH/, + code: /ERR_OSSL_(EVP_)?WRONG_FINAL_BLOCK_LENGTH/, + library: /digital envelope routines|Cipher functions/, + reason: /wrong final block length|WRONG_FINAL_BLOCK_LENGTH/ }; } diff --git a/test/parallel/test-crypto-getcipherinfo.js b/test/parallel/test-crypto-getcipherinfo.js index 98d2a52eceac4bc564fd2878f77b50c336a67a66..bcb2de6e354c26816000f2400d9c1d46de01888a 100644 --- a/test/parallel/test-crypto-getcipherinfo.js +++ b/test/parallel/test-crypto-getcipherinfo.js @@ -62,9 +62,13 @@ assert(getCipherInfo('aes-128-cbc', { ivLength: 16 })); assert(!getCipherInfo('aes-128-ccm', { ivLength: 1 })); assert(!getCipherInfo('aes-128-ccm', { ivLength: 14 })); +/* for (let n = 7; n <= 13; n++) assert(getCipherInfo('aes-128-ccm', { ivLength: n })); +*/ assert(!getCipherInfo('aes-128-ocb', { ivLength: 16 })); +/* for (let n = 1; n < 16; n++) assert(getCipherInfo('aes-128-ocb', { ivLength: n })); +*/ \ No newline at end of file diff --git a/test/parallel/test-crypto-hash-stream-pipe.js b/test/parallel/test-crypto-hash-stream-pipe.js index d22281abbd5c3cab3aaa3ac494301fa6b4a8a968..5f0c6a4aed2e868a1a1049212edf218791cd6868 100644 --- a/test/parallel/test-crypto-hash-stream-pipe.js +++ b/test/parallel/test-crypto-hash-stream-pipe.js @@ -30,11 +30,11 @@ const crypto = require('crypto'); const stream = require('stream'); const s = new stream.PassThrough(); -const h = crypto.createHash('sha3-512'); -const expect = '36a38a2a35e698974d4e5791a3f05b05' + - '198235381e864f91a0e8cd6a26b677ec' + - 'dcde8e2b069bd7355fabd68abd6fc801' + - '19659f25e92f8efc961ee3a7c815c758'; +const h = crypto.createHash('sha512'); +const expect = 'fba055c6fd0c5b6645407749ed7a8b41' + + 'b8f629f2163c3ca3701d864adabda1f8' + + '93c37bf82b22fdd151ba8e357f611da4' + + '88a74b6a5525dd9b69554c6ce5138ad7'; s.pipe(h).on('data', common.mustCall(function(c) { assert.strictEqual(c, expect); diff --git a/test/parallel/test-crypto-hash.js b/test/parallel/test-crypto-hash.js index af2146982c7a3bf7bd7527f44e4b17a3b605026e..f6b91f675cfea367c608892dee078b565814f2dd 100644 --- a/test/parallel/test-crypto-hash.js +++ b/test/parallel/test-crypto-hash.js @@ -182,6 +182,7 @@ assert.throws( // Test XOF hash functions and the outputLength option. { + /* // Default outputLengths. assert.strictEqual(crypto.createHash('shake128').digest('hex'), '7f9c2ba4e88f827d616045507605853e'); @@ -236,6 +237,7 @@ assert.throws( assert.strictEqual(superLongHash.length, 2 * 1024 * 1024); assert.ok(superLongHash.endsWith('193414035ddba77bf7bba97981e656ec')); assert.ok(superLongHash.startsWith('a2a28dbc49cfd6e5d6ceea3d03e77748')); + */ // Non-XOF hash functions should accept valid outputLength options as well. assert.strictEqual(crypto.createHash('sha224', { outputLength: 28 }) diff --git a/test/parallel/test-crypto-padding.js b/test/parallel/test-crypto-padding.js index f1f14b472997e76bb4100edb1c6cf4fc24d1074d..5057e3f9bc5bb78aceffa5e79530f8ceed84e6f7 100644 --- a/test/parallel/test-crypto-padding.js +++ b/test/parallel/test-crypto-padding.js @@ -87,10 +87,9 @@ assert.throws(function() { code: 'ERR_OSSL_WRONG_FINAL_BLOCK_LENGTH', reason: 'wrong final block length', } : { - message: 'error:0607F08A:digital envelope routines:EVP_EncryptFinal_ex:' + - 'data not multiple of block length', - code: 'ERR_OSSL_EVP_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH', - reason: 'data not multiple of block length', + message: /error:0607F08A:digital envelope routines:EVP_EncryptFinal_ex:data not multiple of block length|error:1e00006a:Cipher functions:OPENSSL_internal:DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH/, + code: /ERR_OSSL(_EVP)?_DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH/, + reason: /data not multiple of block length|DATA_NOT_MULTIPLE_OF_BLOCK_LENGTH/, } ); @@ -114,10 +113,9 @@ assert.throws(function() { reason: 'bad decrypt', code: 'ERR_OSSL_BAD_DECRYPT', } : { - message: 'error:06065064:digital envelope routines:EVP_DecryptFinal_ex:' + - 'bad decrypt', - reason: 'bad decrypt', - code: 'ERR_OSSL_EVP_BAD_DECRYPT', + message: /error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt|error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT/, + reason: /bad decrypt|BAD_DECRYPT/, + code: /ERR_OSSL(_EVP)?_BAD_DECRYPT/, }); // No-pad encrypted string should return the same: diff --git a/test/parallel/test-crypto-private-decrypt-gh32240.js b/test/parallel/test-crypto-private-decrypt-gh32240.js index 1785f5eef3d202976666081d09850ed744d83446..e88227a215ba4f7fa196f7642ae694a57d55b3ca 100644 --- a/test/parallel/test-crypto-private-decrypt-gh32240.js +++ b/test/parallel/test-crypto-private-decrypt-gh32240.js @@ -24,7 +24,7 @@ const pkeyEncrypted = pair.privateKey.export({ type: 'pkcs1', format: 'pem', - cipher: 'aes128', + cipher: 'aes-128-cbc', passphrase: 'secret', }); diff --git a/test/parallel/test-crypto-rsa-dsa.js b/test/parallel/test-crypto-rsa-dsa.js index 9afcb38616dafd6da1ab7b5843d68f4f796ca9a6..00d3381056a5a40c549f06d74c130149ba4abc8c 100644 --- a/test/parallel/test-crypto-rsa-dsa.js +++ b/test/parallel/test-crypto-rsa-dsa.js @@ -28,12 +28,11 @@ const dsaPkcs8KeyPem = fixtures.readKey('dsa_private_pkcs8.pem'); const ec = new TextEncoder(); const openssl1DecryptError = { - message: 'error:06065064:digital envelope routines:EVP_DecryptFinal_ex:' + - 'bad decrypt', - code: 'ERR_OSSL_EVP_BAD_DECRYPT', - reason: 'bad decrypt', - function: 'EVP_DecryptFinal_ex', - library: 'digital envelope routines', + message: /error:06065064:digital envelope routines:EVP_DecryptFinal_ex:bad decrypt|error:1e000065:Cipher functions:OPENSSL_internal:BAD_DECRYPT/, + code: /ERR_OSSL(_EVP)?_BAD_DECRYPT/, + reason: /bad decrypt|BAD_DECRYPT/, + function: /EVP_DecryptFinal_ex|OPENSSL_internal/, + library: /digital envelope routines|Cipher functions/, }; const decryptError = common.hasOpenSSL3 ? @@ -397,7 +396,7 @@ assert.throws(() => { assert.strictEqual(verify2.verify(publicKey, signature, 'hex'), true); } - +/* // // Test DSA signing and verification // @@ -472,3 +471,4 @@ const input = 'I AM THE WALRUS'; assert.strictEqual(verify.verify(dsaPubPem, signature, 'hex'), true); } +*/ diff --git a/test/parallel/test-crypto-sign-verify.js b/test/parallel/test-crypto-sign-verify.js index b2c14b1efcd68bd20e9c946106f1ab5fb58627c5..eef0bfe638b641c68fdadd95226a74df044921cb 100644 --- a/test/parallel/test-crypto-sign-verify.js +++ b/test/parallel/test-crypto-sign-verify.js @@ -29,6 +29,7 @@ const keySize = 2048; 'instance when called without `new`'); } +/* // Test handling of exceptional conditions { const library = { @@ -69,6 +70,7 @@ const keySize = 2048; delete Object.prototype.opensslErrorStack; } +*/ assert.throws( () => crypto.createVerify('SHA256').verify({ @@ -342,15 +344,17 @@ assert.throws( padding: crypto.constants.RSA_PKCS1_OAEP_PADDING }); }, common.hasOpenSSL3 ? { - code: 'ERR_OSSL_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE', - message: /illegal or unsupported padding mode/, + code: /^ERR_OSSL_(RSA|EVP)_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE$/, + message: /illegal or unsupported padding mode|ILLEGAL_OR_UNSUPPORTED_PADDING_MODE/, } : { - code: 'ERR_OSSL_RSA_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE', - message: /illegal or unsupported padding mode/, + code: /^ERR_OSSL_(RSA|EVP)_ILLEGAL_OR_UNSUPPORTED_PADDING_MODE$/, + message: /illegal or unsupported padding mode|ILLEGAL_OR_UNSUPPORTED_PADDING_MODE/, + /* opensslErrorStack: [ 'error:06089093:digital envelope routines:EVP_PKEY_CTX_ctrl:' + 'command not supported', ], + */ }); } @@ -420,10 +424,12 @@ assert.throws( public: fixtures.readKey('ed25519_public.pem', 'ascii'), algo: null, sigLen: 64 }, + /* { private: fixtures.readKey('ed448_private.pem', 'ascii'), public: fixtures.readKey('ed448_public.pem', 'ascii'), algo: null, sigLen: 114 }, + */ { private: fixtures.readKey('rsa_private_2048.pem', 'ascii'), public: fixtures.readKey('rsa_public_2048.pem', 'ascii'), algo: 'sha1', @@ -494,7 +500,7 @@ assert.throws( { const data = Buffer.from('Hello world'); - const keys = [['ec-key.pem', 64], ['dsa_private_1025.pem', 40]]; + const keys = [['ec-key.pem', 64]/*, ['dsa_private_1025.pem', 40]*/]; for (const [file, length] of keys) { const privKey = fixtures.readKey(file); diff --git a/test/parallel/test-crypto-stream.js b/test/parallel/test-crypto-stream.js index 008ab129f0e019c659eecf5a76b7eb412c947fe3..6688f5d916f50e1e4fcfff1619c8634a3233f820 100644 --- a/test/parallel/test-crypto-stream.js +++ b/test/parallel/test-crypto-stream.js @@ -76,10 +76,10 @@ cipher.pipe(decipher) library: 'Provider routines', reason: 'bad decrypt', } : { - message: /bad decrypt/, - function: 'EVP_DecryptFinal_ex', - library: 'digital envelope routines', - reason: 'bad decrypt', + message: /bad decrypt|BAD_DECRYPT/, + function: /EVP_DecryptFinal_ex|OPENSSL_internal/, + library: /digital envelope routines|Cipher functions/, + reason: /bad decrypt|BAD_DECRYPT/, })); cipher.end('Papaya!'); // Should not cause an unhandled exception. diff --git a/test/parallel/test-crypto-x509.js b/test/parallel/test-crypto-x509.js index d1782359277dc52d7a60830a6dd958544d610e6b..4c781f062bc505b860b821773070551f4cd80067 100644 --- a/test/parallel/test-crypto-x509.js +++ b/test/parallel/test-crypto-x509.js @@ -110,7 +110,7 @@ const der = Buffer.from( 'A3:06:C5:CE:43:C1:7F:2D:7E:5F:44:A5:EE:A3:CB:97:05:A3:E3:68' ); assert.strictEqual(x509.keyUsage, undefined); - assert.strictEqual(x509.serialNumber, 'ECC9B856270DA9A8'); + assert.match(x509.serialNumber, /ECC9B856270DA9A8/i); assert.deepStrictEqual(x509.raw, der); @@ -196,6 +196,12 @@ const der = Buffer.from( }); mc.port2.postMessage(x509); + const modulusOSSL = 'EF5440701637E28ABB038E5641F828D834C342A9D25EDBB86A2BF' + + '6FBD809CB8E037A98B71708E001242E4DEB54C6164885F599DD87' + + 'A23215745955BE20417E33C4D0D1B80C9DA3DE419A2607195D2FB' + + '75657B0BBFB5EB7D0BBA5122D1B6964C7B570D50B8EC001EEB68D' + + 'FB584437508F3129928D673B30A3E0BF4F50609E6371'; + // Verify that legacy encoding works const legacyObjectCheck = { subject: 'C=US\n' + @@ -219,11 +225,7 @@ const der = Buffer.from( 'CA Issuers - URI:http://ca.nodejs.org/ca.cert' : 'OCSP - URI:http://ocsp.nodejs.org/\n' + 'CA Issuers - URI:http://ca.nodejs.org/ca.cert\n', - modulus: 'EF5440701637E28ABB038E5641F828D834C342A9D25EDBB86A2BF' + - '6FBD809CB8E037A98B71708E001242E4DEB54C6164885F599DD87' + - 'A23215745955BE20417E33C4D0D1B80C9DA3DE419A2607195D2FB' + - '75657B0BBFB5EB7D0BBA5122D1B6964C7B570D50B8EC001EEB68D' + - 'FB584437508F3129928D673B30A3E0BF4F50609E6371', + modulusPattern: new RegExp(modulusOSSL, 'i'), bits: 1024, exponent: '0x10001', valid_from: 'Nov 16 18:42:21 2018 GMT', @@ -237,7 +239,7 @@ const der = Buffer.from( 'D0:39:97:54:B6:D0:B4:46:5B:DE:13:5B:68:86:B6:F2:A8:' + '95:22:D5:6E:8B:35:DA:89:29:CA:A3:06:C5:CE:43:C1:7F:' + '2D:7E:5F:44:A5:EE:A3:CB:97:05:A3:E3:68', - serialNumber: 'ECC9B856270DA9A8' + serialNumberPattern: /ECC9B856270DA9A8/i }; const legacyObject = x509.toLegacyObject(); @@ -246,7 +248,7 @@ const der = Buffer.from( assert.strictEqual(legacyObject.subject, legacyObjectCheck.subject); assert.strictEqual(legacyObject.issuer, legacyObjectCheck.issuer); assert.strictEqual(legacyObject.infoAccess, legacyObjectCheck.infoAccess); - assert.strictEqual(legacyObject.modulus, legacyObjectCheck.modulus); + assert.match(legacyObject.modulus, legacyObjectCheck.modulusPattern); assert.strictEqual(legacyObject.bits, legacyObjectCheck.bits); assert.strictEqual(legacyObject.exponent, legacyObjectCheck.exponent); assert.strictEqual(legacyObject.valid_from, legacyObjectCheck.valid_from); @@ -255,7 +257,5 @@ const der = Buffer.from( assert.strictEqual( legacyObject.fingerprint256, legacyObjectCheck.fingerprint256); - assert.strictEqual( - legacyObject.serialNumber, - legacyObjectCheck.serialNumber); + assert.match(legacyObject.serialNumber, legacyObjectCheck.serialNumberPattern); } diff --git a/test/parallel/test-crypto.js b/test/parallel/test-crypto.js index a8ceb169de2b3de73f062083c42292babc673e73..a3bb574d0e5dc85b4ba3fb0b3bd8782fbb8c8700 100644 --- a/test/parallel/test-crypto.js +++ b/test/parallel/test-crypto.js @@ -67,7 +67,7 @@ assert.throws(() => { // Throws general Error, so there is no opensslErrorStack property. return err instanceof Error && err.name === 'Error' && - /^Error: mac verify failure$/.test(err) && + (/^Error: (mac verify failure|INCORRECT_PASSWORD)$/.test(err)) && !('opensslErrorStack' in err); }); @@ -77,7 +77,7 @@ assert.throws(() => { // Throws general Error, so there is no opensslErrorStack property. return err instanceof Error && err.name === 'Error' && - /^Error: mac verify failure$/.test(err) && + (/^Error: (mac verify failure|INCORRECT_PASSWORD)$/.test(err)) && !('opensslErrorStack' in err); }); @@ -87,7 +87,7 @@ assert.throws(() => { // Throws general Error, so there is no opensslErrorStack property. return err instanceof Error && err.name === 'Error' && - /^Error: not enough data$/.test(err) && + /^Error: (not enough data|BAD_PKCS12_DATA)$/.test(err) && !('opensslErrorStack' in err); }); @@ -150,8 +150,6 @@ assert(crypto.getHashes().includes('sha1')); assert(crypto.getHashes().includes('sha256')); assert(!crypto.getHashes().includes('SHA1')); assert(!crypto.getHashes().includes('SHA256')); -assert(crypto.getHashes().includes('RSA-SHA1')); -assert(!crypto.getHashes().includes('rsa-sha1')); validateList(crypto.getHashes()); // Make sure all of the hashes are supported by OpenSSL for (const algo of crypto.getHashes()) @@ -188,7 +186,7 @@ const encodingError = { // hex input that's not a power of two should throw, not assert in C++ land. ['createCipher', 'createDecipher'].forEach((funcName) => { assert.throws( - () => crypto[funcName]('aes192', 'test').update('0', 'hex'), + () => crypto[funcName]('aes-192-cbc', 'test').update('0', 'hex'), (error) => { assert.ok(!('opensslErrorStack' in error)); if (common.hasFipsCrypto) { @@ -240,15 +238,15 @@ assert.throws(() => { library: 'rsa routines', } : { name: 'Error', - message: /routines:RSA_sign:digest too big for rsa key$/, - library: 'rsa routines', - function: 'RSA_sign', - reason: 'digest too big for rsa key', + message: /routines:RSA_sign:digest too big for rsa key$|routines:OPENSSL_internal:DIGEST_TOO_BIG_FOR_RSA_KEY$/, + library: /rsa routines|RSA routines/, + function: /RSA_sign|OPENSSL_internal/, + reason: /digest too big for rsa key|DIGEST_TOO_BIG_FOR_RSA_KEY/, code: 'ERR_OSSL_RSA_DIGEST_TOO_BIG_FOR_RSA_KEY' }); return true; }); - +/* if (!common.hasOpenSSL3) { assert.throws(() => { // The correct header inside `rsa_private_pkcs8_bad.pem` should have been @@ -276,7 +274,7 @@ if (!common.hasOpenSSL3) { return true; }); } - +*/ // Make sure memory isn't released before being returned console.log(crypto.randomBytes(16)); diff --git a/test/parallel/test-https-agent-additional-options.js b/test/parallel/test-https-agent-additional-options.js index 543ee176fb6af38874fee9f14be76f3fdda11060..fef9f1bc2f9fc6c220cf47847e86e03882b51b1d 100644 --- a/test/parallel/test-https-agent-additional-options.js +++ b/test/parallel/test-https-agent-additional-options.js @@ -13,7 +13,7 @@ const options = { cert: fixtures.readKey('agent1-cert.pem'), ca: fixtures.readKey('ca1-cert.pem'), minVersion: 'TLSv1.1', - ciphers: 'ALL@SECLEVEL=0' + // ciphers: 'ALL@SECLEVEL=0' }; const server = https.Server(options, (req, res) => { @@ -28,7 +28,7 @@ function getBaseOptions(port) { ca: options.ca, rejectUnauthorized: true, servername: 'agent1', - ciphers: 'ALL@SECLEVEL=0' + // ciphers: 'ALL@SECLEVEL=0' }; } diff --git a/test/parallel/test-https-agent-session-eviction.js b/test/parallel/test-https-agent-session-eviction.js index 940c43cc40bf15e51df177ee30ecc69ffbeec296..e95743a91a3c709c7d2c10dc80b3f75b7d988027 100644 --- a/test/parallel/test-https-agent-session-eviction.js +++ b/test/parallel/test-https-agent-session-eviction.js @@ -14,7 +14,7 @@ const options = { key: readKey('agent1-key.pem'), cert: readKey('agent1-cert.pem'), secureOptions: SSL_OP_NO_TICKET, - ciphers: 'RSA@SECLEVEL=0' + // ciphers: 'RSA@SECLEVEL=0' }; // Create TLS1.2 server diff --git a/test/parallel/test-tls-getcertificate-x509.js b/test/parallel/test-tls-getcertificate-x509.js index 5be788f67931131256f7fb0ab802cb0edee58173..0969e417c239b7300f53f6c4434318bc8fe579fe 100644 --- a/test/parallel/test-tls-getcertificate-x509.js +++ b/test/parallel/test-tls-getcertificate-x509.js @@ -20,9 +20,7 @@ const server = tls.createServer(options, function(cleartext) { server.once('secureConnection', common.mustCall(function(socket) { const cert = socket.getX509Certificate(); assert(cert instanceof X509Certificate); - assert.strictEqual( - cert.serialNumber, - 'D0082F458B6EFBE8'); + assert.match(cert.serialNumber, /D0082F458B6EFBE8/i) })); server.listen(0, common.mustCall(function() { @@ -33,10 +31,7 @@ server.listen(0, common.mustCall(function() { const peerCert = socket.getPeerX509Certificate(); assert(peerCert.issuerCertificate instanceof X509Certificate); assert.strictEqual(peerCert.issuerCertificate.issuerCertificate, undefined); - assert.strictEqual( - peerCert.issuerCertificate.serialNumber, - 'ECC9B856270DA9A7' - ); + assert.match(peerCert.issuerCertificate.serialNumber, /ECC9B856270DA9A7/i); server.close(); })); socket.end('Hello'); diff --git a/test/parallel/test-tls-getprotocol.js b/test/parallel/test-tls-getprotocol.js index 02c683c71c8775e84d5d125a4f05560b8206677d..4c6dd20ca0a8d0acdf9f8d1b7153087de9305196 100644 --- a/test/parallel/test-tls-getprotocol.js +++ b/test/parallel/test-tls-getprotocol.js @@ -18,7 +18,7 @@ const clientConfigs = [ const serverConfig = { secureProtocol: 'TLS_method', - ciphers: 'RSA@SECLEVEL=0', + // ciphers: 'RSA@SECLEVEL=0', key: fixtures.readKey('agent2-key.pem'), cert: fixtures.readKey('agent2-cert.pem') }; diff --git a/test/parallel/test-tls-write-error.js b/test/parallel/test-tls-write-error.js index b06f2fa2c53ea72f9a66f0d002dd9281d0259a0f..864fffeebfad75d95416fd47efdea7f222c507a2 100644 --- a/test/parallel/test-tls-write-error.js +++ b/test/parallel/test-tls-write-error.js @@ -17,7 +17,7 @@ const server_cert = fixtures.readKey('agent1-cert.pem'); const opts = { key: server_key, cert: server_cert, - ciphers: 'ALL@SECLEVEL=0' + // ciphers: 'ALL@SECLEVEL=0' }; const server = https.createServer(opts, (req, res) => { diff --git a/test/parallel/test-webcrypto-derivebits.js b/test/parallel/test-webcrypto-derivebits.js index 95c38f454fbb939c9f74f25ec946d0c8e94e4c41..882c01fd812f5ed880fa3482ede92695ad505ff3 100644 --- a/test/parallel/test-webcrypto-derivebits.js +++ b/test/parallel/test-webcrypto-derivebits.js @@ -39,6 +39,7 @@ const { internalBinding } = require('internal/test/binding'); test('P-521').then(common.mustCall()); } +/* // Test HKDF bit derivation { async function test(pass, info, salt, hash, length, expected) { @@ -70,6 +71,7 @@ const { internalBinding } = require('internal/test/binding'); tests.then(common.mustCall()); } +*/ // Test PBKDF2 bit derivation { diff --git a/test/parallel/test-webcrypto-derivekey.js b/test/parallel/test-webcrypto-derivekey.js index ee48a61f4ac8f5e8e4cec96eb03d75cb1c45f56a..5108bbf7499f29bafffda76f3c5270aae0271b44 100644 --- a/test/parallel/test-webcrypto-derivekey.js +++ b/test/parallel/test-webcrypto-derivekey.js @@ -48,6 +48,7 @@ const { internalBinding } = require('internal/test/binding'); test('P-521').then(common.mustCall()); } +/* // Test HKDF bit derivation { async function test(pass, info, salt, hash, expected) { @@ -84,6 +85,7 @@ const { internalBinding } = require('internal/test/binding'); tests.then(common.mustCall()); } +*/ // Test PBKDF2 bit derivation { diff --git a/test/parallel/test-webcrypto-encrypt-decrypt-rsa.js b/test/parallel/test-webcrypto-encrypt-decrypt-rsa.js index 151eebd36c9765df086a020ba42920b2442b1b77..efe97ff2499cba909ac5500d827364fa389a0469 100644 --- a/test/parallel/test-webcrypto-encrypt-decrypt-rsa.js +++ b/test/parallel/test-webcrypto-encrypt-decrypt-rsa.js @@ -127,7 +127,7 @@ async function testEncryptionLongPlaintext({ algorithm, return assert.rejects( subtle.encrypt(algorithm, publicKey, newplaintext), { - message: /data too large/ + message: /data too large|DATA_TOO_LARGE_FOR_KEY_SIZE/ }); } diff --git a/test/parallel/test-webcrypto-export-import-rsa.js b/test/parallel/test-webcrypto-export-import-rsa.js index ab7aa77394ac9989514b7a184900092bd6753996..b0104ac45867a923a8c651e01e8c6975a62f7c61 100644 --- a/test/parallel/test-webcrypto-export-import-rsa.js +++ b/test/parallel/test-webcrypto-export-import-rsa.js @@ -481,6 +481,7 @@ const testVectors = [ await Promise.all(variations); })().then(common.mustCall()); +/* { const publicPem = fixtures.readKey('rsa_pss_public_2048.pem', 'ascii'); const privatePem = fixtures.readKey('rsa_pss_private_2048.pem', 'ascii'); @@ -522,6 +523,7 @@ const testVectors = [ assert.strictEqual(jwk.alg, 'PS256'); })().then(common.mustCall()); } +*/ { const ecPublic = crypto.createPublicKey( diff --git a/test/parallel/test-webcrypto-wrap-unwrap.js b/test/parallel/test-webcrypto-wrap-unwrap.js index 1094845c73e14313860ad476fb7baba2a11b5af4..51972b4b34b191ac59145889dbf2da5c0d407dbe 100644 --- a/test/parallel/test-webcrypto-wrap-unwrap.js +++ b/test/parallel/test-webcrypto-wrap-unwrap.js @@ -18,14 +18,15 @@ const kWrappingData = { wrap: { label: new Uint8Array(8) }, pair: true }, - 'AES-CTR': { + 'AES-CBC': { generate: { length: 128 }, - wrap: { counter: new Uint8Array(16), length: 64 }, + wrap: { iv: new Uint8Array(16) }, pair: false }, - 'AES-CBC': { + /* + 'AES-CTR': { generate: { length: 128 }, - wrap: { iv: new Uint8Array(16) }, + wrap: { counter: new Uint8Array(16), length: 64 }, pair: false }, 'AES-GCM': { @@ -42,6 +43,7 @@ const kWrappingData = { wrap: { }, pair: false } + */ }; function generateWrappingKeys() { diff --git a/test/parallel/test-x509-escaping.js b/test/parallel/test-x509-escaping.js index 99418e4c0bf21c26d5ba0ad9d617419abc625593..fc129b26ea13895353d6ede26bb2d91695c94ba4 100644 --- a/test/parallel/test-x509-escaping.js +++ b/test/parallel/test-x509-escaping.js @@ -425,11 +425,11 @@ const { hasOpenSSL3 } = common; assert.strictEqual(certX509.subjectAltName, 'DNS:evil.example.com'); // The newer X509Certificate API allows customizing this behavior: - assert.strictEqual(certX509.checkHost(servername), servername); + assert.strictEqual(certX509.checkHost(servername), undefined); assert.strictEqual(certX509.checkHost(servername, { subject: 'default' }), undefined); assert.strictEqual(certX509.checkHost(servername, { subject: 'always' }), - servername); + undefined); assert.strictEqual(certX509.checkHost(servername, { subject: 'never' }), undefined); @@ -464,11 +464,11 @@ const { hasOpenSSL3 } = common; assert.strictEqual(certX509.subjectAltName, 'IP Address:1.2.3.4'); // The newer X509Certificate API allows customizing this behavior: - assert.strictEqual(certX509.checkHost(servername), servername); + assert.strictEqual(certX509.checkHost(servername), undefined); assert.strictEqual(certX509.checkHost(servername, { subject: 'default' }), - servername); + undefined); assert.strictEqual(certX509.checkHost(servername, { subject: 'always' }), - servername); + undefined); assert.strictEqual(certX509.checkHost(servername, { subject: 'never' }), undefined);
closed
electron/electron
https://github.com/electron/electron
31,634
[Bug]: crypto.hkdf "Deriving bits failed"
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version v15.3.0 ### What operating system are you using? macOS ### Operating System Version Darwin C02CX0K5MD6V 20.6.0 Darwin Kernel Version 20.6.0: Mon Aug 30 06:12:21 PDT 2021; root:xnu-7195.141.6~3/RELEASE_X86_64 x86_64 ### What arch are you using? x64 ### Last Known Working Electron version none ### Expected Behavior `crypto.hkdf` and `crypto.hkdfSync` work as documented[^1] [^1]: https://nodejs.org/api/crypto.html#cryptohkdfdigest-ikm-salt-info-keylen-callback ### Actual Behavior ``` crypto.hkdfSync('sha256', 'foo', '', '', 32) // Uncaught Error: Deriving bits failed // at Object.hkdfSync (node:internal/crypto/hkdf:140:35) crypto.hkdf('sha256', 'foo', '', '', 32, console.log) // [Error: Deriving bits failed] ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/31634
https://github.com/electron/electron/pull/34767
35ff95d3c71849ac97ced178a2330b9d4651f250
ad2b1fee59c2e4352b0c5664f72c0067a2ef4d7f
2021-10-29T09:01:40Z
c++
2022-06-29T12:53:57Z
patches/node/fix_handle_boringssl_and_openssl_incompatibilities.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Shelley Vohr <[email protected]> Date: Wed, 12 Feb 2020 15:08:04 -0800 Subject: fix: handle BoringSSL and OpenSSL incompatibilities This patch corrects for imcompatibilities between OpenSSL, which Node.js uses, and BoringSSL which Electron uses via Chromium. Each incompatibility typically has ~2 paths forward: * Upstream a shim or adapted implementation to BoringSSL * Alter Node.js functionality to something which both libraries can handle. Where possible, we should seek to make this patch as minimal as possible. Upstreams: - https://github.com/nodejs/node/pull/39054 - https://github.com/nodejs/node/pull/39138 - https://github.com/nodejs/node/pull/39136 diff --git a/src/crypto/crypto_common.cc b/src/crypto/crypto_common.cc index a5aa39c23c1708ac27564a1a77a9f05fc07791e2..630a3400e74f20b1dbee17027c7dbe8688fed4b2 100644 --- a/src/crypto/crypto_common.cc +++ b/src/crypto/crypto_common.cc @@ -162,7 +162,7 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) { const unsigned char* buf; size_t len; size_t rem; - +#ifndef OPENSSL_IS_BORINGSSL if (!SSL_client_hello_get0_ext( ssl.get(), TLSEXT_TYPE_application_layer_protocol_negotiation, @@ -175,13 +175,15 @@ const char* GetClientHelloALPN(const SSLPointer& ssl) { len = (buf[0] << 8) | buf[1]; if (len + 2 != rem) return nullptr; return reinterpret_cast<const char*>(buf + 3); +#endif + return nullptr; } const char* GetClientHelloServerName(const SSLPointer& ssl) { const unsigned char* buf; size_t len; size_t rem; - +#ifndef OPENSSL_IS_BORINGSSL if (!SSL_client_hello_get0_ext( ssl.get(), TLSEXT_TYPE_server_name, @@ -203,6 +205,8 @@ const char* GetClientHelloServerName(const SSLPointer& ssl) { if (len + 2 > rem) return nullptr; return reinterpret_cast<const char*>(buf + 5); +#endif + return nullptr; } const char* GetServerName(SSL* ssl) { @@ -210,7 +214,10 @@ const char* GetServerName(SSL* ssl) { } bool SetGroups(SecureContext* sc, const char* groups) { +#ifndef OPENSSL_IS_BORINGSSL return SSL_CTX_set1_groups_list(**sc, groups) == 1; +#endif + return SSL_CTX_set1_curves_list(**sc, groups) == 1; } const char* X509ErrorCode(long err) { // NOLINT(runtime/int) @@ -1101,14 +1108,14 @@ MaybeLocal<Array> GetClientHelloCiphers( Environment* env, const SSLPointer& ssl) { EscapableHandleScope scope(env->isolate()); - const unsigned char* buf; - size_t len = SSL_client_hello_get0_ciphers(ssl.get(), &buf); + // const unsigned char* buf = nullptr; + size_t len = 0; // SSL_client_hello_get0_ciphers(ssl.get(), &buf); size_t count = len / 2; MaybeStackBuffer<Local<Value>, 16> ciphers(count); int j = 0; for (size_t n = 0; n < len; n += 2) { - const SSL_CIPHER* cipher = SSL_CIPHER_find(ssl.get(), buf); - buf += 2; + const SSL_CIPHER* cipher = nullptr; // SSL_CIPHER_find(ssl.get(), buf); + // buf += 2; Local<Object> obj = Object::New(env->isolate()); if (!Set(env->context(), obj, diff --git a/src/crypto/crypto_dh.cc b/src/crypto/crypto_dh.cc index b6ef5e5b1e004e663fbfd2578b82644cb53051e0..1d48ea6d022304b1e6a4f703fea790437edcc876 100644 --- a/src/crypto/crypto_dh.cc +++ b/src/crypto/crypto_dh.cc @@ -143,13 +143,11 @@ void DiffieHellman::MemoryInfo(MemoryTracker* tracker) const { bool DiffieHellman::Init(const char* p, int p_len, int g) { dh_.reset(DH_new()); if (p_len <= 0) { - ERR_put_error(ERR_LIB_BN, BN_F_BN_GENERATE_PRIME_EX, - BN_R_BITS_TOO_SMALL, __FILE__, __LINE__); + OPENSSL_PUT_ERROR(BN, BN_R_BITS_TOO_SMALL); return false; } if (g <= 1) { - ERR_put_error(ERR_LIB_DH, DH_F_DH_BUILTIN_GENPARAMS, - DH_R_BAD_GENERATOR, __FILE__, __LINE__); + OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR); return false; } BIGNUM* bn_p = @@ -167,21 +165,18 @@ bool DiffieHellman::Init(const char* p, int p_len, int g) { bool DiffieHellman::Init(const char* p, int p_len, const char* g, int g_len) { dh_.reset(DH_new()); if (p_len <= 0) { - ERR_put_error(ERR_LIB_BN, BN_F_BN_GENERATE_PRIME_EX, - BN_R_BITS_TOO_SMALL, __FILE__, __LINE__); + OPENSSL_PUT_ERROR(BN, BN_R_BITS_TOO_SMALL); return false; } if (g_len <= 0) { - ERR_put_error(ERR_LIB_DH, DH_F_DH_BUILTIN_GENPARAMS, - DH_R_BAD_GENERATOR, __FILE__, __LINE__); + OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR); return false; } BIGNUM* bn_g = BN_bin2bn(reinterpret_cast<const unsigned char*>(g), g_len, nullptr); if (BN_is_zero(bn_g) || BN_is_one(bn_g)) { BN_free(bn_g); - ERR_put_error(ERR_LIB_DH, DH_F_DH_BUILTIN_GENPARAMS, - DH_R_BAD_GENERATOR, __FILE__, __LINE__); + OPENSSL_PUT_ERROR(DH, DH_R_BAD_GENERATOR); return false; } BIGNUM* bn_p = @@ -501,16 +496,20 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) { if (!BN_set_word(bn_g.get(), params->params.generator) || !DH_set0_pqg(dh.get(), prime, nullptr, bn_g.get())) return EVPKeyCtxPointer(); - +#ifndef OPENSSL_IS_BORINGSSL params->params.prime_fixed_value.release(); bn_g.release(); key_params = EVPKeyPointer(EVP_PKEY_new()); CHECK(key_params); EVP_PKEY_assign_DH(key_params.get(), dh.release()); +#else + return EVPKeyCtxPointer(); +#endif } else { EVPKeyCtxPointer param_ctx(EVP_PKEY_CTX_new_id(EVP_PKEY_DH, nullptr)); EVP_PKEY* raw_params = nullptr; +#ifndef OPENSSL_IS_BORINGSSL if (!param_ctx || EVP_PKEY_paramgen_init(param_ctx.get()) <= 0 || EVP_PKEY_CTX_set_dh_paramgen_prime_len( @@ -522,8 +521,10 @@ EVPKeyCtxPointer DhKeyGenTraits::Setup(DhKeyPairGenConfig* params) { EVP_PKEY_paramgen(param_ctx.get(), &raw_params) <= 0) { return EVPKeyCtxPointer(); } - key_params = EVPKeyPointer(raw_params); +#else + return EVPKeyCtxPointer(); +#endif } EVPKeyCtxPointer ctx(EVP_PKEY_CTX_new(key_params.get(), nullptr)); diff --git a/src/crypto/crypto_dsa.cc b/src/crypto/crypto_dsa.cc index c7894baf00ee9ce4684f4c752f1c7c9b98163741..655895dbff8b88daa53c7b40a5feca42a461b689 100644 --- a/src/crypto/crypto_dsa.cc +++ b/src/crypto/crypto_dsa.cc @@ -29,7 +29,7 @@ namespace crypto { EVPKeyCtxPointer DsaKeyGenTraits::Setup(DsaKeyPairGenConfig* params) { EVPKeyCtxPointer param_ctx(EVP_PKEY_CTX_new_id(EVP_PKEY_DSA, nullptr)); EVP_PKEY* raw_params = nullptr; - +#ifndef OPENSSL_IS_BORINGSSL if (!param_ctx || EVP_PKEY_paramgen_init(param_ctx.get()) <= 0 || EVP_PKEY_CTX_set_dsa_paramgen_bits( @@ -49,7 +49,9 @@ EVPKeyCtxPointer DsaKeyGenTraits::Setup(DsaKeyPairGenConfig* params) { return EVPKeyCtxPointer(); } } - +#else + return EVPKeyCtxPointer(); +#endif if (EVP_PKEY_paramgen(param_ctx.get(), &raw_params) <= 0) return EVPKeyCtxPointer(); diff --git a/src/crypto/crypto_hkdf.cc b/src/crypto/crypto_hkdf.cc index 0aa96ada47abe4b66fb616c665101278bbe0afb6..1e9a4863c5faea5f6b275483ca16f3a6e8dac25b 100644 --- a/src/crypto/crypto_hkdf.cc +++ b/src/crypto/crypto_hkdf.cc @@ -101,6 +101,7 @@ bool HKDFTraits::DeriveBits( Environment* env, const HKDFConfig& params, ByteSource* out) { +#ifndef OPENSSL_IS_BORINGSSL EVPKeyCtxPointer ctx = EVPKeyCtxPointer(EVP_PKEY_CTX_new_id(EVP_PKEY_HKDF, nullptr)); if (!ctx || @@ -132,6 +133,9 @@ bool HKDFTraits::DeriveBits( *out = std::move(buf); return true; +#else + return false; +#endif } void HKDFConfig::MemoryInfo(MemoryTracker* tracker) const { diff --git a/src/crypto/crypto_random.cc b/src/crypto/crypto_random.cc index fc88deb460314c2620d842ec30141bcd13109d60..c097ccfcffb1158317ba09e7c4beb725ccbab74f 100644 --- a/src/crypto/crypto_random.cc +++ b/src/crypto/crypto_random.cc @@ -150,7 +150,7 @@ Maybe<bool> RandomPrimeTraits::AdditionalConfig( params->bits = bits; params->safe = safe; - params->prime.reset(BN_secure_new()); + params->prime.reset(BN_new()); if (!params->prime) { THROW_ERR_CRYPTO_OPERATION_FAILED(env, "could not generate prime"); return Nothing<bool>(); diff --git a/src/crypto/crypto_rsa.cc b/src/crypto/crypto_rsa.cc index ae4550e9fde8120c35409e495d5b763a95546509..188a7efe76df2a1aa2eb2746f4d748361bba4fb4 100644 --- a/src/crypto/crypto_rsa.cc +++ b/src/crypto/crypto_rsa.cc @@ -621,10 +621,11 @@ Maybe<bool> GetRsaKeyDetail( } if (params->saltLength != nullptr) { - if (ASN1_INTEGER_get_int64(&salt_length, params->saltLength) != 1) { - ThrowCryptoError(env, ERR_get_error(), "ASN1_INTEGER_get_in64 error"); - return Nothing<bool>(); - } + // TODO(codebytere): Upstream a shim to BoringSSL? + // if (ASN1_INTEGER_get_int64(&salt_length, params->saltLength) != 1) { + // ThrowCryptoError(env, ERR_get_error(), "ASN1_INTEGER_get_in64 error"); + // return Nothing<bool>(); + // } } if (target diff --git a/src/crypto/crypto_util.cc b/src/crypto/crypto_util.cc index e1ef170a9f17634d218492a2ce888c3a4365e097..8dffad89c80e0906780d1b26ba9a65ba1e76ce0a 100644 --- a/src/crypto/crypto_util.cc +++ b/src/crypto/crypto_util.cc @@ -508,24 +508,14 @@ Maybe<bool> Decorate(Environment* env, Local<Object> obj, V(BIO) \ V(PKCS7) \ V(X509V3) \ - V(PKCS12) \ V(RAND) \ - V(DSO) \ V(ENGINE) \ V(OCSP) \ V(UI) \ V(COMP) \ V(ECDSA) \ V(ECDH) \ - V(OSSL_STORE) \ - V(FIPS) \ - V(CMS) \ - V(TS) \ V(HMAC) \ - V(CT) \ - V(ASYNC) \ - V(KDF) \ - V(SM2) \ V(USER) \ #define V(name) case ERR_LIB_##name: lib = #name "_"; break; @@ -684,7 +674,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { CHECK(args[0]->IsUint32()); Environment* env = Environment::GetCurrent(args); uint32_t len = args[0].As<Uint32>()->Value(); - char* data = static_cast<char*>(OPENSSL_secure_malloc(len)); + char* data = static_cast<char*>(OPENSSL_malloc(len)); if (data == nullptr) { // There's no memory available for the allocation. // Return nothing. @@ -696,7 +686,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { data, len, [](void* data, size_t len, void* deleter_data) { - OPENSSL_secure_clear_free(data, len); + OPENSSL_clear_free(data, len); }, data); Local<ArrayBuffer> buffer = ArrayBuffer::New(env->isolate(), store); @@ -704,10 +694,12 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { } void SecureHeapUsed(const FunctionCallbackInfo<Value>& args) { +#ifndef OPENSSL_IS_BORINGSSL Environment* env = Environment::GetCurrent(args); if (CRYPTO_secure_malloc_initialized()) args.GetReturnValue().Set( BigInt::New(env->isolate(), CRYPTO_secure_used())); +#endif } } // namespace diff --git a/src/crypto/crypto_util.h b/src/crypto/crypto_util.h index c431159e6f77f8c86844bcadb86012b056d03372..0ce3a8f219a2952f660ff72a6ce36ee109add649 100644 --- a/src/crypto/crypto_util.h +++ b/src/crypto/crypto_util.h @@ -16,7 +16,9 @@ #include <openssl/err.h> #include <openssl/evp.h> #include <openssl/ec.h> +#ifndef OPENSSL_IS_BORINGSSL #include <openssl/kdf.h> +#endif #include <openssl/rsa.h> #include <openssl/dsa.h> #include <openssl/ssl.h> diff --git a/src/node_metadata.h b/src/node_metadata.h index 4486d5af2c1622c7c8f44401dc3ebb986d8e3c2e..db1769f1b3f1617ed8dbbea57b5e324183b42be2 100644 --- a/src/node_metadata.h +++ b/src/node_metadata.h @@ -6,7 +6,7 @@ #include <string> #include "node_version.h" -#if HAVE_OPENSSL +#if 0 #include <openssl/crypto.h> #endif // HAVE_OPENSSL
closed
electron/electron
https://github.com/electron/electron
31,634
[Bug]: crypto.hkdf "Deriving bits failed"
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version v15.3.0 ### What operating system are you using? macOS ### Operating System Version Darwin C02CX0K5MD6V 20.6.0 Darwin Kernel Version 20.6.0: Mon Aug 30 06:12:21 PDT 2021; root:xnu-7195.141.6~3/RELEASE_X86_64 x86_64 ### What arch are you using? x64 ### Last Known Working Electron version none ### Expected Behavior `crypto.hkdf` and `crypto.hkdfSync` work as documented[^1] [^1]: https://nodejs.org/api/crypto.html#cryptohkdfdigest-ikm-salt-info-keylen-callback ### Actual Behavior ``` crypto.hkdfSync('sha256', 'foo', '', '', 32) // Uncaught Error: Deriving bits failed // at Object.hkdfSync (node:internal/crypto/hkdf:140:35) crypto.hkdf('sha256', 'foo', '', '', 32, console.log) // [Error: Deriving bits failed] ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/31634
https://github.com/electron/electron/pull/34767
35ff95d3c71849ac97ced178a2330b9d4651f250
ad2b1fee59c2e4352b0c5664f72c0067a2ef4d7f
2021-10-29T09:01:40Z
c++
2022-06-29T12:53:57Z
patches/node/support_v8_sandboxed_pointers.patch
From 0000000000000000000000000000000000000000 Mon Sep 17 00:00:00 2001 From: Jeremy Rose <[email protected]> Date: Tue, 21 Jun 2022 10:04:21 -0700 Subject: support V8 sandboxed pointers This refactors several allocators to allocate within the V8 memory cage, allowing them to be compatible with the V8_SANDBOXED_POINTERS feature. diff --git a/lib/internal/bootstrap/pre_execution.js b/lib/internal/bootstrap/pre_execution.js index 4c459b58b5a048d9d8a4f15f4011e7cce68089f4..6fb4c8d4567aee5b313ad621ea42699a196f18c7 100644 --- a/lib/internal/bootstrap/pre_execution.js +++ b/lib/internal/bootstrap/pre_execution.js @@ -14,7 +14,6 @@ const { getOptionValue, getEmbedderOptions, } = require('internal/options'); -const { reconnectZeroFillToggle } = require('internal/buffer'); const { defineOperation, emitExperimentalWarning, @@ -26,10 +25,6 @@ const { ERR_MANIFEST_ASSERT_INTEGRITY } = require('internal/errors').codes; const assert = require('internal/assert'); function prepareMainThreadExecution(expandArgv1 = false) { - // TODO(joyeecheung): this is also necessary for workers when they deserialize - // this toggle from the snapshot. - reconnectZeroFillToggle(); - // Patch the process object with legacy properties and normalizations patchProcessObject(expandArgv1); setupTraceCategoryState(); diff --git a/lib/internal/buffer.js b/lib/internal/buffer.js index bd38cf48a7fc6e8d61d8f11fa15c34aee182cbe3..1aa071cdc071dcdaf5c3b4bed0d3d76e5871731d 100644 --- a/lib/internal/buffer.js +++ b/lib/internal/buffer.js @@ -30,7 +30,7 @@ const { hexWrite, ucs2Write, utf8Write, - getZeroFillToggle + setZeroFillToggle } = internalBinding('buffer'); const { untransferable_object_private_symbol, @@ -1055,24 +1055,15 @@ function markAsUntransferable(obj) { // in C++. // |zeroFill| can be undefined when running inside an isolate where we // do not own the ArrayBuffer allocator. Zero fill is always on in that case. -let zeroFill = getZeroFillToggle(); function createUnsafeBuffer(size) { - zeroFill[0] = 0; + setZeroFillToggle(false); try { return new FastBuffer(size); } finally { - zeroFill[0] = 1; + setZeroFillToggle(true) } } -// The connection between the JS land zero fill toggle and the -// C++ one in the NodeArrayBufferAllocator gets lost if the toggle -// is deserialized from the snapshot, because V8 owns the underlying -// memory of this toggle. This resets the connection. -function reconnectZeroFillToggle() { - zeroFill = getZeroFillToggle(); -} - module.exports = { FastBuffer, addBufferPrototypeMethods, @@ -1080,5 +1071,4 @@ module.exports = { createUnsafeBuffer, readUInt16BE, readUInt32BE, - reconnectZeroFillToggle }; diff --git a/src/api/environment.cc b/src/api/environment.cc index 2abf5994405e8da2a04d1b23b75ccd3658398474..024d612a04d83583b397549589d994e32cf0107f 100644 --- a/src/api/environment.cc +++ b/src/api/environment.cc @@ -83,16 +83,16 @@ MaybeLocal<Value> PrepareStackTraceCallback(Local<Context> context, void* NodeArrayBufferAllocator::Allocate(size_t size) { void* ret; if (zero_fill_field_ || per_process::cli_options->zero_fill_all_buffers) - ret = UncheckedCalloc(size); + ret = allocator_->Allocate(size); else - ret = UncheckedMalloc(size); + ret = allocator_->AllocateUninitialized(size); if (LIKELY(ret != nullptr)) total_mem_usage_.fetch_add(size, std::memory_order_relaxed); return ret; } void* NodeArrayBufferAllocator::AllocateUninitialized(size_t size) { - void* ret = node::UncheckedMalloc(size); + void* ret = allocator_->AllocateUninitialized(size); if (LIKELY(ret != nullptr)) total_mem_usage_.fetch_add(size, std::memory_order_relaxed); return ret; @@ -100,7 +100,7 @@ void* NodeArrayBufferAllocator::AllocateUninitialized(size_t size) { void* NodeArrayBufferAllocator::Reallocate( void* data, size_t old_size, size_t size) { - void* ret = UncheckedRealloc<char>(static_cast<char*>(data), size); + void* ret = allocator_->Reallocate(data, old_size, size); if (LIKELY(ret != nullptr) || UNLIKELY(size == 0)) total_mem_usage_.fetch_add(size - old_size, std::memory_order_relaxed); return ret; @@ -108,7 +108,7 @@ void* NodeArrayBufferAllocator::Reallocate( void NodeArrayBufferAllocator::Free(void* data, size_t size) { total_mem_usage_.fetch_sub(size, std::memory_order_relaxed); - free(data); + allocator_->Free(data, size); } DebuggingArrayBufferAllocator::~DebuggingArrayBufferAllocator() { diff --git a/src/crypto/crypto_util.cc b/src/crypto/crypto_util.cc index 8dffad89c80e0906780d1b26ba9a65ba1e76ce0a..45bc99ce75248794e95b2dcb0101c28152e2bfd0 100644 --- a/src/crypto/crypto_util.cc +++ b/src/crypto/crypto_util.cc @@ -318,10 +318,35 @@ ByteSource& ByteSource::operator=(ByteSource&& other) noexcept { return *this; } -std::unique_ptr<BackingStore> ByteSource::ReleaseToBackingStore() { +std::unique_ptr<BackingStore> ByteSource::ReleaseToBackingStore(Environment* env) { // It's ok for allocated_data_ to be nullptr but // only if size_ is zero. CHECK_IMPLIES(size_ > 0, allocated_data_ != nullptr); +#if defined(V8_SANDBOXED_POINTERS) + // When V8 sandboxed pointers are enabled, we have to copy into the memory + // cage. We still want to ensure we erase the data on free though, so + // provide a custom deleter that calls OPENSSL_cleanse. + if (!size()) + return ArrayBuffer::NewBackingStore(env->isolate(), 0); + std::unique_ptr<ArrayBuffer::Allocator> allocator(ArrayBuffer::Allocator::NewDefaultAllocator()); + void* v8_data = allocator->Allocate(size()); + CHECK(v8_data); + memcpy(v8_data, allocated_data_, size()); + OPENSSL_clear_free(allocated_data_, size()); + std::unique_ptr<BackingStore> ptr = ArrayBuffer::NewBackingStore( + v8_data, + size(), + [](void* data, size_t length, void*) { + OPENSSL_cleanse(data, length); + std::unique_ptr<ArrayBuffer::Allocator> allocator(ArrayBuffer::Allocator::NewDefaultAllocator()); + allocator->Free(data, length); + }, nullptr); + CHECK(ptr); + allocated_data_ = nullptr; + data_ = nullptr; + size_ = 0; + return ptr; +#else std::unique_ptr<BackingStore> ptr = ArrayBuffer::NewBackingStore( allocated_data_, size(), @@ -333,10 +358,11 @@ std::unique_ptr<BackingStore> ByteSource::ReleaseToBackingStore() { data_ = nullptr; size_ = 0; return ptr; +#endif // defined(V8_SANDBOXED_POINTERS) } Local<ArrayBuffer> ByteSource::ToArrayBuffer(Environment* env) { - std::unique_ptr<BackingStore> store = ReleaseToBackingStore(); + std::unique_ptr<BackingStore> store = ReleaseToBackingStore(env); return ArrayBuffer::New(env->isolate(), std::move(store)); } @@ -665,6 +691,16 @@ CryptoJobMode GetCryptoJobMode(v8::Local<v8::Value> args) { } namespace { +#if defined(V8_SANDBOXED_POINTERS) +// When V8 sandboxed pointers are enabled, the secure heap cannot be used as +// all ArrayBuffers must be allocated inside the V8 memory cage. +void SecureBuffer(const FunctionCallbackInfo<Value>& args) { + CHECK(args[0]->IsUint32()); + uint32_t len = args[0].As<Uint32>()->Value(); + Local<ArrayBuffer> buffer = ArrayBuffer::New(args.GetIsolate(), len); + args.GetReturnValue().Set(Uint8Array::New(buffer, 0, len)); +} +#else // SecureBuffer uses openssl to allocate a Uint8Array using // OPENSSL_secure_malloc. Because we do not yet actually // make use of secure heap, this has the same semantics as @@ -692,6 +728,7 @@ void SecureBuffer(const FunctionCallbackInfo<Value>& args) { Local<ArrayBuffer> buffer = ArrayBuffer::New(env->isolate(), store); args.GetReturnValue().Set(Uint8Array::New(buffer, 0, len)); } +#endif // defined(V8_SANDBOXED_POINTERS) void SecureHeapUsed(const FunctionCallbackInfo<Value>& args) { #ifndef OPENSSL_IS_BORINGSSL diff --git a/src/crypto/crypto_util.h b/src/crypto/crypto_util.h index 0ce3a8f219a2952f660ff72a6ce36ee109add649..06e9eb72e4ea60db4c63d08b24b80a1e6c4f3eaf 100644 --- a/src/crypto/crypto_util.h +++ b/src/crypto/crypto_util.h @@ -257,7 +257,7 @@ class ByteSource { // Creates a v8::BackingStore that takes over responsibility for // any allocated data. The ByteSource will be reset with size = 0 // after being called. - std::unique_ptr<v8::BackingStore> ReleaseToBackingStore(); + std::unique_ptr<v8::BackingStore> ReleaseToBackingStore(Environment* env); v8::Local<v8::ArrayBuffer> ToArrayBuffer(Environment* env); diff --git a/src/node_buffer.cc b/src/node_buffer.cc index 215bd8003aabe17e43ac780c723cfe971b437eae..eb00eb6f592e20f3c17a529f30b09673774eb1c1 100644 --- a/src/node_buffer.cc +++ b/src/node_buffer.cc @@ -1175,33 +1175,14 @@ void SetBufferPrototype(const FunctionCallbackInfo<Value>& args) { env->set_buffer_prototype_object(proto); } -void GetZeroFillToggle(const FunctionCallbackInfo<Value>& args) { +void SetZeroFillToggle(const FunctionCallbackInfo<Value>& args) { Environment* env = Environment::GetCurrent(args); NodeArrayBufferAllocator* allocator = env->isolate_data()->node_allocator(); Local<ArrayBuffer> ab; - // It can be a nullptr when running inside an isolate where we - // do not own the ArrayBuffer allocator. - if (allocator == nullptr) { - // Create a dummy Uint32Array - the JS land can only toggle the C++ land - // setting when the allocator uses our toggle. With this the toggle in JS - // land results in no-ops. - ab = ArrayBuffer::New(env->isolate(), sizeof(uint32_t)); - } else { + if (allocator != nullptr) { uint32_t* zero_fill_field = allocator->zero_fill_field(); - std::unique_ptr<BackingStore> backing = - ArrayBuffer::NewBackingStore(zero_fill_field, - sizeof(*zero_fill_field), - [](void*, size_t, void*) {}, - nullptr); - ab = ArrayBuffer::New(env->isolate(), std::move(backing)); + *zero_fill_field = args[0]->BooleanValue(env->isolate()); } - - ab->SetPrivate( - env->context(), - env->untransferable_object_private_symbol(), - True(env->isolate())).Check(); - - args.GetReturnValue().Set(Uint32Array::New(ab, 0, 1)); } void DetachArrayBuffer(const FunctionCallbackInfo<Value>& args) { @@ -1310,7 +1291,7 @@ void Initialize(Local<Object> target, env->SetMethod(target, "ucs2Write", StringWrite<UCS2>); env->SetMethod(target, "utf8Write", StringWrite<UTF8>); - env->SetMethod(target, "getZeroFillToggle", GetZeroFillToggle); + env->SetMethod(target, "setZeroFillToggle", SetZeroFillToggle); } } // anonymous namespace @@ -1350,7 +1331,7 @@ void RegisterExternalReferences(ExternalReferenceRegistry* registry) { registry->Register(StringWrite<HEX>); registry->Register(StringWrite<UCS2>); registry->Register(StringWrite<UTF8>); - registry->Register(GetZeroFillToggle); + registry->Register(SetZeroFillToggle); registry->Register(DetachArrayBuffer); registry->Register(CopyArrayBuffer); diff --git a/src/node_i18n.cc b/src/node_i18n.cc index c537a247f55ff070da1988fc8b7309b5692b5c18..59bfb597849cd5a94800d6c83b238ef77245243e 100644 --- a/src/node_i18n.cc +++ b/src/node_i18n.cc @@ -104,7 +104,7 @@ namespace { template <typename T> MaybeLocal<Object> ToBufferEndian(Environment* env, MaybeStackBuffer<T>* buf) { - MaybeLocal<Object> ret = Buffer::New(env, buf); + MaybeLocal<Object> ret = Buffer::Copy(env, reinterpret_cast<char*>(buf->out()), buf->length() * sizeof(T)); if (ret.IsEmpty()) return ret; diff --git a/src/node_internals.h b/src/node_internals.h index d37be23cd63e82d4040777bd0e17ed449ec0b15b..0b66996f11c66800a7e21ee84fa101450b856227 100644 --- a/src/node_internals.h +++ b/src/node_internals.h @@ -118,6 +118,8 @@ class NodeArrayBufferAllocator : public ArrayBufferAllocator { private: uint32_t zero_fill_field_ = 1; // Boolean but exposed as uint32 to JS land. std::atomic<size_t> total_mem_usage_ {0}; + + std::unique_ptr<v8::ArrayBuffer::Allocator> allocator_{v8::ArrayBuffer::Allocator::NewDefaultAllocator()}; }; class DebuggingArrayBufferAllocator final : public NodeArrayBufferAllocator { diff --git a/src/node_serdes.cc b/src/node_serdes.cc index f6f0034bc24d09e3ad65491c7d6be0b9c9db1581..92d5020f293c98c81d3891a82f7320629bf9f926 100644 --- a/src/node_serdes.cc +++ b/src/node_serdes.cc @@ -29,6 +29,11 @@ using v8::ValueSerializer; namespace serdes { +v8::ArrayBuffer::Allocator* GetAllocator() { + static v8::ArrayBuffer::Allocator* allocator = v8::ArrayBuffer::Allocator::NewDefaultAllocator(); + return allocator; +}; + class SerializerContext : public BaseObject, public ValueSerializer::Delegate { public: @@ -37,10 +42,15 @@ class SerializerContext : public BaseObject, ~SerializerContext() override = default; + // v8::ValueSerializer::Delegate void ThrowDataCloneError(Local<String> message) override; Maybe<bool> WriteHostObject(Isolate* isolate, Local<Object> object) override; Maybe<uint32_t> GetSharedArrayBufferId( Isolate* isolate, Local<SharedArrayBuffer> shared_array_buffer) override; + void* ReallocateBufferMemory(void* old_buffer, + size_t old_length, + size_t* new_length) override; + void FreeBufferMemory(void* buffer) override; static void SetTreatArrayBufferViewsAsHostObjects( const FunctionCallbackInfo<Value>& args); @@ -61,6 +71,7 @@ class SerializerContext : public BaseObject, private: ValueSerializer serializer_; + size_t last_length_ = 0; }; class DeserializerContext : public BaseObject, @@ -144,6 +155,24 @@ Maybe<uint32_t> SerializerContext::GetSharedArrayBufferId( return id.ToLocalChecked()->Uint32Value(env()->context()); } +void* SerializerContext::ReallocateBufferMemory(void* old_buffer, + size_t requested_size, + size_t* new_length) { + *new_length = std::max(static_cast<size_t>(4096), requested_size); + if (old_buffer) { + void* ret = GetAllocator()->Reallocate(old_buffer, last_length_, *new_length); + last_length_ = *new_length; + return ret; + } else { + last_length_ = *new_length; + return GetAllocator()->Allocate(*new_length); + } +} + +void SerializerContext::FreeBufferMemory(void* buffer) { + GetAllocator()->Free(buffer, last_length_); +} + Maybe<bool> SerializerContext::WriteHostObject(Isolate* isolate, Local<Object> input) { MaybeLocal<Value> ret; @@ -211,7 +240,12 @@ void SerializerContext::ReleaseBuffer(const FunctionCallbackInfo<Value>& args) { std::pair<uint8_t*, size_t> ret = ctx->serializer_.Release(); auto buf = Buffer::New(ctx->env(), reinterpret_cast<char*>(ret.first), - ret.second); + ret.second, + [](char* data, void* hint){ + if (data) + GetAllocator()->Free(data, reinterpret_cast<size_t>(hint)); + }, + reinterpret_cast<void*>(ctx->last_length_)); if (!buf.IsEmpty()) { args.GetReturnValue().Set(buf.ToLocalChecked());
closed
electron/electron
https://github.com/electron/electron
31,634
[Bug]: crypto.hkdf "Deriving bits failed"
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Electron Version v15.3.0 ### What operating system are you using? macOS ### Operating System Version Darwin C02CX0K5MD6V 20.6.0 Darwin Kernel Version 20.6.0: Mon Aug 30 06:12:21 PDT 2021; root:xnu-7195.141.6~3/RELEASE_X86_64 x86_64 ### What arch are you using? x64 ### Last Known Working Electron version none ### Expected Behavior `crypto.hkdf` and `crypto.hkdfSync` work as documented[^1] [^1]: https://nodejs.org/api/crypto.html#cryptohkdfdigest-ikm-salt-info-keylen-callback ### Actual Behavior ``` crypto.hkdfSync('sha256', 'foo', '', '', 32) // Uncaught Error: Deriving bits failed // at Object.hkdfSync (node:internal/crypto/hkdf:140:35) crypto.hkdf('sha256', 'foo', '', '', 32, console.log) // [Error: Deriving bits failed] ``` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/31634
https://github.com/electron/electron/pull/34767
35ff95d3c71849ac97ced178a2330b9d4651f250
ad2b1fee59c2e4352b0c5664f72c0067a2ef4d7f
2021-10-29T09:01:40Z
c++
2022-06-29T12:53:57Z
script/node-disabled-tests.json
[ "abort/test-abort-backtrace", "async-hooks/test-crypto-pbkdf2", "async-hooks/test-crypto-randomBytes", "parallel/test-bootstrap-modules", "parallel/test-child-process-fork-exec-path", "parallel/test-cli-node-print-help", "parallel/test-cluster-bind-privileged-port", "parallel/test-cluster-shared-handle-bind-privileged-port", "parallel/test-code-cache", "parallel/test-crypto-aes-wrap", "parallel/test-crypto-authenticated-stream", "parallel/test-crypto-des3-wrap", "parallel/test-crypto-dh-stateless", "parallel/test-crypto-ecb", "parallel/test-crypto-engine", "parallel/test-crypto-fips", "parallel/test-crypto-hkdf.js", "parallel/test-crypto-keygen", "parallel/test-crypto-keygen-deprecation", "parallel/test-crypto-key-objects", "parallel/test-crypto-padding-aes256", "parallel/test-crypto-secure-heap", "parallel/test-fs-utimes-y2K38", "parallel/test-heapsnapshot-near-heap-limit-worker.js", "parallel/test-http2-clean-output", "parallel/test-https-agent-session-reuse", "parallel/test-https-options-boolean-check", "parallel/test-icu-minimum-version", "parallel/test-inspector-multisession-ws", "parallel/test-inspector-port-zero-cluster", "parallel/test-inspector-tracing-domain", "parallel/test-module-loading-globalpaths", "parallel/test-module-version", "parallel/test-openssl-ca-options", "parallel/test-process-env-allowed-flags-are-documented", "parallel/test-process-versions", "parallel/test-repl", "parallel/test-repl-underscore", "parallel/test-stdout-close-catch", "parallel/test-tls-cert-chains-concat", "parallel/test-tls-cert-chains-in-ca", "parallel/test-tls-cli-max-version-1.2", "parallel/test-tls-cli-max-version-1.3", "parallel/test-tls-cli-min-version-1.1", "parallel/test-tls-cli-min-version-1.2", "parallel/test-tls-cli-min-version-1.3", "parallel/test-tls-client-auth", "parallel/test-tls-client-getephemeralkeyinfo", "parallel/test-tls-client-mindhsize", "parallel/test-tls-client-reject", "parallel/test-tls-client-renegotiation-13", "parallel/test-tls-cnnic-whitelist", "parallel/test-tls-disable-renegotiation", "parallel/test-tls-empty-sni-context", "parallel/test-tls-env-bad-extra-ca", "parallel/test-tls-env-extra-ca", "parallel/test-tls-finished", "parallel/test-tls-generic-stream", "parallel/test-tls-getcipher", "parallel/test-tls-handshake-error", "parallel/test-tls-handshake-exception", "parallel/test-tls-hello-parser-failure", "parallel/test-tls-honorcipherorder", "parallel/test-tls-junk-closes-server", "parallel/test-tls-junk-server", "parallel/test-tls-key-mismatch", "parallel/test-tls-max-send-fragment", "parallel/test-tls-min-max-version", "parallel/test-tls-multi-key", "parallel/test-tls-multi-pfx", "parallel/test-tls-no-cert-required", "parallel/test-tls-options-boolean-check", "parallel/test-tls-passphrase", "parallel/test-tls-peer-certificate", "parallel/test-tls-pfx-authorizationerror", "parallel/test-tls-psk-circuit", "parallel/test-tls-root-certificates", "parallel/test-tls-server-failed-handshake-emits-clienterror", "parallel/test-tls-set-ciphers", "parallel/test-tls-set-ciphers-error", "parallel/test-tls-set-sigalgs", "parallel/test-tls-socket-allow-half-open-option", "parallel/test-tls-socket-failed-handshake-emits-error", "parallel/test-tls-ticket", "parallel/test-tls-ticket-cluster", "parallel/test-trace-events-all", "parallel/test-trace-events-async-hooks", "parallel/test-trace-events-binding", "parallel/test-trace-events-bootstrap", "parallel/test-trace-events-category-used", "parallel/test-trace-events-console", "parallel/test-trace-events-dynamic-enable", "parallel/test-trace-events-dynamic-enable-workers-disabled", "parallel/test-trace-events-environment", "parallel/test-trace-events-file-pattern", "parallel/test-trace-events-fs-sync", "parallel/test-trace-events-metadata", "parallel/test-trace-events-none", "parallel/test-trace-events-perf", "parallel/test-trace-events-process-exit", "parallel/test-trace-events-promises", "parallel/test-trace-events-v8", "parallel/test-trace-events-vm", "parallel/test-trace-events-worker-metadata", "parallel/test-v8-untrusted-code-mitigations", "parallel/test-webcrypto-derivebits-hkdf", "parallel/test-webcrypto-derivebits-node-dh", "parallel/test-webcrypto-ed25519-ed448", "parallel/test-webcrypto-encrypt-decrypt", "parallel/test-webcrypto-encrypt-decrypt-aes", "parallel/test-webcrypto-encrypt-decrypt-rsa", "parallel/test-webcrypto-keygen", "parallel/test-webcrypto-rsa-pss-params", "parallel/test-webcrypto-sign-verify-node-dsa", "parallel/test-webcrypto-x25519-x448", "parallel/test-worker-debug", "parallel/test-worker-stdio", "parallel/test-zlib-unused-weak", "report/test-report-fatal-error", "report/test-report-getreport", "report/test-report-signal", "report/test-report-uncaught-exception", "report/test-report-uncaught-exception-compat", "report/test-report-uv-handles", "report/test-report-worker", "report/test-report-writereport", "sequential/test-cpu-prof-kill", "sequential/test-diagnostic-dir-cpu-prof", "sequential/test-cpu-prof-drained.js", "sequential/test-tls-connect", "wpt/test-webcrypto" ]
closed
electron/electron
https://github.com/electron/electron
34,783
[Feature Request]: Re add Linux 32bit
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description Linux 32bit binaries are missing as Linux 32bit distros like Arch32, Gentoo, Void, Debian etc still all support Linux 32bit ### Proposed Solution Re add Linux 32bit binaries ### Alternatives Considered N/A ### Additional Information _No response_
https://github.com/electron/electron/issues/34783
https://github.com/electron/electron/pull/34787
c3920c5c02a6875b444a7c4017ba85145b658fec
c885f9063bda5032fe430bbee724f77b66ce034a
2022-06-29T07:26:57Z
c++
2022-06-30T16:23:03Z
docs/breaking-changes.md
# Breaking Changes Breaking changes will be documented here, and deprecation warnings added to JS code where possible, at least [one major version](tutorial/electron-versioning.md#semver) before the change is made. ### Types of Breaking Changes This document uses the following convention to categorize breaking changes: * **API Changed:** An API was changed in such a way that code that has not been updated is guaranteed to throw an exception. * **Behavior Changed:** The behavior of Electron has changed, but not in such a way that an exception will necessarily be thrown. * **Default Changed:** Code depending on the old default may break, not necessarily throwing an exception. The old behavior can be restored by explicitly specifying the value. * **Deprecated:** An API was marked as deprecated. The API will continue to function, but will emit a deprecation warning, and will be removed in a future release. * **Removed:** An API or feature was removed, and is no longer supported by Electron. ## Planned Breaking API Changes (20.0) ### API Changed: `webContents.printToPDF()` `webContents.printToPDF()` has been modified to conform to [`Page.printToPDF`](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) in the Chrome DevTools Protocol. This has been changes in order to address changes upstream that made our previous implementation untenable and rife with bugs. **Arguments Changed** * `pageRanges` **Arguments Removed** * `printSelectionOnly` * `marginsType` * `headerFooter` * `scaleFactor` **Arguments Added** * `headerTemplate` * `footerTemplate` * `displayHeaderFooter` * `margins` * `scale` * `preferCSSPageSize` ```js // Main process const { webContents } = require('electron') webContents.printToPDF({ landscape: true, displayHeaderFooter: true, printBackground: true, scale: 2, pageSize: 'Ledger', margins: { top: 2, bottom: 2, left: 2, right: 2 }, pageRanges: '1-5, 8, 11-13', headerTemplate: '<h1>Title</h1>', footerTemplate: '<div><span class="pageNumber"></span></div>', preferCSSPageSize: true }).then(data => { fs.writeFile(pdfPath, data, (error) => { if (error) throw error console.log(`Wrote PDF successfully to ${pdfPath}`) }) }).catch(error => { console.log(`Failed to write PDF to ${pdfPath}: `, error) }) ``` ### Default Changed: renderers without `nodeIntegration: true` are sandboxed by default Previously, renderers that specified a preload script defaulted to being unsandboxed. This meant that by default, preload scripts had access to Node.js. In Electron 20, this default has changed. Beginning in Electron 20, renderers will be sandboxed by default, unless `nodeIntegration: true` or `sandbox: false` is specified. If your preload scripts do not depend on Node, no action is needed. If your preload scripts _do_ depend on Node, either refactor them to remove Node usage from the renderer, or explicitly specify `sandbox: false` for the relevant renderers. ### Removed: `skipTaskbar` on Linux On X11, `skipTaskbar` sends a `_NET_WM_STATE_SKIP_TASKBAR` message to the X11 window manager. There is not a direct equivalent for Wayland, and the known workarounds have unacceptable tradeoffs (e.g. Window.is_skip_taskbar in GNOME requires unsafe mode), so Electron is unable to support this feature on Linux. ### API Changed: `session.setDevicePermissionHandler(handler)` The handler invoked when `session.setDevicePermissionHandler(handler)` is used has a change to its arguments. This handler no longer is passed a frame `[WebFrameMain](api/web-frame-main.md)`, but instead is passed the `origin`, which is the origin that is checking for device permission. ## Planned Breaking API Changes (19.0) None ## Planned Breaking API Changes (18.0) ### Removed: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (17.0) ### Removed: `desktopCapturer.getSources` in the renderer The `desktopCapturer.getSources` API is now only available in the main process. This has been changed in order to improve the default security of Electron apps. If you need this functionality, it can be replaced as follows: ```js // Main process const { ipcMain, desktopCapturer } = require('electron') ipcMain.handle( 'DESKTOP_CAPTURER_GET_SOURCES', (event, opts) => desktopCapturer.getSources(opts) ) ``` ```js // Renderer process const { ipcRenderer } = require('electron') const desktopCapturer = { getSources: (opts) => ipcRenderer.invoke('DESKTOP_CAPTURER_GET_SOURCES', opts) } ``` However, you should consider further restricting the information returned to the renderer; for instance, displaying a source selector to the user and only returning the selected source. ### Deprecated: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (16.0) ### Behavior Changed: `crashReporter` implementation switched to Crashpad on Linux The underlying implementation of the `crashReporter` API on Linux has changed from Breakpad to Crashpad, bringing it in line with Windows and Mac. As a result of this, child processes are now automatically monitored, and calling `process.crashReporter.start` in Node child processes is no longer needed (and is not advisable, as it will start a second instance of the Crashpad reporter). There are also some subtle changes to how annotations will be reported on Linux, including that long values will no longer be split between annotations appended with `__1`, `__2` and so on, and instead will be truncated at the (new, longer) annotation value limit. ### Deprecated: `desktopCapturer.getSources` in the renderer Usage of the `desktopCapturer.getSources` API in the renderer has been deprecated and will be removed. This change improves the default security of Electron apps. See [here](#removed-desktopcapturergetsources-in-the-renderer) for details on how to replace this API in your app. ## Planned Breaking API Changes (15.0) ### Default Changed: `nativeWindowOpen` defaults to `true` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. `nativeWindowOpen` is no longer experimental, and is now the default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (14.0) ### Removed: `remote` module The `remote` module was deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Removed: `app.allowRendererProcessReuse` The `app.allowRendererProcessReuse` property will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Removed: Browser Window Affinity The `affinity` option when constructing a new `BrowserWindow` will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### API Changed: `window.open()` The optional parameter `frameName` will no longer set the title of the window. This now follows the specification described by the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters) under the corresponding parameter `windowName`. If you were using this parameter to set the title of a window, you can instead use [win.setTitle(title)](api/browser-window.md#winsettitletitle). ### Removed: `worldSafeExecuteJavaScript` In Electron 14, `worldSafeExecuteJavaScript` will be removed. There is no alternative, please ensure your code works with this property enabled. It has been enabled by default since Electron 12. You will be affected by this change if you use either `webFrame.executeJavaScript` or `webFrame.executeJavaScriptInIsolatedWorld`. You will need to ensure that values returned by either of those methods are supported by the [Context Bridge API](api/context-bridge.md#parameter--error--return-type-support) as these methods use the same value passing semantics. ### Removed: BrowserWindowConstructorOptions inheriting from parent windows Prior to Electron 14, windows opened with `window.open` would inherit BrowserWindow constructor options such as `transparent` and `resizable` from their parent window. Beginning with Electron 14, this behavior is removed, and windows will not inherit any BrowserWindow constructor options from their parents. Instead, explicitly set options for the new window with `setWindowOpenHandler`: ```js webContents.setWindowOpenHandler((details) => { return { action: 'allow', overrideBrowserWindowOptions: { // ... } } }) ``` ### Removed: `additionalFeatures` The deprecated `additionalFeatures` property in the `new-window` and `did-create-window` events of WebContents has been removed. Since `new-window` uses positional arguments, the argument is still present, but will always be the empty array `[]`. (Though note, the `new-window` event itself is deprecated, and is replaced by `setWindowOpenHandler`.) Bare keys in window features will now present as keys with the value `true` in the options object. ```js // Removed in Electron 14 // Triggered by window.open('...', '', 'my-key') webContents.on('did-create-window', (window, details) => { if (details.additionalFeatures.includes('my-key')) { // ... } }) // Replace with webContents.on('did-create-window', (window, details) => { if (details.options['my-key']) { // ... } }) ``` ## Planned Breaking API Changes (13.0) ### API Changed: `session.setPermissionCheckHandler(handler)` The `handler` methods first parameter was previously always a `webContents`, it can now sometimes be `null`. You should use the `requestingOrigin`, `embeddingOrigin` and `securityOrigin` properties to respond to the permission check correctly. As the `webContents` can be `null` it can no longer be relied on. ```js // Old code session.setPermissionCheckHandler((webContents, permission) => { if (webContents.getURL().startsWith('https://google.com/') && permission === 'notification') { return true } return false }) // Replace with session.setPermissionCheckHandler((webContents, permission, requestingOrigin) => { if (new URL(requestingOrigin).hostname === 'google.com' && permission === 'notification') { return true } return false }) ``` ### Removed: `shell.moveItemToTrash()` The deprecated synchronous `shell.moveItemToTrash()` API has been removed. Use the asynchronous `shell.trashItem()` instead. ```js // Removed in Electron 13 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ### Removed: `BrowserWindow` extension APIs The deprecated extension APIs have been removed: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Removed in Electron 13 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Removed in Electron 13 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Removed in Electron 13 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Removed in Electron 13 systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Removed in Electron 13 systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Removed in Electron 13 systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ### Deprecated: WebContents `new-window` event The `new-window` event of WebContents has been deprecated. It is replaced by [`webContents.setWindowOpenHandler()`](api/web-contents.md#contentssetwindowopenhandlerhandler). ```js // Deprecated in Electron 13 webContents.on('new-window', (event) => { event.preventDefault() }) // Replace with webContents.setWindowOpenHandler((details) => { return { action: 'deny' } }) ``` ## Planned Breaking API Changes (12.0) ### Removed: Pepper Flash support Chromium has removed support for Flash, and so we must follow suit. See Chromium's [Flash Roadmap](https://www.chromium.org/flash-roadmap) for more details. ### Default Changed: `worldSafeExecuteJavaScript` defaults to `true` In Electron 12, `worldSafeExecuteJavaScript` will be enabled by default. To restore the previous behavior, `worldSafeExecuteJavaScript: false` must be specified in WebPreferences. Please note that setting this option to `false` is **insecure**. This option will be removed in Electron 14 so please migrate your code to support the default value. ### Default Changed: `contextIsolation` defaults to `true` In Electron 12, `contextIsolation` will be enabled by default. To restore the previous behavior, `contextIsolation: false` must be specified in WebPreferences. We [recommend having contextIsolation enabled](tutorial/security.md#3-enable-context-isolation) for the security of your application. Another implication is that `require()` cannot be used in the renderer process unless `nodeIntegration` is `true` and `contextIsolation` is `false`. For more details see: https://github.com/electron/electron/issues/23506 ### Removed: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been removed. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Removed in Electron 12 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Removed: `crashReporter` methods in the renderer process The following `crashReporter` methods are no longer available in the renderer process: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` They should be called only from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Default Changed: `crashReporter.start({ compress: true })` The default value of the `compress` option to `crashReporter.start` has changed from `false` to `true`. This means that crash dumps will be uploaded to the crash ingestion server with the `Content-Encoding: gzip` header, and the body will be compressed. If your crash ingestion server does not support compressed payloads, you can turn off compression by specifying `{ compress: false }` in the crash reporter options. ### Deprecated: `remote` module The `remote` module is deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Deprecated: `shell.moveItemToTrash()` The synchronous `shell.moveItemToTrash()` has been replaced by the new, asynchronous `shell.trashItem()`. ```js // Deprecated in Electron 12 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ## Planned Breaking API Changes (11.0) ### Removed: `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` and `id` property of `BrowserView` The experimental APIs `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` have now been removed. Additionally, the `id` property of `BrowserView` has also been removed. For more detailed information, see [#23578](https://github.com/electron/electron/pull/23578). ## Planned Breaking API Changes (10.0) ### Deprecated: `companyName` argument to `crashReporter.start()` The `companyName` argument to `crashReporter.start()`, which was previously required, is now optional, and further, is deprecated. To get the same behavior in a non-deprecated way, you can pass a `companyName` value in `globalExtra`. ```js // Deprecated in Electron 10 crashReporter.start({ companyName: 'Umbrella Corporation' }) // Replace with crashReporter.start({ globalExtra: { _companyName: 'Umbrella Corporation' } }) ``` ### Deprecated: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been deprecated. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Deprecated in Electron 10 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Deprecated: `crashReporter` methods in the renderer process Calling the following `crashReporter` methods from the renderer process is deprecated: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` The only non-deprecated methods remaining in the `crashReporter` module in the renderer are `addExtraParameter`, `removeExtraParameter` and `getParameters`. All above methods remain non-deprecated when called from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Deprecated: `crashReporter.start({ compress: false })` Setting `{ compress: false }` in `crashReporter.start` is deprecated. Nearly all crash ingestion servers support gzip compression. This option will be removed in a future version of Electron. ### Default Changed: `enableRemoteModule` defaults to `false` In Electron 9, using the remote module without explicitly enabling it via the `enableRemoteModule` WebPreferences option began emitting a warning. In Electron 10, the remote module is now disabled by default. To use the remote module, `enableRemoteModule: true` must be specified in WebPreferences: ```js const w = new BrowserWindow({ webPreferences: { enableRemoteModule: true } }) ``` We [recommend moving away from the remote module](https://medium.com/@nornagon/electrons-remote-module-considered-harmful-70d69500f31). ### `protocol.unregisterProtocol` ### `protocol.uninterceptProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.unregisterProtocol(scheme, () => { /* ... */ }) // Replace with protocol.unregisterProtocol(scheme) ``` ### `protocol.registerFileProtocol` ### `protocol.registerBufferProtocol` ### `protocol.registerStringProtocol` ### `protocol.registerHttpProtocol` ### `protocol.registerStreamProtocol` ### `protocol.interceptFileProtocol` ### `protocol.interceptStringProtocol` ### `protocol.interceptBufferProtocol` ### `protocol.interceptHttpProtocol` ### `protocol.interceptStreamProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.registerFileProtocol(scheme, handler, () => { /* ... */ }) // Replace with protocol.registerFileProtocol(scheme, handler) ``` The registered or intercepted protocol does not have effect on current page until navigation happens. ### `protocol.isProtocolHandled` This API is deprecated and users should use `protocol.isProtocolRegistered` and `protocol.isProtocolIntercepted` instead. ```javascript // Deprecated protocol.isProtocolHandled(scheme).then(() => { /* ... */ }) // Replace with const isRegistered = protocol.isProtocolRegistered(scheme) const isIntercepted = protocol.isProtocolIntercepted(scheme) ``` ## Planned Breaking API Changes (9.0) ### Default Changed: Loading non-context-aware native modules in the renderer process is disabled by default As of Electron 9 we do not allow loading of non-context-aware native modules in the renderer process. This is to improve security, performance and maintainability of Electron as a project. If this impacts you, you can temporarily set `app.allowRendererProcessReuse` to `false` to revert to the old behavior. This flag will only be an option until Electron 11 so you should plan to update your native modules to be context aware. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Deprecated: `BrowserWindow` extension APIs The following extension APIs have been deprecated: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Deprecated in Electron 9 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Deprecated in Electron 9 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Deprecated in Electron 9 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: `<webview>.getWebContents()` This API, which was deprecated in Electron 8.0, is now removed. ```js // Removed in Electron 9.0 webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` ### Removed: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function was deprecated in Electron 8.x, and has been removed in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Behavior Changed: Sending non-JS objects over IPC now throws an exception In Electron 8.0, IPC was changed to use the Structured Clone Algorithm, bringing significant performance improvements. To help ease the transition, the old IPC serialization algorithm was kept and used for some objects that aren't serializable with Structured Clone. In particular, DOM objects (e.g. `Element`, `Location` and `DOMMatrix`), Node.js objects backed by C++ classes (e.g. `process.env`, some members of `Stream`), and Electron objects backed by C++ classes (e.g. `WebContents`, `BrowserWindow` and `WebFrame`) are not serializable with Structured Clone. Whenever the old algorithm was invoked, a deprecation warning was printed. In Electron 9.0, the old serialization algorithm has been removed, and sending such non-serializable objects will now throw an "object could not be cloned" error. ### API Changed: `shell.openItem` is now `shell.openPath` The `shell.openItem` API has been replaced with an asynchronous `shell.openPath` API. You can see the original API proposal and reasoning [here](https://github.com/electron/governance/blob/main/wg-api/spec-documents/shell-openitem.md). ## Planned Breaking API Changes (8.0) ### Behavior Changed: Values sent over IPC are now serialized with Structured Clone Algorithm The algorithm used to serialize objects sent over IPC (through `ipcRenderer.send`, `ipcRenderer.sendSync`, `WebContents.send` and related methods) has been switched from a custom algorithm to V8's built-in [Structured Clone Algorithm][SCA], the same algorithm used to serialize messages for `postMessage`. This brings about a 2x performance improvement for large messages, but also brings some breaking changes in behavior. * Sending Functions, Promises, WeakMaps, WeakSets, or objects containing any such values, over IPC will now throw an exception, instead of silently converting the functions to `undefined`. ```js // Previously: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => results in { value: 3 } arriving in the main process // From Electron 8: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => throws Error("() => {} could not be cloned.") ``` * `NaN`, `Infinity` and `-Infinity` will now be correctly serialized, instead of being converted to `null`. * Objects containing cyclic references will now be correctly serialized, instead of being converted to `null`. * `Set`, `Map`, `Error` and `RegExp` values will be correctly serialized, instead of being converted to `{}`. * `BigInt` values will be correctly serialized, instead of being converted to `null`. * Sparse arrays will be serialized as such, instead of being converted to dense arrays with `null`s. * `Date` objects will be transferred as `Date` objects, instead of being converted to their ISO string representation. * Typed Arrays (such as `Uint8Array`, `Uint16Array`, `Uint32Array` and so on) will be transferred as such, instead of being converted to Node.js `Buffer`. * Node.js `Buffer` objects will be transferred as `Uint8Array`s. You can convert a `Uint8Array` back to a Node.js `Buffer` by wrapping the underlying `ArrayBuffer`: ```js Buffer.from(value.buffer, value.byteOffset, value.byteLength) ``` Sending any objects that aren't native JS types, such as DOM objects (e.g. `Element`, `Location`, `DOMMatrix`), Node.js objects (e.g. `process.env`, `Stream`), or Electron objects (e.g. `WebContents`, `BrowserWindow`, `WebFrame`) is deprecated. In Electron 8, these objects will be serialized as before with a DeprecationWarning message, but starting in Electron 9, sending these kinds of objects will throw a 'could not be cloned' error. [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm ### Deprecated: `<webview>.getWebContents()` This API is implemented using the `remote` module, which has both performance and security implications. Therefore its usage should be explicit. ```js // Deprecated webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` However, it is recommended to avoid using the `remote` module altogether. ```js // main const { ipcMain, webContents } = require('electron') const getGuestForWebContents = (webContentsId, contents) => { const guest = webContents.fromId(webContentsId) if (!guest) { throw new Error(`Invalid webContentsId: ${webContentsId}`) } if (guest.hostWebContents !== contents) { throw new Error('Access denied to webContents') } return guest } ipcMain.handle('openDevTools', (event, webContentsId) => { const guest = getGuestForWebContents(webContentsId, event.sender) guest.openDevTools() }) // renderer const { ipcRenderer } = require('electron') ipcRenderer.invoke('openDevTools', webview.getWebContentsId()) ``` ### Deprecated: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function will emit a warning in Electron 8.x, and cease to exist in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Deprecated events in `systemPreferences` The following `systemPreferences` events have been deprecated: * `inverted-color-scheme-changed` * `high-contrast-color-scheme-changed` Use the new `updated` event on the `nativeTheme` module instead. ```js // Deprecated systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ }) systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ }) // Replace with nativeTheme.on('updated', () => { /* ... */ }) ``` ### Deprecated: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Deprecated systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Deprecated systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Deprecated systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ## Planned Breaking API Changes (7.0) ### Deprecated: Atom.io Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Both will be supported for the foreseeable future but it is recommended that you switch. Deprecated: https://atom.io/download/electron Replace with: https://electronjs.org/headers ### API Changed: `session.clearAuthCache()` no longer accepts options The `session.clearAuthCache` API no longer accepts options for what to clear, and instead unconditionally clears the whole cache. ```js // Deprecated session.clearAuthCache({ type: 'password' }) // Replace with session.clearAuthCache() ``` ### API Changed: `powerMonitor.querySystemIdleState` is now `powerMonitor.getSystemIdleState` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### API Changed: `powerMonitor.querySystemIdleTime` is now `powerMonitor.getSystemIdleTime` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### API Changed: `webFrame.setIsolatedWorldInfo` replaces separate methods ```js // Removed in Electron 7.0 webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### Removed: `marked` property on `getBlinkMemoryInfo` This property was removed in Chromium 77, and as such is no longer available. ### Behavior Changed: `webkitdirectory` attribute for `<input type="file"/>` now lists directory contents The `webkitdirectory` property on HTML file inputs allows them to select folders. Previous versions of Electron had an incorrect implementation where the `event.target.files` of the input returned a `FileList` that returned one `File` corresponding to the selected folder. As of Electron 7, that `FileList` is now list of all files contained within the folder, similarly to Chrome, Firefox, and Edge ([link to MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory)). As an illustration, take a folder with this structure: ```console folder ├── file1 ├── file2 └── file3 ``` In Electron <=6, this would return a `FileList` with a `File` object for: ```console path/to/folder ``` In Electron 7, this now returns a `FileList` with a `File` object for: ```console /path/to/folder/file3 /path/to/folder/file2 /path/to/folder/file1 ``` Note that `webkitdirectory` no longer exposes the path to the selected folder. If you require the path to the selected folder rather than the folder contents, see the `dialog.showOpenDialog` API ([link](api/dialog.md#dialogshowopendialogbrowserwindow-options)). ### API Changed: Callback-based versions of promisified APIs Electron 5 and Electron 6 introduced Promise-based versions of existing asynchronous APIs and deprecated their older, callback-based counterparts. In Electron 7, all deprecated callback-based APIs are now removed. These functions now only return Promises: * `app.getFileIcon()` [#15742](https://github.com/electron/electron/pull/15742) * `app.dock.show()` [#16904](https://github.com/electron/electron/pull/16904) * `contentTracing.getCategories()` [#16583](https://github.com/electron/electron/pull/16583) * `contentTracing.getTraceBufferUsage()` [#16600](https://github.com/electron/electron/pull/16600) * `contentTracing.startRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contentTracing.stopRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contents.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `cookies.flushStore()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.get()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.remove()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.set()` [#16464](https://github.com/electron/electron/pull/16464) * `debugger.sendCommand()` [#16861](https://github.com/electron/electron/pull/16861) * `dialog.showCertificateTrustDialog()` [#17181](https://github.com/electron/electron/pull/17181) * `inAppPurchase.getProducts()` [#17355](https://github.com/electron/electron/pull/17355) * `inAppPurchase.purchaseProduct()`[#17355](https://github.com/electron/electron/pull/17355) * `netLog.stopLogging()` [#16862](https://github.com/electron/electron/pull/16862) * `session.clearAuthCache()` [#17259](https://github.com/electron/electron/pull/17259) * `session.clearCache()` [#17185](https://github.com/electron/electron/pull/17185) * `session.clearHostResolverCache()` [#17229](https://github.com/electron/electron/pull/17229) * `session.clearStorageData()` [#17249](https://github.com/electron/electron/pull/17249) * `session.getBlobData()` [#17303](https://github.com/electron/electron/pull/17303) * `session.getCacheSize()` [#17185](https://github.com/electron/electron/pull/17185) * `session.resolveProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `session.setProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `shell.openExternal()` [#16176](https://github.com/electron/electron/pull/16176) * `webContents.loadFile()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.loadURL()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.hasServiceWorker()` [#16535](https://github.com/electron/electron/pull/16535) * `webContents.printToPDF()` [#16795](https://github.com/electron/electron/pull/16795) * `webContents.savePage()` [#16742](https://github.com/electron/electron/pull/16742) * `webFrame.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `webFrame.executeJavaScriptInIsolatedWorld()` [#17312](https://github.com/electron/electron/pull/17312) * `webviewTag.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `win.capturePage()` [#15743](https://github.com/electron/electron/pull/15743) These functions now have two forms, synchronous and Promise-based asynchronous: * `dialog.showMessageBox()`/`dialog.showMessageBoxSync()` [#17298](https://github.com/electron/electron/pull/17298) * `dialog.showOpenDialog()`/`dialog.showOpenDialogSync()` [#16973](https://github.com/electron/electron/pull/16973) * `dialog.showSaveDialog()`/`dialog.showSaveDialogSync()` [#17054](https://github.com/electron/electron/pull/17054) ## Planned Breaking API Changes (6.0) ### API Changed: `win.setMenu(null)` is now `win.removeMenu()` ```js // Deprecated win.setMenu(null) // Replace with win.removeMenu() ``` ### API Changed: `electron.screen` in the renderer process should be accessed via `remote` ```js // Deprecated require('electron').screen // Replace with require('electron').remote.screen ``` ### API Changed: `require()`ing node builtins in sandboxed renderers no longer implicitly loads the `remote` version ```js // Deprecated require('child_process') // Replace with require('electron').remote.require('child_process') // Deprecated require('fs') // Replace with require('electron').remote.require('fs') // Deprecated require('os') // Replace with require('electron').remote.require('os') // Deprecated require('path') // Replace with require('electron').remote.require('path') ``` ### Deprecated: `powerMonitor.querySystemIdleState` replaced with `powerMonitor.getSystemIdleState` ```js // Deprecated powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### Deprecated: `powerMonitor.querySystemIdleTime` replaced with `powerMonitor.getSystemIdleTime` ```js // Deprecated powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### Deprecated: `app.enableMixedSandbox()` is no longer needed ```js // Deprecated app.enableMixedSandbox() ``` Mixed-sandbox mode is now enabled by default. ### Deprecated: `Tray.setHighlightMode` Under macOS Catalina our former Tray implementation breaks. Apple's native substitute doesn't support changing the highlighting behavior. ```js // Deprecated tray.setHighlightMode(mode) // API will be removed in v7.0 without replacement. ``` ## Planned Breaking API Changes (5.0) ### Default Changed: `nodeIntegration` and `webviewTag` default to false, `contextIsolation` defaults to true The following `webPreferences` option default values are deprecated in favor of the new defaults listed below. | Property | Deprecated Default | New Default | |----------|--------------------|-------------| | `contextIsolation` | `false` | `true` | | `nodeIntegration` | `true` | `false` | | `webviewTag` | `nodeIntegration` if set else `true` | `false` | E.g. Re-enabling the webviewTag ```js const w = new BrowserWindow({ webPreferences: { webviewTag: true } }) ``` ### Behavior Changed: `nodeIntegration` in child windows opened via `nativeWindowOpen` Child windows opened with the `nativeWindowOpen` option will always have Node.js integration disabled, unless `nodeIntegrationInSubFrames` is `true`. ### API Changed: Registering privileged schemes must now be done before app ready Renderer process APIs `webFrame.registerURLSchemeAsPrivileged` and `webFrame.registerURLSchemeAsBypassingCSP` as well as browser process API `protocol.registerStandardSchemes` have been removed. A new API, `protocol.registerSchemesAsPrivileged` has been added and should be used for registering custom schemes with the required privileges. Custom schemes are required to be registered before app ready. ### Deprecated: `webFrame.setIsolatedWorld*` replaced with `webFrame.setIsolatedWorldInfo` ```js // Deprecated webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### API Changed: `webFrame.setSpellCheckProvider` now takes an asynchronous callback The `spellCheck` callback is now asynchronous, and `autoCorrectWord` parameter has been removed. ```js // Deprecated webFrame.setSpellCheckProvider('en-US', true, { spellCheck: (text) => { return !spellchecker.isMisspelled(text) } }) // Replace with webFrame.setSpellCheckProvider('en-US', { spellCheck: (words, callback) => { callback(words.filter(text => spellchecker.isMisspelled(text))) } }) ``` ### API Changed: `webContents.getZoomLevel` and `webContents.getZoomFactor` are now synchronous `webContents.getZoomLevel` and `webContents.getZoomFactor` no longer take callback parameters, instead directly returning their number values. ```js // Deprecated webContents.getZoomLevel((level) => { console.log(level) }) // Replace with const level = webContents.getZoomLevel() console.log(level) ``` ```js // Deprecated webContents.getZoomFactor((factor) => { console.log(factor) }) // Replace with const factor = webContents.getZoomFactor() console.log(factor) ``` ## Planned Breaking API Changes (4.0) The following list includes the breaking API changes made in Electron 4.0. ### `app.makeSingleInstance` ```js // Deprecated app.makeSingleInstance((argv, cwd) => { /* ... */ }) // Replace with app.requestSingleInstanceLock() app.on('second-instance', (event, argv, cwd) => { /* ... */ }) ``` ### `app.releaseSingleInstance` ```js // Deprecated app.releaseSingleInstance() // Replace with app.releaseSingleInstanceLock() ``` ### `app.getGPUInfo` ```js app.getGPUInfo('complete') // Now behaves the same with `basic` on macOS app.getGPUInfo('basic') ``` ### `win_delay_load_hook` When building native modules for windows, the `win_delay_load_hook` variable in the module's `binding.gyp` must be true (which is the default). If this hook is not present, then the native module will fail to load on Windows, with an error message like `Cannot find module`. See the [native module guide](/docs/tutorial/using-native-node-modules.md) for more. ## Breaking API Changes (3.0) The following list includes the breaking API changes in Electron 3.0. ### `app` ```js // Deprecated app.getAppMemoryInfo() // Replace with app.getAppMetrics() // Deprecated const metrics = app.getAppMetrics() const { memory } = metrics[0] // Deprecated property ``` ### `BrowserWindow` ```js // Deprecated const optionsA = { webPreferences: { blinkFeatures: '' } } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { webPreferences: { enableBlinkFeatures: '' } } const windowB = new BrowserWindow(optionsB) // Deprecated window.on('app-command', (e, cmd) => { if (cmd === 'media-play_pause') { // do something } }) // Replace with window.on('app-command', (e, cmd) => { if (cmd === 'media-play-pause') { // do something } }) ``` ### `clipboard` ```js // Deprecated clipboard.readRtf() // Replace with clipboard.readRTF() // Deprecated clipboard.writeRtf() // Replace with clipboard.writeRTF() // Deprecated clipboard.readHtml() // Replace with clipboard.readHTML() // Deprecated clipboard.writeHtml() // Replace with clipboard.writeHTML() ``` ### `crashReporter` ```js // Deprecated crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', autoSubmit: true }) // Replace with crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', uploadToServer: true }) ``` ### `nativeImage` ```js // Deprecated nativeImage.createFromBuffer(buffer, 1.0) // Replace with nativeImage.createFromBuffer(buffer, { scaleFactor: 1.0 }) ``` ### `process` ```js // Deprecated const info = process.getProcessMemoryInfo() ``` ### `screen` ```js // Deprecated screen.getMenuBarHeight() // Replace with screen.getPrimaryDisplay().workArea ``` ### `session` ```js // Deprecated ses.setCertificateVerifyProc((hostname, certificate, callback) => { callback(true) }) // Replace with ses.setCertificateVerifyProc((request, callback) => { callback(0) }) ``` ### `Tray` ```js // Deprecated tray.setHighlightMode(true) // Replace with tray.setHighlightMode('on') // Deprecated tray.setHighlightMode(false) // Replace with tray.setHighlightMode('off') ``` ### `webContents` ```js // Deprecated webContents.openDevTools({ detach: true }) // Replace with webContents.openDevTools({ mode: 'detach' }) // Removed webContents.setSize(options) // There is no replacement for this API ``` ### `webFrame` ```js // Deprecated webFrame.registerURLSchemeAsSecure('app') // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) // Deprecated webFrame.registerURLSchemeAsPrivileged('app', { secure: true }) // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) ``` ### `<webview>` ```js // Removed webview.setAttribute('disableguestresize', '') // There is no replacement for this API // Removed webview.setAttribute('guestinstance', instanceId) // There is no replacement for this API // Keyboard listeners no longer work on webview tag webview.onkeydown = () => { /* handler */ } webview.onkeyup = () => { /* handler */ } ``` ### Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Deprecated: https://atom.io/download/atom-shell Replace with: https://atom.io/download/electron ## Breaking API Changes (2.0) The following list includes the breaking API changes made in Electron 2.0. ### `BrowserWindow` ```js // Deprecated const optionsA = { titleBarStyle: 'hidden-inset' } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { titleBarStyle: 'hiddenInset' } const windowB = new BrowserWindow(optionsB) ``` ### `menu` ```js // Removed menu.popup(browserWindow, 100, 200, 2) // Replaced with menu.popup(browserWindow, { x: 100, y: 200, positioningItem: 2 }) ``` ### `nativeImage` ```js // Removed nativeImage.toPng() // Replaced with nativeImage.toPNG() // Removed nativeImage.toJpeg() // Replaced with nativeImage.toJPEG() ``` ### `process` * `process.versions.electron` and `process.version.chrome` will be made read-only properties for consistency with the other `process.versions` properties set by Node. ### `webContents` ```js // Removed webContents.setZoomLevelLimits(1, 2) // Replaced with webContents.setVisualZoomLevelLimits(1, 2) ``` ### `webFrame` ```js // Removed webFrame.setZoomLevelLimits(1, 2) // Replaced with webFrame.setVisualZoomLevelLimits(1, 2) ``` ### `<webview>` ```js // Removed webview.setZoomLevelLimits(1, 2) // Replaced with webview.setVisualZoomLevelLimits(1, 2) ``` ### Duplicate ARM Assets Each Electron release includes two identical ARM builds with slightly different filenames, like `electron-v1.7.3-linux-arm.zip` and `electron-v1.7.3-linux-armv7l.zip`. The asset with the `v7l` prefix was added to clarify to users which ARM version it supports, and to disambiguate it from future armv6l and arm64 assets that may be produced. The file _without the prefix_ is still being published to avoid breaking any setups that may be consuming it. Starting at 2.0, the unprefixed file will no longer be published. For details, see [6986](https://github.com/electron/electron/pull/6986) and [7189](https://github.com/electron/electron/pull/7189).
closed
electron/electron
https://github.com/electron/electron
34,783
[Feature Request]: Re add Linux 32bit
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a feature request that matches the one I want to file, without success. ### Problem Description Linux 32bit binaries are missing as Linux 32bit distros like Arch32, Gentoo, Void, Debian etc still all support Linux 32bit ### Proposed Solution Re add Linux 32bit binaries ### Alternatives Considered N/A ### Additional Information _No response_
https://github.com/electron/electron/issues/34783
https://github.com/electron/electron/pull/34787
c3920c5c02a6875b444a7c4017ba85145b658fec
c885f9063bda5032fe430bbee724f77b66ce034a
2022-06-29T07:26:57Z
c++
2022-06-30T16:23:03Z
docs/breaking-changes.md
# Breaking Changes Breaking changes will be documented here, and deprecation warnings added to JS code where possible, at least [one major version](tutorial/electron-versioning.md#semver) before the change is made. ### Types of Breaking Changes This document uses the following convention to categorize breaking changes: * **API Changed:** An API was changed in such a way that code that has not been updated is guaranteed to throw an exception. * **Behavior Changed:** The behavior of Electron has changed, but not in such a way that an exception will necessarily be thrown. * **Default Changed:** Code depending on the old default may break, not necessarily throwing an exception. The old behavior can be restored by explicitly specifying the value. * **Deprecated:** An API was marked as deprecated. The API will continue to function, but will emit a deprecation warning, and will be removed in a future release. * **Removed:** An API or feature was removed, and is no longer supported by Electron. ## Planned Breaking API Changes (20.0) ### API Changed: `webContents.printToPDF()` `webContents.printToPDF()` has been modified to conform to [`Page.printToPDF`](https://chromedevtools.github.io/devtools-protocol/tot/Page/#method-printToPDF) in the Chrome DevTools Protocol. This has been changes in order to address changes upstream that made our previous implementation untenable and rife with bugs. **Arguments Changed** * `pageRanges` **Arguments Removed** * `printSelectionOnly` * `marginsType` * `headerFooter` * `scaleFactor` **Arguments Added** * `headerTemplate` * `footerTemplate` * `displayHeaderFooter` * `margins` * `scale` * `preferCSSPageSize` ```js // Main process const { webContents } = require('electron') webContents.printToPDF({ landscape: true, displayHeaderFooter: true, printBackground: true, scale: 2, pageSize: 'Ledger', margins: { top: 2, bottom: 2, left: 2, right: 2 }, pageRanges: '1-5, 8, 11-13', headerTemplate: '<h1>Title</h1>', footerTemplate: '<div><span class="pageNumber"></span></div>', preferCSSPageSize: true }).then(data => { fs.writeFile(pdfPath, data, (error) => { if (error) throw error console.log(`Wrote PDF successfully to ${pdfPath}`) }) }).catch(error => { console.log(`Failed to write PDF to ${pdfPath}: `, error) }) ``` ### Default Changed: renderers without `nodeIntegration: true` are sandboxed by default Previously, renderers that specified a preload script defaulted to being unsandboxed. This meant that by default, preload scripts had access to Node.js. In Electron 20, this default has changed. Beginning in Electron 20, renderers will be sandboxed by default, unless `nodeIntegration: true` or `sandbox: false` is specified. If your preload scripts do not depend on Node, no action is needed. If your preload scripts _do_ depend on Node, either refactor them to remove Node usage from the renderer, or explicitly specify `sandbox: false` for the relevant renderers. ### Removed: `skipTaskbar` on Linux On X11, `skipTaskbar` sends a `_NET_WM_STATE_SKIP_TASKBAR` message to the X11 window manager. There is not a direct equivalent for Wayland, and the known workarounds have unacceptable tradeoffs (e.g. Window.is_skip_taskbar in GNOME requires unsafe mode), so Electron is unable to support this feature on Linux. ### API Changed: `session.setDevicePermissionHandler(handler)` The handler invoked when `session.setDevicePermissionHandler(handler)` is used has a change to its arguments. This handler no longer is passed a frame `[WebFrameMain](api/web-frame-main.md)`, but instead is passed the `origin`, which is the origin that is checking for device permission. ## Planned Breaking API Changes (19.0) None ## Planned Breaking API Changes (18.0) ### Removed: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (17.0) ### Removed: `desktopCapturer.getSources` in the renderer The `desktopCapturer.getSources` API is now only available in the main process. This has been changed in order to improve the default security of Electron apps. If you need this functionality, it can be replaced as follows: ```js // Main process const { ipcMain, desktopCapturer } = require('electron') ipcMain.handle( 'DESKTOP_CAPTURER_GET_SOURCES', (event, opts) => desktopCapturer.getSources(opts) ) ``` ```js // Renderer process const { ipcRenderer } = require('electron') const desktopCapturer = { getSources: (opts) => ipcRenderer.invoke('DESKTOP_CAPTURER_GET_SOURCES', opts) } ``` However, you should consider further restricting the information returned to the renderer; for instance, displaying a source selector to the user and only returning the selected source. ### Deprecated: `nativeWindowOpen` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. Since Electron 15, `nativeWindowOpen` has been enabled by default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (16.0) ### Behavior Changed: `crashReporter` implementation switched to Crashpad on Linux The underlying implementation of the `crashReporter` API on Linux has changed from Breakpad to Crashpad, bringing it in line with Windows and Mac. As a result of this, child processes are now automatically monitored, and calling `process.crashReporter.start` in Node child processes is no longer needed (and is not advisable, as it will start a second instance of the Crashpad reporter). There are also some subtle changes to how annotations will be reported on Linux, including that long values will no longer be split between annotations appended with `__1`, `__2` and so on, and instead will be truncated at the (new, longer) annotation value limit. ### Deprecated: `desktopCapturer.getSources` in the renderer Usage of the `desktopCapturer.getSources` API in the renderer has been deprecated and will be removed. This change improves the default security of Electron apps. See [here](#removed-desktopcapturergetsources-in-the-renderer) for details on how to replace this API in your app. ## Planned Breaking API Changes (15.0) ### Default Changed: `nativeWindowOpen` defaults to `true` Prior to Electron 15, `window.open` was by default shimmed to use `BrowserWindowProxy`. This meant that `window.open('about:blank')` did not work to open synchronously scriptable child windows, among other incompatibilities. `nativeWindowOpen` is no longer experimental, and is now the default. See the documentation for [window.open in Electron](api/window-open.md) for more details. ## Planned Breaking API Changes (14.0) ### Removed: `remote` module The `remote` module was deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Removed: `app.allowRendererProcessReuse` The `app.allowRendererProcessReuse` property will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Removed: Browser Window Affinity The `affinity` option when constructing a new `BrowserWindow` will be removed as part of our plan to more closely align with Chromium's process model for security, performance and maintainability. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### API Changed: `window.open()` The optional parameter `frameName` will no longer set the title of the window. This now follows the specification described by the [native documentation](https://developer.mozilla.org/en-US/docs/Web/API/Window/open#parameters) under the corresponding parameter `windowName`. If you were using this parameter to set the title of a window, you can instead use [win.setTitle(title)](api/browser-window.md#winsettitletitle). ### Removed: `worldSafeExecuteJavaScript` In Electron 14, `worldSafeExecuteJavaScript` will be removed. There is no alternative, please ensure your code works with this property enabled. It has been enabled by default since Electron 12. You will be affected by this change if you use either `webFrame.executeJavaScript` or `webFrame.executeJavaScriptInIsolatedWorld`. You will need to ensure that values returned by either of those methods are supported by the [Context Bridge API](api/context-bridge.md#parameter--error--return-type-support) as these methods use the same value passing semantics. ### Removed: BrowserWindowConstructorOptions inheriting from parent windows Prior to Electron 14, windows opened with `window.open` would inherit BrowserWindow constructor options such as `transparent` and `resizable` from their parent window. Beginning with Electron 14, this behavior is removed, and windows will not inherit any BrowserWindow constructor options from their parents. Instead, explicitly set options for the new window with `setWindowOpenHandler`: ```js webContents.setWindowOpenHandler((details) => { return { action: 'allow', overrideBrowserWindowOptions: { // ... } } }) ``` ### Removed: `additionalFeatures` The deprecated `additionalFeatures` property in the `new-window` and `did-create-window` events of WebContents has been removed. Since `new-window` uses positional arguments, the argument is still present, but will always be the empty array `[]`. (Though note, the `new-window` event itself is deprecated, and is replaced by `setWindowOpenHandler`.) Bare keys in window features will now present as keys with the value `true` in the options object. ```js // Removed in Electron 14 // Triggered by window.open('...', '', 'my-key') webContents.on('did-create-window', (window, details) => { if (details.additionalFeatures.includes('my-key')) { // ... } }) // Replace with webContents.on('did-create-window', (window, details) => { if (details.options['my-key']) { // ... } }) ``` ## Planned Breaking API Changes (13.0) ### API Changed: `session.setPermissionCheckHandler(handler)` The `handler` methods first parameter was previously always a `webContents`, it can now sometimes be `null`. You should use the `requestingOrigin`, `embeddingOrigin` and `securityOrigin` properties to respond to the permission check correctly. As the `webContents` can be `null` it can no longer be relied on. ```js // Old code session.setPermissionCheckHandler((webContents, permission) => { if (webContents.getURL().startsWith('https://google.com/') && permission === 'notification') { return true } return false }) // Replace with session.setPermissionCheckHandler((webContents, permission, requestingOrigin) => { if (new URL(requestingOrigin).hostname === 'google.com' && permission === 'notification') { return true } return false }) ``` ### Removed: `shell.moveItemToTrash()` The deprecated synchronous `shell.moveItemToTrash()` API has been removed. Use the asynchronous `shell.trashItem()` instead. ```js // Removed in Electron 13 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ### Removed: `BrowserWindow` extension APIs The deprecated extension APIs have been removed: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Removed in Electron 13 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Removed in Electron 13 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Removed in Electron 13 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Removed in Electron 13 systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Removed in Electron 13 systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Removed in Electron 13 systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ### Deprecated: WebContents `new-window` event The `new-window` event of WebContents has been deprecated. It is replaced by [`webContents.setWindowOpenHandler()`](api/web-contents.md#contentssetwindowopenhandlerhandler). ```js // Deprecated in Electron 13 webContents.on('new-window', (event) => { event.preventDefault() }) // Replace with webContents.setWindowOpenHandler((details) => { return { action: 'deny' } }) ``` ## Planned Breaking API Changes (12.0) ### Removed: Pepper Flash support Chromium has removed support for Flash, and so we must follow suit. See Chromium's [Flash Roadmap](https://www.chromium.org/flash-roadmap) for more details. ### Default Changed: `worldSafeExecuteJavaScript` defaults to `true` In Electron 12, `worldSafeExecuteJavaScript` will be enabled by default. To restore the previous behavior, `worldSafeExecuteJavaScript: false` must be specified in WebPreferences. Please note that setting this option to `false` is **insecure**. This option will be removed in Electron 14 so please migrate your code to support the default value. ### Default Changed: `contextIsolation` defaults to `true` In Electron 12, `contextIsolation` will be enabled by default. To restore the previous behavior, `contextIsolation: false` must be specified in WebPreferences. We [recommend having contextIsolation enabled](tutorial/security.md#3-enable-context-isolation) for the security of your application. Another implication is that `require()` cannot be used in the renderer process unless `nodeIntegration` is `true` and `contextIsolation` is `false`. For more details see: https://github.com/electron/electron/issues/23506 ### Removed: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been removed. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Removed in Electron 12 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Removed: `crashReporter` methods in the renderer process The following `crashReporter` methods are no longer available in the renderer process: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` They should be called only from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Default Changed: `crashReporter.start({ compress: true })` The default value of the `compress` option to `crashReporter.start` has changed from `false` to `true`. This means that crash dumps will be uploaded to the crash ingestion server with the `Content-Encoding: gzip` header, and the body will be compressed. If your crash ingestion server does not support compressed payloads, you can turn off compression by specifying `{ compress: false }` in the crash reporter options. ### Deprecated: `remote` module The `remote` module is deprecated in Electron 12, and will be removed in Electron 14. It is replaced by the [`@electron/remote`](https://github.com/electron/remote) module. ```js // Deprecated in Electron 12: const { BrowserWindow } = require('electron').remote ``` ```js // Replace with: const { BrowserWindow } = require('@electron/remote') // In the main process: require('@electron/remote/main').initialize() ``` ### Deprecated: `shell.moveItemToTrash()` The synchronous `shell.moveItemToTrash()` has been replaced by the new, asynchronous `shell.trashItem()`. ```js // Deprecated in Electron 12 shell.moveItemToTrash(path) // Replace with shell.trashItem(path).then(/* ... */) ``` ## Planned Breaking API Changes (11.0) ### Removed: `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` and `id` property of `BrowserView` The experimental APIs `BrowserView.{destroy, fromId, fromWebContents, getAllViews}` have now been removed. Additionally, the `id` property of `BrowserView` has also been removed. For more detailed information, see [#23578](https://github.com/electron/electron/pull/23578). ## Planned Breaking API Changes (10.0) ### Deprecated: `companyName` argument to `crashReporter.start()` The `companyName` argument to `crashReporter.start()`, which was previously required, is now optional, and further, is deprecated. To get the same behavior in a non-deprecated way, you can pass a `companyName` value in `globalExtra`. ```js // Deprecated in Electron 10 crashReporter.start({ companyName: 'Umbrella Corporation' }) // Replace with crashReporter.start({ globalExtra: { _companyName: 'Umbrella Corporation' } }) ``` ### Deprecated: `crashReporter.getCrashesDirectory()` The `crashReporter.getCrashesDirectory` method has been deprecated. Usage should be replaced by `app.getPath('crashDumps')`. ```js // Deprecated in Electron 10 crashReporter.getCrashesDirectory() // Replace with app.getPath('crashDumps') ``` ### Deprecated: `crashReporter` methods in the renderer process Calling the following `crashReporter` methods from the renderer process is deprecated: * `crashReporter.start` * `crashReporter.getLastCrashReport` * `crashReporter.getUploadedReports` * `crashReporter.getUploadToServer` * `crashReporter.setUploadToServer` * `crashReporter.getCrashesDirectory` The only non-deprecated methods remaining in the `crashReporter` module in the renderer are `addExtraParameter`, `removeExtraParameter` and `getParameters`. All above methods remain non-deprecated when called from the main process. See [#23265](https://github.com/electron/electron/pull/23265) for more details. ### Deprecated: `crashReporter.start({ compress: false })` Setting `{ compress: false }` in `crashReporter.start` is deprecated. Nearly all crash ingestion servers support gzip compression. This option will be removed in a future version of Electron. ### Default Changed: `enableRemoteModule` defaults to `false` In Electron 9, using the remote module without explicitly enabling it via the `enableRemoteModule` WebPreferences option began emitting a warning. In Electron 10, the remote module is now disabled by default. To use the remote module, `enableRemoteModule: true` must be specified in WebPreferences: ```js const w = new BrowserWindow({ webPreferences: { enableRemoteModule: true } }) ``` We [recommend moving away from the remote module](https://medium.com/@nornagon/electrons-remote-module-considered-harmful-70d69500f31). ### `protocol.unregisterProtocol` ### `protocol.uninterceptProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.unregisterProtocol(scheme, () => { /* ... */ }) // Replace with protocol.unregisterProtocol(scheme) ``` ### `protocol.registerFileProtocol` ### `protocol.registerBufferProtocol` ### `protocol.registerStringProtocol` ### `protocol.registerHttpProtocol` ### `protocol.registerStreamProtocol` ### `protocol.interceptFileProtocol` ### `protocol.interceptStringProtocol` ### `protocol.interceptBufferProtocol` ### `protocol.interceptHttpProtocol` ### `protocol.interceptStreamProtocol` The APIs are now synchronous and the optional callback is no longer needed. ```javascript // Deprecated protocol.registerFileProtocol(scheme, handler, () => { /* ... */ }) // Replace with protocol.registerFileProtocol(scheme, handler) ``` The registered or intercepted protocol does not have effect on current page until navigation happens. ### `protocol.isProtocolHandled` This API is deprecated and users should use `protocol.isProtocolRegistered` and `protocol.isProtocolIntercepted` instead. ```javascript // Deprecated protocol.isProtocolHandled(scheme).then(() => { /* ... */ }) // Replace with const isRegistered = protocol.isProtocolRegistered(scheme) const isIntercepted = protocol.isProtocolIntercepted(scheme) ``` ## Planned Breaking API Changes (9.0) ### Default Changed: Loading non-context-aware native modules in the renderer process is disabled by default As of Electron 9 we do not allow loading of non-context-aware native modules in the renderer process. This is to improve security, performance and maintainability of Electron as a project. If this impacts you, you can temporarily set `app.allowRendererProcessReuse` to `false` to revert to the old behavior. This flag will only be an option until Electron 11 so you should plan to update your native modules to be context aware. For more detailed information see [#18397](https://github.com/electron/electron/issues/18397). ### Deprecated: `BrowserWindow` extension APIs The following extension APIs have been deprecated: * `BrowserWindow.addExtension(path)` * `BrowserWindow.addDevToolsExtension(path)` * `BrowserWindow.removeExtension(name)` * `BrowserWindow.removeDevToolsExtension(name)` * `BrowserWindow.getExtensions()` * `BrowserWindow.getDevToolsExtensions()` Use the session APIs instead: * `ses.loadExtension(path)` * `ses.removeExtension(extension_id)` * `ses.getAllExtensions()` ```js // Deprecated in Electron 9 BrowserWindow.addExtension(path) BrowserWindow.addDevToolsExtension(path) // Replace with session.defaultSession.loadExtension(path) ``` ```js // Deprecated in Electron 9 BrowserWindow.removeExtension(name) BrowserWindow.removeDevToolsExtension(name) // Replace with session.defaultSession.removeExtension(extension_id) ``` ```js // Deprecated in Electron 9 BrowserWindow.getExtensions() BrowserWindow.getDevToolsExtensions() // Replace with session.defaultSession.getAllExtensions() ``` ### Removed: `<webview>.getWebContents()` This API, which was deprecated in Electron 8.0, is now removed. ```js // Removed in Electron 9.0 webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` ### Removed: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function was deprecated in Electron 8.x, and has been removed in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Behavior Changed: Sending non-JS objects over IPC now throws an exception In Electron 8.0, IPC was changed to use the Structured Clone Algorithm, bringing significant performance improvements. To help ease the transition, the old IPC serialization algorithm was kept and used for some objects that aren't serializable with Structured Clone. In particular, DOM objects (e.g. `Element`, `Location` and `DOMMatrix`), Node.js objects backed by C++ classes (e.g. `process.env`, some members of `Stream`), and Electron objects backed by C++ classes (e.g. `WebContents`, `BrowserWindow` and `WebFrame`) are not serializable with Structured Clone. Whenever the old algorithm was invoked, a deprecation warning was printed. In Electron 9.0, the old serialization algorithm has been removed, and sending such non-serializable objects will now throw an "object could not be cloned" error. ### API Changed: `shell.openItem` is now `shell.openPath` The `shell.openItem` API has been replaced with an asynchronous `shell.openPath` API. You can see the original API proposal and reasoning [here](https://github.com/electron/governance/blob/main/wg-api/spec-documents/shell-openitem.md). ## Planned Breaking API Changes (8.0) ### Behavior Changed: Values sent over IPC are now serialized with Structured Clone Algorithm The algorithm used to serialize objects sent over IPC (through `ipcRenderer.send`, `ipcRenderer.sendSync`, `WebContents.send` and related methods) has been switched from a custom algorithm to V8's built-in [Structured Clone Algorithm][SCA], the same algorithm used to serialize messages for `postMessage`. This brings about a 2x performance improvement for large messages, but also brings some breaking changes in behavior. * Sending Functions, Promises, WeakMaps, WeakSets, or objects containing any such values, over IPC will now throw an exception, instead of silently converting the functions to `undefined`. ```js // Previously: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => results in { value: 3 } arriving in the main process // From Electron 8: ipcRenderer.send('channel', { value: 3, someFunction: () => {} }) // => throws Error("() => {} could not be cloned.") ``` * `NaN`, `Infinity` and `-Infinity` will now be correctly serialized, instead of being converted to `null`. * Objects containing cyclic references will now be correctly serialized, instead of being converted to `null`. * `Set`, `Map`, `Error` and `RegExp` values will be correctly serialized, instead of being converted to `{}`. * `BigInt` values will be correctly serialized, instead of being converted to `null`. * Sparse arrays will be serialized as such, instead of being converted to dense arrays with `null`s. * `Date` objects will be transferred as `Date` objects, instead of being converted to their ISO string representation. * Typed Arrays (such as `Uint8Array`, `Uint16Array`, `Uint32Array` and so on) will be transferred as such, instead of being converted to Node.js `Buffer`. * Node.js `Buffer` objects will be transferred as `Uint8Array`s. You can convert a `Uint8Array` back to a Node.js `Buffer` by wrapping the underlying `ArrayBuffer`: ```js Buffer.from(value.buffer, value.byteOffset, value.byteLength) ``` Sending any objects that aren't native JS types, such as DOM objects (e.g. `Element`, `Location`, `DOMMatrix`), Node.js objects (e.g. `process.env`, `Stream`), or Electron objects (e.g. `WebContents`, `BrowserWindow`, `WebFrame`) is deprecated. In Electron 8, these objects will be serialized as before with a DeprecationWarning message, but starting in Electron 9, sending these kinds of objects will throw a 'could not be cloned' error. [SCA]: https://developer.mozilla.org/en-US/docs/Web/API/Web_Workers_API/Structured_clone_algorithm ### Deprecated: `<webview>.getWebContents()` This API is implemented using the `remote` module, which has both performance and security implications. Therefore its usage should be explicit. ```js // Deprecated webview.getWebContents() // Replace with const { remote } = require('electron') remote.webContents.fromId(webview.getWebContentsId()) ``` However, it is recommended to avoid using the `remote` module altogether. ```js // main const { ipcMain, webContents } = require('electron') const getGuestForWebContents = (webContentsId, contents) => { const guest = webContents.fromId(webContentsId) if (!guest) { throw new Error(`Invalid webContentsId: ${webContentsId}`) } if (guest.hostWebContents !== contents) { throw new Error('Access denied to webContents') } return guest } ipcMain.handle('openDevTools', (event, webContentsId) => { const guest = getGuestForWebContents(webContentsId, event.sender) guest.openDevTools() }) // renderer const { ipcRenderer } = require('electron') ipcRenderer.invoke('openDevTools', webview.getWebContentsId()) ``` ### Deprecated: `webFrame.setLayoutZoomLevelLimits()` Chromium has removed support for changing the layout zoom level limits, and it is beyond Electron's capacity to maintain it. The function will emit a warning in Electron 8.x, and cease to exist in Electron 9.x. The layout zoom level limits are now fixed at a minimum of 0.25 and a maximum of 5.0, as defined [here](https://chromium.googlesource.com/chromium/src/+/938b37a6d2886bf8335fc7db792f1eb46c65b2ae/third_party/blink/common/page/page_zoom.cc#11). ### Deprecated events in `systemPreferences` The following `systemPreferences` events have been deprecated: * `inverted-color-scheme-changed` * `high-contrast-color-scheme-changed` Use the new `updated` event on the `nativeTheme` module instead. ```js // Deprecated systemPreferences.on('inverted-color-scheme-changed', () => { /* ... */ }) systemPreferences.on('high-contrast-color-scheme-changed', () => { /* ... */ }) // Replace with nativeTheme.on('updated', () => { /* ... */ }) ``` ### Deprecated: methods in `systemPreferences` The following `systemPreferences` methods have been deprecated: * `systemPreferences.isDarkMode()` * `systemPreferences.isInvertedColorScheme()` * `systemPreferences.isHighContrastColorScheme()` Use the following `nativeTheme` properties instead: * `nativeTheme.shouldUseDarkColors` * `nativeTheme.shouldUseInvertedColorScheme` * `nativeTheme.shouldUseHighContrastColors` ```js // Deprecated systemPreferences.isDarkMode() // Replace with nativeTheme.shouldUseDarkColors // Deprecated systemPreferences.isInvertedColorScheme() // Replace with nativeTheme.shouldUseInvertedColorScheme // Deprecated systemPreferences.isHighContrastColorScheme() // Replace with nativeTheme.shouldUseHighContrastColors ``` ## Planned Breaking API Changes (7.0) ### Deprecated: Atom.io Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Both will be supported for the foreseeable future but it is recommended that you switch. Deprecated: https://atom.io/download/electron Replace with: https://electronjs.org/headers ### API Changed: `session.clearAuthCache()` no longer accepts options The `session.clearAuthCache` API no longer accepts options for what to clear, and instead unconditionally clears the whole cache. ```js // Deprecated session.clearAuthCache({ type: 'password' }) // Replace with session.clearAuthCache() ``` ### API Changed: `powerMonitor.querySystemIdleState` is now `powerMonitor.getSystemIdleState` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### API Changed: `powerMonitor.querySystemIdleTime` is now `powerMonitor.getSystemIdleTime` ```js // Removed in Electron 7.0 powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### API Changed: `webFrame.setIsolatedWorldInfo` replaces separate methods ```js // Removed in Electron 7.0 webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### Removed: `marked` property on `getBlinkMemoryInfo` This property was removed in Chromium 77, and as such is no longer available. ### Behavior Changed: `webkitdirectory` attribute for `<input type="file"/>` now lists directory contents The `webkitdirectory` property on HTML file inputs allows them to select folders. Previous versions of Electron had an incorrect implementation where the `event.target.files` of the input returned a `FileList` that returned one `File` corresponding to the selected folder. As of Electron 7, that `FileList` is now list of all files contained within the folder, similarly to Chrome, Firefox, and Edge ([link to MDN docs](https://developer.mozilla.org/en-US/docs/Web/API/HTMLInputElement/webkitdirectory)). As an illustration, take a folder with this structure: ```console folder ├── file1 ├── file2 └── file3 ``` In Electron <=6, this would return a `FileList` with a `File` object for: ```console path/to/folder ``` In Electron 7, this now returns a `FileList` with a `File` object for: ```console /path/to/folder/file3 /path/to/folder/file2 /path/to/folder/file1 ``` Note that `webkitdirectory` no longer exposes the path to the selected folder. If you require the path to the selected folder rather than the folder contents, see the `dialog.showOpenDialog` API ([link](api/dialog.md#dialogshowopendialogbrowserwindow-options)). ### API Changed: Callback-based versions of promisified APIs Electron 5 and Electron 6 introduced Promise-based versions of existing asynchronous APIs and deprecated their older, callback-based counterparts. In Electron 7, all deprecated callback-based APIs are now removed. These functions now only return Promises: * `app.getFileIcon()` [#15742](https://github.com/electron/electron/pull/15742) * `app.dock.show()` [#16904](https://github.com/electron/electron/pull/16904) * `contentTracing.getCategories()` [#16583](https://github.com/electron/electron/pull/16583) * `contentTracing.getTraceBufferUsage()` [#16600](https://github.com/electron/electron/pull/16600) * `contentTracing.startRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contentTracing.stopRecording()` [#16584](https://github.com/electron/electron/pull/16584) * `contents.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `cookies.flushStore()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.get()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.remove()` [#16464](https://github.com/electron/electron/pull/16464) * `cookies.set()` [#16464](https://github.com/electron/electron/pull/16464) * `debugger.sendCommand()` [#16861](https://github.com/electron/electron/pull/16861) * `dialog.showCertificateTrustDialog()` [#17181](https://github.com/electron/electron/pull/17181) * `inAppPurchase.getProducts()` [#17355](https://github.com/electron/electron/pull/17355) * `inAppPurchase.purchaseProduct()`[#17355](https://github.com/electron/electron/pull/17355) * `netLog.stopLogging()` [#16862](https://github.com/electron/electron/pull/16862) * `session.clearAuthCache()` [#17259](https://github.com/electron/electron/pull/17259) * `session.clearCache()` [#17185](https://github.com/electron/electron/pull/17185) * `session.clearHostResolverCache()` [#17229](https://github.com/electron/electron/pull/17229) * `session.clearStorageData()` [#17249](https://github.com/electron/electron/pull/17249) * `session.getBlobData()` [#17303](https://github.com/electron/electron/pull/17303) * `session.getCacheSize()` [#17185](https://github.com/electron/electron/pull/17185) * `session.resolveProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `session.setProxy()` [#17222](https://github.com/electron/electron/pull/17222) * `shell.openExternal()` [#16176](https://github.com/electron/electron/pull/16176) * `webContents.loadFile()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.loadURL()` [#15855](https://github.com/electron/electron/pull/15855) * `webContents.hasServiceWorker()` [#16535](https://github.com/electron/electron/pull/16535) * `webContents.printToPDF()` [#16795](https://github.com/electron/electron/pull/16795) * `webContents.savePage()` [#16742](https://github.com/electron/electron/pull/16742) * `webFrame.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `webFrame.executeJavaScriptInIsolatedWorld()` [#17312](https://github.com/electron/electron/pull/17312) * `webviewTag.executeJavaScript()` [#17312](https://github.com/electron/electron/pull/17312) * `win.capturePage()` [#15743](https://github.com/electron/electron/pull/15743) These functions now have two forms, synchronous and Promise-based asynchronous: * `dialog.showMessageBox()`/`dialog.showMessageBoxSync()` [#17298](https://github.com/electron/electron/pull/17298) * `dialog.showOpenDialog()`/`dialog.showOpenDialogSync()` [#16973](https://github.com/electron/electron/pull/16973) * `dialog.showSaveDialog()`/`dialog.showSaveDialogSync()` [#17054](https://github.com/electron/electron/pull/17054) ## Planned Breaking API Changes (6.0) ### API Changed: `win.setMenu(null)` is now `win.removeMenu()` ```js // Deprecated win.setMenu(null) // Replace with win.removeMenu() ``` ### API Changed: `electron.screen` in the renderer process should be accessed via `remote` ```js // Deprecated require('electron').screen // Replace with require('electron').remote.screen ``` ### API Changed: `require()`ing node builtins in sandboxed renderers no longer implicitly loads the `remote` version ```js // Deprecated require('child_process') // Replace with require('electron').remote.require('child_process') // Deprecated require('fs') // Replace with require('electron').remote.require('fs') // Deprecated require('os') // Replace with require('electron').remote.require('os') // Deprecated require('path') // Replace with require('electron').remote.require('path') ``` ### Deprecated: `powerMonitor.querySystemIdleState` replaced with `powerMonitor.getSystemIdleState` ```js // Deprecated powerMonitor.querySystemIdleState(threshold, callback) // Replace with synchronous API const idleState = powerMonitor.getSystemIdleState(threshold) ``` ### Deprecated: `powerMonitor.querySystemIdleTime` replaced with `powerMonitor.getSystemIdleTime` ```js // Deprecated powerMonitor.querySystemIdleTime(callback) // Replace with synchronous API const idleTime = powerMonitor.getSystemIdleTime() ``` ### Deprecated: `app.enableMixedSandbox()` is no longer needed ```js // Deprecated app.enableMixedSandbox() ``` Mixed-sandbox mode is now enabled by default. ### Deprecated: `Tray.setHighlightMode` Under macOS Catalina our former Tray implementation breaks. Apple's native substitute doesn't support changing the highlighting behavior. ```js // Deprecated tray.setHighlightMode(mode) // API will be removed in v7.0 without replacement. ``` ## Planned Breaking API Changes (5.0) ### Default Changed: `nodeIntegration` and `webviewTag` default to false, `contextIsolation` defaults to true The following `webPreferences` option default values are deprecated in favor of the new defaults listed below. | Property | Deprecated Default | New Default | |----------|--------------------|-------------| | `contextIsolation` | `false` | `true` | | `nodeIntegration` | `true` | `false` | | `webviewTag` | `nodeIntegration` if set else `true` | `false` | E.g. Re-enabling the webviewTag ```js const w = new BrowserWindow({ webPreferences: { webviewTag: true } }) ``` ### Behavior Changed: `nodeIntegration` in child windows opened via `nativeWindowOpen` Child windows opened with the `nativeWindowOpen` option will always have Node.js integration disabled, unless `nodeIntegrationInSubFrames` is `true`. ### API Changed: Registering privileged schemes must now be done before app ready Renderer process APIs `webFrame.registerURLSchemeAsPrivileged` and `webFrame.registerURLSchemeAsBypassingCSP` as well as browser process API `protocol.registerStandardSchemes` have been removed. A new API, `protocol.registerSchemesAsPrivileged` has been added and should be used for registering custom schemes with the required privileges. Custom schemes are required to be registered before app ready. ### Deprecated: `webFrame.setIsolatedWorld*` replaced with `webFrame.setIsolatedWorldInfo` ```js // Deprecated webFrame.setIsolatedWorldContentSecurityPolicy(worldId, csp) webFrame.setIsolatedWorldHumanReadableName(worldId, name) webFrame.setIsolatedWorldSecurityOrigin(worldId, securityOrigin) // Replace with webFrame.setIsolatedWorldInfo( worldId, { securityOrigin: 'some_origin', name: 'human_readable_name', csp: 'content_security_policy' }) ``` ### API Changed: `webFrame.setSpellCheckProvider` now takes an asynchronous callback The `spellCheck` callback is now asynchronous, and `autoCorrectWord` parameter has been removed. ```js // Deprecated webFrame.setSpellCheckProvider('en-US', true, { spellCheck: (text) => { return !spellchecker.isMisspelled(text) } }) // Replace with webFrame.setSpellCheckProvider('en-US', { spellCheck: (words, callback) => { callback(words.filter(text => spellchecker.isMisspelled(text))) } }) ``` ### API Changed: `webContents.getZoomLevel` and `webContents.getZoomFactor` are now synchronous `webContents.getZoomLevel` and `webContents.getZoomFactor` no longer take callback parameters, instead directly returning their number values. ```js // Deprecated webContents.getZoomLevel((level) => { console.log(level) }) // Replace with const level = webContents.getZoomLevel() console.log(level) ``` ```js // Deprecated webContents.getZoomFactor((factor) => { console.log(factor) }) // Replace with const factor = webContents.getZoomFactor() console.log(factor) ``` ## Planned Breaking API Changes (4.0) The following list includes the breaking API changes made in Electron 4.0. ### `app.makeSingleInstance` ```js // Deprecated app.makeSingleInstance((argv, cwd) => { /* ... */ }) // Replace with app.requestSingleInstanceLock() app.on('second-instance', (event, argv, cwd) => { /* ... */ }) ``` ### `app.releaseSingleInstance` ```js // Deprecated app.releaseSingleInstance() // Replace with app.releaseSingleInstanceLock() ``` ### `app.getGPUInfo` ```js app.getGPUInfo('complete') // Now behaves the same with `basic` on macOS app.getGPUInfo('basic') ``` ### `win_delay_load_hook` When building native modules for windows, the `win_delay_load_hook` variable in the module's `binding.gyp` must be true (which is the default). If this hook is not present, then the native module will fail to load on Windows, with an error message like `Cannot find module`. See the [native module guide](/docs/tutorial/using-native-node-modules.md) for more. ## Breaking API Changes (3.0) The following list includes the breaking API changes in Electron 3.0. ### `app` ```js // Deprecated app.getAppMemoryInfo() // Replace with app.getAppMetrics() // Deprecated const metrics = app.getAppMetrics() const { memory } = metrics[0] // Deprecated property ``` ### `BrowserWindow` ```js // Deprecated const optionsA = { webPreferences: { blinkFeatures: '' } } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { webPreferences: { enableBlinkFeatures: '' } } const windowB = new BrowserWindow(optionsB) // Deprecated window.on('app-command', (e, cmd) => { if (cmd === 'media-play_pause') { // do something } }) // Replace with window.on('app-command', (e, cmd) => { if (cmd === 'media-play-pause') { // do something } }) ``` ### `clipboard` ```js // Deprecated clipboard.readRtf() // Replace with clipboard.readRTF() // Deprecated clipboard.writeRtf() // Replace with clipboard.writeRTF() // Deprecated clipboard.readHtml() // Replace with clipboard.readHTML() // Deprecated clipboard.writeHtml() // Replace with clipboard.writeHTML() ``` ### `crashReporter` ```js // Deprecated crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', autoSubmit: true }) // Replace with crashReporter.start({ companyName: 'Crashly', submitURL: 'https://crash.server.com', uploadToServer: true }) ``` ### `nativeImage` ```js // Deprecated nativeImage.createFromBuffer(buffer, 1.0) // Replace with nativeImage.createFromBuffer(buffer, { scaleFactor: 1.0 }) ``` ### `process` ```js // Deprecated const info = process.getProcessMemoryInfo() ``` ### `screen` ```js // Deprecated screen.getMenuBarHeight() // Replace with screen.getPrimaryDisplay().workArea ``` ### `session` ```js // Deprecated ses.setCertificateVerifyProc((hostname, certificate, callback) => { callback(true) }) // Replace with ses.setCertificateVerifyProc((request, callback) => { callback(0) }) ``` ### `Tray` ```js // Deprecated tray.setHighlightMode(true) // Replace with tray.setHighlightMode('on') // Deprecated tray.setHighlightMode(false) // Replace with tray.setHighlightMode('off') ``` ### `webContents` ```js // Deprecated webContents.openDevTools({ detach: true }) // Replace with webContents.openDevTools({ mode: 'detach' }) // Removed webContents.setSize(options) // There is no replacement for this API ``` ### `webFrame` ```js // Deprecated webFrame.registerURLSchemeAsSecure('app') // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) // Deprecated webFrame.registerURLSchemeAsPrivileged('app', { secure: true }) // Replace with protocol.registerStandardSchemes(['app'], { secure: true }) ``` ### `<webview>` ```js // Removed webview.setAttribute('disableguestresize', '') // There is no replacement for this API // Removed webview.setAttribute('guestinstance', instanceId) // There is no replacement for this API // Keyboard listeners no longer work on webview tag webview.onkeydown = () => { /* handler */ } webview.onkeyup = () => { /* handler */ } ``` ### Node Headers URL This is the URL specified as `disturl` in a `.npmrc` file or as the `--dist-url` command line flag when building native Node modules. Deprecated: https://atom.io/download/atom-shell Replace with: https://atom.io/download/electron ## Breaking API Changes (2.0) The following list includes the breaking API changes made in Electron 2.0. ### `BrowserWindow` ```js // Deprecated const optionsA = { titleBarStyle: 'hidden-inset' } const windowA = new BrowserWindow(optionsA) // Replace with const optionsB = { titleBarStyle: 'hiddenInset' } const windowB = new BrowserWindow(optionsB) ``` ### `menu` ```js // Removed menu.popup(browserWindow, 100, 200, 2) // Replaced with menu.popup(browserWindow, { x: 100, y: 200, positioningItem: 2 }) ``` ### `nativeImage` ```js // Removed nativeImage.toPng() // Replaced with nativeImage.toPNG() // Removed nativeImage.toJpeg() // Replaced with nativeImage.toJPEG() ``` ### `process` * `process.versions.electron` and `process.version.chrome` will be made read-only properties for consistency with the other `process.versions` properties set by Node. ### `webContents` ```js // Removed webContents.setZoomLevelLimits(1, 2) // Replaced with webContents.setVisualZoomLevelLimits(1, 2) ``` ### `webFrame` ```js // Removed webFrame.setZoomLevelLimits(1, 2) // Replaced with webFrame.setVisualZoomLevelLimits(1, 2) ``` ### `<webview>` ```js // Removed webview.setZoomLevelLimits(1, 2) // Replaced with webview.setVisualZoomLevelLimits(1, 2) ``` ### Duplicate ARM Assets Each Electron release includes two identical ARM builds with slightly different filenames, like `electron-v1.7.3-linux-arm.zip` and `electron-v1.7.3-linux-armv7l.zip`. The asset with the `v7l` prefix was added to clarify to users which ARM version it supports, and to disambiguate it from future armv6l and arm64 assets that may be produced. The file _without the prefix_ is still being published to avoid breaking any setups that may be consuming it. Starting at 2.0, the unprefixed file will no longer be published. For details, see [6986](https://github.com/electron/electron/pull/6986) and [7189](https://github.com/electron/electron/pull/7189).
closed
electron/electron
https://github.com/electron/electron
34,763
[Bug]: Overlay's minimize button stays in hovered/focused state after restoring
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version 11 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior When hovering over a "minimize" button in titlebar overlay and clicking it, and then restoring the app - I expect that the button is restored to its original state: ![image](https://user-images.githubusercontent.com/79877362/176010822-fca7de7d-921a-453c-acfe-c45d9e3adc57.png) ### Actual Behavior Instead if I click "minimize" and then restore I see this: ![image](https://user-images.githubusercontent.com/79877362/176010875-c4c0280f-d4b5-4edc-b2b6-16a30261ecdc.png) ### Testcase Gist URL _No response_ ### Additional Information Originally reported in: https://github.com/signalapp/Signal-Desktop/issues/5992
https://github.com/electron/electron/issues/34763
https://github.com/electron/electron/pull/34771
47d8d4cc5c0b945d52cc7c4b21c6cfe749b3df57
7ec88584b50f74b3d596448976781e91ea052e47
2022-06-27T18:30:06Z
c++
2022-07-07T15:17:20Z
shell/browser/native_window_views_win.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <dwmapi.h> #include <shellapi.h> #include <wrl/client.h> #include "base/win/atl.h" // Must be before UIAutomationCore.h #include "content/public/browser/browser_accessibility_state.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/common/electron_constants.h" #include "ui/display/display.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/views/widget/native_widget_private.h" // Must be included after other Windows headers. #include <UIAutomationClient.h> #include <UIAutomationCoreApi.h> namespace electron { namespace { // Convert Win32 WM_APPCOMMANDS to strings. const char* AppCommandToString(int command_id) { switch (command_id) { case APPCOMMAND_BROWSER_BACKWARD: return kBrowserBackward; case APPCOMMAND_BROWSER_FORWARD: return kBrowserForward; case APPCOMMAND_BROWSER_REFRESH: return "browser-refresh"; case APPCOMMAND_BROWSER_STOP: return "browser-stop"; case APPCOMMAND_BROWSER_SEARCH: return "browser-search"; case APPCOMMAND_BROWSER_FAVORITES: return "browser-favorites"; case APPCOMMAND_BROWSER_HOME: return "browser-home"; case APPCOMMAND_VOLUME_MUTE: return "volume-mute"; case APPCOMMAND_VOLUME_DOWN: return "volume-down"; case APPCOMMAND_VOLUME_UP: return "volume-up"; case APPCOMMAND_MEDIA_NEXTTRACK: return "media-nexttrack"; case APPCOMMAND_MEDIA_PREVIOUSTRACK: return "media-previoustrack"; case APPCOMMAND_MEDIA_STOP: return "media-stop"; case APPCOMMAND_MEDIA_PLAY_PAUSE: return "media-play-pause"; case APPCOMMAND_LAUNCH_MAIL: return "launch-mail"; case APPCOMMAND_LAUNCH_MEDIA_SELECT: return "launch-media-select"; case APPCOMMAND_LAUNCH_APP1: return "launch-app1"; case APPCOMMAND_LAUNCH_APP2: return "launch-app2"; case APPCOMMAND_BASS_DOWN: return "bass-down"; case APPCOMMAND_BASS_BOOST: return "bass-boost"; case APPCOMMAND_BASS_UP: return "bass-up"; case APPCOMMAND_TREBLE_DOWN: return "treble-down"; case APPCOMMAND_TREBLE_UP: return "treble-up"; case APPCOMMAND_MICROPHONE_VOLUME_MUTE: return "microphone-volume-mute"; case APPCOMMAND_MICROPHONE_VOLUME_DOWN: return "microphone-volume-down"; case APPCOMMAND_MICROPHONE_VOLUME_UP: return "microphone-volume-up"; case APPCOMMAND_HELP: return "help"; case APPCOMMAND_FIND: return "find"; case APPCOMMAND_NEW: return "new"; case APPCOMMAND_OPEN: return "open"; case APPCOMMAND_CLOSE: return "close"; case APPCOMMAND_SAVE: return "save"; case APPCOMMAND_PRINT: return "print"; case APPCOMMAND_UNDO: return "undo"; case APPCOMMAND_REDO: return "redo"; case APPCOMMAND_COPY: return "copy"; case APPCOMMAND_CUT: return "cut"; case APPCOMMAND_PASTE: return "paste"; case APPCOMMAND_REPLY_TO_MAIL: return "reply-to-mail"; case APPCOMMAND_FORWARD_MAIL: return "forward-mail"; case APPCOMMAND_SEND_MAIL: return "send-mail"; case APPCOMMAND_SPELL_CHECK: return "spell-check"; case APPCOMMAND_MIC_ON_OFF_TOGGLE: return "mic-on-off-toggle"; case APPCOMMAND_CORRECTION_LIST: return "correction-list"; case APPCOMMAND_MEDIA_PLAY: return "media-play"; case APPCOMMAND_MEDIA_PAUSE: return "media-pause"; case APPCOMMAND_MEDIA_RECORD: return "media-record"; case APPCOMMAND_MEDIA_FAST_FORWARD: return "media-fast-forward"; case APPCOMMAND_MEDIA_REWIND: return "media-rewind"; case APPCOMMAND_MEDIA_CHANNEL_UP: return "media-channel-up"; case APPCOMMAND_MEDIA_CHANNEL_DOWN: return "media-channel-down"; case APPCOMMAND_DELETE: return "delete"; case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: return "dictate-or-command-control-toggle"; default: return "unknown"; } } // Copied from ui/views/win/hwnd_message_handler.cc gfx::ResizeEdge GetWindowResizeEdge(WPARAM param) { switch (param) { case WMSZ_BOTTOM: return gfx::ResizeEdge::kBottom; case WMSZ_TOP: return gfx::ResizeEdge::kTop; case WMSZ_LEFT: return gfx::ResizeEdge::kLeft; case WMSZ_RIGHT: return gfx::ResizeEdge::kRight; case WMSZ_TOPLEFT: return gfx::ResizeEdge::kTopLeft; case WMSZ_TOPRIGHT: return gfx::ResizeEdge::kTopRight; case WMSZ_BOTTOMLEFT: return gfx::ResizeEdge::kBottomLeft; case WMSZ_BOTTOMRIGHT: return gfx::ResizeEdge::kBottomRight; default: return gfx::ResizeEdge::kBottomRight; } } bool IsScreenReaderActive() { UINT screenReader = 0; SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); return screenReader && UiaClientsAreListening(); } } // namespace std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_; HHOOK NativeWindowViews::mouse_hook_ = NULL; void NativeWindowViews::Maximize() { // Only use Maximize() when window is NOT transparent style if (!transparent()) { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } else { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); SetBounds(display.work_area(), false); NotifyWindowMaximize(); } } bool NativeWindowViews::ExecuteWindowsCommand(int command_id) { std::string command = AppCommandToString(command_id); NotifyWindowExecuteAppCommand(command); return false; } bool NativeWindowViews::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { NotifyWindowMessage(message, w_param, l_param); // Avoid side effects when calling SetWindowPlacement. if (is_setting_window_placement_) { // Let Chromium handle the WM_NCCALCSIZE message otherwise the window size // would be wrong. // See https://github.com/electron/electron/issues/22393 for more. if (message == WM_NCCALCSIZE) return false; // Otherwise handle the message with default proc, *result = DefWindowProc(GetAcceleratedWidget(), message, w_param, l_param); // and tell Chromium to ignore this message. return true; } switch (message) { // Screen readers send WM_GETOBJECT in order to get the accessibility // object, so take this opportunity to push Chromium into accessible // mode if it isn't already, always say we didn't handle the message // because we still want Chromium to handle returning the actual // accessibility object. case WM_GETOBJECT: { if (checked_for_a11y_support_) return false; const DWORD obj_id = static_cast<DWORD>(l_param); if (obj_id != static_cast<DWORD>(OBJID_CLIENT)) { return false; } if (!IsScreenReaderActive()) { return false; } checked_for_a11y_support_ = true; auto* const axState = content::BrowserAccessibilityState::GetInstance(); if (axState && !axState->IsAccessibleBrowser()) { axState->OnScreenReaderDetected(); Browser::Get()->OnAccessibilitySupportChanged(); } return false; } case WM_GETMINMAXINFO: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); // We do this to work around a Windows bug, where the minimized Window // would report that the closest display to it is not the one that it was // previously on (but the leftmost one instead). We restore the position // of the window during the restore operation, this way chromium can // use the proper display to calculate the scale factor to use. if (!last_normal_placement_bounds_.IsEmpty() && (IsVisible() || IsMinimized()) && GetWindowPlacement(GetAcceleratedWidget(), &wp)) { wp.rcNormalPosition = last_normal_placement_bounds_.ToRECT(); // When calling SetWindowPlacement, Chromium would do window messages // handling. But since we are already in PreHandleMSG this would cause // crash in Chromium under some cases. // // We work around the crash by prevent Chromium from handling window // messages until the SetWindowPlacement call is done. // // See https://github.com/electron/electron/issues/21614 for more. is_setting_window_placement_ = true; SetWindowPlacement(GetAcceleratedWidget(), &wp); is_setting_window_placement_ = false; last_normal_placement_bounds_ = gfx::Rect(); } return false; } case WM_COMMAND: // Handle thumbar button click message. if (HIWORD(w_param) == THBN_CLICKED) return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param)); return false; case WM_SIZING: { is_resizing_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillResize(dpi_bounds, GetWindowResizeEdge(w_param), &prevent_default); if (prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); pending_bounds_change_.reset(); return true; // Tells Windows that the Sizing is handled. } return false; } case WM_SIZE: { // Handle window state change. HandleSizeEvent(w_param, l_param); return false; } case WM_EXITSIZEMOVE: { if (is_resizing_) { NotifyWindowResized(); is_resizing_ = false; } if (is_moving_) { NotifyWindowMoved(); is_moving_ = false; } // If the user dragged or moved the window during one or more // calls to window.setBounds(), we want to apply the most recent // one once they are done with the move or resize operation. if (pending_bounds_change_.has_value()) { SetBounds(pending_bounds_change_.value(), false /* animate */); pending_bounds_change_.reset(); } return false; } case WM_MOVING: { is_moving_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillMove(dpi_bounds, &prevent_default); if (!movable_ || prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); pending_bounds_change_.reset(); return true; // Tells Windows that the Move is handled. If not true, // frameless windows can be moved using // -webkit-app-region: drag elements. } return false; } case WM_ENDSESSION: { if (w_param) { NotifyWindowEndSession(); } return false; } case WM_PARENTNOTIFY: { if (LOWORD(w_param) == WM_CREATE) { // Because of reasons regarding legacy drivers and stuff, a window that // matches the client area is created and used internally by Chromium. // This is used when forwarding mouse messages. We only cache the first // occurrence (the webview window) because dev tools also cause this // message to be sent. if (!legacy_window_) { legacy_window_ = reinterpret_cast<HWND>(l_param); } } return false; } case WM_CONTEXTMENU: { bool prevent_default = false; NotifyWindowSystemContextMenu(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param), &prevent_default); return prevent_default; } case WM_SYSCOMMAND: { // Mask is needed to account for double clicking title bar to maximize WPARAM max_mask = 0xFFF0; if (transparent() && ((w_param & max_mask) == SC_MAXIMIZE)) { return true; } return false; } case WM_INITMENU: { // This is handling the scenario where the menu might get triggered by the // user doing "alt + space" resulting in system maximization and restore // being used on transparent windows when that does not work. if (transparent()) { HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); return true; } return false; } default: { return false; } } } void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { // Here we handle the WM_SIZE event in order to figure out what is the current // window state and notify the user accordingly. switch (w_param) { case SIZE_MAXIMIZED: case SIZE_MINIMIZED: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(GetAcceleratedWidget(), &wp)) { last_normal_placement_bounds_ = gfx::Rect(wp.rcNormalPosition); } // Note that SIZE_MAXIMIZED and SIZE_MINIMIZED might be emitted for // multiple times for one resize because of the SetWindowPlacement call. if (w_param == SIZE_MAXIMIZED && last_window_state_ != ui::SHOW_STATE_MAXIMIZED) { last_window_state_ = ui::SHOW_STATE_MAXIMIZED; NotifyWindowMaximize(); } else if (w_param == SIZE_MINIMIZED && last_window_state_ != ui::SHOW_STATE_MINIMIZED) { last_window_state_ = ui::SHOW_STATE_MINIMIZED; NotifyWindowMinimize(); } break; } case SIZE_RESTORED: switch (last_window_state_) { case ui::SHOW_STATE_MAXIMIZED: last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowUnmaximize(); break; case ui::SHOW_STATE_MINIMIZED: if (IsFullscreen()) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowRestore(); } break; default: break; } break; } } void NativeWindowViews::SetForwardMouseMessages(bool forward) { if (forward && !forwarding_mouse_messages_) { forwarding_mouse_messages_ = true; forwarding_windows_.insert(this); // Subclassing is used to fix some issues when forwarding mouse messages; // see comments in |SubclassProc|. SetWindowSubclass(legacy_window_, SubclassProc, 1, reinterpret_cast<DWORD_PTR>(this)); if (!mouse_hook_) { mouse_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0); } } else if (!forward && forwarding_mouse_messages_) { forwarding_mouse_messages_ = false; forwarding_windows_.erase(this); RemoveWindowSubclass(legacy_window_, SubclassProc, 1); if (forwarding_windows_.empty()) { UnhookWindowsHookEx(mouse_hook_); mouse_hook_ = NULL; } } } LRESULT CALLBACK NativeWindowViews::SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data) { auto* window = reinterpret_cast<NativeWindowViews*>(ref_data); switch (msg) { case WM_MOUSELEAVE: { // When input is forwarded to underlying windows, this message is posted. // If not handled, it interferes with Chromium logic, causing for example // mouseleave events to fire. If those events are used to exit forward // mode, excessive flickering on for example hover items in underlying // windows can occur due to rapidly entering and leaving forwarding mode. // By consuming and ignoring the message, we're essentially telling // Chromium that we have not left the window despite somebody else getting // the messages. As to why this is caught for the legacy window and not // the actual browser window is simply that the legacy window somehow // makes use of these events; posting to the main window didn't work. if (window->forwarding_mouse_messages_) { return 0; } break; } } return DefSubclassProc(hwnd, msg, w_param, l_param); } LRESULT CALLBACK NativeWindowViews::MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param) { if (n_code < 0) { return CallNextHookEx(NULL, n_code, w_param, l_param); } // Post a WM_MOUSEMOVE message for those windows whose client area contains // the cursor since they are in a state where they would otherwise ignore all // mouse input. if (w_param == WM_MOUSEMOVE) { for (auto* window : forwarding_windows_) { // At first I considered enumerating windows to check whether the cursor // was directly above the window, but since nothing bad seems to happen // if we post the message even if some other window occludes it I have // just left it as is. RECT client_rect; GetClientRect(window->legacy_window_, &client_rect); POINT p = reinterpret_cast<MSLLHOOKSTRUCT*>(l_param)->pt; ScreenToClient(window->legacy_window_, &p); if (PtInRect(&client_rect, p)) { WPARAM w = 0; // No virtual keys pressed for our purposes LPARAM l = MAKELPARAM(p.x, p.y); PostMessage(window->legacy_window_, WM_MOUSEMOVE, w, l); } } } return CallNextHookEx(NULL, n_code, w_param, l_param); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,763
[Bug]: Overlay's minimize button stays in hovered/focused state after restoring
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version 11 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior When hovering over a "minimize" button in titlebar overlay and clicking it, and then restoring the app - I expect that the button is restored to its original state: ![image](https://user-images.githubusercontent.com/79877362/176010822-fca7de7d-921a-453c-acfe-c45d9e3adc57.png) ### Actual Behavior Instead if I click "minimize" and then restore I see this: ![image](https://user-images.githubusercontent.com/79877362/176010875-c4c0280f-d4b5-4edc-b2b6-16a30261ecdc.png) ### Testcase Gist URL _No response_ ### Additional Information Originally reported in: https://github.com/signalapp/Signal-Desktop/issues/5992
https://github.com/electron/electron/issues/34763
https://github.com/electron/electron/pull/34771
47d8d4cc5c0b945d52cc7c4b21c6cfe749b3df57
7ec88584b50f74b3d596448976781e91ea052e47
2022-06-27T18:30:06Z
c++
2022-07-07T15:17:20Z
shell/browser/ui/views/win_caption_button_container.h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Modified from // chrome/browser/ui/views/frame/glass_browser_caption_button_container.h #ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_ #define ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_ #include "base/scoped_observation.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/base/pointer/touch_ui_controller.h" #include "ui/views/controls/button/button.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" namespace electron { class WinFrameView; class WinCaptionButton; // Provides a container for Windows 10 caption buttons that can be moved between // frame and browser window as needed. When extended horizontally, becomes a // grab bar for moving the window. class WinCaptionButtonContainer : public views::View, public views::WidgetObserver { public: explicit WinCaptionButtonContainer(WinFrameView* frame_view); ~WinCaptionButtonContainer() override; // Tests to see if the specified |point| (which is expressed in this view's // coordinates and which must be within this view's bounds) is within one of // the caption buttons. Returns one of HitTestCompat enum defined in // ui/base/hit_test.h, HTCAPTION if the area hit would be part of the window's // drag handle, and HTNOWHERE otherwise. // See also ClientView::NonClientHitTest. int NonClientHitTest(const gfx::Point& point) const; gfx::Size GetButtonSize() const; void SetButtonSize(gfx::Size size); // Sets caption button visibility and enabled state based on window state. // Only one of maximize or restore button should ever be visible at the same // time, and both are disabled in tablet UI mode. void UpdateButtons(); private: // views::View: void AddedToWidget() override; void RemovedFromWidget() override; // views::WidgetObserver: void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& new_bounds) override; void ResetWindowControls(); WinFrameView* const frame_view_; WinCaptionButton* const minimize_button_; WinCaptionButton* const maximize_button_; WinCaptionButton* const restore_button_; WinCaptionButton* const close_button_; base::ScopedObservation<views::Widget, views::WidgetObserver> widget_observation_{this}; base::CallbackListSubscription subscription_ = ui::TouchUiController::Get()->RegisterCallback( base::BindRepeating(&WinCaptionButtonContainer::UpdateButtons, base::Unretained(this))); }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_
closed
electron/electron
https://github.com/electron/electron
34,763
[Bug]: Overlay's minimize button stays in hovered/focused state after restoring
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version 11 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior When hovering over a "minimize" button in titlebar overlay and clicking it, and then restoring the app - I expect that the button is restored to its original state: ![image](https://user-images.githubusercontent.com/79877362/176010822-fca7de7d-921a-453c-acfe-c45d9e3adc57.png) ### Actual Behavior Instead if I click "minimize" and then restore I see this: ![image](https://user-images.githubusercontent.com/79877362/176010875-c4c0280f-d4b5-4edc-b2b6-16a30261ecdc.png) ### Testcase Gist URL _No response_ ### Additional Information Originally reported in: https://github.com/signalapp/Signal-Desktop/issues/5992
https://github.com/electron/electron/issues/34763
https://github.com/electron/electron/pull/34771
47d8d4cc5c0b945d52cc7c4b21c6cfe749b3df57
7ec88584b50f74b3d596448976781e91ea052e47
2022-06-27T18:30:06Z
c++
2022-07-07T15:17:20Z
shell/browser/native_window_views_win.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include <dwmapi.h> #include <shellapi.h> #include <wrl/client.h> #include "base/win/atl.h" // Must be before UIAutomationCore.h #include "content/public/browser/browser_accessibility_state.h" #include "shell/browser/browser.h" #include "shell/browser/native_window_views.h" #include "shell/browser/ui/views/root_view.h" #include "shell/common/electron_constants.h" #include "ui/display/display.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/geometry/insets.h" #include "ui/gfx/geometry/resize_utils.h" #include "ui/views/widget/native_widget_private.h" // Must be included after other Windows headers. #include <UIAutomationClient.h> #include <UIAutomationCoreApi.h> namespace electron { namespace { // Convert Win32 WM_APPCOMMANDS to strings. const char* AppCommandToString(int command_id) { switch (command_id) { case APPCOMMAND_BROWSER_BACKWARD: return kBrowserBackward; case APPCOMMAND_BROWSER_FORWARD: return kBrowserForward; case APPCOMMAND_BROWSER_REFRESH: return "browser-refresh"; case APPCOMMAND_BROWSER_STOP: return "browser-stop"; case APPCOMMAND_BROWSER_SEARCH: return "browser-search"; case APPCOMMAND_BROWSER_FAVORITES: return "browser-favorites"; case APPCOMMAND_BROWSER_HOME: return "browser-home"; case APPCOMMAND_VOLUME_MUTE: return "volume-mute"; case APPCOMMAND_VOLUME_DOWN: return "volume-down"; case APPCOMMAND_VOLUME_UP: return "volume-up"; case APPCOMMAND_MEDIA_NEXTTRACK: return "media-nexttrack"; case APPCOMMAND_MEDIA_PREVIOUSTRACK: return "media-previoustrack"; case APPCOMMAND_MEDIA_STOP: return "media-stop"; case APPCOMMAND_MEDIA_PLAY_PAUSE: return "media-play-pause"; case APPCOMMAND_LAUNCH_MAIL: return "launch-mail"; case APPCOMMAND_LAUNCH_MEDIA_SELECT: return "launch-media-select"; case APPCOMMAND_LAUNCH_APP1: return "launch-app1"; case APPCOMMAND_LAUNCH_APP2: return "launch-app2"; case APPCOMMAND_BASS_DOWN: return "bass-down"; case APPCOMMAND_BASS_BOOST: return "bass-boost"; case APPCOMMAND_BASS_UP: return "bass-up"; case APPCOMMAND_TREBLE_DOWN: return "treble-down"; case APPCOMMAND_TREBLE_UP: return "treble-up"; case APPCOMMAND_MICROPHONE_VOLUME_MUTE: return "microphone-volume-mute"; case APPCOMMAND_MICROPHONE_VOLUME_DOWN: return "microphone-volume-down"; case APPCOMMAND_MICROPHONE_VOLUME_UP: return "microphone-volume-up"; case APPCOMMAND_HELP: return "help"; case APPCOMMAND_FIND: return "find"; case APPCOMMAND_NEW: return "new"; case APPCOMMAND_OPEN: return "open"; case APPCOMMAND_CLOSE: return "close"; case APPCOMMAND_SAVE: return "save"; case APPCOMMAND_PRINT: return "print"; case APPCOMMAND_UNDO: return "undo"; case APPCOMMAND_REDO: return "redo"; case APPCOMMAND_COPY: return "copy"; case APPCOMMAND_CUT: return "cut"; case APPCOMMAND_PASTE: return "paste"; case APPCOMMAND_REPLY_TO_MAIL: return "reply-to-mail"; case APPCOMMAND_FORWARD_MAIL: return "forward-mail"; case APPCOMMAND_SEND_MAIL: return "send-mail"; case APPCOMMAND_SPELL_CHECK: return "spell-check"; case APPCOMMAND_MIC_ON_OFF_TOGGLE: return "mic-on-off-toggle"; case APPCOMMAND_CORRECTION_LIST: return "correction-list"; case APPCOMMAND_MEDIA_PLAY: return "media-play"; case APPCOMMAND_MEDIA_PAUSE: return "media-pause"; case APPCOMMAND_MEDIA_RECORD: return "media-record"; case APPCOMMAND_MEDIA_FAST_FORWARD: return "media-fast-forward"; case APPCOMMAND_MEDIA_REWIND: return "media-rewind"; case APPCOMMAND_MEDIA_CHANNEL_UP: return "media-channel-up"; case APPCOMMAND_MEDIA_CHANNEL_DOWN: return "media-channel-down"; case APPCOMMAND_DELETE: return "delete"; case APPCOMMAND_DICTATE_OR_COMMAND_CONTROL_TOGGLE: return "dictate-or-command-control-toggle"; default: return "unknown"; } } // Copied from ui/views/win/hwnd_message_handler.cc gfx::ResizeEdge GetWindowResizeEdge(WPARAM param) { switch (param) { case WMSZ_BOTTOM: return gfx::ResizeEdge::kBottom; case WMSZ_TOP: return gfx::ResizeEdge::kTop; case WMSZ_LEFT: return gfx::ResizeEdge::kLeft; case WMSZ_RIGHT: return gfx::ResizeEdge::kRight; case WMSZ_TOPLEFT: return gfx::ResizeEdge::kTopLeft; case WMSZ_TOPRIGHT: return gfx::ResizeEdge::kTopRight; case WMSZ_BOTTOMLEFT: return gfx::ResizeEdge::kBottomLeft; case WMSZ_BOTTOMRIGHT: return gfx::ResizeEdge::kBottomRight; default: return gfx::ResizeEdge::kBottomRight; } } bool IsScreenReaderActive() { UINT screenReader = 0; SystemParametersInfo(SPI_GETSCREENREADER, 0, &screenReader, 0); return screenReader && UiaClientsAreListening(); } } // namespace std::set<NativeWindowViews*> NativeWindowViews::forwarding_windows_; HHOOK NativeWindowViews::mouse_hook_ = NULL; void NativeWindowViews::Maximize() { // Only use Maximize() when window is NOT transparent style if (!transparent()) { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } else { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); SetBounds(display.work_area(), false); NotifyWindowMaximize(); } } bool NativeWindowViews::ExecuteWindowsCommand(int command_id) { std::string command = AppCommandToString(command_id); NotifyWindowExecuteAppCommand(command); return false; } bool NativeWindowViews::PreHandleMSG(UINT message, WPARAM w_param, LPARAM l_param, LRESULT* result) { NotifyWindowMessage(message, w_param, l_param); // Avoid side effects when calling SetWindowPlacement. if (is_setting_window_placement_) { // Let Chromium handle the WM_NCCALCSIZE message otherwise the window size // would be wrong. // See https://github.com/electron/electron/issues/22393 for more. if (message == WM_NCCALCSIZE) return false; // Otherwise handle the message with default proc, *result = DefWindowProc(GetAcceleratedWidget(), message, w_param, l_param); // and tell Chromium to ignore this message. return true; } switch (message) { // Screen readers send WM_GETOBJECT in order to get the accessibility // object, so take this opportunity to push Chromium into accessible // mode if it isn't already, always say we didn't handle the message // because we still want Chromium to handle returning the actual // accessibility object. case WM_GETOBJECT: { if (checked_for_a11y_support_) return false; const DWORD obj_id = static_cast<DWORD>(l_param); if (obj_id != static_cast<DWORD>(OBJID_CLIENT)) { return false; } if (!IsScreenReaderActive()) { return false; } checked_for_a11y_support_ = true; auto* const axState = content::BrowserAccessibilityState::GetInstance(); if (axState && !axState->IsAccessibleBrowser()) { axState->OnScreenReaderDetected(); Browser::Get()->OnAccessibilitySupportChanged(); } return false; } case WM_GETMINMAXINFO: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); // We do this to work around a Windows bug, where the minimized Window // would report that the closest display to it is not the one that it was // previously on (but the leftmost one instead). We restore the position // of the window during the restore operation, this way chromium can // use the proper display to calculate the scale factor to use. if (!last_normal_placement_bounds_.IsEmpty() && (IsVisible() || IsMinimized()) && GetWindowPlacement(GetAcceleratedWidget(), &wp)) { wp.rcNormalPosition = last_normal_placement_bounds_.ToRECT(); // When calling SetWindowPlacement, Chromium would do window messages // handling. But since we are already in PreHandleMSG this would cause // crash in Chromium under some cases. // // We work around the crash by prevent Chromium from handling window // messages until the SetWindowPlacement call is done. // // See https://github.com/electron/electron/issues/21614 for more. is_setting_window_placement_ = true; SetWindowPlacement(GetAcceleratedWidget(), &wp); is_setting_window_placement_ = false; last_normal_placement_bounds_ = gfx::Rect(); } return false; } case WM_COMMAND: // Handle thumbar button click message. if (HIWORD(w_param) == THBN_CLICKED) return taskbar_host_.HandleThumbarButtonEvent(LOWORD(w_param)); return false; case WM_SIZING: { is_resizing_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillResize(dpi_bounds, GetWindowResizeEdge(w_param), &prevent_default); if (prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); pending_bounds_change_.reset(); return true; // Tells Windows that the Sizing is handled. } return false; } case WM_SIZE: { // Handle window state change. HandleSizeEvent(w_param, l_param); return false; } case WM_EXITSIZEMOVE: { if (is_resizing_) { NotifyWindowResized(); is_resizing_ = false; } if (is_moving_) { NotifyWindowMoved(); is_moving_ = false; } // If the user dragged or moved the window during one or more // calls to window.setBounds(), we want to apply the most recent // one once they are done with the move or resize operation. if (pending_bounds_change_.has_value()) { SetBounds(pending_bounds_change_.value(), false /* animate */); pending_bounds_change_.reset(); } return false; } case WM_MOVING: { is_moving_ = true; bool prevent_default = false; gfx::Rect bounds = gfx::Rect(*reinterpret_cast<RECT*>(l_param)); HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = ScreenToDIPRect(hwnd, bounds); NotifyWindowWillMove(dpi_bounds, &prevent_default); if (!movable_ || prevent_default) { ::GetWindowRect(hwnd, reinterpret_cast<RECT*>(l_param)); pending_bounds_change_.reset(); return true; // Tells Windows that the Move is handled. If not true, // frameless windows can be moved using // -webkit-app-region: drag elements. } return false; } case WM_ENDSESSION: { if (w_param) { NotifyWindowEndSession(); } return false; } case WM_PARENTNOTIFY: { if (LOWORD(w_param) == WM_CREATE) { // Because of reasons regarding legacy drivers and stuff, a window that // matches the client area is created and used internally by Chromium. // This is used when forwarding mouse messages. We only cache the first // occurrence (the webview window) because dev tools also cause this // message to be sent. if (!legacy_window_) { legacy_window_ = reinterpret_cast<HWND>(l_param); } } return false; } case WM_CONTEXTMENU: { bool prevent_default = false; NotifyWindowSystemContextMenu(GET_X_LPARAM(l_param), GET_Y_LPARAM(l_param), &prevent_default); return prevent_default; } case WM_SYSCOMMAND: { // Mask is needed to account for double clicking title bar to maximize WPARAM max_mask = 0xFFF0; if (transparent() && ((w_param & max_mask) == SC_MAXIMIZE)) { return true; } return false; } case WM_INITMENU: { // This is handling the scenario where the menu might get triggered by the // user doing "alt + space" resulting in system maximization and restore // being used on transparent windows when that does not work. if (transparent()) { HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); EnableMenuItem(menu, SC_MAXIMIZE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); EnableMenuItem(menu, SC_RESTORE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); return true; } return false; } default: { return false; } } } void NativeWindowViews::HandleSizeEvent(WPARAM w_param, LPARAM l_param) { // Here we handle the WM_SIZE event in order to figure out what is the current // window state and notify the user accordingly. switch (w_param) { case SIZE_MAXIMIZED: case SIZE_MINIMIZED: { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); if (GetWindowPlacement(GetAcceleratedWidget(), &wp)) { last_normal_placement_bounds_ = gfx::Rect(wp.rcNormalPosition); } // Note that SIZE_MAXIMIZED and SIZE_MINIMIZED might be emitted for // multiple times for one resize because of the SetWindowPlacement call. if (w_param == SIZE_MAXIMIZED && last_window_state_ != ui::SHOW_STATE_MAXIMIZED) { last_window_state_ = ui::SHOW_STATE_MAXIMIZED; NotifyWindowMaximize(); } else if (w_param == SIZE_MINIMIZED && last_window_state_ != ui::SHOW_STATE_MINIMIZED) { last_window_state_ = ui::SHOW_STATE_MINIMIZED; NotifyWindowMinimize(); } break; } case SIZE_RESTORED: switch (last_window_state_) { case ui::SHOW_STATE_MAXIMIZED: last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowUnmaximize(); break; case ui::SHOW_STATE_MINIMIZED: if (IsFullscreen()) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowRestore(); } break; default: break; } break; } } void NativeWindowViews::SetForwardMouseMessages(bool forward) { if (forward && !forwarding_mouse_messages_) { forwarding_mouse_messages_ = true; forwarding_windows_.insert(this); // Subclassing is used to fix some issues when forwarding mouse messages; // see comments in |SubclassProc|. SetWindowSubclass(legacy_window_, SubclassProc, 1, reinterpret_cast<DWORD_PTR>(this)); if (!mouse_hook_) { mouse_hook_ = SetWindowsHookEx(WH_MOUSE_LL, MouseHookProc, NULL, 0); } } else if (!forward && forwarding_mouse_messages_) { forwarding_mouse_messages_ = false; forwarding_windows_.erase(this); RemoveWindowSubclass(legacy_window_, SubclassProc, 1); if (forwarding_windows_.empty()) { UnhookWindowsHookEx(mouse_hook_); mouse_hook_ = NULL; } } } LRESULT CALLBACK NativeWindowViews::SubclassProc(HWND hwnd, UINT msg, WPARAM w_param, LPARAM l_param, UINT_PTR subclass_id, DWORD_PTR ref_data) { auto* window = reinterpret_cast<NativeWindowViews*>(ref_data); switch (msg) { case WM_MOUSELEAVE: { // When input is forwarded to underlying windows, this message is posted. // If not handled, it interferes with Chromium logic, causing for example // mouseleave events to fire. If those events are used to exit forward // mode, excessive flickering on for example hover items in underlying // windows can occur due to rapidly entering and leaving forwarding mode. // By consuming and ignoring the message, we're essentially telling // Chromium that we have not left the window despite somebody else getting // the messages. As to why this is caught for the legacy window and not // the actual browser window is simply that the legacy window somehow // makes use of these events; posting to the main window didn't work. if (window->forwarding_mouse_messages_) { return 0; } break; } } return DefSubclassProc(hwnd, msg, w_param, l_param); } LRESULT CALLBACK NativeWindowViews::MouseHookProc(int n_code, WPARAM w_param, LPARAM l_param) { if (n_code < 0) { return CallNextHookEx(NULL, n_code, w_param, l_param); } // Post a WM_MOUSEMOVE message for those windows whose client area contains // the cursor since they are in a state where they would otherwise ignore all // mouse input. if (w_param == WM_MOUSEMOVE) { for (auto* window : forwarding_windows_) { // At first I considered enumerating windows to check whether the cursor // was directly above the window, but since nothing bad seems to happen // if we post the message even if some other window occludes it I have // just left it as is. RECT client_rect; GetClientRect(window->legacy_window_, &client_rect); POINT p = reinterpret_cast<MSLLHOOKSTRUCT*>(l_param)->pt; ScreenToClient(window->legacy_window_, &p); if (PtInRect(&client_rect, p)) { WPARAM w = 0; // No virtual keys pressed for our purposes LPARAM l = MAKELPARAM(p.x, p.y); PostMessage(window->legacy_window_, WM_MOUSEMOVE, w, l); } } } return CallNextHookEx(NULL, n_code, w_param, l_param); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,763
[Bug]: Overlay's minimize button stays in hovered/focused state after restoring
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.5 ### What operating system are you using? Windows ### Operating System Version 11 ### What arch are you using? x64 ### Last Known Working Electron version N/A ### Expected Behavior When hovering over a "minimize" button in titlebar overlay and clicking it, and then restoring the app - I expect that the button is restored to its original state: ![image](https://user-images.githubusercontent.com/79877362/176010822-fca7de7d-921a-453c-acfe-c45d9e3adc57.png) ### Actual Behavior Instead if I click "minimize" and then restore I see this: ![image](https://user-images.githubusercontent.com/79877362/176010875-c4c0280f-d4b5-4edc-b2b6-16a30261ecdc.png) ### Testcase Gist URL _No response_ ### Additional Information Originally reported in: https://github.com/signalapp/Signal-Desktop/issues/5992
https://github.com/electron/electron/issues/34763
https://github.com/electron/electron/pull/34771
47d8d4cc5c0b945d52cc7c4b21c6cfe749b3df57
7ec88584b50f74b3d596448976781e91ea052e47
2022-06-27T18:30:06Z
c++
2022-07-07T15:17:20Z
shell/browser/ui/views/win_caption_button_container.h
// Copyright 2020 The Chromium Authors. All rights reserved. // Use of this source code is governed by a BSD-style license that can be // found in the LICENSE file. // Modified from // chrome/browser/ui/views/frame/glass_browser_caption_button_container.h #ifndef ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_ #define ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_ #include "base/scoped_observation.h" #include "ui/base/metadata/metadata_header_macros.h" #include "ui/base/pointer/touch_ui_controller.h" #include "ui/views/controls/button/button.h" #include "ui/views/view.h" #include "ui/views/widget/widget.h" #include "ui/views/widget/widget_observer.h" namespace electron { class WinFrameView; class WinCaptionButton; // Provides a container for Windows 10 caption buttons that can be moved between // frame and browser window as needed. When extended horizontally, becomes a // grab bar for moving the window. class WinCaptionButtonContainer : public views::View, public views::WidgetObserver { public: explicit WinCaptionButtonContainer(WinFrameView* frame_view); ~WinCaptionButtonContainer() override; // Tests to see if the specified |point| (which is expressed in this view's // coordinates and which must be within this view's bounds) is within one of // the caption buttons. Returns one of HitTestCompat enum defined in // ui/base/hit_test.h, HTCAPTION if the area hit would be part of the window's // drag handle, and HTNOWHERE otherwise. // See also ClientView::NonClientHitTest. int NonClientHitTest(const gfx::Point& point) const; gfx::Size GetButtonSize() const; void SetButtonSize(gfx::Size size); // Sets caption button visibility and enabled state based on window state. // Only one of maximize or restore button should ever be visible at the same // time, and both are disabled in tablet UI mode. void UpdateButtons(); private: // views::View: void AddedToWidget() override; void RemovedFromWidget() override; // views::WidgetObserver: void OnWidgetBoundsChanged(views::Widget* widget, const gfx::Rect& new_bounds) override; void ResetWindowControls(); WinFrameView* const frame_view_; WinCaptionButton* const minimize_button_; WinCaptionButton* const maximize_button_; WinCaptionButton* const restore_button_; WinCaptionButton* const close_button_; base::ScopedObservation<views::Widget, views::WidgetObserver> widget_observation_{this}; base::CallbackListSubscription subscription_ = ui::TouchUiController::Get()->RegisterCallback( base::BindRepeating(&WinCaptionButtonContainer::UpdateButtons, base::Unretained(this))); }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_UI_VIEWS_WIN_CAPTION_BUTTON_CONTAINER_H_
closed
electron/electron
https://github.com/electron/electron
34,822
[Bug]: `setTrafficLightPosition` is reset when calling `setRepresentedFilename`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.7 ### What operating system are you using? macOS ### Operating System Version 12.4 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The traffic light position should remain stable. ### Actual Behavior The traffic light position changes after the presented file name is changed for the window. ### Testcase Gist URL https://gist.github.com/9ad043673ca425c92bbb4e1f951c455c ### Additional Information ![Recording 2022-07-05 at 06 23 50](https://user-images.githubusercontent.com/900690/177249087-a480a68a-1c2e-4470-8781-38be162c61a0.gif)
https://github.com/electron/electron/issues/34822
https://github.com/electron/electron/pull/34834
e83c3ec74442f0533e2d66c53fa84a075ebc20ae
1941c88442b61f3e83125f197becc83cf6975a9c
2022-07-05T04:24:03Z
c++
2022-07-08T06:33:42Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" // This view would inform Chromium to resize the hosted views::View. // // The overridden methods should behave the same with BridgedContentView. @interface ElectronAdaptedContentView : NSView { @private views::NativeWidgetMacNSWindowHost* bridge_host_; } @end @implementation ElectronAdaptedContentView - (id)initWithShell:(electron::NativeWindowMac*)shell { if ((self = [self init])) { bridge_host_ = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell->GetNativeWindow()); } return self; } - (void)viewDidMoveToWindow { // When this view is added to a window, AppKit calls setFrameSize before it is // added to the window, so the behavior in setFrameSize is not triggered. NSWindow* window = [self window]; if (window) [self setFrameSize:NSZeroSize]; } - (void)setFrameSize:(NSSize)newSize { // The size passed in here does not always use // -[NSWindow contentRectForFrameRect]. The following ensures that the // contentView for a frameless window can extend over the titlebar of the new // window containing it, since AppKit requires a titlebar to give frameless // windows correct shadows and rounded corners. NSWindow* window = [self window]; if (window && [window contentView] == self) { newSize = [window contentRectForFrameRect:[window frame]].size; // Ensure that the window geometry be updated on the host side before the // view size is updated. bridge_host_->GetInProcessNSWindowBridge()->UpdateWindowGeometry(); } [super setFrameSize:newSize]; // The OnViewSizeChanged is marked private in derived class. static_cast<remote_cocoa::mojom::NativeWidgetNSWindowHost*>(bridge_host_) ->OnViewSizeChanged(gfx::Size(newSize.width, newSize.height)); } @end // This view always takes the size of its superview. It is intended to be used // as a NSWindow's contentView. It is needed because NSWindow's implementation // explicitly resizes the contentView at inopportune times. @interface FullSizeContentView : NSView @end @implementation FullSizeContentView // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. - (void)setFrameSize:(NSSize)size { if ([self superview]) size = [[self superview] bounds].size; [super setFrameSize:size]; } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. - (void)viewDidMoveToSuperview { [self setFrame:[[self superview] bounds]]; } @end @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorBarStyle) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // Removing NSWindowStyleMaskTitled removes window title, which removes // rounded corners of window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = 0; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_.reset(); }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]); [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]); [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; // Use an NSEvent monitor to listen for the wheel event. BOOL __block began = NO; wheel_event_monitor_ = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskScrollWheel handler:^(NSEvent* event) { if ([[event window] windowNumber] != [window_ windowNumber]) return event; if (!began && (([event phase] == NSEventPhaseMayBegin) || ([event phase] == NSEventPhaseBegan))) { this->NotifyWindowScrollTouchBegin(); began = YES; } else if (began && (([event phase] == NSEventPhaseEnded) || ([event phase] == NSEventPhaseCancelled))) { this->NotifyWindowScrollTouchEnd(); began = NO; } return event; }]; // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { SetHasDeferredWindowClose(true); return; } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. SetEnabled(true); [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Retain the child window before closing it. If the last reference to the // NSWindow goes away inside -[NSWindow close], then bad stuff can happen. // See e.g. http://crbug.com/616701. base::scoped_nsobject<NSWindow> child_window(window_, base::scoped_policy::RETAIN); [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. SetEnabled(true); if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // Hide all children of the current window before hiding the window. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm // expects this when window visibility changes. if ([window_ childWindows]) { for (NSWindow* child in [window_ childWindows]) { [child orderOut:nil]; } } // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; // For a window to be visible, it must be visible to the user in the // foreground of the app, which means that it should not be minimized or // occluded return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { [window_ beginSheet:window_ completionHandler:^(NSModalResponse returnCode) { NSLog(@"modal enabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::SetFullScreen(bool fullscreen) { // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::ENTERING : FullScreenTransitionState::EXITING; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; [window_ orderWindow:NSWindowAbove relativeTo:id.id]; return true; } void NativeWindowMac::MoveTop() { [window_ orderWindow:NSWindowAbove relativeTo:0]; } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::NONE; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [window_ flushWindow]; [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; SetFullScreen(true); } else if (!kiosk && is_kiosk_) { [NSApp setPresentationOptions:kiosk_options_]; is_kiosk_ = false; SetFullScreen(false); } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=372?q=kWindowCaptureMacV2&ss=chromium // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[[NSImageView alloc] init] autorelease]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[[ElectronProgressBar alloc] initWithFrame:frame] autorelease]; [progress_indicator setStyle:NSProgressIndicatorBarStyle]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to functionally // mimic app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { ProcessSerialNumber psn = {0, kCurrentProcess}; if (visibleOnFullScreen) { [window_ setCanHide:NO]; TransformProcessType(&psn, kProcessTransformToUIElementApplication); } else { [window_ setCanHide:YES]; TransformProcessType(&psn, kProcessTransformToForegroundApplication); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } std::string dep_warn = " has been deprecated and removed as of macOS 10.15."; node::Environment* env = node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); NSVisualEffectMaterial vibrancyType{}; if (type == "appearance-based") { EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialAppearanceBased; } else if (type == "light") { EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialLight; } else if (type == "dark") { EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialDark; } else if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "medium-light") { EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialMediumLight; } else if (type == "ultra-dark") { EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialUltraDark; } if (@available(macOS 10.14, *)) { if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]] autorelease]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetTrafficLightPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetTrafficLightPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_.reset([[ElectronTouchBar alloc] initWithDelegate:window_delegate_.get() window:this settings:std::move(items)]); [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_.reset([[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]); [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); if (wheel_event_monitor_) { [NSEvent removeMonitor:wheel_event_monitor_]; wheel_event_monitor_ = nil; } } void NativeWindowMac::OverrideNSWindowContentView() { // When using `views::Widget` to hold WebContents, Chromium would use // `BridgedContentView` as content view, which does not support draggable // regions. In order to make draggable regions work, we have to replace the // content view with a simple NSView. if (has_frame()) { container_view_.reset( [[ElectronAdaptedContentView alloc] initWithShell:this]); } else { container_view_.reset([[FullSizeContentView alloc] init]); [container_view_ setFrame:[[[window_ contentView] superview] bounds]]; } [container_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [window_ setContentView:container_view_]; AddContentViewLayers(); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]); [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } if (!has_frame()) { // In OSX 10.10, adding subviews to the root view for the NSView hierarchy // produces warnings. To eliminate the warnings, we resize the contentView // to fill the window, and add subviews to that. // http://crbug.com/380412 if (!original_set_frame_size) { Class cl = [[window_ contentView] class]; original_set_frame_size = class_replaceMethod( cl, @selector(setFrameSize:), (IMP)SetFrameSize, "v@:{_NSSize=ff}"); original_view_did_move_to_superview = class_replaceMethod(cl, @selector(viewDidMoveToSuperview), (IMP)ViewDidMoveToSuperview, "v@:"); [[window_ contentView] viewDidMoveToWindow]; } } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) { if (is_modal()) return; NativeWindow::SetParentWindow(parent); // Do not remove/add if we are already properly attached. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. if ([window_ parentWindow]) [[window_ parentWindow] removeChildWindow:window_]; // Set new parent window. // Note that this method will force the window to become visible. if (parent && attach) { // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [parent->GetNativeWindow().GetNativeNSWindow() addChildWindow:window_ ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,822
[Bug]: `setTrafficLightPosition` is reset when calling `setRepresentedFilename`
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.7 ### What operating system are you using? macOS ### Operating System Version 12.4 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version _No response_ ### Expected Behavior The traffic light position should remain stable. ### Actual Behavior The traffic light position changes after the presented file name is changed for the window. ### Testcase Gist URL https://gist.github.com/9ad043673ca425c92bbb4e1f951c455c ### Additional Information ![Recording 2022-07-05 at 06 23 50](https://user-images.githubusercontent.com/900690/177249087-a480a68a-1c2e-4470-8781-38be162c61a0.gif)
https://github.com/electron/electron/issues/34822
https://github.com/electron/electron/pull/34834
e83c3ec74442f0533e2d66c53fa84a075ebc20ae
1941c88442b61f3e83125f197becc83cf6975a9c
2022-07-05T04:24:03Z
c++
2022-07-08T06:33:42Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" // This view would inform Chromium to resize the hosted views::View. // // The overridden methods should behave the same with BridgedContentView. @interface ElectronAdaptedContentView : NSView { @private views::NativeWidgetMacNSWindowHost* bridge_host_; } @end @implementation ElectronAdaptedContentView - (id)initWithShell:(electron::NativeWindowMac*)shell { if ((self = [self init])) { bridge_host_ = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell->GetNativeWindow()); } return self; } - (void)viewDidMoveToWindow { // When this view is added to a window, AppKit calls setFrameSize before it is // added to the window, so the behavior in setFrameSize is not triggered. NSWindow* window = [self window]; if (window) [self setFrameSize:NSZeroSize]; } - (void)setFrameSize:(NSSize)newSize { // The size passed in here does not always use // -[NSWindow contentRectForFrameRect]. The following ensures that the // contentView for a frameless window can extend over the titlebar of the new // window containing it, since AppKit requires a titlebar to give frameless // windows correct shadows and rounded corners. NSWindow* window = [self window]; if (window && [window contentView] == self) { newSize = [window contentRectForFrameRect:[window frame]].size; // Ensure that the window geometry be updated on the host side before the // view size is updated. bridge_host_->GetInProcessNSWindowBridge()->UpdateWindowGeometry(); } [super setFrameSize:newSize]; // The OnViewSizeChanged is marked private in derived class. static_cast<remote_cocoa::mojom::NativeWidgetNSWindowHost*>(bridge_host_) ->OnViewSizeChanged(gfx::Size(newSize.width, newSize.height)); } @end // This view always takes the size of its superview. It is intended to be used // as a NSWindow's contentView. It is needed because NSWindow's implementation // explicitly resizes the contentView at inopportune times. @interface FullSizeContentView : NSView @end @implementation FullSizeContentView // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. - (void)setFrameSize:(NSSize)size { if ([self superview]) size = [[self superview] bounds].size; [super setFrameSize:size]; } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. - (void)viewDidMoveToSuperview { [self setFrame:[[self superview] bounds]]; } @end @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorBarStyle) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // Removing NSWindowStyleMaskTitled removes window title, which removes // rounded corners of window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = 0; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_.reset(); }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]); [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]); [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; // Use an NSEvent monitor to listen for the wheel event. BOOL __block began = NO; wheel_event_monitor_ = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskScrollWheel handler:^(NSEvent* event) { if ([[event window] windowNumber] != [window_ windowNumber]) return event; if (!began && (([event phase] == NSEventPhaseMayBegin) || ([event phase] == NSEventPhaseBegan))) { this->NotifyWindowScrollTouchBegin(); began = YES; } else if (began && (([event phase] == NSEventPhaseEnded) || ([event phase] == NSEventPhaseCancelled))) { this->NotifyWindowScrollTouchEnd(); began = NO; } return event; }]; // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { SetHasDeferredWindowClose(true); return; } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. SetEnabled(true); [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Retain the child window before closing it. If the last reference to the // NSWindow goes away inside -[NSWindow close], then bad stuff can happen. // See e.g. http://crbug.com/616701. base::scoped_nsobject<NSWindow> child_window(window_, base::scoped_policy::RETAIN); [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. SetEnabled(true); if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // Hide all children of the current window before hiding the window. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm // expects this when window visibility changes. if ([window_ childWindows]) { for (NSWindow* child in [window_ childWindows]) { [child orderOut:nil]; } } // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; // For a window to be visible, it must be visible to the user in the // foreground of the app, which means that it should not be minimized or // occluded return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { [window_ beginSheet:window_ completionHandler:^(NSModalResponse returnCode) { NSLog(@"modal enabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::SetFullScreen(bool fullscreen) { // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::ENTERING : FullScreenTransitionState::EXITING; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; [window_ orderWindow:NSWindowAbove relativeTo:id.id]; return true; } void NativeWindowMac::MoveTop() { [window_ orderWindow:NSWindowAbove relativeTo:0]; } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::NONE; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [window_ flushWindow]; [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; SetFullScreen(true); } else if (!kiosk && is_kiosk_) { [NSApp setPresentationOptions:kiosk_options_]; is_kiosk_ = false; SetFullScreen(false); } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=372?q=kWindowCaptureMacV2&ss=chromium // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[[NSImageView alloc] init] autorelease]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[[ElectronProgressBar alloc] initWithFrame:frame] autorelease]; [progress_indicator setStyle:NSProgressIndicatorBarStyle]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to functionally // mimic app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { ProcessSerialNumber psn = {0, kCurrentProcess}; if (visibleOnFullScreen) { [window_ setCanHide:NO]; TransformProcessType(&psn, kProcessTransformToUIElementApplication); } else { [window_ setCanHide:YES]; TransformProcessType(&psn, kProcessTransformToForegroundApplication); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } std::string dep_warn = " has been deprecated and removed as of macOS 10.15."; node::Environment* env = node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); NSVisualEffectMaterial vibrancyType{}; if (type == "appearance-based") { EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialAppearanceBased; } else if (type == "light") { EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialLight; } else if (type == "dark") { EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialDark; } else if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "medium-light") { EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialMediumLight; } else if (type == "ultra-dark") { EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialUltraDark; } if (@available(macOS 10.14, *)) { if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]] autorelease]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetTrafficLightPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetTrafficLightPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_.reset([[ElectronTouchBar alloc] initWithDelegate:window_delegate_.get() window:this settings:std::move(items)]); [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_.reset([[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]); [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); if (wheel_event_monitor_) { [NSEvent removeMonitor:wheel_event_monitor_]; wheel_event_monitor_ = nil; } } void NativeWindowMac::OverrideNSWindowContentView() { // When using `views::Widget` to hold WebContents, Chromium would use // `BridgedContentView` as content view, which does not support draggable // regions. In order to make draggable regions work, we have to replace the // content view with a simple NSView. if (has_frame()) { container_view_.reset( [[ElectronAdaptedContentView alloc] initWithShell:this]); } else { container_view_.reset([[FullSizeContentView alloc] init]); [container_view_ setFrame:[[[window_ contentView] superview] bounds]]; } [container_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [window_ setContentView:container_view_]; AddContentViewLayers(); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]); [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } if (!has_frame()) { // In OSX 10.10, adding subviews to the root view for the NSView hierarchy // produces warnings. To eliminate the warnings, we resize the contentView // to fill the window, and add subviews to that. // http://crbug.com/380412 if (!original_set_frame_size) { Class cl = [[window_ contentView] class]; original_set_frame_size = class_replaceMethod( cl, @selector(setFrameSize:), (IMP)SetFrameSize, "v@:{_NSSize=ff}"); original_view_did_move_to_superview = class_replaceMethod(cl, @selector(viewDidMoveToSuperview), (IMP)ViewDidMoveToSuperview, "v@:"); [[window_ contentView] viewDidMoveToWindow]; } } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) { if (is_modal()) return; NativeWindow::SetParentWindow(parent); // Do not remove/add if we are already properly attached. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. if ([window_ parentWindow]) [[window_ parentWindow] removeChildWindow:window_]; // Set new parent window. // Note that this method will force the window to become visible. if (parent && attach) { // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [parent->GetNativeWindow().GetNativeNSWindow() addChildWindow:window_ ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,852
[Bug]: Electorn 18 app is missing desktopFileName window property
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.4 ### What operating system are you using? Other Linux ### Operating System Version Manjaro Linux ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `desktopFileName` window property should not be empty ![image](https://user-images.githubusercontent.com/61285/177988205-9de3f548-11da-41e7-9d8c-fbc289977148.png) ### Actual Behavior `desktopFileName` window property is empty With Electron 17.4.3 - OK ![image](https://user-images.githubusercontent.com/61285/177988036-3d4dcb27-706a-4708-b853-91c8bf063687.png) ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34852
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-07-08T12:02:26Z
c++
2022-07-11T18:26:18Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // TODO(ckerr): remove in Electron v20.0.0 // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; return; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) SetWMSpecState(static_cast<x11::Window>(GetAcceleratedWidget()), skip, x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,852
[Bug]: Electorn 18 app is missing desktopFileName window property
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.4 ### What operating system are you using? Other Linux ### Operating System Version Manjaro Linux ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `desktopFileName` window property should not be empty ![image](https://user-images.githubusercontent.com/61285/177988205-9de3f548-11da-41e7-9d8c-fbc289977148.png) ### Actual Behavior `desktopFileName` window property is empty With Electron 17.4.3 - OK ![image](https://user-images.githubusercontent.com/61285/177988036-3d4dcb27-706a-4708-b853-91c8bf063687.png) ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34852
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-07-08T12:02:26Z
c++
2022-07-11T18:26:18Z
shell/browser/notifications/linux/libnotify_notification.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/notifications/linux/libnotify_notification.h" #include <set> #include <string> #include "base/files/file_enumerator.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "shell/browser/notifications/notification_delegate.h" #include "shell/browser/ui/gtk_util.h" #include "shell/common/application_info.h" #include "shell/common/platform_util.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gtk/gtk_util.h" // nogncheck namespace electron { namespace { LibNotifyLoader libnotify_loader_; const std::set<std::string>& GetServerCapabilities() { static std::set<std::string> caps; if (caps.empty()) { auto* capabilities = libnotify_loader_.notify_get_server_caps(); for (auto* l = capabilities; l != nullptr; l = l->next) caps.insert(static_cast<const char*>(l->data)); g_list_free_full(capabilities, g_free); } return caps; } bool HasCapability(const std::string& capability) { return GetServerCapabilities().count(capability) != 0; } bool NotifierSupportsActions() { if (getenv("ELECTRON_USE_UBUNTU_NOTIFIER")) return false; return HasCapability("actions"); } void log_and_clear_error(GError* error, const char* context) { LOG(ERROR) << context << ": domain=" << error->domain << " code=" << error->code << " message=\"" << error->message << '"'; g_error_free(error); } } // namespace // static bool LibnotifyNotification::Initialize() { if (!libnotify_loader_.Load("libnotify.so.4") && // most common one !libnotify_loader_.Load("libnotify.so.5") && !libnotify_loader_.Load("libnotify.so.1") && !libnotify_loader_.Load("libnotify.so")) { LOG(WARNING) << "Unable to find libnotify; notifications disabled"; return false; } if (!libnotify_loader_.notify_is_initted() && !libnotify_loader_.notify_init(GetApplicationName().c_str())) { LOG(WARNING) << "Unable to initialize libnotify; notifications disabled"; return false; } return true; } LibnotifyNotification::LibnotifyNotification(NotificationDelegate* delegate, NotificationPresenter* presenter) : Notification(delegate, presenter) {} LibnotifyNotification::~LibnotifyNotification() { if (notification_) { g_signal_handlers_disconnect_by_data(notification_, this); g_object_unref(notification_); } } void LibnotifyNotification::Show(const NotificationOptions& options) { notification_ = libnotify_loader_.notify_notification_new( base::UTF16ToUTF8(options.title).c_str(), base::UTF16ToUTF8(options.msg).c_str(), nullptr); g_signal_connect(notification_, "closed", G_CALLBACK(OnNotificationClosedThunk), this); // NB: On Unity and on any other DE using Notify-OSD, adding a notification // action will cause the notification to display as a modal dialog box. if (NotifierSupportsActions()) { libnotify_loader_.notify_notification_add_action( notification_, "default", "View", OnNotificationViewThunk, this, nullptr); } NotifyUrgency urgency = NOTIFY_URGENCY_NORMAL; if (options.urgency == u"critical") { urgency = NOTIFY_URGENCY_CRITICAL; } else if (options.urgency == u"low") { urgency = NOTIFY_URGENCY_LOW; } // Set the urgency level of the notification. libnotify_loader_.notify_notification_set_urgency(notification_, urgency); if (!options.icon.drawsNothing()) { GdkPixbuf* pixbuf = gtk_util::GdkPixbufFromSkBitmap(options.icon); libnotify_loader_.notify_notification_set_image_from_pixbuf(notification_, pixbuf); g_object_unref(pixbuf); } // Set the timeout duration for the notification bool neverTimeout = options.timeout_type == u"never"; int timeout = (neverTimeout) ? NOTIFY_EXPIRES_NEVER : NOTIFY_EXPIRES_DEFAULT; libnotify_loader_.notify_notification_set_timeout(notification_, timeout); if (!options.tag.empty()) { GQuark id = g_quark_from_string(options.tag.c_str()); g_object_set(G_OBJECT(notification_), "id", id, NULL); } // Always try to append notifications. // Unique tags can be used to prevent this. if (HasCapability("append")) { libnotify_loader_.notify_notification_set_hint_string(notification_, "append", "true"); } else if (HasCapability("x-canonical-append")) { libnotify_loader_.notify_notification_set_hint_string( notification_, "x-canonical-append", "true"); } // Send the desktop name to identify the application // The desktop-entry is the part before the .desktop std::string desktop_id; if (platform_util::GetDesktopName(&desktop_id)) { const std::string suffix{".desktop"}; if (base::EndsWith(desktop_id, suffix, base::CompareCase::INSENSITIVE_ASCII)) { desktop_id.resize(desktop_id.size() - suffix.size()); } libnotify_loader_.notify_notification_set_hint_string( notification_, "desktop-entry", desktop_id.c_str()); } GError* error = nullptr; libnotify_loader_.notify_notification_show(notification_, &error); if (error) { log_and_clear_error(error, "notify_notification_show"); NotificationFailed(); return; } if (delegate()) delegate()->NotificationDisplayed(); } void LibnotifyNotification::Dismiss() { if (!notification_) { Destroy(); return; } GError* error = nullptr; libnotify_loader_.notify_notification_close(notification_, &error); if (error) { log_and_clear_error(error, "notify_notification_close"); Destroy(); } } void LibnotifyNotification::OnNotificationClosed( NotifyNotification* notification) { NotificationDismissed(); } void LibnotifyNotification::OnNotificationView(NotifyNotification* notification, char* action) { NotificationClicked(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,852
[Bug]: Electorn 18 app is missing desktopFileName window property
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.4 ### What operating system are you using? Other Linux ### Operating System Version Manjaro Linux ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `desktopFileName` window property should not be empty ![image](https://user-images.githubusercontent.com/61285/177988205-9de3f548-11da-41e7-9d8c-fbc289977148.png) ### Actual Behavior `desktopFileName` window property is empty With Electron 17.4.3 - OK ![image](https://user-images.githubusercontent.com/61285/177988036-3d4dcb27-706a-4708-b853-91c8bf063687.png) ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34852
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-07-08T12:02:26Z
c++
2022-07-11T18:26:18Z
shell/common/platform_util.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_ #define ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_ #include <string> #include "base/callback_forward.h" #include "base/files/file_path.h" #include "build/build_config.h" class GURL; namespace platform_util { typedef base::OnceCallback<void(const std::string&)> OpenCallback; // Show the given file in a file manager. If possible, select the file. // Must be called from the UI thread. void ShowItemInFolder(const base::FilePath& full_path); // Open the given file in the desktop's default manner. // Must be called from the UI thread. void OpenPath(const base::FilePath& full_path, OpenCallback callback); struct OpenExternalOptions { bool activate = true; base::FilePath working_dir; }; // Open the given external protocol URL in the desktop's default manner. // (For example, mailto: URLs in the default mail user agent.) void OpenExternal(const GURL& url, const OpenExternalOptions& options, OpenCallback callback); // Move a file to trash, asynchronously. void TrashItem(const base::FilePath& full_path, base::OnceCallback<void(bool, const std::string&)> callback); void Beep(); #if BUILDFLAG(IS_WIN) // SHGetFolderPath calls not covered by Chromium bool GetFolderPath(int key, base::FilePath* result); #endif #if BUILDFLAG(IS_MAC) bool GetLoginItemEnabled(); bool SetLoginItemEnabled(bool enabled); #endif #if BUILDFLAG(IS_LINUX) // Returns a success flag. // Unlike libgtkui, does *not* use "chromium-browser.desktop" as a fallback. bool GetDesktopName(std::string* setme); #endif } // namespace platform_util #endif // ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_
closed
electron/electron
https://github.com/electron/electron
34,852
[Bug]: Electorn 18 app is missing desktopFileName window property
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.4 ### What operating system are you using? Other Linux ### Operating System Version Manjaro Linux ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `desktopFileName` window property should not be empty ![image](https://user-images.githubusercontent.com/61285/177988205-9de3f548-11da-41e7-9d8c-fbc289977148.png) ### Actual Behavior `desktopFileName` window property is empty With Electron 17.4.3 - OK ![image](https://user-images.githubusercontent.com/61285/177988036-3d4dcb27-706a-4708-b853-91c8bf063687.png) ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34852
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-07-08T12:02:26Z
c++
2022-07-11T18:26:18Z
shell/common/platform_util_linux.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/platform_util.h" #include <fcntl.h> #include <stdio.h> #include <string> #include <vector> #include "base/cancelable_callback.h" #include "base/containers/contains.h" #include "base/environment.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/nix/xdg_util.h" #include "base/no_destructor.h" #include "base/posix/eintr_wrapper.h" #include "base/process/kill.h" #include "base/process/launch.h" #include "base/threading/thread_restrictions.h" #include "components/dbus/thread_linux/dbus_thread_linux.h" #include "content/public/browser/browser_thread.h" #include "dbus/bus.h" #include "dbus/message.h" #include "dbus/object_proxy.h" #include "shell/common/platform_util_internal.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gtk/gtk_util.h" // nogncheck #include "url/gurl.h" #define ELECTRON_TRASH "ELECTRON_TRASH" namespace platform_util { void OpenFolder(const base::FilePath& full_path); } namespace { const char kMethodListActivatableNames[] = "ListActivatableNames"; const char kMethodNameHasOwner[] = "NameHasOwner"; const char kFreedesktopFileManagerName[] = "org.freedesktop.FileManager1"; const char kFreedesktopFileManagerPath[] = "/org/freedesktop/FileManager1"; const char kMethodShowItems[] = "ShowItems"; const char kFreedesktopPortalName[] = "org.freedesktop.portal.Desktop"; const char kFreedesktopPortalPath[] = "/org/freedesktop/portal/desktop"; const char kFreedesktopPortalOpenURI[] = "org.freedesktop.portal.OpenURI"; const char kMethodOpenDirectory[] = "OpenDirectory"; class ShowItemHelper { public: static ShowItemHelper& GetInstance() { static base::NoDestructor<ShowItemHelper> instance; return *instance; } ShowItemHelper() {} ShowItemHelper(const ShowItemHelper&) = delete; ShowItemHelper& operator=(const ShowItemHelper&) = delete; void ShowItemInFolder(const base::FilePath& full_path) { if (!bus_) { // Sets up the D-Bus connection. dbus::Bus::Options bus_options; bus_options.bus_type = dbus::Bus::SESSION; bus_options.connection_type = dbus::Bus::PRIVATE; bus_options.dbus_task_runner = dbus_thread_linux::GetTaskRunner(); bus_ = base::MakeRefCounted<dbus::Bus>(bus_options); } if (!dbus_proxy_) { dbus_proxy_ = bus_->GetObjectProxy(DBUS_SERVICE_DBUS, dbus::ObjectPath(DBUS_PATH_DBUS)); } if (prefer_filemanager_interface_.has_value()) { if (prefer_filemanager_interface_.value()) { ShowItemUsingFileManager(full_path); } else { ShowItemUsingFreedesktopPortal(full_path); } } else { CheckFileManagerRunning(full_path); } } private: void CheckFileManagerRunning(const base::FilePath& full_path) { dbus::MethodCall method_call(DBUS_INTERFACE_DBUS, kMethodNameHasOwner); dbus::MessageWriter writer(&method_call); writer.AppendString(kFreedesktopFileManagerName); dbus_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&ShowItemHelper::CheckFileManagerRunningResponse, base::Unretained(this), full_path)); } void CheckFileManagerRunningResponse(const base::FilePath& full_path, dbus::Response* response) { if (prefer_filemanager_interface_.has_value()) { ShowItemInFolder(full_path); return; } bool is_running = false; if (!response) { LOG(ERROR) << "Failed to call " << kMethodNameHasOwner; } else { dbus::MessageReader reader(response); bool owned = false; if (!reader.PopBool(&owned)) { LOG(ERROR) << "Failed to read " << kMethodNameHasOwner << " response"; } else if (owned) { is_running = true; } } if (is_running) { prefer_filemanager_interface_ = true; ShowItemInFolder(full_path); } else { CheckFileManagerActivatable(full_path); } } void CheckFileManagerActivatable(const base::FilePath& full_path) { dbus::MethodCall method_call(DBUS_INTERFACE_DBUS, kMethodListActivatableNames); dbus_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&ShowItemHelper::CheckFileManagerActivatableResponse, base::Unretained(this), full_path)); } void CheckFileManagerActivatableResponse(const base::FilePath& full_path, dbus::Response* response) { if (prefer_filemanager_interface_.has_value()) { ShowItemInFolder(full_path); return; } bool is_activatable = false; if (!response) { LOG(ERROR) << "Failed to call " << kMethodListActivatableNames; } else { dbus::MessageReader reader(response); std::vector<std::string> names; if (!reader.PopArrayOfStrings(&names)) { LOG(ERROR) << "Failed to read " << kMethodListActivatableNames << " response"; } else if (base::Contains(names, kFreedesktopFileManagerName)) { is_activatable = true; } } prefer_filemanager_interface_ = is_activatable; ShowItemInFolder(full_path); } void ShowItemUsingFreedesktopPortal(const base::FilePath& full_path) { if (!object_proxy_) { object_proxy_ = bus_->GetObjectProxy( kFreedesktopPortalName, dbus::ObjectPath(kFreedesktopPortalPath)); } base::ScopedFD fd( HANDLE_EINTR(open(full_path.value().c_str(), O_RDONLY | O_CLOEXEC))); if (!fd.is_valid()) { LOG(ERROR) << "Failed to open " << full_path << " for URI portal"; // If the call fails, at least open the parent folder. platform_util::OpenFolder(full_path.DirName()); return; } dbus::MethodCall open_directory_call(kFreedesktopPortalOpenURI, kMethodOpenDirectory); dbus::MessageWriter writer(&open_directory_call); writer.AppendString(""); // Note that AppendFileDescriptor() duplicates the fd, so we shouldn't // release ownership of it here. writer.AppendFileDescriptor(fd.get()); dbus::MessageWriter options_writer(nullptr); writer.OpenArray("{sv}", &options_writer); writer.CloseContainer(&options_writer); ShowItemUsingBusCall(&open_directory_call, full_path); } void ShowItemUsingFileManager(const base::FilePath& full_path) { if (!object_proxy_) { object_proxy_ = bus_->GetObjectProxy(kFreedesktopFileManagerName, dbus::ObjectPath(kFreedesktopFileManagerPath)); } dbus::MethodCall show_items_call(kFreedesktopFileManagerName, kMethodShowItems); dbus::MessageWriter writer(&show_items_call); writer.AppendArrayOfStrings( {"file://" + full_path.value()}); // List of file(s) to highlight. writer.AppendString({}); // startup-id ShowItemUsingBusCall(&show_items_call, full_path); } void ShowItemUsingBusCall(dbus::MethodCall* call, const base::FilePath& full_path) { object_proxy_->CallMethod( call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&ShowItemHelper::ShowItemInFolderResponse, base::Unretained(this), full_path, call->GetMember())); } void ShowItemInFolderResponse(const base::FilePath& full_path, const std::string& method, dbus::Response* response) { if (response) return; LOG(ERROR) << "Error calling " << method; // If the bus call fails, at least open the parent folder. platform_util::OpenFolder(full_path.DirName()); } scoped_refptr<dbus::Bus> bus_; dbus::ObjectProxy* dbus_proxy_ = nullptr; dbus::ObjectProxy* object_proxy_ = nullptr; absl::optional<bool> prefer_filemanager_interface_; }; // Descriptions pulled from https://linux.die.net/man/1/xdg-open std::string GetErrorDescription(int error_code) { switch (error_code) { case 1: return "Error in command line syntax"; case 2: return "The item does not exist"; case 3: return "A required tool could not be found"; case 4: return "The action failed"; default: return ""; } } bool XDGUtil(const std::vector<std::string>& argv, const base::FilePath& working_directory, const bool wait_for_exit, platform_util::OpenCallback callback) { base::LaunchOptions options; options.current_directory = working_directory; options.allow_new_privs = true; // xdg-open can fall back on mailcap which eventually might plumb through // to a command that needs a terminal. Set the environment variable telling // it that we definitely don't have a terminal available and that it should // bring up a new terminal if necessary. See "man mailcap". options.environment["MM_NOTTTY"] = "1"; base::Process process = base::LaunchProcess(argv, options); if (!process.IsValid()) return false; if (wait_for_exit) { base::ScopedAllowBaseSyncPrimitivesForTesting allow_sync; // required by WaitForExit int exit_code = -1; bool success = process.WaitForExit(&exit_code); if (!callback.is_null()) std::move(callback).Run(GetErrorDescription(exit_code)); return success ? (exit_code == 0) : false; } base::EnsureProcessGetsReaped(std::move(process)); return true; } bool XDGOpen(const base::FilePath& working_directory, const std::string& path, const bool wait_for_exit, platform_util::OpenCallback callback) { return XDGUtil({"xdg-open", path}, working_directory, wait_for_exit, std::move(callback)); } bool XDGEmail(const std::string& email, const bool wait_for_exit) { return XDGUtil({"xdg-email", email}, base::FilePath(), wait_for_exit, platform_util::OpenCallback()); } } // namespace namespace platform_util { void ShowItemInFolder(const base::FilePath& full_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); ShowItemHelper::GetInstance().ShowItemInFolder(full_path); } void OpenPath(const base::FilePath& full_path, OpenCallback callback) { // This is async, so we don't care about the return value. XDGOpen(full_path.DirName(), full_path.value(), true, std::move(callback)); } void OpenFolder(const base::FilePath& full_path) { if (!base::DirectoryExists(full_path)) return; XDGOpen(full_path.DirName(), ".", false, platform_util::OpenCallback()); } void OpenExternal(const GURL& url, const OpenExternalOptions& options, OpenCallback callback) { // Don't wait for exit, since we don't want to wait for the browser/email // client window to close before returning if (url.SchemeIs("mailto")) { bool success = XDGEmail(url.spec(), false); std::move(callback).Run(success ? "" : "Failed to open path"); } else { bool success = XDGOpen(base::FilePath(), url.spec(), false, platform_util::OpenCallback()); std::move(callback).Run(success ? "" : "Failed to open path"); } } bool MoveItemToTrash(const base::FilePath& full_path, bool delete_on_fail) { auto env = base::Environment::Create(); // find the trash method std::string trash; if (!env->GetVar(ELECTRON_TRASH, &trash)) { // Determine desktop environment and set accordingly. const auto desktop_env(base::nix::GetDesktopEnvironment(env.get())); if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE4 || desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE5) { trash = "kioclient5"; } else if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE3) { trash = "kioclient"; } } // build the invocation std::vector<std::string> argv; const auto& filename = full_path.value(); if (trash == "kioclient5" || trash == "kioclient") { argv = {trash, "move", filename, "trash:/"}; } else if (trash == "trash-cli") { argv = {"trash-put", filename}; } else if (trash == "gvfs-trash") { argv = {"gvfs-trash", filename}; // deprecated, but still exists } else { argv = {"gio", "trash", filename}; } return XDGUtil(argv, base::FilePath(), true, platform_util::OpenCallback()); } namespace internal { bool PlatformTrashItem(const base::FilePath& full_path, std::string* error) { if (!MoveItemToTrash(full_path, false)) { // TODO(nornagon): at least include the exit code? *error = "Failed to move item to trash"; return false; } return true; } } // namespace internal void Beep() { // echo '\a' > /dev/console FILE* fp = fopen("/dev/console", "a"); if (fp == nullptr) { fp = fopen("/dev/tty", "a"); } if (fp != nullptr) { fprintf(fp, "\a"); fclose(fp); } } bool GetDesktopName(std::string* setme) { return base::Environment::Create()->GetVar("CHROME_DESKTOP", setme); } } // namespace platform_util
closed
electron/electron
https://github.com/electron/electron
33,578
[Bug]: app_id not set when running Electron with native Wayland
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.1 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version 18.0.0 ### Expected Behavior The `app_id` window property should be set to the same value as `class` under X11. ### Actual Behavior `app_id` is an empty string when running Electron under Wayland. ### Testcase Gist URL _No response_ ### Additional Information While most apps would crash prior to #33355, the default page if you run `electron --ozone-platform=wayland` would still run and properly set `app_id`.
https://github.com/electron/electron/issues/33578
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-04-02T08:20:54Z
c++
2022-07-11T18:26:18Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // TODO(ckerr): remove in Electron v20.0.0 // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; return; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) SetWMSpecState(static_cast<x11::Window>(GetAcceleratedWidget()), skip, x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,578
[Bug]: app_id not set when running Electron with native Wayland
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.1 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version 18.0.0 ### Expected Behavior The `app_id` window property should be set to the same value as `class` under X11. ### Actual Behavior `app_id` is an empty string when running Electron under Wayland. ### Testcase Gist URL _No response_ ### Additional Information While most apps would crash prior to #33355, the default page if you run `electron --ozone-platform=wayland` would still run and properly set `app_id`.
https://github.com/electron/electron/issues/33578
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-04-02T08:20:54Z
c++
2022-07-11T18:26:18Z
shell/browser/notifications/linux/libnotify_notification.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/notifications/linux/libnotify_notification.h" #include <set> #include <string> #include "base/files/file_enumerator.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "shell/browser/notifications/notification_delegate.h" #include "shell/browser/ui/gtk_util.h" #include "shell/common/application_info.h" #include "shell/common/platform_util.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gtk/gtk_util.h" // nogncheck namespace electron { namespace { LibNotifyLoader libnotify_loader_; const std::set<std::string>& GetServerCapabilities() { static std::set<std::string> caps; if (caps.empty()) { auto* capabilities = libnotify_loader_.notify_get_server_caps(); for (auto* l = capabilities; l != nullptr; l = l->next) caps.insert(static_cast<const char*>(l->data)); g_list_free_full(capabilities, g_free); } return caps; } bool HasCapability(const std::string& capability) { return GetServerCapabilities().count(capability) != 0; } bool NotifierSupportsActions() { if (getenv("ELECTRON_USE_UBUNTU_NOTIFIER")) return false; return HasCapability("actions"); } void log_and_clear_error(GError* error, const char* context) { LOG(ERROR) << context << ": domain=" << error->domain << " code=" << error->code << " message=\"" << error->message << '"'; g_error_free(error); } } // namespace // static bool LibnotifyNotification::Initialize() { if (!libnotify_loader_.Load("libnotify.so.4") && // most common one !libnotify_loader_.Load("libnotify.so.5") && !libnotify_loader_.Load("libnotify.so.1") && !libnotify_loader_.Load("libnotify.so")) { LOG(WARNING) << "Unable to find libnotify; notifications disabled"; return false; } if (!libnotify_loader_.notify_is_initted() && !libnotify_loader_.notify_init(GetApplicationName().c_str())) { LOG(WARNING) << "Unable to initialize libnotify; notifications disabled"; return false; } return true; } LibnotifyNotification::LibnotifyNotification(NotificationDelegate* delegate, NotificationPresenter* presenter) : Notification(delegate, presenter) {} LibnotifyNotification::~LibnotifyNotification() { if (notification_) { g_signal_handlers_disconnect_by_data(notification_, this); g_object_unref(notification_); } } void LibnotifyNotification::Show(const NotificationOptions& options) { notification_ = libnotify_loader_.notify_notification_new( base::UTF16ToUTF8(options.title).c_str(), base::UTF16ToUTF8(options.msg).c_str(), nullptr); g_signal_connect(notification_, "closed", G_CALLBACK(OnNotificationClosedThunk), this); // NB: On Unity and on any other DE using Notify-OSD, adding a notification // action will cause the notification to display as a modal dialog box. if (NotifierSupportsActions()) { libnotify_loader_.notify_notification_add_action( notification_, "default", "View", OnNotificationViewThunk, this, nullptr); } NotifyUrgency urgency = NOTIFY_URGENCY_NORMAL; if (options.urgency == u"critical") { urgency = NOTIFY_URGENCY_CRITICAL; } else if (options.urgency == u"low") { urgency = NOTIFY_URGENCY_LOW; } // Set the urgency level of the notification. libnotify_loader_.notify_notification_set_urgency(notification_, urgency); if (!options.icon.drawsNothing()) { GdkPixbuf* pixbuf = gtk_util::GdkPixbufFromSkBitmap(options.icon); libnotify_loader_.notify_notification_set_image_from_pixbuf(notification_, pixbuf); g_object_unref(pixbuf); } // Set the timeout duration for the notification bool neverTimeout = options.timeout_type == u"never"; int timeout = (neverTimeout) ? NOTIFY_EXPIRES_NEVER : NOTIFY_EXPIRES_DEFAULT; libnotify_loader_.notify_notification_set_timeout(notification_, timeout); if (!options.tag.empty()) { GQuark id = g_quark_from_string(options.tag.c_str()); g_object_set(G_OBJECT(notification_), "id", id, NULL); } // Always try to append notifications. // Unique tags can be used to prevent this. if (HasCapability("append")) { libnotify_loader_.notify_notification_set_hint_string(notification_, "append", "true"); } else if (HasCapability("x-canonical-append")) { libnotify_loader_.notify_notification_set_hint_string( notification_, "x-canonical-append", "true"); } // Send the desktop name to identify the application // The desktop-entry is the part before the .desktop std::string desktop_id; if (platform_util::GetDesktopName(&desktop_id)) { const std::string suffix{".desktop"}; if (base::EndsWith(desktop_id, suffix, base::CompareCase::INSENSITIVE_ASCII)) { desktop_id.resize(desktop_id.size() - suffix.size()); } libnotify_loader_.notify_notification_set_hint_string( notification_, "desktop-entry", desktop_id.c_str()); } GError* error = nullptr; libnotify_loader_.notify_notification_show(notification_, &error); if (error) { log_and_clear_error(error, "notify_notification_show"); NotificationFailed(); return; } if (delegate()) delegate()->NotificationDisplayed(); } void LibnotifyNotification::Dismiss() { if (!notification_) { Destroy(); return; } GError* error = nullptr; libnotify_loader_.notify_notification_close(notification_, &error); if (error) { log_and_clear_error(error, "notify_notification_close"); Destroy(); } } void LibnotifyNotification::OnNotificationClosed( NotifyNotification* notification) { NotificationDismissed(); } void LibnotifyNotification::OnNotificationView(NotifyNotification* notification, char* action) { NotificationClicked(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,578
[Bug]: app_id not set when running Electron with native Wayland
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.1 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version 18.0.0 ### Expected Behavior The `app_id` window property should be set to the same value as `class` under X11. ### Actual Behavior `app_id` is an empty string when running Electron under Wayland. ### Testcase Gist URL _No response_ ### Additional Information While most apps would crash prior to #33355, the default page if you run `electron --ozone-platform=wayland` would still run and properly set `app_id`.
https://github.com/electron/electron/issues/33578
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-04-02T08:20:54Z
c++
2022-07-11T18:26:18Z
shell/common/platform_util.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_ #define ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_ #include <string> #include "base/callback_forward.h" #include "base/files/file_path.h" #include "build/build_config.h" class GURL; namespace platform_util { typedef base::OnceCallback<void(const std::string&)> OpenCallback; // Show the given file in a file manager. If possible, select the file. // Must be called from the UI thread. void ShowItemInFolder(const base::FilePath& full_path); // Open the given file in the desktop's default manner. // Must be called from the UI thread. void OpenPath(const base::FilePath& full_path, OpenCallback callback); struct OpenExternalOptions { bool activate = true; base::FilePath working_dir; }; // Open the given external protocol URL in the desktop's default manner. // (For example, mailto: URLs in the default mail user agent.) void OpenExternal(const GURL& url, const OpenExternalOptions& options, OpenCallback callback); // Move a file to trash, asynchronously. void TrashItem(const base::FilePath& full_path, base::OnceCallback<void(bool, const std::string&)> callback); void Beep(); #if BUILDFLAG(IS_WIN) // SHGetFolderPath calls not covered by Chromium bool GetFolderPath(int key, base::FilePath* result); #endif #if BUILDFLAG(IS_MAC) bool GetLoginItemEnabled(); bool SetLoginItemEnabled(bool enabled); #endif #if BUILDFLAG(IS_LINUX) // Returns a success flag. // Unlike libgtkui, does *not* use "chromium-browser.desktop" as a fallback. bool GetDesktopName(std::string* setme); #endif } // namespace platform_util #endif // ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_
closed
electron/electron
https://github.com/electron/electron
33,578
[Bug]: app_id not set when running Electron with native Wayland
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.1 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version 18.0.0 ### Expected Behavior The `app_id` window property should be set to the same value as `class` under X11. ### Actual Behavior `app_id` is an empty string when running Electron under Wayland. ### Testcase Gist URL _No response_ ### Additional Information While most apps would crash prior to #33355, the default page if you run `electron --ozone-platform=wayland` would still run and properly set `app_id`.
https://github.com/electron/electron/issues/33578
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-04-02T08:20:54Z
c++
2022-07-11T18:26:18Z
shell/common/platform_util_linux.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/platform_util.h" #include <fcntl.h> #include <stdio.h> #include <string> #include <vector> #include "base/cancelable_callback.h" #include "base/containers/contains.h" #include "base/environment.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/nix/xdg_util.h" #include "base/no_destructor.h" #include "base/posix/eintr_wrapper.h" #include "base/process/kill.h" #include "base/process/launch.h" #include "base/threading/thread_restrictions.h" #include "components/dbus/thread_linux/dbus_thread_linux.h" #include "content/public/browser/browser_thread.h" #include "dbus/bus.h" #include "dbus/message.h" #include "dbus/object_proxy.h" #include "shell/common/platform_util_internal.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gtk/gtk_util.h" // nogncheck #include "url/gurl.h" #define ELECTRON_TRASH "ELECTRON_TRASH" namespace platform_util { void OpenFolder(const base::FilePath& full_path); } namespace { const char kMethodListActivatableNames[] = "ListActivatableNames"; const char kMethodNameHasOwner[] = "NameHasOwner"; const char kFreedesktopFileManagerName[] = "org.freedesktop.FileManager1"; const char kFreedesktopFileManagerPath[] = "/org/freedesktop/FileManager1"; const char kMethodShowItems[] = "ShowItems"; const char kFreedesktopPortalName[] = "org.freedesktop.portal.Desktop"; const char kFreedesktopPortalPath[] = "/org/freedesktop/portal/desktop"; const char kFreedesktopPortalOpenURI[] = "org.freedesktop.portal.OpenURI"; const char kMethodOpenDirectory[] = "OpenDirectory"; class ShowItemHelper { public: static ShowItemHelper& GetInstance() { static base::NoDestructor<ShowItemHelper> instance; return *instance; } ShowItemHelper() {} ShowItemHelper(const ShowItemHelper&) = delete; ShowItemHelper& operator=(const ShowItemHelper&) = delete; void ShowItemInFolder(const base::FilePath& full_path) { if (!bus_) { // Sets up the D-Bus connection. dbus::Bus::Options bus_options; bus_options.bus_type = dbus::Bus::SESSION; bus_options.connection_type = dbus::Bus::PRIVATE; bus_options.dbus_task_runner = dbus_thread_linux::GetTaskRunner(); bus_ = base::MakeRefCounted<dbus::Bus>(bus_options); } if (!dbus_proxy_) { dbus_proxy_ = bus_->GetObjectProxy(DBUS_SERVICE_DBUS, dbus::ObjectPath(DBUS_PATH_DBUS)); } if (prefer_filemanager_interface_.has_value()) { if (prefer_filemanager_interface_.value()) { ShowItemUsingFileManager(full_path); } else { ShowItemUsingFreedesktopPortal(full_path); } } else { CheckFileManagerRunning(full_path); } } private: void CheckFileManagerRunning(const base::FilePath& full_path) { dbus::MethodCall method_call(DBUS_INTERFACE_DBUS, kMethodNameHasOwner); dbus::MessageWriter writer(&method_call); writer.AppendString(kFreedesktopFileManagerName); dbus_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&ShowItemHelper::CheckFileManagerRunningResponse, base::Unretained(this), full_path)); } void CheckFileManagerRunningResponse(const base::FilePath& full_path, dbus::Response* response) { if (prefer_filemanager_interface_.has_value()) { ShowItemInFolder(full_path); return; } bool is_running = false; if (!response) { LOG(ERROR) << "Failed to call " << kMethodNameHasOwner; } else { dbus::MessageReader reader(response); bool owned = false; if (!reader.PopBool(&owned)) { LOG(ERROR) << "Failed to read " << kMethodNameHasOwner << " response"; } else if (owned) { is_running = true; } } if (is_running) { prefer_filemanager_interface_ = true; ShowItemInFolder(full_path); } else { CheckFileManagerActivatable(full_path); } } void CheckFileManagerActivatable(const base::FilePath& full_path) { dbus::MethodCall method_call(DBUS_INTERFACE_DBUS, kMethodListActivatableNames); dbus_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&ShowItemHelper::CheckFileManagerActivatableResponse, base::Unretained(this), full_path)); } void CheckFileManagerActivatableResponse(const base::FilePath& full_path, dbus::Response* response) { if (prefer_filemanager_interface_.has_value()) { ShowItemInFolder(full_path); return; } bool is_activatable = false; if (!response) { LOG(ERROR) << "Failed to call " << kMethodListActivatableNames; } else { dbus::MessageReader reader(response); std::vector<std::string> names; if (!reader.PopArrayOfStrings(&names)) { LOG(ERROR) << "Failed to read " << kMethodListActivatableNames << " response"; } else if (base::Contains(names, kFreedesktopFileManagerName)) { is_activatable = true; } } prefer_filemanager_interface_ = is_activatable; ShowItemInFolder(full_path); } void ShowItemUsingFreedesktopPortal(const base::FilePath& full_path) { if (!object_proxy_) { object_proxy_ = bus_->GetObjectProxy( kFreedesktopPortalName, dbus::ObjectPath(kFreedesktopPortalPath)); } base::ScopedFD fd( HANDLE_EINTR(open(full_path.value().c_str(), O_RDONLY | O_CLOEXEC))); if (!fd.is_valid()) { LOG(ERROR) << "Failed to open " << full_path << " for URI portal"; // If the call fails, at least open the parent folder. platform_util::OpenFolder(full_path.DirName()); return; } dbus::MethodCall open_directory_call(kFreedesktopPortalOpenURI, kMethodOpenDirectory); dbus::MessageWriter writer(&open_directory_call); writer.AppendString(""); // Note that AppendFileDescriptor() duplicates the fd, so we shouldn't // release ownership of it here. writer.AppendFileDescriptor(fd.get()); dbus::MessageWriter options_writer(nullptr); writer.OpenArray("{sv}", &options_writer); writer.CloseContainer(&options_writer); ShowItemUsingBusCall(&open_directory_call, full_path); } void ShowItemUsingFileManager(const base::FilePath& full_path) { if (!object_proxy_) { object_proxy_ = bus_->GetObjectProxy(kFreedesktopFileManagerName, dbus::ObjectPath(kFreedesktopFileManagerPath)); } dbus::MethodCall show_items_call(kFreedesktopFileManagerName, kMethodShowItems); dbus::MessageWriter writer(&show_items_call); writer.AppendArrayOfStrings( {"file://" + full_path.value()}); // List of file(s) to highlight. writer.AppendString({}); // startup-id ShowItemUsingBusCall(&show_items_call, full_path); } void ShowItemUsingBusCall(dbus::MethodCall* call, const base::FilePath& full_path) { object_proxy_->CallMethod( call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&ShowItemHelper::ShowItemInFolderResponse, base::Unretained(this), full_path, call->GetMember())); } void ShowItemInFolderResponse(const base::FilePath& full_path, const std::string& method, dbus::Response* response) { if (response) return; LOG(ERROR) << "Error calling " << method; // If the bus call fails, at least open the parent folder. platform_util::OpenFolder(full_path.DirName()); } scoped_refptr<dbus::Bus> bus_; dbus::ObjectProxy* dbus_proxy_ = nullptr; dbus::ObjectProxy* object_proxy_ = nullptr; absl::optional<bool> prefer_filemanager_interface_; }; // Descriptions pulled from https://linux.die.net/man/1/xdg-open std::string GetErrorDescription(int error_code) { switch (error_code) { case 1: return "Error in command line syntax"; case 2: return "The item does not exist"; case 3: return "A required tool could not be found"; case 4: return "The action failed"; default: return ""; } } bool XDGUtil(const std::vector<std::string>& argv, const base::FilePath& working_directory, const bool wait_for_exit, platform_util::OpenCallback callback) { base::LaunchOptions options; options.current_directory = working_directory; options.allow_new_privs = true; // xdg-open can fall back on mailcap which eventually might plumb through // to a command that needs a terminal. Set the environment variable telling // it that we definitely don't have a terminal available and that it should // bring up a new terminal if necessary. See "man mailcap". options.environment["MM_NOTTTY"] = "1"; base::Process process = base::LaunchProcess(argv, options); if (!process.IsValid()) return false; if (wait_for_exit) { base::ScopedAllowBaseSyncPrimitivesForTesting allow_sync; // required by WaitForExit int exit_code = -1; bool success = process.WaitForExit(&exit_code); if (!callback.is_null()) std::move(callback).Run(GetErrorDescription(exit_code)); return success ? (exit_code == 0) : false; } base::EnsureProcessGetsReaped(std::move(process)); return true; } bool XDGOpen(const base::FilePath& working_directory, const std::string& path, const bool wait_for_exit, platform_util::OpenCallback callback) { return XDGUtil({"xdg-open", path}, working_directory, wait_for_exit, std::move(callback)); } bool XDGEmail(const std::string& email, const bool wait_for_exit) { return XDGUtil({"xdg-email", email}, base::FilePath(), wait_for_exit, platform_util::OpenCallback()); } } // namespace namespace platform_util { void ShowItemInFolder(const base::FilePath& full_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); ShowItemHelper::GetInstance().ShowItemInFolder(full_path); } void OpenPath(const base::FilePath& full_path, OpenCallback callback) { // This is async, so we don't care about the return value. XDGOpen(full_path.DirName(), full_path.value(), true, std::move(callback)); } void OpenFolder(const base::FilePath& full_path) { if (!base::DirectoryExists(full_path)) return; XDGOpen(full_path.DirName(), ".", false, platform_util::OpenCallback()); } void OpenExternal(const GURL& url, const OpenExternalOptions& options, OpenCallback callback) { // Don't wait for exit, since we don't want to wait for the browser/email // client window to close before returning if (url.SchemeIs("mailto")) { bool success = XDGEmail(url.spec(), false); std::move(callback).Run(success ? "" : "Failed to open path"); } else { bool success = XDGOpen(base::FilePath(), url.spec(), false, platform_util::OpenCallback()); std::move(callback).Run(success ? "" : "Failed to open path"); } } bool MoveItemToTrash(const base::FilePath& full_path, bool delete_on_fail) { auto env = base::Environment::Create(); // find the trash method std::string trash; if (!env->GetVar(ELECTRON_TRASH, &trash)) { // Determine desktop environment and set accordingly. const auto desktop_env(base::nix::GetDesktopEnvironment(env.get())); if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE4 || desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE5) { trash = "kioclient5"; } else if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE3) { trash = "kioclient"; } } // build the invocation std::vector<std::string> argv; const auto& filename = full_path.value(); if (trash == "kioclient5" || trash == "kioclient") { argv = {trash, "move", filename, "trash:/"}; } else if (trash == "trash-cli") { argv = {"trash-put", filename}; } else if (trash == "gvfs-trash") { argv = {"gvfs-trash", filename}; // deprecated, but still exists } else { argv = {"gio", "trash", filename}; } return XDGUtil(argv, base::FilePath(), true, platform_util::OpenCallback()); } namespace internal { bool PlatformTrashItem(const base::FilePath& full_path, std::string* error) { if (!MoveItemToTrash(full_path, false)) { // TODO(nornagon): at least include the exit code? *error = "Failed to move item to trash"; return false; } return true; } } // namespace internal void Beep() { // echo '\a' > /dev/console FILE* fp = fopen("/dev/console", "a"); if (fp == nullptr) { fp = fopen("/dev/tty", "a"); } if (fp != nullptr) { fprintf(fp, "\a"); fclose(fp); } } bool GetDesktopName(std::string* setme) { return base::Environment::Create()->GetVar("CHROME_DESKTOP", setme); } } // namespace platform_util
closed
electron/electron
https://github.com/electron/electron
34,852
[Bug]: Electorn 18 app is missing desktopFileName window property
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.4 ### What operating system are you using? Other Linux ### Operating System Version Manjaro Linux ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `desktopFileName` window property should not be empty ![image](https://user-images.githubusercontent.com/61285/177988205-9de3f548-11da-41e7-9d8c-fbc289977148.png) ### Actual Behavior `desktopFileName` window property is empty With Electron 17.4.3 - OK ![image](https://user-images.githubusercontent.com/61285/177988036-3d4dcb27-706a-4708-b853-91c8bf063687.png) ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34852
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-07-08T12:02:26Z
c++
2022-07-11T18:26:18Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // TODO(ckerr): remove in Electron v20.0.0 // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; return; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) SetWMSpecState(static_cast<x11::Window>(GetAcceleratedWidget()), skip, x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,852
[Bug]: Electorn 18 app is missing desktopFileName window property
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.4 ### What operating system are you using? Other Linux ### Operating System Version Manjaro Linux ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `desktopFileName` window property should not be empty ![image](https://user-images.githubusercontent.com/61285/177988205-9de3f548-11da-41e7-9d8c-fbc289977148.png) ### Actual Behavior `desktopFileName` window property is empty With Electron 17.4.3 - OK ![image](https://user-images.githubusercontent.com/61285/177988036-3d4dcb27-706a-4708-b853-91c8bf063687.png) ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34852
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-07-08T12:02:26Z
c++
2022-07-11T18:26:18Z
shell/browser/notifications/linux/libnotify_notification.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/notifications/linux/libnotify_notification.h" #include <set> #include <string> #include "base/files/file_enumerator.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "shell/browser/notifications/notification_delegate.h" #include "shell/browser/ui/gtk_util.h" #include "shell/common/application_info.h" #include "shell/common/platform_util.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gtk/gtk_util.h" // nogncheck namespace electron { namespace { LibNotifyLoader libnotify_loader_; const std::set<std::string>& GetServerCapabilities() { static std::set<std::string> caps; if (caps.empty()) { auto* capabilities = libnotify_loader_.notify_get_server_caps(); for (auto* l = capabilities; l != nullptr; l = l->next) caps.insert(static_cast<const char*>(l->data)); g_list_free_full(capabilities, g_free); } return caps; } bool HasCapability(const std::string& capability) { return GetServerCapabilities().count(capability) != 0; } bool NotifierSupportsActions() { if (getenv("ELECTRON_USE_UBUNTU_NOTIFIER")) return false; return HasCapability("actions"); } void log_and_clear_error(GError* error, const char* context) { LOG(ERROR) << context << ": domain=" << error->domain << " code=" << error->code << " message=\"" << error->message << '"'; g_error_free(error); } } // namespace // static bool LibnotifyNotification::Initialize() { if (!libnotify_loader_.Load("libnotify.so.4") && // most common one !libnotify_loader_.Load("libnotify.so.5") && !libnotify_loader_.Load("libnotify.so.1") && !libnotify_loader_.Load("libnotify.so")) { LOG(WARNING) << "Unable to find libnotify; notifications disabled"; return false; } if (!libnotify_loader_.notify_is_initted() && !libnotify_loader_.notify_init(GetApplicationName().c_str())) { LOG(WARNING) << "Unable to initialize libnotify; notifications disabled"; return false; } return true; } LibnotifyNotification::LibnotifyNotification(NotificationDelegate* delegate, NotificationPresenter* presenter) : Notification(delegate, presenter) {} LibnotifyNotification::~LibnotifyNotification() { if (notification_) { g_signal_handlers_disconnect_by_data(notification_, this); g_object_unref(notification_); } } void LibnotifyNotification::Show(const NotificationOptions& options) { notification_ = libnotify_loader_.notify_notification_new( base::UTF16ToUTF8(options.title).c_str(), base::UTF16ToUTF8(options.msg).c_str(), nullptr); g_signal_connect(notification_, "closed", G_CALLBACK(OnNotificationClosedThunk), this); // NB: On Unity and on any other DE using Notify-OSD, adding a notification // action will cause the notification to display as a modal dialog box. if (NotifierSupportsActions()) { libnotify_loader_.notify_notification_add_action( notification_, "default", "View", OnNotificationViewThunk, this, nullptr); } NotifyUrgency urgency = NOTIFY_URGENCY_NORMAL; if (options.urgency == u"critical") { urgency = NOTIFY_URGENCY_CRITICAL; } else if (options.urgency == u"low") { urgency = NOTIFY_URGENCY_LOW; } // Set the urgency level of the notification. libnotify_loader_.notify_notification_set_urgency(notification_, urgency); if (!options.icon.drawsNothing()) { GdkPixbuf* pixbuf = gtk_util::GdkPixbufFromSkBitmap(options.icon); libnotify_loader_.notify_notification_set_image_from_pixbuf(notification_, pixbuf); g_object_unref(pixbuf); } // Set the timeout duration for the notification bool neverTimeout = options.timeout_type == u"never"; int timeout = (neverTimeout) ? NOTIFY_EXPIRES_NEVER : NOTIFY_EXPIRES_DEFAULT; libnotify_loader_.notify_notification_set_timeout(notification_, timeout); if (!options.tag.empty()) { GQuark id = g_quark_from_string(options.tag.c_str()); g_object_set(G_OBJECT(notification_), "id", id, NULL); } // Always try to append notifications. // Unique tags can be used to prevent this. if (HasCapability("append")) { libnotify_loader_.notify_notification_set_hint_string(notification_, "append", "true"); } else if (HasCapability("x-canonical-append")) { libnotify_loader_.notify_notification_set_hint_string( notification_, "x-canonical-append", "true"); } // Send the desktop name to identify the application // The desktop-entry is the part before the .desktop std::string desktop_id; if (platform_util::GetDesktopName(&desktop_id)) { const std::string suffix{".desktop"}; if (base::EndsWith(desktop_id, suffix, base::CompareCase::INSENSITIVE_ASCII)) { desktop_id.resize(desktop_id.size() - suffix.size()); } libnotify_loader_.notify_notification_set_hint_string( notification_, "desktop-entry", desktop_id.c_str()); } GError* error = nullptr; libnotify_loader_.notify_notification_show(notification_, &error); if (error) { log_and_clear_error(error, "notify_notification_show"); NotificationFailed(); return; } if (delegate()) delegate()->NotificationDisplayed(); } void LibnotifyNotification::Dismiss() { if (!notification_) { Destroy(); return; } GError* error = nullptr; libnotify_loader_.notify_notification_close(notification_, &error); if (error) { log_and_clear_error(error, "notify_notification_close"); Destroy(); } } void LibnotifyNotification::OnNotificationClosed( NotifyNotification* notification) { NotificationDismissed(); } void LibnotifyNotification::OnNotificationView(NotifyNotification* notification, char* action) { NotificationClicked(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,852
[Bug]: Electorn 18 app is missing desktopFileName window property
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.4 ### What operating system are you using? Other Linux ### Operating System Version Manjaro Linux ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `desktopFileName` window property should not be empty ![image](https://user-images.githubusercontent.com/61285/177988205-9de3f548-11da-41e7-9d8c-fbc289977148.png) ### Actual Behavior `desktopFileName` window property is empty With Electron 17.4.3 - OK ![image](https://user-images.githubusercontent.com/61285/177988036-3d4dcb27-706a-4708-b853-91c8bf063687.png) ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34852
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-07-08T12:02:26Z
c++
2022-07-11T18:26:18Z
shell/common/platform_util.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_ #define ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_ #include <string> #include "base/callback_forward.h" #include "base/files/file_path.h" #include "build/build_config.h" class GURL; namespace platform_util { typedef base::OnceCallback<void(const std::string&)> OpenCallback; // Show the given file in a file manager. If possible, select the file. // Must be called from the UI thread. void ShowItemInFolder(const base::FilePath& full_path); // Open the given file in the desktop's default manner. // Must be called from the UI thread. void OpenPath(const base::FilePath& full_path, OpenCallback callback); struct OpenExternalOptions { bool activate = true; base::FilePath working_dir; }; // Open the given external protocol URL in the desktop's default manner. // (For example, mailto: URLs in the default mail user agent.) void OpenExternal(const GURL& url, const OpenExternalOptions& options, OpenCallback callback); // Move a file to trash, asynchronously. void TrashItem(const base::FilePath& full_path, base::OnceCallback<void(bool, const std::string&)> callback); void Beep(); #if BUILDFLAG(IS_WIN) // SHGetFolderPath calls not covered by Chromium bool GetFolderPath(int key, base::FilePath* result); #endif #if BUILDFLAG(IS_MAC) bool GetLoginItemEnabled(); bool SetLoginItemEnabled(bool enabled); #endif #if BUILDFLAG(IS_LINUX) // Returns a success flag. // Unlike libgtkui, does *not* use "chromium-browser.desktop" as a fallback. bool GetDesktopName(std::string* setme); #endif } // namespace platform_util #endif // ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_
closed
electron/electron
https://github.com/electron/electron
34,852
[Bug]: Electorn 18 app is missing desktopFileName window property
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.4 ### What operating system are you using? Other Linux ### Operating System Version Manjaro Linux ### What arch are you using? x64 ### Last Known Working Electron version 17.4.3 ### Expected Behavior `desktopFileName` window property should not be empty ![image](https://user-images.githubusercontent.com/61285/177988205-9de3f548-11da-41e7-9d8c-fbc289977148.png) ### Actual Behavior `desktopFileName` window property is empty With Electron 17.4.3 - OK ![image](https://user-images.githubusercontent.com/61285/177988036-3d4dcb27-706a-4708-b853-91c8bf063687.png) ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34852
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-07-08T12:02:26Z
c++
2022-07-11T18:26:18Z
shell/common/platform_util_linux.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/platform_util.h" #include <fcntl.h> #include <stdio.h> #include <string> #include <vector> #include "base/cancelable_callback.h" #include "base/containers/contains.h" #include "base/environment.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/nix/xdg_util.h" #include "base/no_destructor.h" #include "base/posix/eintr_wrapper.h" #include "base/process/kill.h" #include "base/process/launch.h" #include "base/threading/thread_restrictions.h" #include "components/dbus/thread_linux/dbus_thread_linux.h" #include "content/public/browser/browser_thread.h" #include "dbus/bus.h" #include "dbus/message.h" #include "dbus/object_proxy.h" #include "shell/common/platform_util_internal.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gtk/gtk_util.h" // nogncheck #include "url/gurl.h" #define ELECTRON_TRASH "ELECTRON_TRASH" namespace platform_util { void OpenFolder(const base::FilePath& full_path); } namespace { const char kMethodListActivatableNames[] = "ListActivatableNames"; const char kMethodNameHasOwner[] = "NameHasOwner"; const char kFreedesktopFileManagerName[] = "org.freedesktop.FileManager1"; const char kFreedesktopFileManagerPath[] = "/org/freedesktop/FileManager1"; const char kMethodShowItems[] = "ShowItems"; const char kFreedesktopPortalName[] = "org.freedesktop.portal.Desktop"; const char kFreedesktopPortalPath[] = "/org/freedesktop/portal/desktop"; const char kFreedesktopPortalOpenURI[] = "org.freedesktop.portal.OpenURI"; const char kMethodOpenDirectory[] = "OpenDirectory"; class ShowItemHelper { public: static ShowItemHelper& GetInstance() { static base::NoDestructor<ShowItemHelper> instance; return *instance; } ShowItemHelper() {} ShowItemHelper(const ShowItemHelper&) = delete; ShowItemHelper& operator=(const ShowItemHelper&) = delete; void ShowItemInFolder(const base::FilePath& full_path) { if (!bus_) { // Sets up the D-Bus connection. dbus::Bus::Options bus_options; bus_options.bus_type = dbus::Bus::SESSION; bus_options.connection_type = dbus::Bus::PRIVATE; bus_options.dbus_task_runner = dbus_thread_linux::GetTaskRunner(); bus_ = base::MakeRefCounted<dbus::Bus>(bus_options); } if (!dbus_proxy_) { dbus_proxy_ = bus_->GetObjectProxy(DBUS_SERVICE_DBUS, dbus::ObjectPath(DBUS_PATH_DBUS)); } if (prefer_filemanager_interface_.has_value()) { if (prefer_filemanager_interface_.value()) { ShowItemUsingFileManager(full_path); } else { ShowItemUsingFreedesktopPortal(full_path); } } else { CheckFileManagerRunning(full_path); } } private: void CheckFileManagerRunning(const base::FilePath& full_path) { dbus::MethodCall method_call(DBUS_INTERFACE_DBUS, kMethodNameHasOwner); dbus::MessageWriter writer(&method_call); writer.AppendString(kFreedesktopFileManagerName); dbus_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&ShowItemHelper::CheckFileManagerRunningResponse, base::Unretained(this), full_path)); } void CheckFileManagerRunningResponse(const base::FilePath& full_path, dbus::Response* response) { if (prefer_filemanager_interface_.has_value()) { ShowItemInFolder(full_path); return; } bool is_running = false; if (!response) { LOG(ERROR) << "Failed to call " << kMethodNameHasOwner; } else { dbus::MessageReader reader(response); bool owned = false; if (!reader.PopBool(&owned)) { LOG(ERROR) << "Failed to read " << kMethodNameHasOwner << " response"; } else if (owned) { is_running = true; } } if (is_running) { prefer_filemanager_interface_ = true; ShowItemInFolder(full_path); } else { CheckFileManagerActivatable(full_path); } } void CheckFileManagerActivatable(const base::FilePath& full_path) { dbus::MethodCall method_call(DBUS_INTERFACE_DBUS, kMethodListActivatableNames); dbus_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&ShowItemHelper::CheckFileManagerActivatableResponse, base::Unretained(this), full_path)); } void CheckFileManagerActivatableResponse(const base::FilePath& full_path, dbus::Response* response) { if (prefer_filemanager_interface_.has_value()) { ShowItemInFolder(full_path); return; } bool is_activatable = false; if (!response) { LOG(ERROR) << "Failed to call " << kMethodListActivatableNames; } else { dbus::MessageReader reader(response); std::vector<std::string> names; if (!reader.PopArrayOfStrings(&names)) { LOG(ERROR) << "Failed to read " << kMethodListActivatableNames << " response"; } else if (base::Contains(names, kFreedesktopFileManagerName)) { is_activatable = true; } } prefer_filemanager_interface_ = is_activatable; ShowItemInFolder(full_path); } void ShowItemUsingFreedesktopPortal(const base::FilePath& full_path) { if (!object_proxy_) { object_proxy_ = bus_->GetObjectProxy( kFreedesktopPortalName, dbus::ObjectPath(kFreedesktopPortalPath)); } base::ScopedFD fd( HANDLE_EINTR(open(full_path.value().c_str(), O_RDONLY | O_CLOEXEC))); if (!fd.is_valid()) { LOG(ERROR) << "Failed to open " << full_path << " for URI portal"; // If the call fails, at least open the parent folder. platform_util::OpenFolder(full_path.DirName()); return; } dbus::MethodCall open_directory_call(kFreedesktopPortalOpenURI, kMethodOpenDirectory); dbus::MessageWriter writer(&open_directory_call); writer.AppendString(""); // Note that AppendFileDescriptor() duplicates the fd, so we shouldn't // release ownership of it here. writer.AppendFileDescriptor(fd.get()); dbus::MessageWriter options_writer(nullptr); writer.OpenArray("{sv}", &options_writer); writer.CloseContainer(&options_writer); ShowItemUsingBusCall(&open_directory_call, full_path); } void ShowItemUsingFileManager(const base::FilePath& full_path) { if (!object_proxy_) { object_proxy_ = bus_->GetObjectProxy(kFreedesktopFileManagerName, dbus::ObjectPath(kFreedesktopFileManagerPath)); } dbus::MethodCall show_items_call(kFreedesktopFileManagerName, kMethodShowItems); dbus::MessageWriter writer(&show_items_call); writer.AppendArrayOfStrings( {"file://" + full_path.value()}); // List of file(s) to highlight. writer.AppendString({}); // startup-id ShowItemUsingBusCall(&show_items_call, full_path); } void ShowItemUsingBusCall(dbus::MethodCall* call, const base::FilePath& full_path) { object_proxy_->CallMethod( call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&ShowItemHelper::ShowItemInFolderResponse, base::Unretained(this), full_path, call->GetMember())); } void ShowItemInFolderResponse(const base::FilePath& full_path, const std::string& method, dbus::Response* response) { if (response) return; LOG(ERROR) << "Error calling " << method; // If the bus call fails, at least open the parent folder. platform_util::OpenFolder(full_path.DirName()); } scoped_refptr<dbus::Bus> bus_; dbus::ObjectProxy* dbus_proxy_ = nullptr; dbus::ObjectProxy* object_proxy_ = nullptr; absl::optional<bool> prefer_filemanager_interface_; }; // Descriptions pulled from https://linux.die.net/man/1/xdg-open std::string GetErrorDescription(int error_code) { switch (error_code) { case 1: return "Error in command line syntax"; case 2: return "The item does not exist"; case 3: return "A required tool could not be found"; case 4: return "The action failed"; default: return ""; } } bool XDGUtil(const std::vector<std::string>& argv, const base::FilePath& working_directory, const bool wait_for_exit, platform_util::OpenCallback callback) { base::LaunchOptions options; options.current_directory = working_directory; options.allow_new_privs = true; // xdg-open can fall back on mailcap which eventually might plumb through // to a command that needs a terminal. Set the environment variable telling // it that we definitely don't have a terminal available and that it should // bring up a new terminal if necessary. See "man mailcap". options.environment["MM_NOTTTY"] = "1"; base::Process process = base::LaunchProcess(argv, options); if (!process.IsValid()) return false; if (wait_for_exit) { base::ScopedAllowBaseSyncPrimitivesForTesting allow_sync; // required by WaitForExit int exit_code = -1; bool success = process.WaitForExit(&exit_code); if (!callback.is_null()) std::move(callback).Run(GetErrorDescription(exit_code)); return success ? (exit_code == 0) : false; } base::EnsureProcessGetsReaped(std::move(process)); return true; } bool XDGOpen(const base::FilePath& working_directory, const std::string& path, const bool wait_for_exit, platform_util::OpenCallback callback) { return XDGUtil({"xdg-open", path}, working_directory, wait_for_exit, std::move(callback)); } bool XDGEmail(const std::string& email, const bool wait_for_exit) { return XDGUtil({"xdg-email", email}, base::FilePath(), wait_for_exit, platform_util::OpenCallback()); } } // namespace namespace platform_util { void ShowItemInFolder(const base::FilePath& full_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); ShowItemHelper::GetInstance().ShowItemInFolder(full_path); } void OpenPath(const base::FilePath& full_path, OpenCallback callback) { // This is async, so we don't care about the return value. XDGOpen(full_path.DirName(), full_path.value(), true, std::move(callback)); } void OpenFolder(const base::FilePath& full_path) { if (!base::DirectoryExists(full_path)) return; XDGOpen(full_path.DirName(), ".", false, platform_util::OpenCallback()); } void OpenExternal(const GURL& url, const OpenExternalOptions& options, OpenCallback callback) { // Don't wait for exit, since we don't want to wait for the browser/email // client window to close before returning if (url.SchemeIs("mailto")) { bool success = XDGEmail(url.spec(), false); std::move(callback).Run(success ? "" : "Failed to open path"); } else { bool success = XDGOpen(base::FilePath(), url.spec(), false, platform_util::OpenCallback()); std::move(callback).Run(success ? "" : "Failed to open path"); } } bool MoveItemToTrash(const base::FilePath& full_path, bool delete_on_fail) { auto env = base::Environment::Create(); // find the trash method std::string trash; if (!env->GetVar(ELECTRON_TRASH, &trash)) { // Determine desktop environment and set accordingly. const auto desktop_env(base::nix::GetDesktopEnvironment(env.get())); if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE4 || desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE5) { trash = "kioclient5"; } else if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE3) { trash = "kioclient"; } } // build the invocation std::vector<std::string> argv; const auto& filename = full_path.value(); if (trash == "kioclient5" || trash == "kioclient") { argv = {trash, "move", filename, "trash:/"}; } else if (trash == "trash-cli") { argv = {"trash-put", filename}; } else if (trash == "gvfs-trash") { argv = {"gvfs-trash", filename}; // deprecated, but still exists } else { argv = {"gio", "trash", filename}; } return XDGUtil(argv, base::FilePath(), true, platform_util::OpenCallback()); } namespace internal { bool PlatformTrashItem(const base::FilePath& full_path, std::string* error) { if (!MoveItemToTrash(full_path, false)) { // TODO(nornagon): at least include the exit code? *error = "Failed to move item to trash"; return false; } return true; } } // namespace internal void Beep() { // echo '\a' > /dev/console FILE* fp = fopen("/dev/console", "a"); if (fp == nullptr) { fp = fopen("/dev/tty", "a"); } if (fp != nullptr) { fprintf(fp, "\a"); fclose(fp); } } bool GetDesktopName(std::string* setme) { return base::Environment::Create()->GetVar("CHROME_DESKTOP", setme); } } // namespace platform_util
closed
electron/electron
https://github.com/electron/electron
33,578
[Bug]: app_id not set when running Electron with native Wayland
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.1 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version 18.0.0 ### Expected Behavior The `app_id` window property should be set to the same value as `class` under X11. ### Actual Behavior `app_id` is an empty string when running Electron under Wayland. ### Testcase Gist URL _No response_ ### Additional Information While most apps would crash prior to #33355, the default page if you run `electron --ozone-platform=wayland` would still run and properly set `app_id`.
https://github.com/electron/electron/issues/33578
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-04-02T08:20:54Z
c++
2022-07-11T18:26:18Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // TODO(ckerr): remove in Electron v20.0.0 // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; return; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) SetWMSpecState(static_cast<x11::Window>(GetAcceleratedWidget()), skip, x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,578
[Bug]: app_id not set when running Electron with native Wayland
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.1 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version 18.0.0 ### Expected Behavior The `app_id` window property should be set to the same value as `class` under X11. ### Actual Behavior `app_id` is an empty string when running Electron under Wayland. ### Testcase Gist URL _No response_ ### Additional Information While most apps would crash prior to #33355, the default page if you run `electron --ozone-platform=wayland` would still run and properly set `app_id`.
https://github.com/electron/electron/issues/33578
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-04-02T08:20:54Z
c++
2022-07-11T18:26:18Z
shell/browser/notifications/linux/libnotify_notification.cc
// Copyright (c) 2015 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/notifications/linux/libnotify_notification.h" #include <set> #include <string> #include "base/files/file_enumerator.h" #include "base/logging.h" #include "base/strings/string_util.h" #include "base/strings/utf_string_conversions.h" #include "shell/browser/notifications/notification_delegate.h" #include "shell/browser/ui/gtk_util.h" #include "shell/common/application_info.h" #include "shell/common/platform_util.h" #include "third_party/skia/include/core/SkBitmap.h" #include "ui/gtk/gtk_util.h" // nogncheck namespace electron { namespace { LibNotifyLoader libnotify_loader_; const std::set<std::string>& GetServerCapabilities() { static std::set<std::string> caps; if (caps.empty()) { auto* capabilities = libnotify_loader_.notify_get_server_caps(); for (auto* l = capabilities; l != nullptr; l = l->next) caps.insert(static_cast<const char*>(l->data)); g_list_free_full(capabilities, g_free); } return caps; } bool HasCapability(const std::string& capability) { return GetServerCapabilities().count(capability) != 0; } bool NotifierSupportsActions() { if (getenv("ELECTRON_USE_UBUNTU_NOTIFIER")) return false; return HasCapability("actions"); } void log_and_clear_error(GError* error, const char* context) { LOG(ERROR) << context << ": domain=" << error->domain << " code=" << error->code << " message=\"" << error->message << '"'; g_error_free(error); } } // namespace // static bool LibnotifyNotification::Initialize() { if (!libnotify_loader_.Load("libnotify.so.4") && // most common one !libnotify_loader_.Load("libnotify.so.5") && !libnotify_loader_.Load("libnotify.so.1") && !libnotify_loader_.Load("libnotify.so")) { LOG(WARNING) << "Unable to find libnotify; notifications disabled"; return false; } if (!libnotify_loader_.notify_is_initted() && !libnotify_loader_.notify_init(GetApplicationName().c_str())) { LOG(WARNING) << "Unable to initialize libnotify; notifications disabled"; return false; } return true; } LibnotifyNotification::LibnotifyNotification(NotificationDelegate* delegate, NotificationPresenter* presenter) : Notification(delegate, presenter) {} LibnotifyNotification::~LibnotifyNotification() { if (notification_) { g_signal_handlers_disconnect_by_data(notification_, this); g_object_unref(notification_); } } void LibnotifyNotification::Show(const NotificationOptions& options) { notification_ = libnotify_loader_.notify_notification_new( base::UTF16ToUTF8(options.title).c_str(), base::UTF16ToUTF8(options.msg).c_str(), nullptr); g_signal_connect(notification_, "closed", G_CALLBACK(OnNotificationClosedThunk), this); // NB: On Unity and on any other DE using Notify-OSD, adding a notification // action will cause the notification to display as a modal dialog box. if (NotifierSupportsActions()) { libnotify_loader_.notify_notification_add_action( notification_, "default", "View", OnNotificationViewThunk, this, nullptr); } NotifyUrgency urgency = NOTIFY_URGENCY_NORMAL; if (options.urgency == u"critical") { urgency = NOTIFY_URGENCY_CRITICAL; } else if (options.urgency == u"low") { urgency = NOTIFY_URGENCY_LOW; } // Set the urgency level of the notification. libnotify_loader_.notify_notification_set_urgency(notification_, urgency); if (!options.icon.drawsNothing()) { GdkPixbuf* pixbuf = gtk_util::GdkPixbufFromSkBitmap(options.icon); libnotify_loader_.notify_notification_set_image_from_pixbuf(notification_, pixbuf); g_object_unref(pixbuf); } // Set the timeout duration for the notification bool neverTimeout = options.timeout_type == u"never"; int timeout = (neverTimeout) ? NOTIFY_EXPIRES_NEVER : NOTIFY_EXPIRES_DEFAULT; libnotify_loader_.notify_notification_set_timeout(notification_, timeout); if (!options.tag.empty()) { GQuark id = g_quark_from_string(options.tag.c_str()); g_object_set(G_OBJECT(notification_), "id", id, NULL); } // Always try to append notifications. // Unique tags can be used to prevent this. if (HasCapability("append")) { libnotify_loader_.notify_notification_set_hint_string(notification_, "append", "true"); } else if (HasCapability("x-canonical-append")) { libnotify_loader_.notify_notification_set_hint_string( notification_, "x-canonical-append", "true"); } // Send the desktop name to identify the application // The desktop-entry is the part before the .desktop std::string desktop_id; if (platform_util::GetDesktopName(&desktop_id)) { const std::string suffix{".desktop"}; if (base::EndsWith(desktop_id, suffix, base::CompareCase::INSENSITIVE_ASCII)) { desktop_id.resize(desktop_id.size() - suffix.size()); } libnotify_loader_.notify_notification_set_hint_string( notification_, "desktop-entry", desktop_id.c_str()); } GError* error = nullptr; libnotify_loader_.notify_notification_show(notification_, &error); if (error) { log_and_clear_error(error, "notify_notification_show"); NotificationFailed(); return; } if (delegate()) delegate()->NotificationDisplayed(); } void LibnotifyNotification::Dismiss() { if (!notification_) { Destroy(); return; } GError* error = nullptr; libnotify_loader_.notify_notification_close(notification_, &error); if (error) { log_and_clear_error(error, "notify_notification_close"); Destroy(); } } void LibnotifyNotification::OnNotificationClosed( NotifyNotification* notification) { NotificationDismissed(); } void LibnotifyNotification::OnNotificationView(NotifyNotification* notification, char* action) { NotificationClicked(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,578
[Bug]: app_id not set when running Electron with native Wayland
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.1 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version 18.0.0 ### Expected Behavior The `app_id` window property should be set to the same value as `class` under X11. ### Actual Behavior `app_id` is an empty string when running Electron under Wayland. ### Testcase Gist URL _No response_ ### Additional Information While most apps would crash prior to #33355, the default page if you run `electron --ozone-platform=wayland` would still run and properly set `app_id`.
https://github.com/electron/electron/issues/33578
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-04-02T08:20:54Z
c++
2022-07-11T18:26:18Z
shell/common/platform_util.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_ #define ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_ #include <string> #include "base/callback_forward.h" #include "base/files/file_path.h" #include "build/build_config.h" class GURL; namespace platform_util { typedef base::OnceCallback<void(const std::string&)> OpenCallback; // Show the given file in a file manager. If possible, select the file. // Must be called from the UI thread. void ShowItemInFolder(const base::FilePath& full_path); // Open the given file in the desktop's default manner. // Must be called from the UI thread. void OpenPath(const base::FilePath& full_path, OpenCallback callback); struct OpenExternalOptions { bool activate = true; base::FilePath working_dir; }; // Open the given external protocol URL in the desktop's default manner. // (For example, mailto: URLs in the default mail user agent.) void OpenExternal(const GURL& url, const OpenExternalOptions& options, OpenCallback callback); // Move a file to trash, asynchronously. void TrashItem(const base::FilePath& full_path, base::OnceCallback<void(bool, const std::string&)> callback); void Beep(); #if BUILDFLAG(IS_WIN) // SHGetFolderPath calls not covered by Chromium bool GetFolderPath(int key, base::FilePath* result); #endif #if BUILDFLAG(IS_MAC) bool GetLoginItemEnabled(); bool SetLoginItemEnabled(bool enabled); #endif #if BUILDFLAG(IS_LINUX) // Returns a success flag. // Unlike libgtkui, does *not* use "chromium-browser.desktop" as a fallback. bool GetDesktopName(std::string* setme); #endif } // namespace platform_util #endif // ELECTRON_SHELL_COMMON_PLATFORM_UTIL_H_
closed
electron/electron
https://github.com/electron/electron
33,578
[Bug]: app_id not set when running Electron with native Wayland
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.1 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version 18.0.0 ### Expected Behavior The `app_id` window property should be set to the same value as `class` under X11. ### Actual Behavior `app_id` is an empty string when running Electron under Wayland. ### Testcase Gist URL _No response_ ### Additional Information While most apps would crash prior to #33355, the default page if you run `electron --ozone-platform=wayland` would still run and properly set `app_id`.
https://github.com/electron/electron/issues/33578
https://github.com/electron/electron/pull/34855
8f3fb8db09ac049894c8ab099979810899f9435b
f63bba8ce24917f1c78a8804496fe0f5b461b0af
2022-04-02T08:20:54Z
c++
2022-07-11T18:26:18Z
shell/common/platform_util_linux.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/common/platform_util.h" #include <fcntl.h> #include <stdio.h> #include <string> #include <vector> #include "base/cancelable_callback.h" #include "base/containers/contains.h" #include "base/environment.h" #include "base/files/file_util.h" #include "base/logging.h" #include "base/nix/xdg_util.h" #include "base/no_destructor.h" #include "base/posix/eintr_wrapper.h" #include "base/process/kill.h" #include "base/process/launch.h" #include "base/threading/thread_restrictions.h" #include "components/dbus/thread_linux/dbus_thread_linux.h" #include "content/public/browser/browser_thread.h" #include "dbus/bus.h" #include "dbus/message.h" #include "dbus/object_proxy.h" #include "shell/common/platform_util_internal.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/gtk/gtk_util.h" // nogncheck #include "url/gurl.h" #define ELECTRON_TRASH "ELECTRON_TRASH" namespace platform_util { void OpenFolder(const base::FilePath& full_path); } namespace { const char kMethodListActivatableNames[] = "ListActivatableNames"; const char kMethodNameHasOwner[] = "NameHasOwner"; const char kFreedesktopFileManagerName[] = "org.freedesktop.FileManager1"; const char kFreedesktopFileManagerPath[] = "/org/freedesktop/FileManager1"; const char kMethodShowItems[] = "ShowItems"; const char kFreedesktopPortalName[] = "org.freedesktop.portal.Desktop"; const char kFreedesktopPortalPath[] = "/org/freedesktop/portal/desktop"; const char kFreedesktopPortalOpenURI[] = "org.freedesktop.portal.OpenURI"; const char kMethodOpenDirectory[] = "OpenDirectory"; class ShowItemHelper { public: static ShowItemHelper& GetInstance() { static base::NoDestructor<ShowItemHelper> instance; return *instance; } ShowItemHelper() {} ShowItemHelper(const ShowItemHelper&) = delete; ShowItemHelper& operator=(const ShowItemHelper&) = delete; void ShowItemInFolder(const base::FilePath& full_path) { if (!bus_) { // Sets up the D-Bus connection. dbus::Bus::Options bus_options; bus_options.bus_type = dbus::Bus::SESSION; bus_options.connection_type = dbus::Bus::PRIVATE; bus_options.dbus_task_runner = dbus_thread_linux::GetTaskRunner(); bus_ = base::MakeRefCounted<dbus::Bus>(bus_options); } if (!dbus_proxy_) { dbus_proxy_ = bus_->GetObjectProxy(DBUS_SERVICE_DBUS, dbus::ObjectPath(DBUS_PATH_DBUS)); } if (prefer_filemanager_interface_.has_value()) { if (prefer_filemanager_interface_.value()) { ShowItemUsingFileManager(full_path); } else { ShowItemUsingFreedesktopPortal(full_path); } } else { CheckFileManagerRunning(full_path); } } private: void CheckFileManagerRunning(const base::FilePath& full_path) { dbus::MethodCall method_call(DBUS_INTERFACE_DBUS, kMethodNameHasOwner); dbus::MessageWriter writer(&method_call); writer.AppendString(kFreedesktopFileManagerName); dbus_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&ShowItemHelper::CheckFileManagerRunningResponse, base::Unretained(this), full_path)); } void CheckFileManagerRunningResponse(const base::FilePath& full_path, dbus::Response* response) { if (prefer_filemanager_interface_.has_value()) { ShowItemInFolder(full_path); return; } bool is_running = false; if (!response) { LOG(ERROR) << "Failed to call " << kMethodNameHasOwner; } else { dbus::MessageReader reader(response); bool owned = false; if (!reader.PopBool(&owned)) { LOG(ERROR) << "Failed to read " << kMethodNameHasOwner << " response"; } else if (owned) { is_running = true; } } if (is_running) { prefer_filemanager_interface_ = true; ShowItemInFolder(full_path); } else { CheckFileManagerActivatable(full_path); } } void CheckFileManagerActivatable(const base::FilePath& full_path) { dbus::MethodCall method_call(DBUS_INTERFACE_DBUS, kMethodListActivatableNames); dbus_proxy_->CallMethod( &method_call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&ShowItemHelper::CheckFileManagerActivatableResponse, base::Unretained(this), full_path)); } void CheckFileManagerActivatableResponse(const base::FilePath& full_path, dbus::Response* response) { if (prefer_filemanager_interface_.has_value()) { ShowItemInFolder(full_path); return; } bool is_activatable = false; if (!response) { LOG(ERROR) << "Failed to call " << kMethodListActivatableNames; } else { dbus::MessageReader reader(response); std::vector<std::string> names; if (!reader.PopArrayOfStrings(&names)) { LOG(ERROR) << "Failed to read " << kMethodListActivatableNames << " response"; } else if (base::Contains(names, kFreedesktopFileManagerName)) { is_activatable = true; } } prefer_filemanager_interface_ = is_activatable; ShowItemInFolder(full_path); } void ShowItemUsingFreedesktopPortal(const base::FilePath& full_path) { if (!object_proxy_) { object_proxy_ = bus_->GetObjectProxy( kFreedesktopPortalName, dbus::ObjectPath(kFreedesktopPortalPath)); } base::ScopedFD fd( HANDLE_EINTR(open(full_path.value().c_str(), O_RDONLY | O_CLOEXEC))); if (!fd.is_valid()) { LOG(ERROR) << "Failed to open " << full_path << " for URI portal"; // If the call fails, at least open the parent folder. platform_util::OpenFolder(full_path.DirName()); return; } dbus::MethodCall open_directory_call(kFreedesktopPortalOpenURI, kMethodOpenDirectory); dbus::MessageWriter writer(&open_directory_call); writer.AppendString(""); // Note that AppendFileDescriptor() duplicates the fd, so we shouldn't // release ownership of it here. writer.AppendFileDescriptor(fd.get()); dbus::MessageWriter options_writer(nullptr); writer.OpenArray("{sv}", &options_writer); writer.CloseContainer(&options_writer); ShowItemUsingBusCall(&open_directory_call, full_path); } void ShowItemUsingFileManager(const base::FilePath& full_path) { if (!object_proxy_) { object_proxy_ = bus_->GetObjectProxy(kFreedesktopFileManagerName, dbus::ObjectPath(kFreedesktopFileManagerPath)); } dbus::MethodCall show_items_call(kFreedesktopFileManagerName, kMethodShowItems); dbus::MessageWriter writer(&show_items_call); writer.AppendArrayOfStrings( {"file://" + full_path.value()}); // List of file(s) to highlight. writer.AppendString({}); // startup-id ShowItemUsingBusCall(&show_items_call, full_path); } void ShowItemUsingBusCall(dbus::MethodCall* call, const base::FilePath& full_path) { object_proxy_->CallMethod( call, dbus::ObjectProxy::TIMEOUT_USE_DEFAULT, base::BindOnce(&ShowItemHelper::ShowItemInFolderResponse, base::Unretained(this), full_path, call->GetMember())); } void ShowItemInFolderResponse(const base::FilePath& full_path, const std::string& method, dbus::Response* response) { if (response) return; LOG(ERROR) << "Error calling " << method; // If the bus call fails, at least open the parent folder. platform_util::OpenFolder(full_path.DirName()); } scoped_refptr<dbus::Bus> bus_; dbus::ObjectProxy* dbus_proxy_ = nullptr; dbus::ObjectProxy* object_proxy_ = nullptr; absl::optional<bool> prefer_filemanager_interface_; }; // Descriptions pulled from https://linux.die.net/man/1/xdg-open std::string GetErrorDescription(int error_code) { switch (error_code) { case 1: return "Error in command line syntax"; case 2: return "The item does not exist"; case 3: return "A required tool could not be found"; case 4: return "The action failed"; default: return ""; } } bool XDGUtil(const std::vector<std::string>& argv, const base::FilePath& working_directory, const bool wait_for_exit, platform_util::OpenCallback callback) { base::LaunchOptions options; options.current_directory = working_directory; options.allow_new_privs = true; // xdg-open can fall back on mailcap which eventually might plumb through // to a command that needs a terminal. Set the environment variable telling // it that we definitely don't have a terminal available and that it should // bring up a new terminal if necessary. See "man mailcap". options.environment["MM_NOTTTY"] = "1"; base::Process process = base::LaunchProcess(argv, options); if (!process.IsValid()) return false; if (wait_for_exit) { base::ScopedAllowBaseSyncPrimitivesForTesting allow_sync; // required by WaitForExit int exit_code = -1; bool success = process.WaitForExit(&exit_code); if (!callback.is_null()) std::move(callback).Run(GetErrorDescription(exit_code)); return success ? (exit_code == 0) : false; } base::EnsureProcessGetsReaped(std::move(process)); return true; } bool XDGOpen(const base::FilePath& working_directory, const std::string& path, const bool wait_for_exit, platform_util::OpenCallback callback) { return XDGUtil({"xdg-open", path}, working_directory, wait_for_exit, std::move(callback)); } bool XDGEmail(const std::string& email, const bool wait_for_exit) { return XDGUtil({"xdg-email", email}, base::FilePath(), wait_for_exit, platform_util::OpenCallback()); } } // namespace namespace platform_util { void ShowItemInFolder(const base::FilePath& full_path) { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); ShowItemHelper::GetInstance().ShowItemInFolder(full_path); } void OpenPath(const base::FilePath& full_path, OpenCallback callback) { // This is async, so we don't care about the return value. XDGOpen(full_path.DirName(), full_path.value(), true, std::move(callback)); } void OpenFolder(const base::FilePath& full_path) { if (!base::DirectoryExists(full_path)) return; XDGOpen(full_path.DirName(), ".", false, platform_util::OpenCallback()); } void OpenExternal(const GURL& url, const OpenExternalOptions& options, OpenCallback callback) { // Don't wait for exit, since we don't want to wait for the browser/email // client window to close before returning if (url.SchemeIs("mailto")) { bool success = XDGEmail(url.spec(), false); std::move(callback).Run(success ? "" : "Failed to open path"); } else { bool success = XDGOpen(base::FilePath(), url.spec(), false, platform_util::OpenCallback()); std::move(callback).Run(success ? "" : "Failed to open path"); } } bool MoveItemToTrash(const base::FilePath& full_path, bool delete_on_fail) { auto env = base::Environment::Create(); // find the trash method std::string trash; if (!env->GetVar(ELECTRON_TRASH, &trash)) { // Determine desktop environment and set accordingly. const auto desktop_env(base::nix::GetDesktopEnvironment(env.get())); if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE4 || desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE5) { trash = "kioclient5"; } else if (desktop_env == base::nix::DESKTOP_ENVIRONMENT_KDE3) { trash = "kioclient"; } } // build the invocation std::vector<std::string> argv; const auto& filename = full_path.value(); if (trash == "kioclient5" || trash == "kioclient") { argv = {trash, "move", filename, "trash:/"}; } else if (trash == "trash-cli") { argv = {"trash-put", filename}; } else if (trash == "gvfs-trash") { argv = {"gvfs-trash", filename}; // deprecated, but still exists } else { argv = {"gio", "trash", filename}; } return XDGUtil(argv, base::FilePath(), true, platform_util::OpenCallback()); } namespace internal { bool PlatformTrashItem(const base::FilePath& full_path, std::string* error) { if (!MoveItemToTrash(full_path, false)) { // TODO(nornagon): at least include the exit code? *error = "Failed to move item to trash"; return false; } return true; } } // namespace internal void Beep() { // echo '\a' > /dev/console FILE* fp = fopen("/dev/console", "a"); if (fp == nullptr) { fp = fopen("/dev/tty", "a"); } if (fp != nullptr) { fprintf(fp, "\a"); fclose(fp); } } bool GetDesktopName(std::string* setme) { return base::Environment::Create()->GetVar("CHROME_DESKTOP", setme); } } // namespace platform_util
closed
electron/electron
https://github.com/electron/electron
32,889
[Bug]: AlwaysOnTop is not working
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version v17.0.0-alpha.4 ### What operating system are you using? Ubuntu ### Operating System Version Linux 5.16.8-051608-generic #202202101327-Ubuntu SMP PREEMPT Thu Feb 10 13:36:40 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux ### What arch are you using? x64 ### Last Known Working Electron version v17.0.0-alpha.3 ### Expected Behavior Window stays always on top. The gnome menu should indicate that "always on top" is set. ### Actual Behavior Window does not stays always on top. The gnome menu does not indicate that "always on top" is set. ### Testcase Gist URL https://gist.github.com/69c948d4ed20768b71d6332efe61fc77 ### Additional Information _No response_
https://github.com/electron/electron/issues/32889
https://github.com/electron/electron/pull/34766
46e5c537c87d8f81e468448629c36995329f824b
440c575aa6c47a2258824945fa5442c5a89cfe0f
2022-02-14T15:32:43Z
c++
2022-07-13T18:59:57Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // TODO(ckerr): remove in Electron v20.0.0 // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; return; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) SetWMSpecState(static_cast<x11::Window>(GetAcceleratedWidget()), skip, x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
32,889
[Bug]: AlwaysOnTop is not working
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version v17.0.0-alpha.4 ### What operating system are you using? Ubuntu ### Operating System Version Linux 5.16.8-051608-generic #202202101327-Ubuntu SMP PREEMPT Thu Feb 10 13:36:40 UTC 2022 x86_64 x86_64 x86_64 GNU/Linux ### What arch are you using? x64 ### Last Known Working Electron version v17.0.0-alpha.3 ### Expected Behavior Window stays always on top. The gnome menu should indicate that "always on top" is set. ### Actual Behavior Window does not stays always on top. The gnome menu does not indicate that "always on top" is set. ### Testcase Gist URL https://gist.github.com/69c948d4ed20768b71d6332efe61fc77 ### Additional Information _No response_
https://github.com/electron/electron/issues/32889
https://github.com/electron/electron/pull/34766
46e5c537c87d8f81e468448629c36995329f824b
440c575aa6c47a2258824945fa5442c5a89cfe0f
2022-02-14T15:32:43Z
c++
2022-07-13T18:59:57Z
shell/browser/native_window_views.cc
// Copyright (c) 2014 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_views.h" #if BUILDFLAG(IS_WIN) #include <wrl/client.h> #endif #include <memory> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/stl_util.h" #include "base/strings/utf_string_conversions.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/native_browser_view_views.h" #include "shell/browser/ui/drag_util.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/ui/views/root_view.h" #include "shell/browser/web_contents_preferences.h" #include "shell/browser/web_view_manager.h" #include "shell/browser/window_list.h" #include "shell/common/electron_constants.h" #include "shell/common/gin_converters/image_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/options_switches.h" #include "ui/aura/window_tree_host.h" #include "ui/base/hit_test.h" #include "ui/gfx/image/image.h" #include "ui/gfx/native_widget_types.h" #include "ui/views/background.h" #include "ui/views/controls/webview/unhandled_keyboard_event_handler.h" #include "ui/views/controls/webview/webview.h" #include "ui/views/widget/native_widget_private.h" #include "ui/views/widget/widget.h" #include "ui/views/window/client_view.h" #include "ui/wm/core/shadow_types.h" #include "ui/wm/core/window_util.h" #if BUILDFLAG(IS_LINUX) #include "base/strings/string_util.h" #include "shell/browser/browser.h" #include "shell/browser/linux/unity_service.h" #include "shell/browser/ui/electron_desktop_window_tree_host_linux.h" #include "shell/browser/ui/views/client_frame_view_linux.h" #include "shell/browser/ui/views/frameless_view.h" #include "shell/browser/ui/views/native_frame_view.h" #include "shell/common/platform_util.h" #include "ui/views/widget/desktop_aura/desktop_native_widget_aura.h" #include "ui/views/window/native_frame_view.h" #if defined(USE_OZONE) #include "shell/browser/ui/views/global_menu_bar_x11.h" #include "shell/browser/ui/x/event_disabler.h" #include "shell/browser/ui/x/x_window_utils.h" #include "ui/base/x/x11_util.h" #include "ui/gfx/x/shape.h" #include "ui/gfx/x/x11_atom_cache.h" #include "ui/gfx/x/xproto.h" #include "ui/gfx/x/xproto_util.h" #include "ui/ozone/public/ozone_platform.h" #endif #elif BUILDFLAG(IS_WIN) #include "base/win/win_util.h" #include "content/public/common/color_parser.h" #include "shell/browser/ui/views/win_frame_view.h" #include "shell/browser/ui/win/electron_desktop_native_widget_aura.h" #include "skia/ext/skia_utils_win.h" #include "ui/base/win/shell.h" #include "ui/display/screen.h" #include "ui/display/win/screen_win.h" #include "ui/gfx/color_utils.h" #endif namespace electron { #if BUILDFLAG(IS_WIN) // Similar to the ones in display::win::ScreenWin, but with rounded values // These help to avoid problems that arise from unresizable windows where the // original ceil()-ed values can cause calculation errors, since converting // both ways goes through a ceil() call. Related issue: #15816 gfx::Rect ScreenToDIPRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect dip_rect = ScaleToRoundedRect(pixel_bounds, 1.0f / scale_factor); dip_rect.set_origin( display::win::ScreenWin::ScreenToDIPRect(hwnd, pixel_bounds).origin()); return dip_rect; } #endif namespace { #if BUILDFLAG(IS_WIN) const LPCWSTR kUniqueTaskBarClassName = L"Shell_TrayWnd"; void FlipWindowStyle(HWND handle, bool on, DWORD flag) { DWORD style = ::GetWindowLong(handle, GWL_STYLE); if (on) style |= flag; else style &= ~flag; ::SetWindowLong(handle, GWL_STYLE, style); // Window's frame styles are cached so we need to call SetWindowPos // with the SWP_FRAMECHANGED flag to update cache properly. ::SetWindowPos(handle, 0, 0, 0, 0, 0, // ignored SWP_FRAMECHANGED | SWP_NOMOVE | SWP_NOSIZE | SWP_NOZORDER | SWP_NOACTIVATE | SWP_NOOWNERZORDER); } gfx::Rect DIPToScreenRect(HWND hwnd, const gfx::Rect& pixel_bounds) { float scale_factor = display::win::ScreenWin::GetScaleFactorForHWND(hwnd); gfx::Rect screen_rect = ScaleToRoundedRect(pixel_bounds, scale_factor); screen_rect.set_origin( display::win::ScreenWin::DIPToScreenRect(hwnd, pixel_bounds).origin()); return screen_rect; } #endif #if defined(USE_OZONE) bool CreateGlobalMenuBar() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .supports_global_application_menus; } #endif #if defined(USE_OZONE_PLATFORM_X11) bool IsX11() { return ui::OzonePlatform::GetInstance() ->GetPlatformProperties() .electron_can_call_x11; } #endif class NativeWindowClientView : public views::ClientView { public: NativeWindowClientView(views::Widget* widget, views::View* root_view, NativeWindowViews* window) : views::ClientView(widget, root_view), window_(window) {} ~NativeWindowClientView() override = default; // disable copy NativeWindowClientView(const NativeWindowClientView&) = delete; NativeWindowClientView& operator=(const NativeWindowClientView&) = delete; views::CloseRequestResult OnWindowCloseRequested() override { window_->NotifyWindowCloseButtonClicked(); return views::CloseRequestResult::kCannotClose; } private: NativeWindowViews* window_; }; } // namespace NativeWindowViews::NativeWindowViews(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(std::make_unique<RootView>(this)), keyboard_event_handler_( std::make_unique<views::UnhandledKeyboardEventHandler>()) { options.Get(options::kTitle, &title_); bool menu_bar_autohide; if (options.Get(options::kAutoHideMenuBar, &menu_bar_autohide)) root_view_->SetAutoHideMenuBar(menu_bar_autohide); #if BUILDFLAG(IS_WIN) // On Windows we rely on the CanResize() to indicate whether window can be // resized, and it should be set before window is created. options.Get(options::kResizable, &resizable_); options.Get(options::kMinimizable, &minimizable_); options.Get(options::kMaximizable, &maximizable_); // Transparent window must not have thick frame. options.Get("thickFrame", &thick_frame_); if (transparent()) thick_frame_ = false; overlay_button_color_ = color_utils::GetSysSkColor(COLOR_BTNFACE); overlay_symbol_color_ = color_utils::GetSysSkColor(COLOR_BTNTEXT); v8::Local<v8::Value> titlebar_overlay; if (options.Get(options::ktitleBarOverlay, &titlebar_overlay) && titlebar_overlay->IsObject()) { gin_helper::Dictionary titlebar_overlay_obj = gin::Dictionary::CreateEmpty(options.isolate()); options.Get(options::ktitleBarOverlay, &titlebar_overlay_obj); std::string overlay_color_string; if (titlebar_overlay_obj.Get(options::kOverlayButtonColor, &overlay_color_string)) { bool success = content::ParseCssColorString(overlay_color_string, &overlay_button_color_); DCHECK(success); } std::string overlay_symbol_color_string; if (titlebar_overlay_obj.Get(options::kOverlaySymbolColor, &overlay_symbol_color_string)) { bool success = content::ParseCssColorString(overlay_symbol_color_string, &overlay_symbol_color_); DCHECK(success); } } if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); #endif if (enable_larger_than_screen()) // We need to set a default maximum window size here otherwise Windows // will not allow us to resize the window larger than scree. // Setting directly to INT_MAX somehow doesn't work, so we just divide // by 10, which should still be large enough. SetContentSizeConstraints(extensions::SizeConstraints( gfx::Size(), gfx::Size(INT_MAX / 10, INT_MAX / 10))); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); gfx::Rect bounds(0, 0, width, height); widget_size_ = bounds.size(); widget()->AddObserver(this); views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.remove_standard_frame = !has_frame() || has_client_frame(); // If a client frame, we need to draw our own shadows. if (transparent() || has_client_frame()) params.opacity = views::Widget::InitParams::WindowOpacity::kTranslucent; // The given window is most likely not rectangular since it uses // transparency and has no standard frame, don't show a shadow for it. if (transparent() && !has_frame()) params.shadow_type = views::Widget::InitParams::ShadowType::kNone; bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) params.activatable = views::Widget::InitParams::Activatable::kNo; #if BUILDFLAG(IS_WIN) if (parent) params.parent = parent->GetNativeWindow(); params.native_widget = new ElectronDesktopNativeWidgetAura(this); #elif BUILDFLAG(IS_LINUX) std::string name = Browser::Get()->GetName(); // Set WM_WINDOW_ROLE. params.wm_role_name = "browser-window"; // Set WM_CLASS. params.wm_class_name = base::ToLowerASCII(name); params.wm_class_class = name; // Set Wayland application ID. params.wayland_app_id = platform_util::GetXdgAppId(); auto* native_widget = new views::DesktopNativeWidgetAura(widget()); params.native_widget = native_widget; params.desktop_window_tree_host = new ElectronDesktopWindowTreeHostLinux(this, native_widget); #endif widget()->Init(std::move(params)); SetCanResize(resizable_); bool fullscreen = false; options.Get(options::kFullscreen, &fullscreen); std::string window_type; options.Get(options::kType, &window_type); #if BUILDFLAG(IS_LINUX) // Set _GTK_THEME_VARIANT to dark if we have "dark-theme" option set. bool use_dark_theme = false; if (options.Get(options::kDarkTheme, &use_dark_theme) && use_dark_theme) { SetGTKDarkThemeEnabled(use_dark_theme); } if (parent) SetParentWindow(parent); #endif #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // TODO(ckerr): remove in Electron v20.0.0 // Before the window is mapped the SetWMSpecState can not work, so we have // to manually set the _NET_WM_STATE. std::vector<x11::Atom> state_atom_list; bool skip_taskbar = false; if (options.Get(options::kSkipTaskbar, &skip_taskbar) && skip_taskbar) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); } // Before the window is mapped, there is no SHOW_FULLSCREEN_STATE. if (fullscreen) { state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_FULLSCREEN")); } if (parent) { // Force using dialog type for child window. window_type = "dialog"; // Modal window needs the _NET_WM_STATE_MODAL hint. if (is_modal()) state_atom_list.push_back(x11::GetAtom("_NET_WM_STATE_MODAL")); } if (!state_atom_list.empty()) SetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), x11::Atom::ATOM, state_atom_list); // Set the _NET_WM_WINDOW_TYPE. if (!window_type.empty()) SetWindowType(static_cast<x11::Window>(GetAcceleratedWidget()), window_type); } #endif #if BUILDFLAG(IS_WIN) if (!has_frame()) { // Set Window style so that we get a minimize and maximize animation when // frameless. DWORD frame_style = WS_CAPTION | WS_OVERLAPPED; if (resizable_) frame_style |= WS_THICKFRAME; if (minimizable_) frame_style |= WS_MINIMIZEBOX; if (maximizable_) frame_style |= WS_MAXIMIZEBOX; // We should not show a frame for transparent window. if (!thick_frame_) frame_style &= ~(WS_THICKFRAME | WS_CAPTION); ::SetWindowLong(GetAcceleratedWidget(), GWL_STYLE, frame_style); } LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (window_type == "toolbar") ex_style |= WS_EX_TOOLWINDOW; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); #endif if (has_frame() && !has_client_frame()) { // TODO(zcbenz): This was used to force using native frame on Windows 2003, // we should check whether setting it in InitParams can work. widget()->set_frame_type(views::Widget::FrameType::kForceNative); widget()->FrameTypeChanged(); #if BUILDFLAG(IS_WIN) // thickFrame also works for normal window. if (!thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), false, WS_THICKFRAME); #endif } // Default content view. SetContentView(new views::View()); gfx::Size size = bounds.size(); if (has_frame() && options.Get(options::kUseContentSize, &use_content_size_) && use_content_size_) size = ContentBoundsToWindowBounds(gfx::Rect(size)).size(); widget()->CenterWindow(size); #if BUILDFLAG(IS_WIN) // Save initial window state. if (fullscreen) last_window_state_ = ui::SHOW_STATE_FULLSCREEN; else last_window_state_ = ui::SHOW_STATE_NORMAL; #endif // Listen to mouse events. aura::Window* window = GetNativeWindow(); if (window) window->AddPreTargetHandler(this); #if BUILDFLAG(IS_LINUX) // On linux after the widget is initialized we might have to force set the // bounds if the bounds are smaller than the current display SetBounds(gfx::Rect(GetPosition(), bounds.size()), false); #endif SetOwnedByWidget(false); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowViews* window) { if (window->is_modal() && window->parent()) { auto* parent = window->parent(); // Enable parent window after current window gets closed. static_cast<NativeWindowViews*>(parent)->DecrementChildModals(); // Focus on parent window. parent->Focus(true); } window->NotifyWindowClosed(); }, this)); } NativeWindowViews::~NativeWindowViews() { widget()->RemoveObserver(this); #if BUILDFLAG(IS_WIN) // Disable mouse forwarding to relinquish resources, should any be held. SetForwardMouseMessages(false); #endif aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::SetGTKDarkThemeEnabled(bool use_dark_theme) { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { const std::string color = use_dark_theme ? "dark" : "light"; x11::SetStringProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_GTK_THEME_VARIANT"), x11::GetAtom("UTF8_STRING"), color); } #endif } void NativeWindowViews::SetContentView(views::View* view) { if (content_view()) { root_view_->RemoveChildView(content_view()); } set_content_view(view); focused_view_ = view; root_view_->AddChildView(content_view()); root_view_->Layout(); } void NativeWindowViews::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } widget()->Close(); } void NativeWindowViews::CloseImmediately() { widget()->CloseNow(); } void NativeWindowViews::Focus(bool focus) { // For hidden window focus() should do nothing. if (!IsVisible()) return; if (focus) { widget()->Activate(); } else { widget()->Deactivate(); } } bool NativeWindowViews::IsFocused() { return widget()->IsActive(); } void NativeWindowViews::Show() { if (is_modal() && NativeWindow::parent() && !widget()->native_widget_private()->IsVisible()) static_cast<NativeWindowViews*>(parent())->IncrementChildModals(); widget()->native_widget_private()->Show(GetRestoredState(), gfx::Rect()); // explicitly focus the window widget()->Activate(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::ShowInactive() { widget()->ShowInactive(); NotifyWindowShow(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowMapped(); #endif } void NativeWindowViews::Hide() { if (is_modal() && NativeWindow::parent()) static_cast<NativeWindowViews*>(parent())->DecrementChildModals(); widget()->Hide(); NotifyWindowHide(); #if defined(USE_OZONE) if (global_menu_bar_) global_menu_bar_->OnWindowUnmapped(); #endif #if BUILDFLAG(IS_WIN) // When the window is removed from the taskbar via win.hide(), // the thumbnail buttons need to be set up again. // Ensure that when the window is hidden, // the taskbar host is notified that it should re-add them. taskbar_host_.SetThumbarButtonsAdded(false); #endif } bool NativeWindowViews::IsVisible() { return widget()->IsVisible(); } bool NativeWindowViews::IsEnabled() { #if BUILDFLAG(IS_WIN) return ::IsWindowEnabled(GetAcceleratedWidget()); #elif BUILDFLAG(IS_LINUX) #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) return !event_disabler_.get(); #endif NOTIMPLEMENTED(); return true; #endif } void NativeWindowViews::IncrementChildModals() { num_modal_children_++; SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::DecrementChildModals() { if (num_modal_children_ > 0) { num_modal_children_--; } SetEnabledInternal(ShouldBeEnabled()); } void NativeWindowViews::SetEnabled(bool enable) { if (enable != is_enabled_) { is_enabled_ = enable; SetEnabledInternal(ShouldBeEnabled()); } } bool NativeWindowViews::ShouldBeEnabled() { return is_enabled_ && (num_modal_children_ == 0); } void NativeWindowViews::SetEnabledInternal(bool enable) { if (enable && IsEnabled()) { return; } else if (!enable && !IsEnabled()) { return; } #if BUILDFLAG(IS_WIN) ::EnableWindow(GetAcceleratedWidget(), enable); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { views::DesktopWindowTreeHostPlatform* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); if (enable) { tree_host->RemoveEventRewriter(event_disabler_.get()); event_disabler_.reset(); } else { event_disabler_ = std::make_unique<EventDisabler>(); tree_host->AddEventRewriter(event_disabler_.get()); } } #endif } #if BUILDFLAG(IS_LINUX) void NativeWindowViews::Maximize() { if (IsVisible()) { widget()->Maximize(); } else { widget()->native_widget_private()->Show(ui::SHOW_STATE_MAXIMIZED, gfx::Rect()); NotifyWindowShow(); } } #endif void NativeWindowViews::Unmaximize() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) if (transparent()) { SetBounds(restore_bounds_, false); NotifyWindowUnmaximize(); return; } #endif widget()->Restore(); } } bool NativeWindowViews::IsMaximized() { if (widget()->IsMaximized()) { return true; } else { #if BUILDFLAG(IS_WIN) if (transparent()) { // Compare the size of the window with the size of the display auto display = display::Screen::GetScreen()->GetDisplayNearestWindow( GetNativeWindow()); // Maximized if the window is the same dimensions and placement as the // display return GetBounds() == display.work_area(); } #endif return false; } } void NativeWindowViews::Minimize() { if (IsVisible()) widget()->Minimize(); else widget()->native_widget_private()->Show(ui::SHOW_STATE_MINIMIZED, gfx::Rect()); } void NativeWindowViews::Restore() { widget()->Restore(); } bool NativeWindowViews::IsMinimized() { return widget()->IsMinimized(); } void NativeWindowViews::SetFullScreen(bool fullscreen) { if (!IsFullScreenable()) return; #if BUILDFLAG(IS_WIN) // There is no native fullscreen state on Windows. bool leaving_fullscreen = IsFullscreen() && !fullscreen; if (fullscreen) { last_window_state_ = ui::SHOW_STATE_FULLSCREEN; NotifyWindowEnterFullScreen(); } else { last_window_state_ = ui::SHOW_STATE_NORMAL; NotifyWindowLeaveFullScreen(); } // For window without WS_THICKFRAME style, we can not call SetFullscreen(). // This path will be used for transparent windows as well. if (!thick_frame_) { if (fullscreen) { restore_bounds_ = GetBounds(); auto display = display::Screen::GetScreen()->GetDisplayNearestPoint(GetPosition()); SetBounds(display.bounds(), false); } else { SetBounds(restore_bounds_, false); } return; } // We set the new value after notifying, so we can handle the size event // correctly. widget()->SetFullscreen(fullscreen); // If restoring from fullscreen and the window isn't visible, force visible, // else a non-responsive window shell could be rendered. // (this situation may arise when app starts with fullscreen: true) // Note: the following must be after "widget()->SetFullscreen(fullscreen);" if (leaving_fullscreen && !IsVisible()) FlipWindowStyle(GetAcceleratedWidget(), true, WS_VISIBLE); #else if (IsVisible()) widget()->SetFullscreen(fullscreen); else if (fullscreen) widget()->native_widget_private()->Show(ui::SHOW_STATE_FULLSCREEN, gfx::Rect()); // Auto-hide menubar when in fullscreen. if (fullscreen) SetMenuBarVisibility(false); else SetMenuBarVisibility(!IsMenuBarAutoHide()); #endif } bool NativeWindowViews::IsFullscreen() const { return widget()->IsFullscreen(); } void NativeWindowViews::SetBounds(const gfx::Rect& bounds, bool animate) { #if BUILDFLAG(IS_WIN) if (is_moving_ || is_resizing_) { pending_bounds_change_ = bounds; return; } #endif #if BUILDFLAG(IS_WIN) || BUILDFLAG(IS_LINUX) // On Linux and Windows the minimum and maximum size should be updated with // window size when window is not resizable. if (!resizable_) { SetMaximumSize(bounds.size()); SetMinimumSize(bounds.size()); } #endif widget()->SetBounds(bounds); } gfx::Rect NativeWindowViews::GetBounds() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return widget()->GetRestoredBounds(); #endif return widget()->GetWindowBoundsInScreen(); } gfx::Rect NativeWindowViews::GetContentBounds() { return content_view() ? content_view()->GetBoundsInScreen() : gfx::Rect(); } gfx::Size NativeWindowViews::GetContentSize() { #if BUILDFLAG(IS_WIN) if (IsMinimized()) return NativeWindow::GetContentSize(); #endif return content_view() ? content_view()->size() : gfx::Size(); } gfx::Rect NativeWindowViews::GetNormalBounds() { return widget()->GetRestoredBounds(); } void NativeWindowViews::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { NativeWindow::SetContentSizeConstraints(size_constraints); #if BUILDFLAG(IS_WIN) // Changing size constraints would force adding the WS_THICKFRAME style, so // do nothing if thickFrame is false. if (!thick_frame_) return; #endif // widget_delegate() is only available after Init() is called, we make use of // this to determine whether native widget has initialized. if (widget() && widget()->widget_delegate()) widget()->OnSizeConstraintsChanged(); if (resizable_) old_size_constraints_ = size_constraints; } void NativeWindowViews::SetResizable(bool resizable) { if (resizable != resizable_) { // On Linux there is no "resizable" property of a window, we have to set // both the minimum and maximum size to the window size to achieve it. if (resizable) { SetContentSizeConstraints(old_size_constraints_); SetMaximizable(maximizable_); } else { old_size_constraints_ = GetContentSizeConstraints(); resizable_ = false; gfx::Size content_size = GetContentSize(); SetContentSizeConstraints( extensions::SizeConstraints(content_size, content_size)); } } #if BUILDFLAG(IS_WIN) if (has_frame() && thick_frame_) FlipWindowStyle(GetAcceleratedWidget(), resizable, WS_THICKFRAME); #endif resizable_ = resizable; SetCanResize(resizable_); } bool NativeWindowViews::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; #if BUILDFLAG(IS_WIN) const HWND otherWindow = reinterpret_cast<HWND>(id.id); if (!::IsWindow(otherWindow)) return false; ::SetWindowPos(GetAcceleratedWidget(), GetWindow(otherWindow, GW_HWNDPREV), 0, 0, 0, 0, SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { if (!IsWindowValid(static_cast<x11::Window>(id.id))) return false; electron::MoveWindowAbove(static_cast<x11::Window>(GetAcceleratedWidget()), static_cast<x11::Window>(id.id)); } #endif return true; } void NativeWindowViews::MoveTop() { // TODO(julien.isorce): fix chromium in order to use existing // widget()->StackAtTop(). #if BUILDFLAG(IS_WIN) gfx::Point pos = GetPosition(); gfx::Size size = GetSize(); ::SetWindowPos(GetAcceleratedWidget(), HWND_TOP, pos.x(), pos.y(), size.width(), size.height(), SWP_NOACTIVATE | SWP_NOMOVE | SWP_NOSIZE | SWP_SHOWWINDOW); #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) electron::MoveWindowToForeground( static_cast<x11::Window>(GetAcceleratedWidget())); #endif } bool NativeWindowViews::IsResizable() { #if BUILDFLAG(IS_WIN) if (has_frame()) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_THICKFRAME; #endif return resizable_; } void NativeWindowViews::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); gfx::SizeF aspect(aspect_ratio, 1.0); // Scale up because SetAspectRatio() truncates aspect value to int aspect.Scale(100); widget()->SetAspectRatio(aspect); } void NativeWindowViews::SetMovable(bool movable) { movable_ = movable; } bool NativeWindowViews::IsMovable() { #if BUILDFLAG(IS_WIN) return movable_; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMinimizable(bool minimizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), minimizable, WS_MINIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif minimizable_ = minimizable; } bool NativeWindowViews::IsMinimizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MINIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetMaximizable(bool maximizable) { #if BUILDFLAG(IS_WIN) FlipWindowStyle(GetAcceleratedWidget(), maximizable, WS_MAXIMIZEBOX); if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif maximizable_ = maximizable; } bool NativeWindowViews::IsMaximizable() { #if BUILDFLAG(IS_WIN) return ::GetWindowLong(GetAcceleratedWidget(), GWL_STYLE) & WS_MAXIMIZEBOX; #else return true; // Not implemented on Linux. #endif } void NativeWindowViews::SetExcludedFromShownWindowsMenu(bool excluded) {} bool NativeWindowViews::IsExcludedFromShownWindowsMenu() { // return false on unsupported platforms return false; } void NativeWindowViews::SetFullScreenable(bool fullscreenable) { fullscreenable_ = fullscreenable; } bool NativeWindowViews::IsFullScreenable() { return fullscreenable_; } void NativeWindowViews::SetClosable(bool closable) { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); if (closable) { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_ENABLED); } else { EnableMenuItem(menu, SC_CLOSE, MF_BYCOMMAND | MF_DISABLED | MF_GRAYED); } if (IsWindowControlsOverlayEnabled()) { auto* frame_view = static_cast<WinFrameView*>(widget()->non_client_view()->frame_view()); frame_view->caption_button_container()->UpdateButtons(); } #endif } bool NativeWindowViews::IsClosable() { #if BUILDFLAG(IS_WIN) HMENU menu = GetSystemMenu(GetAcceleratedWidget(), false); MENUITEMINFO info; memset(&info, 0, sizeof(info)); info.cbSize = sizeof(info); info.fMask = MIIM_STATE; if (!GetMenuItemInfo(menu, SC_CLOSE, false, &info)) { return false; } return !(info.fState & MFS_DISABLED); #elif BUILDFLAG(IS_LINUX) return true; #endif } void NativeWindowViews::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level, int relativeLevel) { bool level_changed = z_order != widget()->GetZOrderLevel(); widget()->SetZOrderLevel(z_order); #if BUILDFLAG(IS_WIN) // Reset the placement flag. behind_task_bar_ = false; if (z_order != ui::ZOrderLevel::kNormal) { // On macOS the window is placed behind the Dock for the following levels. // Re-use the same names on Windows to make it easier for the user. static const std::vector<std::string> levels = { "floating", "torn-off-menu", "modal-panel", "main-menu", "status"}; behind_task_bar_ = base::Contains(levels, level); } #endif MoveBehindTaskBarIfNeeded(); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (level_changed) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowViews::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowViews::Center() { widget()->CenterWindow(GetSize()); } void NativeWindowViews::Invalidate() { widget()->SchedulePaintInRect(gfx::Rect(GetBounds().size())); } void NativeWindowViews::SetTitle(const std::string& title) { title_ = title; widget()->UpdateWindowTitle(); } std::string NativeWindowViews::GetTitle() { return title_; } void NativeWindowViews::FlashFrame(bool flash) { #if BUILDFLAG(IS_WIN) // The Chromium's implementation has a bug stopping flash. if (!flash) { FLASHWINFO fwi; fwi.cbSize = sizeof(fwi); fwi.hwnd = GetAcceleratedWidget(); fwi.dwFlags = FLASHW_STOP; fwi.uCount = 0; FlashWindowEx(&fwi); return; } #endif widget()->FlashFrame(flash); } void NativeWindowViews::SetSkipTaskbar(bool skip) { #if BUILDFLAG(IS_WIN) Microsoft::WRL::ComPtr<ITaskbarList> taskbar; if (FAILED(::CoCreateInstance(CLSID_TaskbarList, nullptr, CLSCTX_INPROC_SERVER, IID_PPV_ARGS(&taskbar))) || FAILED(taskbar->HrInit())) return; if (skip) { taskbar->DeleteTab(GetAcceleratedWidget()); } else { taskbar->AddTab(GetAcceleratedWidget()); taskbar_host_.RestoreThumbarButtons(GetAcceleratedWidget()); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) SetWMSpecState(static_cast<x11::Window>(GetAcceleratedWidget()), skip, x11::GetAtom("_NET_WM_STATE_SKIP_TASKBAR")); #endif } void NativeWindowViews::SetSimpleFullScreen(bool simple_fullscreen) { SetFullScreen(simple_fullscreen); } bool NativeWindowViews::IsSimpleFullScreen() { return IsFullscreen(); } void NativeWindowViews::SetKiosk(bool kiosk) { SetFullScreen(kiosk); } bool NativeWindowViews::IsKiosk() { return IsFullscreen(); } bool NativeWindowViews::IsTabletMode() const { #if BUILDFLAG(IS_WIN) return base::win::IsWindows10OrGreaterTabletMode(GetAcceleratedWidget()); #else return false; #endif } SkColor NativeWindowViews::GetBackgroundColor() { auto* background = root_view_->background(); if (!background) return SK_ColorTRANSPARENT; return background->get_color(); } void NativeWindowViews::SetBackgroundColor(SkColor background_color) { // web views' background color. root_view_->SetBackground(views::CreateSolidBackground(background_color)); #if BUILDFLAG(IS_WIN) // Set the background color of native window. HBRUSH brush = CreateSolidBrush(skia::SkColorToCOLORREF(background_color)); ULONG_PTR previous_brush = SetClassLongPtr(GetAcceleratedWidget(), GCLP_HBRBACKGROUND, reinterpret_cast<LONG_PTR>(brush)); if (previous_brush) DeleteObject((HBRUSH)previous_brush); InvalidateRect(GetAcceleratedWidget(), NULL, 1); #endif } void NativeWindowViews::SetHasShadow(bool has_shadow) { wm::SetShadowElevation(GetNativeWindow(), has_shadow ? wm::kShadowElevationInactiveWindow : wm::kShadowElevationNone); } bool NativeWindowViews::HasShadow() { return GetNativeWindow()->GetProperty(wm::kShadowElevationKey) != wm::kShadowElevationNone; } void NativeWindowViews::SetOpacity(const double opacity) { #if BUILDFLAG(IS_WIN) const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); HWND hwnd = GetAcceleratedWidget(); if (!layered_) { LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } ::SetLayeredWindowAttributes(hwnd, 0, boundedOpacity * 255, LWA_ALPHA); opacity_ = boundedOpacity; #else opacity_ = 1.0; // setOpacity unsupported on Linux #endif } double NativeWindowViews::GetOpacity() { return opacity_; } void NativeWindowViews::SetIgnoreMouseEvents(bool ignore, bool forward) { #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (ignore) ex_style |= (WS_EX_TRANSPARENT | WS_EX_LAYERED); else ex_style &= ~(WS_EX_TRANSPARENT | WS_EX_LAYERED); if (layered_) ex_style |= WS_EX_LAYERED; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); // Forwarding is always disabled when not ignoring mouse messages. if (!ignore) { SetForwardMouseMessages(false); } else { SetForwardMouseMessages(forward); } #elif defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { auto* connection = x11::Connection::Get(); if (ignore) { x11::Rectangle r{0, 0, 1, 1}; connection->shape().Rectangles({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .ordering = x11::ClipOrdering::YXBanded, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .rectangles = {r}, }); } else { connection->shape().Mask({ .operation = x11::Shape::So::Set, .destination_kind = x11::Shape::Sk::Input, .destination_window = static_cast<x11::Window>(GetAcceleratedWidget()), .source_bitmap = x11::Pixmap::None, }); } } #endif } void NativeWindowViews::SetContentProtection(bool enable) { #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); DWORD affinity = enable ? WDA_EXCLUDEFROMCAPTURE : WDA_NONE; ::SetWindowDisplayAffinity(hwnd, affinity); if (!layered_) { // Workaround to prevent black window on screen capture after hiding and // showing the BrowserWindow. LONG ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); ex_style |= WS_EX_LAYERED; ::SetWindowLong(hwnd, GWL_EXSTYLE, ex_style); layered_ = true; } #endif } void NativeWindowViews::SetFocusable(bool focusable) { widget()->widget_delegate()->SetCanActivate(focusable); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); if (focusable) ex_style &= ~WS_EX_NOACTIVATE; else ex_style |= WS_EX_NOACTIVATE; ::SetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE, ex_style); SetSkipTaskbar(!focusable); Focus(false); #endif } bool NativeWindowViews::IsFocusable() { bool can_activate = widget()->widget_delegate()->CanActivate(); #if BUILDFLAG(IS_WIN) LONG ex_style = ::GetWindowLong(GetAcceleratedWidget(), GWL_EXSTYLE); bool no_activate = ex_style & WS_EX_NOACTIVATE; return !no_activate && can_activate; #else return can_activate; #endif } void NativeWindowViews::SetMenu(ElectronMenuModel* menu_model) { #if defined(USE_OZONE) // Remove global menu bar. if (global_menu_bar_ && menu_model == nullptr) { global_menu_bar_.reset(); root_view_->UnregisterAcceleratorsWithFocusManager(); return; } // Use global application menu bar when possible. if (CreateGlobalMenuBar() && ShouldUseGlobalMenuBar()) { if (!global_menu_bar_) global_menu_bar_ = std::make_unique<GlobalMenuBarX11>(this); if (global_menu_bar_->IsServerStarted()) { root_view_->RegisterAcceleratorsWithFocusManager(menu_model); global_menu_bar_->SetMenu(menu_model); return; } } #endif // Should reset content size when setting menu. gfx::Size content_size = GetContentSize(); bool should_reset_size = use_content_size_ && has_frame() && !IsMenuBarAutoHide() && ((!!menu_model) != root_view_->HasMenu()); root_view_->SetMenu(menu_model); if (should_reset_size) { // Enlarge the size constraints for the menu. int menu_bar_height = root_view_->GetMenuBarHeight(); extensions::SizeConstraints constraints = GetContentSizeConstraints(); if (constraints.HasMinimumSize()) { gfx::Size min_size = constraints.GetMinimumSize(); min_size.set_height(min_size.height() + menu_bar_height); constraints.set_minimum_size(min_size); } if (constraints.HasMaximumSize()) { gfx::Size max_size = constraints.GetMaximumSize(); max_size.set_height(max_size.height() + menu_bar_height); constraints.set_maximum_size(max_size); } SetContentSizeConstraints(constraints); // Resize the window to make sure content size is not changed. SetContentSize(content_size); } } void NativeWindowViews::AddBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->AddChildView( view->GetInspectableWebContentsView()->GetView()); } void NativeWindowViews::RemoveBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } if (view->GetInspectableWebContentsView()) content_view()->RemoveChildView( view->GetInspectableWebContentsView()->GetView()); remove_browser_view(view); } void NativeWindowViews::SetTopBrowserView(NativeBrowserView* view) { if (!content_view()) return; if (!view) { return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) content_view()->ReorderChildView( view->GetInspectableWebContentsView()->GetView(), -1); } void NativeWindowViews::SetParentWindow(NativeWindow* parent) { NativeWindow::SetParentWindow(parent); #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) x11::SetProperty( static_cast<x11::Window>(GetAcceleratedWidget()), x11::Atom::WM_TRANSIENT_FOR, x11::Atom::WINDOW, parent ? static_cast<x11::Window>(parent->GetAcceleratedWidget()) : ui::GetX11RootWindow()); #elif BUILDFLAG(IS_WIN) // To set parentship between windows into Windows is better to play with the // owner instead of the parent, as Windows natively seems to do if a parent // is specified at window creation time. // For do this we must NOT use the ::SetParent function, instead we must use // the ::GetWindowLongPtr or ::SetWindowLongPtr functions with "nIndex" set // to "GWLP_HWNDPARENT" which actually means the window owner. HWND hwndParent = parent ? parent->GetAcceleratedWidget() : NULL; if (hwndParent == (HWND)::GetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT)) return; ::SetWindowLongPtr(GetAcceleratedWidget(), GWLP_HWNDPARENT, (LONG_PTR)hwndParent); // Ensures the visibility if (IsVisible()) { WINDOWPLACEMENT wp; wp.length = sizeof(WINDOWPLACEMENT); ::GetWindowPlacement(GetAcceleratedWidget(), &wp); ::ShowWindow(GetAcceleratedWidget(), SW_HIDE); ::ShowWindow(GetAcceleratedWidget(), wp.showCmd); ::BringWindowToTop(GetAcceleratedWidget()); } #endif } gfx::NativeView NativeWindowViews::GetNativeView() const { return widget()->GetNativeView(); } gfx::NativeWindow NativeWindowViews::GetNativeWindow() const { return widget()->GetNativeWindow(); } void NativeWindowViews::SetProgressBar(double progress, NativeWindow::ProgressState state) { #if BUILDFLAG(IS_WIN) taskbar_host_.SetProgressBar(GetAcceleratedWidget(), progress, state); #elif BUILDFLAG(IS_LINUX) if (unity::IsRunning()) { unity::SetProgressFraction(progress); } #endif } void NativeWindowViews::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) { #if BUILDFLAG(IS_WIN) SkBitmap overlay_bitmap = overlay.AsBitmap(); taskbar_host_.SetOverlayIcon(GetAcceleratedWidget(), overlay_bitmap, description); #endif } void NativeWindowViews::SetAutoHideMenuBar(bool auto_hide) { root_view_->SetAutoHideMenuBar(auto_hide); } bool NativeWindowViews::IsMenuBarAutoHide() { return root_view_->IsMenuBarAutoHide(); } void NativeWindowViews::SetMenuBarVisibility(bool visible) { root_view_->SetMenuBarVisibility(visible); } bool NativeWindowViews::IsMenuBarVisible() { return root_view_->IsMenuBarVisible(); } void NativeWindowViews::SetVisibleOnAllWorkspaces( bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { widget()->SetVisibleOnAllWorkspaces(visible); } bool NativeWindowViews::IsVisibleOnAllWorkspaces() { #if defined(USE_OZONE_PLATFORM_X11) if (IsX11()) { // Use the presence/absence of _NET_WM_STATE_STICKY in _NET_WM_STATE to // determine whether the current window is visible on all workspaces. x11::Atom sticky_atom = x11::GetAtom("_NET_WM_STATE_STICKY"); std::vector<x11::Atom> wm_states; GetArrayProperty(static_cast<x11::Window>(GetAcceleratedWidget()), x11::GetAtom("_NET_WM_STATE"), &wm_states); return std::find(wm_states.begin(), wm_states.end(), sticky_atom) != wm_states.end(); } #endif return false; } content::DesktopMediaID NativeWindowViews::GetDesktopMediaID() const { const gfx::AcceleratedWidget accelerated_widget = GetAcceleratedWidget(); content::DesktopMediaID::Id window_handle = content::DesktopMediaID::kNullId; content::DesktopMediaID::Id aura_id = content::DesktopMediaID::kNullId; #if BUILDFLAG(IS_WIN) window_handle = reinterpret_cast<content::DesktopMediaID::Id>(accelerated_widget); #elif BUILDFLAG(IS_LINUX) window_handle = static_cast<uint32_t>(accelerated_widget); #endif aura::WindowTreeHost* const host = aura::WindowTreeHost::GetForAcceleratedWidget(accelerated_widget); aura::Window* const aura_window = host ? host->window() : nullptr; if (aura_window) { aura_id = content::DesktopMediaID::RegisterNativeWindow( content::DesktopMediaID::TYPE_WINDOW, aura_window) .window_id; } // No constructor to pass the aura_id. Make sure to not use the other // constructor that has a third parameter, it is for yet another purpose. content::DesktopMediaID result = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, window_handle); // Confusing but this is how content::DesktopMediaID is designed. The id // property is the window handle whereas the window_id property is an id // given by a map containing all aura instances. result.window_id = aura_id; return result; } gfx::AcceleratedWidget NativeWindowViews::GetAcceleratedWidget() const { if (GetNativeWindow() && GetNativeWindow()->GetHost()) return GetNativeWindow()->GetHost()->GetAcceleratedWidget(); else return gfx::kNullAcceleratedWidget; } NativeWindowHandle NativeWindowViews::GetNativeWindowHandle() const { return GetAcceleratedWidget(); } gfx::Rect NativeWindowViews::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect window_bounds(bounds); #if BUILDFLAG(IS_WIN) if (widget()->non_client_view()) { HWND hwnd = GetAcceleratedWidget(); gfx::Rect dpi_bounds = DIPToScreenRect(hwnd, bounds); window_bounds = ScreenToDIPRect( hwnd, widget()->non_client_view()->GetWindowBoundsForClientBounds( dpi_bounds)); } #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); window_bounds.set_y(window_bounds.y() - menu_bar_height); window_bounds.set_height(window_bounds.height() + menu_bar_height); } return window_bounds; } gfx::Rect NativeWindowViews::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (!has_frame()) return bounds; gfx::Rect content_bounds(bounds); #if BUILDFLAG(IS_WIN) HWND hwnd = GetAcceleratedWidget(); content_bounds.set_size(DIPToScreenRect(hwnd, content_bounds).size()); RECT rect; SetRectEmpty(&rect); DWORD style = ::GetWindowLong(hwnd, GWL_STYLE); DWORD ex_style = ::GetWindowLong(hwnd, GWL_EXSTYLE); AdjustWindowRectEx(&rect, style, FALSE, ex_style); content_bounds.set_width(content_bounds.width() - (rect.right - rect.left)); content_bounds.set_height(content_bounds.height() - (rect.bottom - rect.top)); content_bounds.set_size(ScreenToDIPRect(hwnd, content_bounds).size()); #endif if (root_view_->HasMenu() && root_view_->IsMenuBarVisible()) { int menu_bar_height = root_view_->GetMenuBarHeight(); content_bounds.set_y(content_bounds.y() + menu_bar_height); content_bounds.set_height(content_bounds.height() - menu_bar_height); } return content_bounds; } void NativeWindowViews::UpdateDraggableRegions( const std::vector<mojom::DraggableRegionPtr>& regions) { draggable_region_ = DraggableRegionsToSkRegion(regions); } #if BUILDFLAG(IS_WIN) void NativeWindowViews::SetIcon(HICON window_icon, HICON app_icon) { // We are responsible for storing the images. window_icon_ = base::win::ScopedHICON(CopyIcon(window_icon)); app_icon_ = base::win::ScopedHICON(CopyIcon(app_icon)); HWND hwnd = GetAcceleratedWidget(); SendMessage(hwnd, WM_SETICON, ICON_SMALL, reinterpret_cast<LPARAM>(window_icon_.get())); SendMessage(hwnd, WM_SETICON, ICON_BIG, reinterpret_cast<LPARAM>(app_icon_.get())); } #elif BUILDFLAG(IS_LINUX) void NativeWindowViews::SetIcon(const gfx::ImageSkia& icon) { auto* tree_host = views::DesktopWindowTreeHostLinux::GetHostForWidget( GetAcceleratedWidget()); tree_host->SetWindowIcons(icon, {}); } #endif void NativeWindowViews::OnWidgetActivationChanged(views::Widget* changed_widget, bool active) { if (changed_widget != widget()) return; if (active) { MoveBehindTaskBarIfNeeded(); NativeWindow::NotifyWindowFocus(); } else { NativeWindow::NotifyWindowBlur(); } // Hide menu bar when window is blurred. if (!active && IsMenuBarAutoHide() && IsMenuBarVisible()) SetMenuBarVisibility(false); root_view_->ResetAltState(); } void NativeWindowViews::OnWidgetBoundsChanged(views::Widget* changed_widget, const gfx::Rect& bounds) { if (changed_widget != widget()) return; // Note: We intentionally use `GetBounds()` instead of `bounds` to properly // handle minimized windows on Windows. const auto new_bounds = GetBounds(); if (widget_size_ != new_bounds.size()) { int width_delta = new_bounds.width() - widget_size_.width(); int height_delta = new_bounds.height() - widget_size_.height(); for (NativeBrowserView* item : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(item); native_view->SetAutoResizeProportions(widget_size_); native_view->AutoResize(new_bounds, width_delta, height_delta); } NotifyWindowResize(); widget_size_ = new_bounds.size(); } } void NativeWindowViews::OnWidgetDestroying(views::Widget* widget) { aura::Window* window = GetNativeWindow(); if (window) window->RemovePreTargetHandler(this); } void NativeWindowViews::OnWidgetDestroyed(views::Widget* changed_widget) { widget_destroyed_ = true; } views::View* NativeWindowViews::GetInitiallyFocusedView() { return focused_view_; } bool NativeWindowViews::CanMaximize() const { return resizable_ && maximizable_; } bool NativeWindowViews::CanMinimize() const { #if BUILDFLAG(IS_WIN) return minimizable_; #elif BUILDFLAG(IS_LINUX) return true; #endif } std::u16string NativeWindowViews::GetWindowTitle() const { return base::UTF8ToUTF16(title_); } views::View* NativeWindowViews::GetContentsView() { return root_view_.get(); } bool NativeWindowViews::ShouldDescendIntoChildForEventHandling( gfx::NativeView child, const gfx::Point& location) { // App window should claim mouse events that fall within any BrowserViews' // draggable region. for (auto* view : browser_views()) { auto* native_view = static_cast<NativeBrowserViewViews*>(view); auto* view_draggable_region = native_view->draggable_region(); if (view_draggable_region && view_draggable_region->contains(location.x(), location.y())) return false; } // App window should claim mouse events that fall within the draggable region. if (draggable_region() && draggable_region()->contains(location.x(), location.y())) return false; // And the events on border for dragging resizable frameless window. if ((!has_frame() || has_client_frame()) && resizable_) { auto* frame = static_cast<FramelessView*>(widget()->non_client_view()->frame_view()); return frame->ResizingBorderHitTest(location) == HTNOWHERE; } return true; } views::ClientView* NativeWindowViews::CreateClientView(views::Widget* widget) { return new NativeWindowClientView(widget, root_view_.get(), this); } std::unique_ptr<views::NonClientFrameView> NativeWindowViews::CreateNonClientFrameView(views::Widget* widget) { #if BUILDFLAG(IS_WIN) auto frame_view = std::make_unique<WinFrameView>(); frame_view->Init(this, widget); return frame_view; #else if (has_frame() && !has_client_frame()) { return std::make_unique<NativeFrameView>(this, widget); } else { auto frame_view = has_frame() && has_client_frame() ? std::make_unique<ClientFrameViewLinux>() : std::make_unique<FramelessView>(); frame_view->Init(this, widget); return frame_view; } #endif } void NativeWindowViews::OnWidgetMove() { NotifyWindowMove(); } void NativeWindowViews::HandleKeyboardEvent( content::WebContents*, const content::NativeWebKeyboardEvent& event) { if (widget_destroyed_) return; #if BUILDFLAG(IS_LINUX) if (event.windows_key_code == ui::VKEY_BROWSER_BACK) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event.windows_key_code == ui::VKEY_BROWSER_FORWARD) NotifyWindowExecuteAppCommand(kBrowserForward); #endif keyboard_event_handler_->HandleKeyboardEvent(event, root_view_->GetFocusManager()); root_view_->HandleKeyEvent(event); } void NativeWindowViews::OnMouseEvent(ui::MouseEvent* event) { if (event->type() != ui::ET_MOUSE_PRESSED) return; // Alt+Click should not toggle menu bar. root_view_->ResetAltState(); #if BUILDFLAG(IS_LINUX) if (event->changed_button_flags() == ui::EF_BACK_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserBackward); else if (event->changed_button_flags() == ui::EF_FORWARD_MOUSE_BUTTON) NotifyWindowExecuteAppCommand(kBrowserForward); #endif } ui::WindowShowState NativeWindowViews::GetRestoredState() { if (IsMaximized()) { #if BUILDFLAG(IS_WIN) // Only restore Maximized state when window is NOT transparent style if (!transparent()) { return ui::SHOW_STATE_MAXIMIZED; } #else return ui::SHOW_STATE_MAXIMIZED; #endif } if (IsFullscreen()) return ui::SHOW_STATE_FULLSCREEN; return ui::SHOW_STATE_NORMAL; } void NativeWindowViews::MoveBehindTaskBarIfNeeded() { #if BUILDFLAG(IS_WIN) if (behind_task_bar_) { const HWND task_bar_hwnd = ::FindWindow(kUniqueTaskBarClassName, nullptr); ::SetWindowPos(GetAcceleratedWidget(), task_bar_hwnd, 0, 0, 0, 0, SWP_NOMOVE | SWP_NOSIZE | SWP_NOACTIVATE); } #endif // TODO(julien.isorce): Implement X11 case. } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowViews(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,707
[Bug]: Disabling BrowserWindow object causes crash on MacOS
### Preflight Checklist - [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version Tested on versions 19.0.5, 18.3.4, 17.4.8 and 16.2.8 ### What operating system are you using? macOS ### Operating System Version Monterey v12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version Went all the way back to 12.2.3 and issue was still present. ### Expected Behavior When calling `setEnabled(false)` on a `BrowserWindow` object, I would expect the window to become disabled or some error to be thrown if it fails. ### Actual Behavior **Behavior** Calling `setEnabled(false)` on a `BrowserWindow` object causes Electron to quit abruptly on MacOS. No stack trace is given in the terminal but a message is printed that reads: `<path to Electron.app>/Electron.app/Contents/MacOS/Electron exited with signal SIGTRAP` Using an Intel based Mac the error message was the same except it exited with `SIGILL`. Surrounding the code in a try/catch block does not stop Electron from crashing. **Reproduce** Add the following line to the [quickstart repo in index.js on line 17](https://github.com/electron/electron-quick-start/blob/master/main.js#L17): `mainWindow.setEnabled(false);` To slightly delay so Electron/OS has time to show a window before crashing, use this instead: `setTimeout(() => { mainWindow.setEnabled(false); }, 1000);` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34707
https://github.com/electron/electron/pull/34904
38848c5bf77b2fa62b3dddecfe1aecba8d4ae48f
eb8c9452cb38b6bd32bdc92724cc1fb42a3d43dc
2022-06-22T21:37:03Z
c++
2022-07-19T10:31:49Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" // This view would inform Chromium to resize the hosted views::View. // // The overridden methods should behave the same with BridgedContentView. @interface ElectronAdaptedContentView : NSView { @private views::NativeWidgetMacNSWindowHost* bridge_host_; } @end @implementation ElectronAdaptedContentView - (id)initWithShell:(electron::NativeWindowMac*)shell { if ((self = [self init])) { bridge_host_ = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell->GetNativeWindow()); } return self; } - (void)viewDidMoveToWindow { // When this view is added to a window, AppKit calls setFrameSize before it is // added to the window, so the behavior in setFrameSize is not triggered. NSWindow* window = [self window]; if (window) [self setFrameSize:NSZeroSize]; } - (void)setFrameSize:(NSSize)newSize { // The size passed in here does not always use // -[NSWindow contentRectForFrameRect]. The following ensures that the // contentView for a frameless window can extend over the titlebar of the new // window containing it, since AppKit requires a titlebar to give frameless // windows correct shadows and rounded corners. NSWindow* window = [self window]; if (window && [window contentView] == self) { newSize = [window contentRectForFrameRect:[window frame]].size; // Ensure that the window geometry be updated on the host side before the // view size is updated. bridge_host_->GetInProcessNSWindowBridge()->UpdateWindowGeometry(); } [super setFrameSize:newSize]; // The OnViewSizeChanged is marked private in derived class. static_cast<remote_cocoa::mojom::NativeWidgetNSWindowHost*>(bridge_host_) ->OnViewSizeChanged(gfx::Size(newSize.width, newSize.height)); } @end // This view always takes the size of its superview. It is intended to be used // as a NSWindow's contentView. It is needed because NSWindow's implementation // explicitly resizes the contentView at inopportune times. @interface FullSizeContentView : NSView @end @implementation FullSizeContentView // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. - (void)setFrameSize:(NSSize)size { if ([self superview]) size = [[self superview] bounds].size; [super setFrameSize:size]; } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. - (void)viewDidMoveToSuperview { [self setFrame:[[self superview] bounds]]; } @end @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorBarStyle) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // Removing NSWindowStyleMaskTitled removes window title, which removes // rounded corners of window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = 0; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_.reset(); }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]); [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]); [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; // Use an NSEvent monitor to listen for the wheel event. BOOL __block began = NO; wheel_event_monitor_ = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskScrollWheel handler:^(NSEvent* event) { if ([[event window] windowNumber] != [window_ windowNumber]) return event; if (!began && (([event phase] == NSEventPhaseMayBegin) || ([event phase] == NSEventPhaseBegan))) { this->NotifyWindowScrollTouchBegin(); began = YES; } else if (began && (([event phase] == NSEventPhaseEnded) || ([event phase] == NSEventPhaseCancelled))) { this->NotifyWindowScrollTouchEnd(); began = NO; } return event; }]; // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { SetHasDeferredWindowClose(true); return; } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. SetEnabled(true); [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Retain the child window before closing it. If the last reference to the // NSWindow goes away inside -[NSWindow close], then bad stuff can happen. // See e.g. http://crbug.com/616701. base::scoped_nsobject<NSWindow> child_window(window_, base::scoped_policy::RETAIN); [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. SetEnabled(true); if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // Hide all children of the current window before hiding the window. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm // expects this when window visibility changes. if ([window_ childWindows]) { for (NSWindow* child in [window_ childWindows]) { [child orderOut:nil]; } } // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; // For a window to be visible, it must be visible to the user in the // foreground of the app, which means that it should not be minimized or // occluded return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { [window_ beginSheet:window_ completionHandler:^(NSModalResponse returnCode) { NSLog(@"modal enabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::SetFullScreen(bool fullscreen) { // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::ENTERING : FullScreenTransitionState::EXITING; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; [window_ orderWindow:NSWindowAbove relativeTo:id.id]; return true; } void NativeWindowMac::MoveTop() { [window_ orderWindow:NSWindowAbove relativeTo:0]; } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::NONE; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [window_ flushWindow]; [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; SetFullScreen(true); } else if (!kiosk && is_kiosk_) { [NSApp setPresentationOptions:kiosk_options_]; is_kiosk_ = false; SetFullScreen(false); } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=372?q=kWindowCaptureMacV2&ss=chromium // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[[NSImageView alloc] init] autorelease]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[[ElectronProgressBar alloc] initWithFrame:frame] autorelease]; [progress_indicator setStyle:NSProgressIndicatorBarStyle]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to functionally // mimic app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { ProcessSerialNumber psn = {0, kCurrentProcess}; if (visibleOnFullScreen) { [window_ setCanHide:NO]; TransformProcessType(&psn, kProcessTransformToUIElementApplication); } else { [window_ setCanHide:YES]; TransformProcessType(&psn, kProcessTransformToForegroundApplication); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } std::string dep_warn = " has been deprecated and removed as of macOS 10.15."; node::Environment* env = node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); NSVisualEffectMaterial vibrancyType{}; if (type == "appearance-based") { EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialAppearanceBased; } else if (type == "light") { EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialLight; } else if (type == "dark") { EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialDark; } else if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "medium-light") { EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialMediumLight; } else if (type == "ultra-dark") { EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialUltraDark; } if (@available(macOS 10.14, *)) { if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]] autorelease]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetTrafficLightPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetTrafficLightPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_.reset([[ElectronTouchBar alloc] initWithDelegate:window_delegate_.get() window:this settings:std::move(items)]); [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_.reset([[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]); [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); if (wheel_event_monitor_) { [NSEvent removeMonitor:wheel_event_monitor_]; wheel_event_monitor_ = nil; } } void NativeWindowMac::OverrideNSWindowContentView() { // When using `views::Widget` to hold WebContents, Chromium would use // `BridgedContentView` as content view, which does not support draggable // regions. In order to make draggable regions work, we have to replace the // content view with a simple NSView. if (has_frame()) { container_view_.reset( [[ElectronAdaptedContentView alloc] initWithShell:this]); } else { container_view_.reset([[FullSizeContentView alloc] init]); [container_view_ setFrame:[[[window_ contentView] superview] bounds]]; } [container_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [window_ setContentView:container_view_]; AddContentViewLayers(); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]); [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } if (!has_frame()) { // In OSX 10.10, adding subviews to the root view for the NSView hierarchy // produces warnings. To eliminate the warnings, we resize the contentView // to fill the window, and add subviews to that. // http://crbug.com/380412 if (!original_set_frame_size) { Class cl = [[window_ contentView] class]; original_set_frame_size = class_replaceMethod( cl, @selector(setFrameSize:), (IMP)SetFrameSize, "v@:{_NSSize=ff}"); original_view_did_move_to_superview = class_replaceMethod(cl, @selector(viewDidMoveToSuperview), (IMP)ViewDidMoveToSuperview, "v@:"); [[window_ contentView] viewDidMoveToWindow]; } } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) { if (is_modal()) return; NativeWindow::SetParentWindow(parent); // Do not remove/add if we are already properly attached. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. if ([window_ parentWindow]) [[window_ parentWindow] removeChildWindow:window_]; // Set new parent window. // Note that this method will force the window to become visible. if (parent && attach) { // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [parent->GetNativeWindow().GetNativeNSWindow() addChildWindow:window_ ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,707
[Bug]: Disabling BrowserWindow object causes crash on MacOS
### Preflight Checklist - [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version Tested on versions 19.0.5, 18.3.4, 17.4.8 and 16.2.8 ### What operating system are you using? macOS ### Operating System Version Monterey v12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version Went all the way back to 12.2.3 and issue was still present. ### Expected Behavior When calling `setEnabled(false)` on a `BrowserWindow` object, I would expect the window to become disabled or some error to be thrown if it fails. ### Actual Behavior **Behavior** Calling `setEnabled(false)` on a `BrowserWindow` object causes Electron to quit abruptly on MacOS. No stack trace is given in the terminal but a message is printed that reads: `<path to Electron.app>/Electron.app/Contents/MacOS/Electron exited with signal SIGTRAP` Using an Intel based Mac the error message was the same except it exited with `SIGILL`. Surrounding the code in a try/catch block does not stop Electron from crashing. **Reproduce** Add the following line to the [quickstart repo in index.js on line 17](https://github.com/electron/electron-quick-start/blob/master/main.js#L17): `mainWindow.setEnabled(false);` To slightly delay so Electron/OS has time to show a window before crashing, use this instead: `setTimeout(() => { mainWindow.setEnabled(false); }, 1000);` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34707
https://github.com/electron/electron/pull/34904
38848c5bf77b2fa62b3dddecfe1aecba8d4ae48f
eb8c9452cb38b6bd32bdc92724cc1fb42a3d43dc
2022-06-22T21:37:03Z
c++
2022-07-19T10:31:49Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as http from 'http'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { areColorsSimilar, captureScreen, CHROMA_COLOR_HEX, getPixelColor } from './screen-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = emittedOnce(w, 'maximize'); const shown = emittedOnce(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await delay(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = emittedOnce(w, 'blur'); const isShown = emittedOnce(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = emittedOnce(w, 'focus'); const isShown = emittedOnce(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { await emittedOnce(w, 'focus', () => w.show()); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.webContents.incrementCapturerCount(); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); it('should increase the capturer count', () => { const w = new BrowserWindow({ show: false }); w.webContents.incrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.true(); w.webContents.decrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.false(); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | childProcess.ChildProcess | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); // TODO(nornagon): disabled due to flakiness. it.skip('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath], { stdio: 'inherit' }); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = emittedOnce(w, 'hide'); let shown = emittedOnce(w, 'show'); const maximize = emittedOnce(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = emittedOnce(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await delay(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await delay(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: CHROMA_COLOR_HEX, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html')); await emittedOnce(foregroundWindow, 'ready-to-show'); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true(); expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: CHROMA_COLOR_HEX }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
34,707
[Bug]: Disabling BrowserWindow object causes crash on MacOS
### Preflight Checklist - [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version Tested on versions 19.0.5, 18.3.4, 17.4.8 and 16.2.8 ### What operating system are you using? macOS ### Operating System Version Monterey v12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version Went all the way back to 12.2.3 and issue was still present. ### Expected Behavior When calling `setEnabled(false)` on a `BrowserWindow` object, I would expect the window to become disabled or some error to be thrown if it fails. ### Actual Behavior **Behavior** Calling `setEnabled(false)` on a `BrowserWindow` object causes Electron to quit abruptly on MacOS. No stack trace is given in the terminal but a message is printed that reads: `<path to Electron.app>/Electron.app/Contents/MacOS/Electron exited with signal SIGTRAP` Using an Intel based Mac the error message was the same except it exited with `SIGILL`. Surrounding the code in a try/catch block does not stop Electron from crashing. **Reproduce** Add the following line to the [quickstart repo in index.js on line 17](https://github.com/electron/electron-quick-start/blob/master/main.js#L17): `mainWindow.setEnabled(false);` To slightly delay so Electron/OS has time to show a window before crashing, use this instead: `setTimeout(() => { mainWindow.setEnabled(false); }, 1000);` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34707
https://github.com/electron/electron/pull/34904
38848c5bf77b2fa62b3dddecfe1aecba8d4ae48f
eb8c9452cb38b6bd32bdc92724cc1fb42a3d43dc
2022-06-22T21:37:03Z
c++
2022-07-19T10:31:49Z
shell/browser/native_window_mac.mm
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/native_window_mac.h" #include <AvailabilityMacros.h> #include <objc/objc-runtime.h> #include <algorithm> #include <string> #include <utility> #include <vector> #include "base/cxx17_backports.h" #include "base/mac/mac_util.h" #include "base/mac/scoped_cftyperef.h" #include "base/strings/sys_string_conversions.h" #include "components/remote_cocoa/app_shim/native_widget_ns_window_bridge.h" #include "components/remote_cocoa/browser/scoped_cg_window_id.h" #include "content/public/browser/browser_accessibility_state.h" #include "content/public/browser/browser_task_traits.h" #include "content/public/browser/browser_thread.h" #include "content/public/browser/desktop_media_id.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/native_browser_view_mac.h" #include "shell/browser/ui/cocoa/electron_native_widget_mac.h" #include "shell/browser/ui/cocoa/electron_ns_window.h" #include "shell/browser/ui/cocoa/electron_ns_window_delegate.h" #include "shell/browser/ui/cocoa/electron_preview_item.h" #include "shell/browser/ui/cocoa/electron_touch_bar.h" #include "shell/browser/ui/cocoa/root_view_mac.h" #include "shell/browser/ui/cocoa/window_buttons_proxy.h" #include "shell/browser/ui/inspectable_web_contents.h" #include "shell/browser/ui/inspectable_web_contents_view.h" #include "shell/browser/window_list.h" #include "shell/common/gin_converters/gfx_converter.h" #include "shell/common/gin_helper/dictionary.h" #include "shell/common/node_includes.h" #include "shell/common/options_switches.h" #include "shell/common/process_util.h" #include "skia/ext/skia_utils_mac.h" #include "third_party/webrtc/modules/desktop_capture/mac/window_list_utils.h" #include "ui/display/screen.h" #include "ui/gfx/skia_util.h" #include "ui/gl/gpu_switching_manager.h" #include "ui/views/background.h" #include "ui/views/cocoa/native_widget_mac_ns_window_host.h" #include "ui/views/widget/widget.h" // This view would inform Chromium to resize the hosted views::View. // // The overridden methods should behave the same with BridgedContentView. @interface ElectronAdaptedContentView : NSView { @private views::NativeWidgetMacNSWindowHost* bridge_host_; } @end @implementation ElectronAdaptedContentView - (id)initWithShell:(electron::NativeWindowMac*)shell { if ((self = [self init])) { bridge_host_ = views::NativeWidgetMacNSWindowHost::GetFromNativeWindow( shell->GetNativeWindow()); } return self; } - (void)viewDidMoveToWindow { // When this view is added to a window, AppKit calls setFrameSize before it is // added to the window, so the behavior in setFrameSize is not triggered. NSWindow* window = [self window]; if (window) [self setFrameSize:NSZeroSize]; } - (void)setFrameSize:(NSSize)newSize { // The size passed in here does not always use // -[NSWindow contentRectForFrameRect]. The following ensures that the // contentView for a frameless window can extend over the titlebar of the new // window containing it, since AppKit requires a titlebar to give frameless // windows correct shadows and rounded corners. NSWindow* window = [self window]; if (window && [window contentView] == self) { newSize = [window contentRectForFrameRect:[window frame]].size; // Ensure that the window geometry be updated on the host side before the // view size is updated. bridge_host_->GetInProcessNSWindowBridge()->UpdateWindowGeometry(); } [super setFrameSize:newSize]; // The OnViewSizeChanged is marked private in derived class. static_cast<remote_cocoa::mojom::NativeWidgetNSWindowHost*>(bridge_host_) ->OnViewSizeChanged(gfx::Size(newSize.width, newSize.height)); } @end // This view always takes the size of its superview. It is intended to be used // as a NSWindow's contentView. It is needed because NSWindow's implementation // explicitly resizes the contentView at inopportune times. @interface FullSizeContentView : NSView @end @implementation FullSizeContentView // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. - (void)setFrameSize:(NSSize)size { if ([self superview]) size = [[self superview] bounds].size; [super setFrameSize:size]; } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. - (void)viewDidMoveToSuperview { [self setFrame:[[self superview] bounds]]; } @end @interface ElectronProgressBar : NSProgressIndicator @end @implementation ElectronProgressBar - (void)drawRect:(NSRect)dirtyRect { if (self.style != NSProgressIndicatorBarStyle) return; // Draw edges of rounded rect. NSRect rect = NSInsetRect([self bounds], 1.0, 1.0); CGFloat radius = rect.size.height / 2; NSBezierPath* bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:2.0]; [[NSColor grayColor] set]; [bezier_path stroke]; // Fill the rounded rect. rect = NSInsetRect(rect, 2.0, 2.0); radius = rect.size.height / 2; bezier_path = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [bezier_path setLineWidth:1.0]; [bezier_path addClip]; // Calculate the progress width. rect.size.width = floor(rect.size.width * ([self doubleValue] / [self maxValue])); // Fill the progress bar with color blue. [[NSColor colorWithSRGBRed:0.2 green:0.6 blue:1 alpha:1] set]; NSRectFill(rect); } @end namespace gin { template <> struct Converter<electron::NativeWindowMac::VisualEffectState> { static bool FromV8(v8::Isolate* isolate, v8::Handle<v8::Value> val, electron::NativeWindowMac::VisualEffectState* out) { using VisualEffectState = electron::NativeWindowMac::VisualEffectState; std::string visual_effect_state; if (!ConvertFromV8(isolate, val, &visual_effect_state)) return false; if (visual_effect_state == "followWindow") { *out = VisualEffectState::kFollowWindow; } else if (visual_effect_state == "active") { *out = VisualEffectState::kActive; } else if (visual_effect_state == "inactive") { *out = VisualEffectState::kInactive; } else { return false; } return true; } }; } // namespace gin namespace electron { namespace { bool IsFramelessWindow(NSView* view) { NSWindow* nswindow = [view window]; if (![nswindow respondsToSelector:@selector(shell)]) return false; NativeWindow* window = [static_cast<ElectronNSWindow*>(nswindow) shell]; return window && !window->has_frame(); } IMP original_set_frame_size = nullptr; IMP original_view_did_move_to_superview = nullptr; // This method is directly called by NSWindow during a window resize on OSX // 10.10.0, beta 2. We must override it to prevent the content view from // shrinking. void SetFrameSize(NSView* self, SEL _cmd, NSSize size) { if (!IsFramelessWindow(self)) { auto original = reinterpret_cast<decltype(&SetFrameSize)>(original_set_frame_size); return original(self, _cmd, size); } // For frameless window, resize the view to cover full window. if ([self superview]) size = [[self superview] bounds].size; auto super_impl = reinterpret_cast<decltype(&SetFrameSize)>( [[self superclass] instanceMethodForSelector:_cmd]); super_impl(self, _cmd, size); } // The contentView gets moved around during certain full-screen operations. // This is less than ideal, and should eventually be removed. void ViewDidMoveToSuperview(NSView* self, SEL _cmd) { if (!IsFramelessWindow(self)) { // [BridgedContentView viewDidMoveToSuperview]; auto original = reinterpret_cast<decltype(&ViewDidMoveToSuperview)>( original_view_did_move_to_superview); if (original) original(self, _cmd); return; } [self setFrame:[[self superview] bounds]]; } } // namespace NativeWindowMac::NativeWindowMac(const gin_helper::Dictionary& options, NativeWindow* parent) : NativeWindow(options, parent), root_view_(new RootViewMac(this)) { ui::NativeTheme::GetInstanceForNativeUi()->AddObserver(this); display::Screen::GetScreen()->AddObserver(this); int width = 800, height = 600; options.Get(options::kWidth, &width); options.Get(options::kHeight, &height); NSRect main_screen_rect = [[[NSScreen screens] firstObject] frame]; gfx::Rect bounds(round((NSWidth(main_screen_rect) - width) / 2), round((NSHeight(main_screen_rect) - height) / 2), width, height); bool resizable = true; options.Get(options::kResizable, &resizable); options.Get(options::kZoomToPageWidth, &zoom_to_page_width_); options.Get(options::kSimpleFullScreen, &always_simple_fullscreen_); options.GetOptional(options::kTrafficLightPosition, &traffic_light_position_); options.Get(options::kVisualEffectState, &visual_effect_state_); if (options.Has(options::kFullscreenWindowTitle)) { EmitWarning( node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()), "\"fullscreenWindowTitle\" option has been deprecated and is " "no-op now.", "electron"); } bool minimizable = true; options.Get(options::kMinimizable, &minimizable); bool maximizable = true; options.Get(options::kMaximizable, &maximizable); bool closable = true; options.Get(options::kClosable, &closable); std::string tabbingIdentifier; options.Get(options::kTabbingIdentifier, &tabbingIdentifier); std::string windowType; options.Get(options::kType, &windowType); bool useStandardWindow = true; // eventually deprecate separate "standardWindow" option in favor of // standard / textured window types options.Get(options::kStandardWindow, &useStandardWindow); if (windowType == "textured") { useStandardWindow = false; } // The window without titlebar is treated the same with frameless window. if (title_bar_style_ != TitleBarStyle::kNormal) set_has_frame(false); NSUInteger styleMask = NSWindowStyleMaskTitled; // Removing NSWindowStyleMaskTitled removes window title, which removes // rounded corners of window. bool rounded_corner = true; options.Get(options::kRoundedCorners, &rounded_corner); if (!rounded_corner && !has_frame()) styleMask = 0; if (minimizable) styleMask |= NSWindowStyleMaskMiniaturizable; if (closable) styleMask |= NSWindowStyleMaskClosable; if (resizable) styleMask |= NSWindowStyleMaskResizable; if (!useStandardWindow || transparent() || !has_frame()) styleMask |= NSWindowStyleMaskTexturedBackground; // Create views::Widget and assign window_ with it. // TODO(zcbenz): Get rid of the window_ in future. views::Widget::InitParams params; params.ownership = views::Widget::InitParams::WIDGET_OWNS_NATIVE_WIDGET; params.bounds = bounds; params.delegate = this; params.type = views::Widget::InitParams::TYPE_WINDOW; params.native_widget = new ElectronNativeWidgetMac(this, windowType, styleMask, widget()); widget()->Init(std::move(params)); SetCanResize(resizable); window_ = static_cast<ElectronNSWindow*>( widget()->GetNativeWindow().GetNativeNSWindow()); RegisterDeleteDelegateCallback(base::BindOnce( [](NativeWindowMac* window) { if (window->window_) window->window_ = nil; if (window->buttons_proxy_) window->buttons_proxy_.reset(); }, this)); [window_ setEnableLargerThanScreen:enable_larger_than_screen()]; window_delegate_.reset([[ElectronNSWindowDelegate alloc] initWithShell:this]); [window_ setDelegate:window_delegate_]; // Only use native parent window for non-modal windows. if (parent && !is_modal()) { SetParentWindow(parent); } if (transparent()) { // Setting the background color to clear will also hide the shadow. [window_ setBackgroundColor:[NSColor clearColor]]; } if (windowType == "desktop") { [window_ setLevel:kCGDesktopWindowLevel - 1]; [window_ setDisableKeyOrMainWindow:YES]; [window_ setCollectionBehavior:(NSWindowCollectionBehaviorCanJoinAllSpaces | NSWindowCollectionBehaviorStationary | NSWindowCollectionBehaviorIgnoresCycle)]; } if (windowType == "panel") { [window_ setLevel:NSFloatingWindowLevel]; } bool focusable; if (options.Get(options::kFocusable, &focusable) && !focusable) [window_ setDisableKeyOrMainWindow:YES]; if (transparent() || !has_frame()) { // Don't show title bar. [window_ setTitlebarAppearsTransparent:YES]; [window_ setTitleVisibility:NSWindowTitleHidden]; // Remove non-transparent corners, see // https://github.com/electron/electron/issues/517. [window_ setOpaque:NO]; // Show window buttons if titleBarStyle is not "normal". if (title_bar_style_ == TitleBarStyle::kNormal) { InternalSetWindowButtonVisibility(false); } else { buttons_proxy_.reset([[WindowButtonsProxy alloc] initWithWindow:window_]); [buttons_proxy_ setHeight:titlebar_overlay_height()]; if (traffic_light_position_) { [buttons_proxy_ setMargin:*traffic_light_position_]; } else if (title_bar_style_ == TitleBarStyle::kHiddenInset) { // For macOS >= 11, while this value does not match official macOS apps // like Safari or Notes, it matches titleBarStyle's old implementation // before Electron <= 12. [buttons_proxy_ setMargin:gfx::Point(12, 11)]; } if (title_bar_style_ == TitleBarStyle::kCustomButtonsOnHover) { [buttons_proxy_ setShowOnHover:YES]; } else { // customButtonsOnHover does not show buttons initially. InternalSetWindowButtonVisibility(true); } } } // Create a tab only if tabbing identifier is specified and window has // a native title bar. if (tabbingIdentifier.empty() || transparent() || !has_frame()) { [window_ setTabbingMode:NSWindowTabbingModeDisallowed]; } else { [window_ setTabbingIdentifier:base::SysUTF8ToNSString(tabbingIdentifier)]; } // Resize to content bounds. bool use_content_size = false; options.Get(options::kUseContentSize, &use_content_size); if (!has_frame() || use_content_size) SetContentSize(gfx::Size(width, height)); // Enable the NSView to accept first mouse event. bool acceptsFirstMouse = false; options.Get(options::kAcceptFirstMouse, &acceptsFirstMouse); [window_ setAcceptsFirstMouse:acceptsFirstMouse]; // Disable auto-hiding cursor. bool disableAutoHideCursor = false; options.Get(options::kDisableAutoHideCursor, &disableAutoHideCursor); [window_ setDisableAutoHideCursor:disableAutoHideCursor]; // Use an NSEvent monitor to listen for the wheel event. BOOL __block began = NO; wheel_event_monitor_ = [NSEvent addLocalMonitorForEventsMatchingMask:NSEventMaskScrollWheel handler:^(NSEvent* event) { if ([[event window] windowNumber] != [window_ windowNumber]) return event; if (!began && (([event phase] == NSEventPhaseMayBegin) || ([event phase] == NSEventPhaseBegan))) { this->NotifyWindowScrollTouchBegin(); began = YES; } else if (began && (([event phase] == NSEventPhaseEnded) || ([event phase] == NSEventPhaseCancelled))) { this->NotifyWindowScrollTouchEnd(); began = NO; } return event; }]; // Set maximizable state last to ensure zoom button does not get reset // by calls to other APIs. SetMaximizable(maximizable); // Default content view. SetContentView(new views::View()); AddContentViewLayers(); UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } NativeWindowMac::~NativeWindowMac() = default; void NativeWindowMac::SetContentView(views::View* view) { views::View* root_view = GetContentsView(); if (content_view()) root_view->RemoveChildView(content_view()); set_content_view(view); root_view->AddChildView(content_view()); root_view->Layout(); } void NativeWindowMac::Close() { if (!IsClosable()) { WindowList::WindowCloseCancelled(this); return; } if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { SetHasDeferredWindowClose(true); return; } // If a sheet is attached to the window when we call // [window_ performClose:nil], the window won't close properly // even after the user has ended the sheet. // Ensure it's closed before calling [window_ performClose:nil]. SetEnabled(true); [window_ performClose:nil]; // Closing a sheet doesn't trigger windowShouldClose, // so we need to manually call it ourselves here. if (is_modal() && parent() && IsVisible()) { NotifyWindowCloseButtonClicked(); } } void NativeWindowMac::CloseImmediately() { // Retain the child window before closing it. If the last reference to the // NSWindow goes away inside -[NSWindow close], then bad stuff can happen. // See e.g. http://crbug.com/616701. base::scoped_nsobject<NSWindow> child_window(window_, base::scoped_policy::RETAIN); [window_ close]; } void NativeWindowMac::Focus(bool focus) { if (!IsVisible()) return; if (focus) { [[NSApplication sharedApplication] activateIgnoringOtherApps:NO]; [window_ makeKeyAndOrderFront:nil]; } else { [window_ orderOut:nil]; [window_ orderBack:nil]; } } bool NativeWindowMac::IsFocused() { return [window_ isKeyWindow]; } void NativeWindowMac::Show() { if (is_modal() && parent()) { NSWindow* window = parent()->GetNativeWindow().GetNativeNSWindow(); if ([window_ sheetParent] == nil) [window beginSheet:window_ completionHandler:^(NSModalResponse){ }]; return; } // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); // This method is supposed to put focus on window, however if the app does not // have focus then "makeKeyAndOrderFront" will only show the window. [NSApp activateIgnoringOtherApps:YES]; [window_ makeKeyAndOrderFront:nil]; } void NativeWindowMac::ShowInactive() { // Reattach the window to the parent to actually show it. if (parent()) InternalSetParentWindow(parent(), true); [window_ orderFrontRegardless]; } void NativeWindowMac::Hide() { // If a sheet is attached to the window when we call [window_ orderOut:nil], // the sheet won't be able to show again on the same window. // Ensure it's closed before calling [window_ orderOut:nil]. SetEnabled(true); if (is_modal() && parent()) { [window_ orderOut:nil]; [parent()->GetNativeWindow().GetNativeNSWindow() endSheet:window_]; return; } // Hide all children of the current window before hiding the window. // components/remote_cocoa/app_shim/native_widget_ns_window_bridge.mm // expects this when window visibility changes. if ([window_ childWindows]) { for (NSWindow* child in [window_ childWindows]) { [child orderOut:nil]; } } // Detach the window from the parent before. if (parent()) InternalSetParentWindow(parent(), false); [window_ orderOut:nil]; } bool NativeWindowMac::IsVisible() { bool occluded = [window_ occlusionState] == NSWindowOcclusionStateVisible; // For a window to be visible, it must be visible to the user in the // foreground of the app, which means that it should not be minimized or // occluded return [window_ isVisible] && !occluded && !IsMinimized(); } bool NativeWindowMac::IsEnabled() { return [window_ attachedSheet] == nil; } void NativeWindowMac::SetEnabled(bool enable) { if (!enable) { [window_ beginSheet:window_ completionHandler:^(NSModalResponse returnCode) { NSLog(@"modal enabled"); return; }]; } else if ([window_ attachedSheet]) { [window_ endSheet:[window_ attachedSheet]]; } } void NativeWindowMac::Maximize() { const bool is_visible = [window_ isVisible]; if (IsMaximized()) { if (!is_visible) ShowInactive(); return; } // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ zoom:nil]; if (!is_visible) { ShowInactive(); NotifyWindowMaximize(); } } void NativeWindowMac::Unmaximize() { // Bail if the last user set bounds were the same size as the window // screen (e.g. the user set the window to maximized via setBounds) // // Per docs during zoom: // > If there’s no saved user state because there has been no previous // > zoom,the size and location of the window don’t change. // // However, in classic Apple fashion, this is not the case in practice, // and the frame inexplicably becomes very tiny. We should prevent // zoom from being called if the window is being unmaximized and its // unmaximized window bounds are themselves functionally maximized. if (!IsMaximized() || user_set_bounds_maximized_) return; [window_ zoom:nil]; } bool NativeWindowMac::IsMaximized() { if (HasStyleMask(NSWindowStyleMaskResizable) != 0) return [window_ isZoomed]; NSRect rectScreen = GetAspectRatio() > 0.0 ? default_frame_for_zoom() : [[NSScreen mainScreen] visibleFrame]; return NSEqualRects([window_ frame], rectScreen); } void NativeWindowMac::Minimize() { if (IsMinimized()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); [window_ miniaturize:nil]; } void NativeWindowMac::Restore() { [window_ deminiaturize:nil]; } bool NativeWindowMac::IsMinimized() { return [window_ isMiniaturized]; } bool NativeWindowMac::HandleDeferredClose() { if (has_deferred_window_close_) { SetHasDeferredWindowClose(false); Close(); return true; } return false; } void NativeWindowMac::SetFullScreen(bool fullscreen) { // [NSWindow -toggleFullScreen] is an asynchronous operation, which means // that it's possible to call it while a fullscreen transition is currently // in process. This can create weird behavior (incl. phantom windows), // so we want to schedule a transition for when the current one has completed. if (fullscreen_transition_state() != FullScreenTransitionState::NONE) { if (!pending_transitions_.empty()) { bool last_pending = pending_transitions_.back(); // Only push new transitions if they're different than the last transition // in the queue. if (last_pending != fullscreen) pending_transitions_.push(fullscreen); } else { pending_transitions_.push(fullscreen); } return; } if (fullscreen == IsFullscreen()) return; // Take note of the current window size if (IsNormal()) UpdateWindowOriginalFrame(); // This needs to be set here because it can be the case that // SetFullScreen is called by a user before windowWillEnterFullScreen // or windowWillExitFullScreen are invoked, and so a potential transition // could be dropped. fullscreen_transition_state_ = fullscreen ? FullScreenTransitionState::ENTERING : FullScreenTransitionState::EXITING; [window_ toggleFullScreenMode:nil]; } bool NativeWindowMac::IsFullscreen() const { return HasStyleMask(NSWindowStyleMaskFullScreen); } void NativeWindowMac::SetBounds(const gfx::Rect& bounds, bool animate) { // Do nothing if in fullscreen mode. if (IsFullscreen()) return; // Check size constraints since setFrame does not check it. gfx::Size size = bounds.size(); size.SetToMax(GetMinimumSize()); gfx::Size max_size = GetMaximumSize(); if (!max_size.IsEmpty()) size.SetToMin(max_size); NSRect cocoa_bounds = NSMakeRect(bounds.x(), 0, size.width(), size.height()); // Flip coordinates based on the primary screen. NSScreen* screen = [[NSScreen screens] firstObject]; cocoa_bounds.origin.y = NSHeight([screen frame]) - size.height() - bounds.y(); [window_ setFrame:cocoa_bounds display:YES animate:animate]; user_set_bounds_maximized_ = IsMaximized() ? true : false; UpdateWindowOriginalFrame(); } gfx::Rect NativeWindowMac::GetBounds() { NSRect frame = [window_ frame]; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; } bool NativeWindowMac::IsNormal() { return NativeWindow::IsNormal() && !IsSimpleFullScreen(); } gfx::Rect NativeWindowMac::GetNormalBounds() { if (IsNormal()) { return GetBounds(); } NSRect frame = original_frame_; gfx::Rect bounds(frame.origin.x, 0, NSWidth(frame), NSHeight(frame)); NSScreen* screen = [[NSScreen screens] firstObject]; bounds.set_y(NSHeight([screen frame]) - NSMaxY(frame)); return bounds; // Works on OS_WIN ! // return widget()->GetRestoredBounds(); } void NativeWindowMac::SetContentSizeConstraints( const extensions::SizeConstraints& size_constraints) { auto convertSize = [this](const gfx::Size& size) { // Our frameless window still has titlebar attached, so setting contentSize // will result in actual content size being larger. if (!has_frame()) { NSRect frame = NSMakeRect(0, 0, size.width(), size.height()); NSRect content = [window_ originalContentRectForFrameRect:frame]; return content.size; } else { return NSMakeSize(size.width(), size.height()); } }; NSView* content = [window_ contentView]; if (size_constraints.HasMinimumSize()) { NSSize min_size = convertSize(size_constraints.GetMinimumSize()); [window_ setContentMinSize:[content convertSize:min_size toView:nil]]; } if (size_constraints.HasMaximumSize()) { NSSize max_size = convertSize(size_constraints.GetMaximumSize()); [window_ setContentMaxSize:[content convertSize:max_size toView:nil]]; } NativeWindow::SetContentSizeConstraints(size_constraints); } bool NativeWindowMac::MoveAbove(const std::string& sourceId) { const content::DesktopMediaID id = content::DesktopMediaID::Parse(sourceId); if (id.type != content::DesktopMediaID::TYPE_WINDOW) return false; // Check if the window source is valid. const CGWindowID window_id = id.id; if (!webrtc::GetWindowOwnerPid(window_id)) return false; [window_ orderWindow:NSWindowAbove relativeTo:id.id]; return true; } void NativeWindowMac::MoveTop() { [window_ orderWindow:NSWindowAbove relativeTo:0]; } void NativeWindowMac::SetResizable(bool resizable) { ScopedDisableResize disable_resize; SetStyleMask(resizable, NSWindowStyleMaskResizable); SetCanResize(resizable); } bool NativeWindowMac::IsResizable() { bool in_fs_transition = fullscreen_transition_state() != FullScreenTransitionState::NONE; bool has_rs_mask = HasStyleMask(NSWindowStyleMaskResizable); return has_rs_mask && !IsFullscreen() && !in_fs_transition; } void NativeWindowMac::SetMovable(bool movable) { [window_ setMovable:movable]; } bool NativeWindowMac::IsMovable() { return [window_ isMovable]; } void NativeWindowMac::SetMinimizable(bool minimizable) { SetStyleMask(minimizable, NSWindowStyleMaskMiniaturizable); } bool NativeWindowMac::IsMinimizable() { return HasStyleMask(NSWindowStyleMaskMiniaturizable); } void NativeWindowMac::SetMaximizable(bool maximizable) { maximizable_ = maximizable; [[window_ standardWindowButton:NSWindowZoomButton] setEnabled:maximizable]; } bool NativeWindowMac::IsMaximizable() { return [[window_ standardWindowButton:NSWindowZoomButton] isEnabled]; } void NativeWindowMac::SetFullScreenable(bool fullscreenable) { SetCollectionBehavior(fullscreenable, NSWindowCollectionBehaviorFullScreenPrimary); // On EL Capitan this flag is required to hide fullscreen button. SetCollectionBehavior(!fullscreenable, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsFullScreenable() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorFullScreenPrimary; } void NativeWindowMac::SetClosable(bool closable) { SetStyleMask(closable, NSWindowStyleMaskClosable); } bool NativeWindowMac::IsClosable() { return HasStyleMask(NSWindowStyleMaskClosable); } void NativeWindowMac::SetAlwaysOnTop(ui::ZOrderLevel z_order, const std::string& level_name, int relative_level) { if (z_order == ui::ZOrderLevel::kNormal) { SetWindowLevel(NSNormalWindowLevel); return; } int level = NSNormalWindowLevel; if (level_name == "floating") { level = NSFloatingWindowLevel; } else if (level_name == "torn-off-menu") { level = NSTornOffMenuWindowLevel; } else if (level_name == "modal-panel") { level = NSModalPanelWindowLevel; } else if (level_name == "main-menu") { level = NSMainMenuWindowLevel; } else if (level_name == "status") { level = NSStatusWindowLevel; } else if (level_name == "pop-up-menu") { level = NSPopUpMenuWindowLevel; } else if (level_name == "screen-saver") { level = NSScreenSaverWindowLevel; } SetWindowLevel(level + relative_level); } std::string NativeWindowMac::GetAlwaysOnTopLevel() { std::string level_name = "normal"; int level = [window_ level]; if (level == NSFloatingWindowLevel) { level_name = "floating"; } else if (level == NSTornOffMenuWindowLevel) { level_name = "torn-off-menu"; } else if (level == NSModalPanelWindowLevel) { level_name = "modal-panel"; } else if (level == NSMainMenuWindowLevel) { level_name = "main-menu"; } else if (level == NSStatusWindowLevel) { level_name = "status"; } else if (level == NSPopUpMenuWindowLevel) { level_name = "pop-up-menu"; } else if (level == NSScreenSaverWindowLevel) { level_name = "screen-saver"; } return level_name; } void NativeWindowMac::SetWindowLevel(int unbounded_level) { int level = std::min( std::max(unbounded_level, CGWindowLevelForKey(kCGMinimumWindowLevelKey)), CGWindowLevelForKey(kCGMaximumWindowLevelKey)); ui::ZOrderLevel z_order_level = level == NSNormalWindowLevel ? ui::ZOrderLevel::kNormal : ui::ZOrderLevel::kFloatingWindow; bool did_z_order_level_change = z_order_level != GetZOrderLevel(); was_maximizable_ = IsMaximizable(); // We need to explicitly keep the NativeWidget up to date, since it stores the // window level in a local variable, rather than reading it from the NSWindow. // Unfortunately, it results in a second setLevel call. It's not ideal, but we // don't expect this to cause any user-visible jank. widget()->SetZOrderLevel(z_order_level); [window_ setLevel:level]; // Set level will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(was_maximizable_); // This must be notified at the very end or IsAlwaysOnTop // will not yet have been updated to reflect the new status if (did_z_order_level_change) NativeWindow::NotifyWindowAlwaysOnTopChanged(); } ui::ZOrderLevel NativeWindowMac::GetZOrderLevel() { return widget()->GetZOrderLevel(); } void NativeWindowMac::Center() { [window_ center]; } void NativeWindowMac::Invalidate() { [window_ flushWindow]; [[window_ contentView] setNeedsDisplay:YES]; } void NativeWindowMac::SetTitle(const std::string& title) { [window_ setTitle:base::SysUTF8ToNSString(title)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetTitle() { return base::SysNSStringToUTF8([window_ title]); } void NativeWindowMac::FlashFrame(bool flash) { if (flash) { attention_request_id_ = [NSApp requestUserAttention:NSInformationalRequest]; } else { [NSApp cancelUserAttentionRequest:attention_request_id_]; attention_request_id_ = 0; } } void NativeWindowMac::SetSkipTaskbar(bool skip) {} bool NativeWindowMac::IsExcludedFromShownWindowsMenu() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); return [window isExcludedFromWindowsMenu]; } void NativeWindowMac::SetExcludedFromShownWindowsMenu(bool excluded) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); [window setExcludedFromWindowsMenu:excluded]; } void NativeWindowMac::OnDisplayMetricsChanged(const display::Display& display, uint32_t changed_metrics) { // We only want to force screen recalibration if we're in simpleFullscreen // mode. if (!is_simple_fullscreen_) return; content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::UpdateFrame, GetWeakPtr())); } void NativeWindowMac::SetSimpleFullScreen(bool simple_fullscreen) { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); if (simple_fullscreen && !is_simple_fullscreen_) { is_simple_fullscreen_ = true; // Take note of the current window size and level if (IsNormal()) { UpdateWindowOriginalFrame(); original_level_ = [window_ level]; } simple_fullscreen_options_ = [NSApp currentSystemPresentationOptions]; simple_fullscreen_mask_ = [window styleMask]; // We can simulate the pre-Lion fullscreen by auto-hiding the dock and menu // bar NSApplicationPresentationOptions options = NSApplicationPresentationAutoHideDock | NSApplicationPresentationAutoHideMenuBar; [NSApp setPresentationOptions:options]; was_maximizable_ = IsMaximizable(); was_movable_ = IsMovable(); NSRect fullscreenFrame = [window.screen frame]; // If our app has dock hidden, set the window level higher so another app's // menu bar doesn't appear on top of our fullscreen app. if ([[NSRunningApplication currentApplication] activationPolicy] != NSApplicationActivationPolicyRegular) { window.level = NSPopUpMenuWindowLevel; } // Always hide the titlebar in simple fullscreen mode. // // Note that we must remove the NSWindowStyleMaskTitled style instead of // using the [window_ setTitleVisibility:], as the latter would leave the // window with rounded corners. SetStyleMask(false, NSWindowStyleMaskTitled); if (!window_button_visibility_.has_value()) { // Lets keep previous behaviour - hide window controls in titled // fullscreen mode when not specified otherwise. InternalSetWindowButtonVisibility(false); } [window setFrame:fullscreenFrame display:YES animate:YES]; // Fullscreen windows can't be resized, minimized, maximized, or moved SetMinimizable(false); SetResizable(false); SetMaximizable(false); SetMovable(false); } else if (!simple_fullscreen && is_simple_fullscreen_) { is_simple_fullscreen_ = false; [window setFrame:original_frame_ display:YES animate:YES]; window.level = original_level_; [NSApp setPresentationOptions:simple_fullscreen_options_]; // Restore original style mask ScopedDisableResize disable_resize; [window_ setStyleMask:simple_fullscreen_mask_]; // Restore window manipulation abilities SetMaximizable(was_maximizable_); SetMovable(was_movable_); // Restore default window controls visibility state. if (!window_button_visibility_.has_value()) { bool visibility; if (has_frame()) visibility = true; else visibility = title_bar_style_ != TitleBarStyle::kNormal; InternalSetWindowButtonVisibility(visibility); } if (buttons_proxy_) [buttons_proxy_ redraw]; } } bool NativeWindowMac::IsSimpleFullScreen() { return is_simple_fullscreen_; } void NativeWindowMac::SetKiosk(bool kiosk) { if (kiosk && !is_kiosk_) { kiosk_options_ = [NSApp currentSystemPresentationOptions]; NSApplicationPresentationOptions options = NSApplicationPresentationHideDock | NSApplicationPresentationHideMenuBar | NSApplicationPresentationDisableAppleMenu | NSApplicationPresentationDisableProcessSwitching | NSApplicationPresentationDisableForceQuit | NSApplicationPresentationDisableSessionTermination | NSApplicationPresentationDisableHideApplication; [NSApp setPresentationOptions:options]; is_kiosk_ = true; SetFullScreen(true); } else if (!kiosk && is_kiosk_) { [NSApp setPresentationOptions:kiosk_options_]; is_kiosk_ = false; SetFullScreen(false); } } bool NativeWindowMac::IsKiosk() { return is_kiosk_; } void NativeWindowMac::SetBackgroundColor(SkColor color) { base::ScopedCFTypeRef<CGColorRef> cgcolor( skia::CGColorCreateFromSkColor(color)); [[[window_ contentView] layer] setBackgroundColor:cgcolor]; } SkColor NativeWindowMac::GetBackgroundColor() { CGColorRef color = [[[window_ contentView] layer] backgroundColor]; if (!color) return SK_ColorTRANSPARENT; return skia::CGColorRefToSkColor(color); } void NativeWindowMac::SetHasShadow(bool has_shadow) { [window_ setHasShadow:has_shadow]; } bool NativeWindowMac::HasShadow() { return [window_ hasShadow]; } void NativeWindowMac::SetOpacity(const double opacity) { const double boundedOpacity = base::clamp(opacity, 0.0, 1.0); [window_ setAlphaValue:boundedOpacity]; } double NativeWindowMac::GetOpacity() { return [window_ alphaValue]; } void NativeWindowMac::SetRepresentedFilename(const std::string& filename) { [window_ setRepresentedFilename:base::SysUTF8ToNSString(filename)]; if (buttons_proxy_) [buttons_proxy_ redraw]; } std::string NativeWindowMac::GetRepresentedFilename() { return base::SysNSStringToUTF8([window_ representedFilename]); } void NativeWindowMac::SetDocumentEdited(bool edited) { [window_ setDocumentEdited:edited]; if (buttons_proxy_) [buttons_proxy_ redraw]; } bool NativeWindowMac::IsDocumentEdited() { return [window_ isDocumentEdited]; } void NativeWindowMac::SetIgnoreMouseEvents(bool ignore, bool forward) { [window_ setIgnoresMouseEvents:ignore]; if (!ignore) { SetForwardMouseMessages(NO); } else { SetForwardMouseMessages(forward); } } void NativeWindowMac::SetContentProtection(bool enable) { [window_ setSharingType:enable ? NSWindowSharingNone : NSWindowSharingReadOnly]; } void NativeWindowMac::SetFocusable(bool focusable) { // No known way to unfocus the window if it had the focus. Here we do not // want to call Focus(false) because it moves the window to the back, i.e. // at the bottom in term of z-order. [window_ setDisableKeyOrMainWindow:!focusable]; } bool NativeWindowMac::IsFocusable() { return ![window_ disableKeyOrMainWindow]; } void NativeWindowMac::AddBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::RemoveBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } if (view->GetInspectableWebContentsView()) [view->GetInspectableWebContentsView()->GetNativeView().GetNativeNSView() removeFromSuperview]; remove_browser_view(view); [CATransaction commit]; } void NativeWindowMac::SetTopBrowserView(NativeBrowserView* view) { [CATransaction begin]; [CATransaction setDisableActions:YES]; if (!view) { [CATransaction commit]; return; } remove_browser_view(view); add_browser_view(view); if (view->GetInspectableWebContentsView()) { auto* native_view = view->GetInspectableWebContentsView() ->GetNativeView() .GetNativeNSView(); [[window_ contentView] addSubview:native_view positioned:NSWindowAbove relativeTo:nil]; native_view.hidden = NO; } [CATransaction commit]; } void NativeWindowMac::SetParentWindow(NativeWindow* parent) { InternalSetParentWindow(parent, IsVisible()); } gfx::NativeView NativeWindowMac::GetNativeView() const { return [window_ contentView]; } gfx::NativeWindow NativeWindowMac::GetNativeWindow() const { return window_; } gfx::AcceleratedWidget NativeWindowMac::GetAcceleratedWidget() const { return [window_ windowNumber]; } content::DesktopMediaID NativeWindowMac::GetDesktopMediaID() const { auto desktop_media_id = content::DesktopMediaID( content::DesktopMediaID::TYPE_WINDOW, GetAcceleratedWidget()); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/browser/media/webrtc/native_desktop_media_list.cc;l=372?q=kWindowCaptureMacV2&ss=chromium // Refs https://github.com/electron/electron/pull/30507 // TODO(deepak1556): Match upstream for `kWindowCaptureMacV2` #if 0 if (remote_cocoa::ScopedCGWindowID::Get(desktop_media_id.id)) { desktop_media_id.window_id = desktop_media_id.id; } #endif return desktop_media_id; } NativeWindowHandle NativeWindowMac::GetNativeWindowHandle() const { return [window_ contentView]; } void NativeWindowMac::SetProgressBar(double progress, const NativeWindow::ProgressState state) { NSDockTile* dock_tile = [NSApp dockTile]; // Sometimes macOS would install a default contentView for dock, we must // verify whether NSProgressIndicator has been installed. bool first_time = !dock_tile.contentView || [[dock_tile.contentView subviews] count] == 0 || ![[[dock_tile.contentView subviews] lastObject] isKindOfClass:[NSProgressIndicator class]]; // For the first time API invoked, we need to create a ContentView in // DockTile. if (first_time) { NSImageView* image_view = [[[NSImageView alloc] init] autorelease]; [image_view setImage:[NSApp applicationIconImage]]; [dock_tile setContentView:image_view]; NSRect frame = NSMakeRect(0.0f, 0.0f, dock_tile.size.width, 15.0); NSProgressIndicator* progress_indicator = [[[ElectronProgressBar alloc] initWithFrame:frame] autorelease]; [progress_indicator setStyle:NSProgressIndicatorBarStyle]; [progress_indicator setIndeterminate:NO]; [progress_indicator setBezeled:YES]; [progress_indicator setMinValue:0]; [progress_indicator setMaxValue:1]; [progress_indicator setHidden:NO]; [dock_tile.contentView addSubview:progress_indicator]; } NSProgressIndicator* progress_indicator = static_cast<NSProgressIndicator*>( [[[dock_tile contentView] subviews] lastObject]); if (progress < 0) { [progress_indicator setHidden:YES]; } else if (progress > 1) { [progress_indicator setHidden:NO]; [progress_indicator setIndeterminate:YES]; [progress_indicator setDoubleValue:1]; } else { [progress_indicator setHidden:NO]; [progress_indicator setDoubleValue:progress]; } [dock_tile display]; } void NativeWindowMac::SetOverlayIcon(const gfx::Image& overlay, const std::string& description) {} void NativeWindowMac::SetVisibleOnAllWorkspaces(bool visible, bool visibleOnFullScreen, bool skipTransformProcessType) { // In order for NSWindows to be visible on fullscreen we need to functionally // mimic app.dock.hide() since Apple changed the underlying functionality of // NSWindows starting with 10.14 to disallow NSWindows from floating on top of // fullscreen apps. if (!skipTransformProcessType) { ProcessSerialNumber psn = {0, kCurrentProcess}; if (visibleOnFullScreen) { [window_ setCanHide:NO]; TransformProcessType(&psn, kProcessTransformToUIElementApplication); } else { [window_ setCanHide:YES]; TransformProcessType(&psn, kProcessTransformToForegroundApplication); } } SetCollectionBehavior(visible, NSWindowCollectionBehaviorCanJoinAllSpaces); SetCollectionBehavior(visibleOnFullScreen, NSWindowCollectionBehaviorFullScreenAuxiliary); } bool NativeWindowMac::IsVisibleOnAllWorkspaces() { NSUInteger collectionBehavior = [window_ collectionBehavior]; return collectionBehavior & NSWindowCollectionBehaviorCanJoinAllSpaces; } void NativeWindowMac::SetAutoHideCursor(bool auto_hide) { [window_ setDisableAutoHideCursor:!auto_hide]; } void NativeWindowMac::UpdateVibrancyRadii(bool fullscreen) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (vibrantView != nil && !vibrancy_type_.empty()) { const bool no_rounded_corner = !HasStyleMask(NSWindowStyleMaskTitled); if (!has_frame() && !is_modal() && !no_rounded_corner) { CGFloat radius; if (fullscreen) { radius = 0.0f; } else if (@available(macOS 11.0, *)) { radius = 9.0f; } else { // Smaller corner radius on versions prior to Big Sur. radius = 5.0f; } CGFloat dimension = 2 * radius + 1; NSSize size = NSMakeSize(dimension, dimension); NSImage* maskImage = [NSImage imageWithSize:size flipped:NO drawingHandler:^BOOL(NSRect rect) { NSBezierPath* bezierPath = [NSBezierPath bezierPathWithRoundedRect:rect xRadius:radius yRadius:radius]; [[NSColor blackColor] set]; [bezierPath fill]; return YES; }]; [maskImage setCapInsets:NSEdgeInsetsMake(radius, radius, radius, radius)]; [maskImage setResizingMode:NSImageResizingModeStretch]; [vibrantView setMaskImage:maskImage]; [window_ setCornerMask:maskImage]; } } } void NativeWindowMac::UpdateWindowOriginalFrame() { original_frame_ = [window_ frame]; } void NativeWindowMac::SetVibrancy(const std::string& type) { NSVisualEffectView* vibrantView = [window_ vibrantView]; if (type.empty()) { if (vibrantView == nil) return; [vibrantView removeFromSuperview]; [window_ setVibrantView:nil]; return; } std::string dep_warn = " has been deprecated and removed as of macOS 10.15."; node::Environment* env = node::Environment::GetCurrent(JavascriptEnvironment::GetIsolate()); NSVisualEffectMaterial vibrancyType{}; if (type == "appearance-based") { EmitWarning(env, "NSVisualEffectMaterialAppearanceBased" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialAppearanceBased; } else if (type == "light") { EmitWarning(env, "NSVisualEffectMaterialLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialLight; } else if (type == "dark") { EmitWarning(env, "NSVisualEffectMaterialDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialDark; } else if (type == "titlebar") { vibrancyType = NSVisualEffectMaterialTitlebar; } if (type == "selection") { vibrancyType = NSVisualEffectMaterialSelection; } else if (type == "menu") { vibrancyType = NSVisualEffectMaterialMenu; } else if (type == "popover") { vibrancyType = NSVisualEffectMaterialPopover; } else if (type == "sidebar") { vibrancyType = NSVisualEffectMaterialSidebar; } else if (type == "medium-light") { EmitWarning(env, "NSVisualEffectMaterialMediumLight" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialMediumLight; } else if (type == "ultra-dark") { EmitWarning(env, "NSVisualEffectMaterialUltraDark" + dep_warn, "electron"); vibrancyType = NSVisualEffectMaterialUltraDark; } if (@available(macOS 10.14, *)) { if (type == "header") { vibrancyType = NSVisualEffectMaterialHeaderView; } else if (type == "sheet") { vibrancyType = NSVisualEffectMaterialSheet; } else if (type == "window") { vibrancyType = NSVisualEffectMaterialWindowBackground; } else if (type == "hud") { vibrancyType = NSVisualEffectMaterialHUDWindow; } else if (type == "fullscreen-ui") { vibrancyType = NSVisualEffectMaterialFullScreenUI; } else if (type == "tooltip") { vibrancyType = NSVisualEffectMaterialToolTip; } else if (type == "content") { vibrancyType = NSVisualEffectMaterialContentBackground; } else if (type == "under-window") { vibrancyType = NSVisualEffectMaterialUnderWindowBackground; } else if (type == "under-page") { vibrancyType = NSVisualEffectMaterialUnderPageBackground; } } if (vibrancyType) { vibrancy_type_ = type; if (vibrantView == nil) { vibrantView = [[[NSVisualEffectView alloc] initWithFrame:[[window_ contentView] bounds]] autorelease]; [window_ setVibrantView:vibrantView]; [vibrantView setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [vibrantView setBlendingMode:NSVisualEffectBlendingModeBehindWindow]; if (visual_effect_state_ == VisualEffectState::kActive) { [vibrantView setState:NSVisualEffectStateActive]; } else if (visual_effect_state_ == VisualEffectState::kInactive) { [vibrantView setState:NSVisualEffectStateInactive]; } else { [vibrantView setState:NSVisualEffectStateFollowsWindowActiveState]; } [[window_ contentView] addSubview:vibrantView positioned:NSWindowBelow relativeTo:nil]; UpdateVibrancyRadii(IsFullscreen()); } [vibrantView setMaterial:vibrancyType]; } } void NativeWindowMac::SetWindowButtonVisibility(bool visible) { window_button_visibility_ = visible; if (buttons_proxy_) { if (visible) [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:visible]; } if (title_bar_style_ != TitleBarStyle::kCustomButtonsOnHover) InternalSetWindowButtonVisibility(visible); NotifyLayoutWindowControlsOverlay(); } bool NativeWindowMac::GetWindowButtonVisibility() const { return ![window_ standardWindowButton:NSWindowZoomButton].hidden || ![window_ standardWindowButton:NSWindowMiniaturizeButton].hidden || ![window_ standardWindowButton:NSWindowCloseButton].hidden; } void NativeWindowMac::SetTrafficLightPosition( absl::optional<gfx::Point> position) { traffic_light_position_ = std::move(position); if (buttons_proxy_) { [buttons_proxy_ setMargin:traffic_light_position_]; NotifyLayoutWindowControlsOverlay(); } } absl::optional<gfx::Point> NativeWindowMac::GetTrafficLightPosition() const { return traffic_light_position_; } void NativeWindowMac::RedrawTrafficLights() { if (buttons_proxy_ && !IsFullscreen()) [buttons_proxy_ redraw]; } // In simpleFullScreen mode, update the frame for new bounds. void NativeWindowMac::UpdateFrame() { NSWindow* window = GetNativeWindow().GetNativeNSWindow(); NSRect fullscreenFrame = [window.screen frame]; [window setFrame:fullscreenFrame display:YES animate:YES]; } void NativeWindowMac::SetTouchBar( std::vector<gin_helper::PersistentDictionary> items) { touch_bar_.reset([[ElectronTouchBar alloc] initWithDelegate:window_delegate_.get() window:this settings:std::move(items)]); [window_ setTouchBar:nil]; } void NativeWindowMac::RefreshTouchBarItem(const std::string& item_id) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ refreshTouchBarItem:[window_ touchBar] id:item_id]; } void NativeWindowMac::SetEscapeTouchBarItem( gin_helper::PersistentDictionary item) { if (touch_bar_ && [window_ touchBar]) [touch_bar_ setEscapeTouchBarItem:std::move(item) forTouchBar:[window_ touchBar]]; } void NativeWindowMac::SelectPreviousTab() { [window_ selectPreviousTab:nil]; } void NativeWindowMac::SelectNextTab() { [window_ selectNextTab:nil]; } void NativeWindowMac::MergeAllWindows() { [window_ mergeAllWindows:nil]; } void NativeWindowMac::MoveTabToNewWindow() { [window_ moveTabToNewWindow:nil]; } void NativeWindowMac::ToggleTabBar() { [window_ toggleTabBar:nil]; } bool NativeWindowMac::AddTabbedWindow(NativeWindow* window) { if (window_ == window->GetNativeWindow().GetNativeNSWindow()) { return false; } else { [window_ addTabbedWindow:window->GetNativeWindow().GetNativeNSWindow() ordered:NSWindowAbove]; } return true; } void NativeWindowMac::SetAspectRatio(double aspect_ratio, const gfx::Size& extra_size) { NativeWindow::SetAspectRatio(aspect_ratio, extra_size); // Reset the behaviour to default if aspect_ratio is set to 0 or less. if (aspect_ratio > 0.0) { NSSize aspect_ratio_size = NSMakeSize(aspect_ratio, 1.0); if (has_frame()) [window_ setContentAspectRatio:aspect_ratio_size]; else [window_ setAspectRatio:aspect_ratio_size]; } else { [window_ setResizeIncrements:NSMakeSize(1.0, 1.0)]; } } void NativeWindowMac::PreviewFile(const std::string& path, const std::string& display_name) { preview_item_.reset([[ElectronPreviewItem alloc] initWithURL:[NSURL fileURLWithPath:base::SysUTF8ToNSString(path)] title:base::SysUTF8ToNSString(display_name)]); [[QLPreviewPanel sharedPreviewPanel] makeKeyAndOrderFront:nil]; } void NativeWindowMac::CloseFilePreview() { if ([QLPreviewPanel sharedPreviewPanelExists]) { [[QLPreviewPanel sharedPreviewPanel] close]; } } gfx::Rect NativeWindowMac::ContentBoundsToWindowBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect window_bounds( [window_ frameRectForContentRect:bounds.ToCGRect()]); int frame_height = window_bounds.height() - bounds.height(); window_bounds.set_y(window_bounds.y() - frame_height); return window_bounds; } else { return bounds; } } gfx::Rect NativeWindowMac::WindowBoundsToContentBounds( const gfx::Rect& bounds) const { if (has_frame()) { gfx::Rect content_bounds( [window_ contentRectForFrameRect:bounds.ToCGRect()]); int frame_height = bounds.height() - content_bounds.height(); content_bounds.set_y(content_bounds.y() + frame_height); return content_bounds; } else { return bounds; } } void NativeWindowMac::NotifyWindowEnterFullScreen() { NativeWindow::NotifyWindowEnterFullScreen(); // Restore the window title under fullscreen mode. if (buttons_proxy_) [window_ setTitleVisibility:NSWindowTitleVisible]; } void NativeWindowMac::NotifyWindowLeaveFullScreen() { NativeWindow::NotifyWindowLeaveFullScreen(); // Restore window buttons. if (buttons_proxy_ && window_button_visibility_.value_or(true)) { [buttons_proxy_ redraw]; [buttons_proxy_ setVisible:YES]; } } void NativeWindowMac::NotifyWindowWillEnterFullScreen() { UpdateVibrancyRadii(true); } void NativeWindowMac::NotifyWindowWillLeaveFullScreen() { if (buttons_proxy_) { // Hide window title when leaving fullscreen. [window_ setTitleVisibility:NSWindowTitleHidden]; // Hide the container otherwise traffic light buttons jump. [buttons_proxy_ setVisible:NO]; } UpdateVibrancyRadii(false); } void NativeWindowMac::SetActive(bool is_key) { is_active_ = is_key; } bool NativeWindowMac::IsActive() const { return is_active_; } void NativeWindowMac::Cleanup() { DCHECK(!IsClosed()); ui::NativeTheme::GetInstanceForNativeUi()->RemoveObserver(this); display::Screen::GetScreen()->RemoveObserver(this); if (wheel_event_monitor_) { [NSEvent removeMonitor:wheel_event_monitor_]; wheel_event_monitor_ = nil; } } void NativeWindowMac::OverrideNSWindowContentView() { // When using `views::Widget` to hold WebContents, Chromium would use // `BridgedContentView` as content view, which does not support draggable // regions. In order to make draggable regions work, we have to replace the // content view with a simple NSView. if (has_frame()) { container_view_.reset( [[ElectronAdaptedContentView alloc] initWithShell:this]); } else { container_view_.reset([[FullSizeContentView alloc] init]); [container_view_ setFrame:[[[window_ contentView] superview] bounds]]; } [container_view_ setAutoresizingMask:NSViewWidthSizable | NSViewHeightSizable]; [window_ setContentView:container_view_]; AddContentViewLayers(); } bool NativeWindowMac::HasStyleMask(NSUInteger flag) const { return [window_ styleMask] & flag; } void NativeWindowMac::SetStyleMask(bool on, NSUInteger flag) { // Changing the styleMask of a frameless windows causes it to change size so // we explicitly disable resizing while setting it. ScopedDisableResize disable_resize; if (on) [window_ setStyleMask:[window_ styleMask] | flag]; else [window_ setStyleMask:[window_ styleMask] & (~flag)]; // Change style mask will make the zoom button revert to default, probably // a bug of Cocoa or macOS. SetMaximizable(maximizable_); } void NativeWindowMac::SetCollectionBehavior(bool on, NSUInteger flag) { if (on) [window_ setCollectionBehavior:[window_ collectionBehavior] | flag]; else [window_ setCollectionBehavior:[window_ collectionBehavior] & (~flag)]; // Change collectionBehavior will make the zoom button revert to default, // probably a bug of Cocoa or macOS. SetMaximizable(maximizable_); } views::View* NativeWindowMac::GetContentsView() { return root_view_.get(); } bool NativeWindowMac::CanMaximize() const { return maximizable_; } void NativeWindowMac::OnNativeThemeUpdated(ui::NativeTheme* observed_theme) { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&NativeWindow::RedrawTrafficLights, GetWeakPtr())); } void NativeWindowMac::AddContentViewLayers() { // Make sure the bottom corner is rounded for non-modal windows: // http://crbug.com/396264. if (!is_modal()) { // For normal window, we need to explicitly set layer for contentView to // make setBackgroundColor work correctly. // There is no need to do so for frameless window, and doing so would make // titleBarStyle stop working. if (has_frame()) { base::scoped_nsobject<CALayer> background_layer([[CALayer alloc] init]); [background_layer setAutoresizingMask:kCALayerWidthSizable | kCALayerHeightSizable]; [[window_ contentView] setLayer:background_layer]; } [[window_ contentView] setWantsLayer:YES]; } if (!has_frame()) { // In OSX 10.10, adding subviews to the root view for the NSView hierarchy // produces warnings. To eliminate the warnings, we resize the contentView // to fill the window, and add subviews to that. // http://crbug.com/380412 if (!original_set_frame_size) { Class cl = [[window_ contentView] class]; original_set_frame_size = class_replaceMethod( cl, @selector(setFrameSize:), (IMP)SetFrameSize, "v@:{_NSSize=ff}"); original_view_did_move_to_superview = class_replaceMethod(cl, @selector(viewDidMoveToSuperview), (IMP)ViewDidMoveToSuperview, "v@:"); [[window_ contentView] viewDidMoveToWindow]; } } } void NativeWindowMac::InternalSetWindowButtonVisibility(bool visible) { [[window_ standardWindowButton:NSWindowCloseButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowMiniaturizeButton] setHidden:!visible]; [[window_ standardWindowButton:NSWindowZoomButton] setHidden:!visible]; } void NativeWindowMac::InternalSetParentWindow(NativeWindow* parent, bool attach) { if (is_modal()) return; NativeWindow::SetParentWindow(parent); // Do not remove/add if we are already properly attached. if (attach && parent && [window_ parentWindow] == parent->GetNativeWindow().GetNativeNSWindow()) return; // Remove current parent window. if ([window_ parentWindow]) [[window_ parentWindow] removeChildWindow:window_]; // Set new parent window. // Note that this method will force the window to become visible. if (parent && attach) { // Attaching a window as a child window resets its window level, so // save and restore it afterwards. NSInteger level = window_.level; [parent->GetNativeWindow().GetNativeNSWindow() addChildWindow:window_ ordered:NSWindowAbove]; [window_ setLevel:level]; } } void NativeWindowMac::SetForwardMouseMessages(bool forward) { [window_ setAcceptsMouseMovedEvents:forward]; } gfx::Rect NativeWindowMac::GetWindowControlsOverlayRect() { if (titlebar_overlay_ && buttons_proxy_ && window_button_visibility_.value_or(true)) { NSRect buttons = [buttons_proxy_ getButtonsContainerBounds]; gfx::Rect overlay; overlay.set_width(GetContentSize().width() - NSWidth(buttons)); if ([buttons_proxy_ useCustomHeight]) { overlay.set_height(titlebar_overlay_height()); } else { overlay.set_height(NSHeight(buttons)); } if (!base::i18n::IsRTL()) overlay.set_x(NSMaxX(buttons)); return overlay; } return gfx::Rect(); } // static NativeWindow* NativeWindow::Create(const gin_helper::Dictionary& options, NativeWindow* parent) { return new NativeWindowMac(options, parent); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,707
[Bug]: Disabling BrowserWindow object causes crash on MacOS
### Preflight Checklist - [x] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version Tested on versions 19.0.5, 18.3.4, 17.4.8 and 16.2.8 ### What operating system are you using? macOS ### Operating System Version Monterey v12.3 ### What arch are you using? arm64 (including Apple Silicon) ### Last Known Working Electron version Went all the way back to 12.2.3 and issue was still present. ### Expected Behavior When calling `setEnabled(false)` on a `BrowserWindow` object, I would expect the window to become disabled or some error to be thrown if it fails. ### Actual Behavior **Behavior** Calling `setEnabled(false)` on a `BrowserWindow` object causes Electron to quit abruptly on MacOS. No stack trace is given in the terminal but a message is printed that reads: `<path to Electron.app>/Electron.app/Contents/MacOS/Electron exited with signal SIGTRAP` Using an Intel based Mac the error message was the same except it exited with `SIGILL`. Surrounding the code in a try/catch block does not stop Electron from crashing. **Reproduce** Add the following line to the [quickstart repo in index.js on line 17](https://github.com/electron/electron-quick-start/blob/master/main.js#L17): `mainWindow.setEnabled(false);` To slightly delay so Electron/OS has time to show a window before crashing, use this instead: `setTimeout(() => { mainWindow.setEnabled(false); }, 1000);` ### Testcase Gist URL _No response_ ### Additional Information _No response_
https://github.com/electron/electron/issues/34707
https://github.com/electron/electron/pull/34904
38848c5bf77b2fa62b3dddecfe1aecba8d4ae48f
eb8c9452cb38b6bd32bdc92724cc1fb42a3d43dc
2022-06-22T21:37:03Z
c++
2022-07-19T10:31:49Z
spec-main/api-browser-window-spec.ts
import { expect } from 'chai'; import * as childProcess from 'child_process'; import * as path from 'path'; import * as fs from 'fs'; import * as qs from 'querystring'; import * as http from 'http'; import { AddressInfo } from 'net'; import { app, BrowserWindow, BrowserView, dialog, ipcMain, OnBeforeSendHeadersListenerDetails, protocol, screen, webContents, session, WebContents, BrowserWindowConstructorOptions } from 'electron/main'; import { emittedOnce, emittedUntil, emittedNTimes } from './events-helpers'; import { ifit, ifdescribe, defer, delay } from './spec-helpers'; import { closeWindow, closeAllWindows } from './window-helpers'; import { areColorsSimilar, captureScreen, CHROMA_COLOR_HEX, getPixelColor } from './screen-helpers'; const features = process._linkedBinding('electron_common_features'); const fixtures = path.resolve(__dirname, '..', 'spec', 'fixtures'); const mainFixtures = path.resolve(__dirname, 'fixtures'); // Is the display's scale factor possibly causing rounding of pixel coordinate // values? const isScaleFactorRounding = () => { const { scaleFactor } = screen.getPrimaryDisplay(); // Return true if scale factor is non-integer value if (Math.round(scaleFactor) !== scaleFactor) return true; // Return true if scale factor is odd number above 2 return scaleFactor > 2 && scaleFactor % 2 === 1; }; const expectBoundsEqual = (actual: any, expected: any) => { if (!isScaleFactorRounding()) { expect(expected).to.deep.equal(actual); } else if (Array.isArray(actual)) { expect(actual[0]).to.be.closeTo(expected[0], 1); expect(actual[1]).to.be.closeTo(expected[1], 1); } else { expect(actual.x).to.be.closeTo(expected.x, 1); expect(actual.y).to.be.closeTo(expected.y, 1); expect(actual.width).to.be.closeTo(expected.width, 1); expect(actual.height).to.be.closeTo(expected.height, 1); } }; const isBeforeUnload = (event: Event, level: number, message: string) => { return (message === 'beforeunload'); }; describe('BrowserWindow module', () => { describe('BrowserWindow constructor', () => { it('allows passing void 0 as the webContents', async () => { expect(() => { const w = new BrowserWindow({ show: false, // apparently void 0 had different behaviour from undefined in the // issue that this test is supposed to catch. webContents: void 0 // eslint-disable-line no-void } as any); w.destroy(); }).not.to.throw(); }); ifit(process.platform === 'linux')('does not crash when setting large window icons', async () => { const appPath = path.join(__dirname, 'spec-main', 'fixtures', 'apps', 'xwindow-icon'); const appProcess = childProcess.spawn(process.execPath, [appPath]); await new Promise((resolve) => { appProcess.once('exit', resolve); }); }); it('does not crash or throw when passed an invalid icon', async () => { expect(() => { const w = new BrowserWindow({ icon: undefined } as any); w.destroy(); }).not.to.throw(); }); }); describe('garbage collection', () => { const v8Util = process._linkedBinding('electron_common_v8_util'); afterEach(closeAllWindows); it('window does not get garbage collected when opened', async () => { const w = new BrowserWindow({ show: false }); // Keep a weak reference to the window. // eslint-disable-next-line no-undef const wr = new WeakRef(w); await delay(); // Do garbage collection, since |w| is not referenced in this closure // it would be gone after next call if there is no other reference. v8Util.requestGarbageCollectionForTesting(); await delay(); expect(wr.deref()).to.not.be.undefined(); }); }); describe('BrowserWindow.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should work if called when a messageBox is showing', async () => { const closed = emittedOnce(w, 'closed'); dialog.showMessageBox(w, { message: 'Hello Error' }); w.close(); await closed; }); it('closes window without rounded corners', async () => { await closeWindow(w); w = new BrowserWindow({ show: false, frame: false, roundedCorners: false }); const closed = emittedOnce(w, 'closed'); w.close(); await closed; }); it('should not crash if called after webContents is destroyed', () => { w.webContents.destroy(); w.webContents.on('destroyed', () => w.close()); }); it('should emit unload handler', async () => { await w.loadFile(path.join(fixtures, 'api', 'unload.html')); const closed = emittedOnce(w, 'closed'); w.close(); await closed; const test = path.join(fixtures, 'api', 'unload'); const content = fs.readFileSync(test); fs.unlinkSync(test); expect(String(content)).to.equal('unload'); }); it('should emit beforeunload handler', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); }); it('should not crash when keyboard event is sent before closing', async () => { await w.loadURL('data:text/html,pls no crash'); const closed = emittedOnce(w, 'closed'); w.webContents.sendInputEvent({ type: 'keyDown', keyCode: 'Escape' }); w.close(); await closed; }); describe('when invoked synchronously inside navigation observer', () => { let server: http.Server = null as unknown as http.Server; let url: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/net-error': response.destroy(); break; case '/301': response.statusCode = 301; response.setHeader('Location', '/200'); response.end(); break; case '/200': response.statusCode = 200; response.end('hello'); break; case '/title': response.statusCode = 200; response.end('<title>Hello</title>'); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { url = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); const events = [ { name: 'did-start-loading', path: '/200' }, { name: 'dom-ready', path: '/200' }, { name: 'page-title-updated', path: '/title' }, { name: 'did-stop-loading', path: '/200' }, { name: 'did-finish-load', path: '/200' }, { name: 'did-frame-finish-load', path: '/200' }, { name: 'did-fail-load', path: '/net-error' } ]; for (const { name, path } of events) { it(`should not crash when closed during ${name}`, async () => { const w = new BrowserWindow({ show: false }); w.webContents.once((name as any), () => { w.close(); }); const destroyed = emittedOnce(w.webContents, 'destroyed'); w.webContents.loadURL(url + path); await destroyed; }); } }); }); describe('window.close()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('should emit unload event', async () => { w.loadFile(path.join(fixtures, 'api', 'close.html')); await emittedOnce(w, 'closed'); const test = path.join(fixtures, 'api', 'close'); const content = fs.readFileSync(test).toString(); fs.unlinkSync(test); expect(content).to.equal('close'); }); it('should emit beforeunload event', async function () { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.webContents.executeJavaScript('window.close()', true); await emittedOnce(w.webContents, 'before-unload-fired'); }); }); describe('BrowserWindow.destroy()', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('prevents users to access methods of webContents', async () => { const contents = w.webContents; w.destroy(); await new Promise(setImmediate); expect(() => { contents.getProcessId(); }).to.throw('Object has been destroyed'); }); it('should not crash when destroying windows with pending events', () => { const focusListener = () => { }; app.on('browser-window-focus', focusListener); const windowCount = 3; const windowOptions = { show: false, width: 400, height: 400, webPreferences: { backgroundThrottling: false } }; const windows = Array.from(Array(windowCount)).map(() => new BrowserWindow(windowOptions)); windows.forEach(win => win.show()); windows.forEach(win => win.focus()); windows.forEach(win => win.destroy()); app.removeListener('browser-window-focus', focusListener); }); }); describe('BrowserWindow.loadURL(url)', () => { let w = null as unknown as BrowserWindow; const scheme = 'other'; const srcPath = path.join(fixtures, 'api', 'loaded-from-dataurl.js'); before(() => { protocol.registerFileProtocol(scheme, (request, callback) => { callback(srcPath); }); }); after(() => { protocol.unregisterProtocol(scheme); }); beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); let server = null as unknown as http.Server; let url = null as unknown as string; let postData = null as any; before((done) => { const filePath = path.join(fixtures, 'pages', 'a.html'); const fileStats = fs.statSync(filePath); postData = [ { type: 'rawData', bytes: Buffer.from('username=test&file=') }, { type: 'file', filePath: filePath, offset: 0, length: fileStats.size, modificationTime: fileStats.mtime.getTime() / 1000 } ]; server = http.createServer((req, res) => { function respond () { if (req.method === 'POST') { let body = ''; req.on('data', (data) => { if (data) body += data; }); req.on('end', () => { const parsedData = qs.parse(body); fs.readFile(filePath, (err, data) => { if (err) return; if (parsedData.username === 'test' && parsedData.file === data.toString()) { res.end(); } }); }); } else if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else { res.end(); } } setTimeout(respond, req.url && req.url.includes('slow') ? 200 : 0); }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('should emit did-start-loading event', async () => { const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.loadURL('about:blank'); await didStartLoading; }); it('should emit ready-to-show event', async () => { const readyToShow = emittedOnce(w, 'ready-to-show'); w.loadURL('about:blank'); await readyToShow; }); // TODO(deepak1556): The error code now seems to be `ERR_FAILED`, verify what // changed and adjust the test. it.skip('should emit did-fail-load event for files that do not exist', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('file://a.txt'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(code).to.equal(-6); expect(desc).to.equal('ERR_FILE_NOT_FOUND'); expect(isMainFrame).to.equal(true); }); it('should emit did-fail-load event for invalid URL', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL('http://example:port'); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should set `mainFrame = false` on did-fail-load events in iframes', async () => { const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadFile(path.join(fixtures, 'api', 'did-fail-load-iframe.html')); const [,,,, isMainFrame] = await didFailLoad; expect(isMainFrame).to.equal(false); }); it('does not crash in did-fail-provisional-load handler', (done) => { w.webContents.once('did-fail-provisional-load', () => { w.loadURL('http://127.0.0.1:11111'); done(); }); w.loadURL('http://127.0.0.1:11111'); }); it('should emit did-fail-load event for URL exceeding character limit', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const didFailLoad = emittedOnce(w.webContents, 'did-fail-load'); w.loadURL(`data:image/png;base64,${data}`); const [, code, desc,, isMainFrame] = await didFailLoad; expect(desc).to.equal('ERR_INVALID_URL'); expect(code).to.equal(-300); expect(isMainFrame).to.equal(true); }); it('should return a promise', () => { const p = w.loadURL('about:blank'); expect(p).to.have.property('then'); }); it('should return a promise that resolves', async () => { await expect(w.loadURL('about:blank')).to.eventually.be.fulfilled(); }); it('should return a promise that rejects on a load failure', async () => { const data = Buffer.alloc(2 * 1024 * 1024).toString('base64'); const p = w.loadURL(`data:image/png;base64,${data}`); await expect(p).to.eventually.be.rejected; }); it('should return a promise that resolves even if pushState occurs during navigation', async () => { const p = w.loadURL('data:text/html,<script>window.history.pushState({}, "/foo")</script>'); await expect(p).to.eventually.be.fulfilled; }); describe('POST navigations', () => { afterEach(() => { w.webContents.session.webRequest.onBeforeSendHeaders(null); }); it('supports specifying POST data', async () => { await w.loadURL(url, { postData }); }); it('sets the content type header on URL encoded forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type']).to.equal('application/x-www-form-urlencoded'); }); it('sets the content type header on multi part forms', async () => { await w.loadURL(url); const requestDetails: Promise<OnBeforeSendHeadersListenerDetails> = new Promise(resolve => { w.webContents.session.webRequest.onBeforeSendHeaders((details) => { resolve(details); }); }); w.webContents.executeJavaScript(` form = document.createElement('form') document.body.appendChild(form) form.method = 'POST' form.enctype = 'multipart/form-data' file = document.createElement('input') file.type = 'file' file.name = 'file' form.appendChild(file) form.submit() `); const details = await requestDetails; expect(details.requestHeaders['Content-Type'].startsWith('multipart/form-data; boundary=----WebKitFormBoundary')).to.equal(true); }); }); it('should support base url for data urls', async () => { await w.loadURL('data:text/html,<script src="loaded-from-dataurl.js"></script>', { baseURLForDataURL: `other://${path.join(fixtures, 'api')}${path.sep}` }); expect(await w.webContents.executeJavaScript('window.ping')).to.equal('pong'); }); }); for (const sandbox of [false, true]) { describe(`navigation events${sandbox ? ' with sandbox' : ''}`, () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: false, sandbox } }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('will-navigate event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/navigate-top') { res.end('<a target=_top href="/">navigate _top</a>'); } else { res.end(''); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}/`; done(); }); }); after(() => { server.close(); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-navigate', () => { w.close(); done(); }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('can be prevented', (done) => { let willNavigate = false; w.webContents.once('will-navigate', (e) => { willNavigate = true; e.preventDefault(); }); w.webContents.on('did-stop-loading', () => { if (willNavigate) { // i.e. it shouldn't have had '?navigated' appended to it. try { expect(w.webContents.getURL().endsWith('will-navigate.html')).to.be.true(); done(); } catch (e) { done(e); } } }); w.loadFile(path.join(fixtures, 'pages', 'will-navigate.html')); }); it('is triggered when navigating from file: to http:', async () => { await w.loadFile(path.join(fixtures, 'api', 'blank.html')); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.match(/^file:/); }); it('is triggered when navigating from about:blank to http:', async () => { await w.loadURL('about:blank'); w.webContents.executeJavaScript(`location.href = ${JSON.stringify(url)}`); const navigatedTo = await new Promise(resolve => { w.webContents.once('will-navigate', (e, url) => { e.preventDefault(); resolve(url); }); }); expect(navigatedTo).to.equal(url); expect(w.webContents.getURL()).to.equal('about:blank'); }); it('is triggered when a cross-origin iframe navigates _top', async () => { await w.loadURL(`data:text/html,<iframe src="http://127.0.0.1:${(server.address() as AddressInfo).port}/navigate-top"></iframe>`); await delay(1000); w.webContents.debugger.attach('1.1'); const targets = await w.webContents.debugger.sendCommand('Target.getTargets'); const iframeTarget = targets.targetInfos.find((t: any) => t.type === 'iframe'); const { sessionId } = await w.webContents.debugger.sendCommand('Target.attachToTarget', { targetId: iframeTarget.targetId, flatten: true }); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mousePressed', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); await w.webContents.debugger.sendCommand('Input.dispatchMouseEvent', { type: 'mouseReleased', x: 10, y: 10, clickCount: 1, button: 'left' }, sessionId); let willNavigateEmitted = false; w.webContents.on('will-navigate', () => { willNavigateEmitted = true; }); await emittedOnce(w.webContents, 'did-navigate'); expect(willNavigateEmitted).to.be.true(); }); }); describe('will-redirect event', () => { let server = null as unknown as http.Server; let url = null as unknown as string; before((done) => { server = http.createServer((req, res) => { if (req.url === '/302') { res.setHeader('Location', '/200'); res.statusCode = 302; res.end(); } else if (req.url === '/navigate-302') { res.end(`<html><body><script>window.location='${url}/302'</script></body></html>`); } else { res.end(); } }); server.listen(0, '127.0.0.1', () => { url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; done(); }); }); after(() => { server.close(); }); it('is emitted on redirects', async () => { const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; }); it('is emitted after will-navigate on redirects', async () => { let navigateCalled = false; w.webContents.on('will-navigate', () => { navigateCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/navigate-302`); await willRedirect; expect(navigateCalled).to.equal(true, 'should have called will-navigate first'); }); it('is emitted before did-stop-loading on redirects', async () => { let stopCalled = false; w.webContents.on('did-stop-loading', () => { stopCalled = true; }); const willRedirect = emittedOnce(w.webContents, 'will-redirect'); w.loadURL(`${url}/302`); await willRedirect; expect(stopCalled).to.equal(false, 'should not have called did-stop-loading first'); }); it('allows the window to be closed from the event listener', (done) => { w.webContents.once('will-redirect', () => { w.close(); done(); }); w.loadURL(`${url}/302`); }); it('can be prevented', (done) => { w.webContents.once('will-redirect', (event) => { event.preventDefault(); }); w.webContents.on('will-navigate', (e, u) => { expect(u).to.equal(`${url}/302`); }); w.webContents.on('did-stop-loading', () => { try { expect(w.webContents.getURL()).to.equal( `${url}/navigate-302`, 'url should not have changed after navigation event' ); done(); } catch (e) { done(e); } }); w.webContents.on('will-redirect', (e, u) => { try { expect(u).to.equal(`${url}/200`); } catch (e) { done(e); } }); w.loadURL(`${url}/navigate-302`); }); }); }); } describe('focus and visibility', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.show()', () => { it('should focus on window', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isFocused()).to.equal(true); }); it('should make the window visible', async () => { await emittedOnce(w, 'focus', () => w.show()); expect(w.isVisible()).to.equal(true); }); it('emits when window is shown', async () => { const show = emittedOnce(w, 'show'); w.show(); await show; expect(w.isVisible()).to.equal(true); }); }); describe('BrowserWindow.hide()', () => { it('should defocus on window', () => { w.hide(); expect(w.isFocused()).to.equal(false); }); it('should make the window not visible', () => { w.show(); w.hide(); expect(w.isVisible()).to.equal(false); }); it('emits when window is hidden', async () => { const shown = emittedOnce(w, 'show'); w.show(); await shown; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; expect(w.isVisible()).to.equal(false); }); }); describe('BrowserWindow.showInactive()', () => { it('should not focus on window', () => { w.showInactive(); expect(w.isFocused()).to.equal(false); }); // TODO(dsanders11): Enable for Linux once CI plays nice with these kinds of tests ifit(process.platform !== 'linux')('should not restore maximized windows', async () => { const maximize = emittedOnce(w, 'maximize'); const shown = emittedOnce(w, 'show'); w.maximize(); // TODO(dsanders11): The maximize event isn't firing on macOS for a window initially hidden if (process.platform !== 'darwin') { await maximize; } else { await delay(1000); } w.showInactive(); await shown; expect(w.isMaximized()).to.equal(true); }); }); describe('BrowserWindow.focus()', () => { it('does not make the window become visible', () => { expect(w.isVisible()).to.equal(false); w.focus(); expect(w.isVisible()).to.equal(false); }); ifit(process.platform !== 'win32')('focuses a blurred window', async () => { { const isBlurred = emittedOnce(w, 'blur'); const isShown = emittedOnce(w, 'show'); w.show(); w.blur(); await isShown; await isBlurred; } expect(w.isFocused()).to.equal(false); w.focus(); expect(w.isFocused()).to.equal(true); }); ifit(process.platform !== 'linux')('acquires focus status from the other windows', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w1.focus(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w2.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w3.focus(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); // TODO(RaisinTen): Make this work on Windows too. // Refs: https://github.com/electron/electron/issues/20464. ifdescribe(process.platform !== 'win32')('BrowserWindow.blur()', () => { it('removes focus from window', async () => { { const isFocused = emittedOnce(w, 'focus'); const isShown = emittedOnce(w, 'show'); w.show(); await isShown; await isFocused; } expect(w.isFocused()).to.equal(true); w.blur(); expect(w.isFocused()).to.equal(false); }); ifit(process.platform !== 'linux')('transfers focus status to the next window', async () => { const w1 = new BrowserWindow({ show: false }); const w2 = new BrowserWindow({ show: false }); const w3 = new BrowserWindow({ show: false }); { const isFocused3 = emittedOnce(w3, 'focus'); const isShown1 = emittedOnce(w1, 'show'); const isShown2 = emittedOnce(w2, 'show'); const isShown3 = emittedOnce(w3, 'show'); w1.show(); w2.show(); w3.show(); await isShown1; await isShown2; await isShown3; await isFocused3; } // TODO(RaisinTen): Investigate why this assertion fails only on Linux. expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); w3.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(true); expect(w3.isFocused()).to.equal(false); w2.blur(); expect(w1.isFocused()).to.equal(true); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(false); w1.blur(); expect(w1.isFocused()).to.equal(false); expect(w2.isFocused()).to.equal(false); expect(w3.isFocused()).to.equal(true); { const isClosed1 = emittedOnce(w1, 'closed'); const isClosed2 = emittedOnce(w2, 'closed'); const isClosed3 = emittedOnce(w3, 'closed'); w1.destroy(); w2.destroy(); w3.destroy(); await isClosed1; await isClosed2; await isClosed3; } }); }); describe('BrowserWindow.getFocusedWindow()', () => { it('returns the opener window when dev tools window is focused', async () => { await emittedOnce(w, 'focus', () => w.show()); w.webContents.openDevTools({ mode: 'undocked' }); await emittedOnce(w.webContents, 'devtools-focused'); expect(BrowserWindow.getFocusedWindow()).to.equal(w); }); }); describe('BrowserWindow.moveTop()', () => { it('should not steal focus', async () => { const posDelta = 50; const wShownInactive = emittedOnce(w, 'show'); w.showInactive(); await wShownInactive; expect(w.isFocused()).to.equal(false); const otherWindow = new BrowserWindow({ show: false, title: 'otherWindow' }); const otherWindowShown = emittedOnce(otherWindow, 'show'); const otherWindowFocused = emittedOnce(otherWindow, 'focus'); otherWindow.show(); await otherWindowShown; await otherWindowFocused; expect(otherWindow.isFocused()).to.equal(true); w.moveTop(); const wPos = w.getPosition(); const wMoving = emittedOnce(w, 'move'); w.setPosition(wPos[0] + posDelta, wPos[1] + posDelta); await wMoving; expect(w.isFocused()).to.equal(false); expect(otherWindow.isFocused()).to.equal(true); const wFocused = emittedOnce(w, 'focus'); const otherWindowBlurred = emittedOnce(otherWindow, 'blur'); w.focus(); await wFocused; await otherWindowBlurred; expect(w.isFocused()).to.equal(true); otherWindow.moveTop(); const otherWindowPos = otherWindow.getPosition(); const otherWindowMoving = emittedOnce(otherWindow, 'move'); otherWindow.setPosition(otherWindowPos[0] + posDelta, otherWindowPos[1] + posDelta); await otherWindowMoving; expect(otherWindow.isFocused()).to.equal(false); expect(w.isFocused()).to.equal(true); await closeWindow(otherWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); }); }); ifdescribe(features.isDesktopCapturerEnabled())('BrowserWindow.moveAbove(mediaSourceId)', () => { it('should throw an exception if wrong formatting', async () => { const fakeSourceIds = [ 'none', 'screen:0', 'window:fake', 'window:1234', 'foobar:1:2' ]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should throw an exception if wrong type', async () => { const fakeSourceIds = [null as any, 123 as any]; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Error processing argument at index 0 */); }); }); it('should throw an exception if invalid window', async () => { // It is very unlikely that these window id exist. const fakeSourceIds = ['window:99999999:0', 'window:123456:1', 'window:123456:9']; fakeSourceIds.forEach((sourceId) => { expect(() => { w.moveAbove(sourceId); }).to.throw(/Invalid media source id/); }); }); it('should not throw an exception', async () => { const w2 = new BrowserWindow({ show: false, title: 'window2' }); const w2Shown = emittedOnce(w2, 'show'); w2.show(); await w2Shown; expect(() => { w.moveAbove(w2.getMediaSourceId()); }).to.not.throw(); await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.setFocusable()', () => { it('can set unfocusable window to focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); const w2Focused = emittedOnce(w2, 'focus'); w2.setFocusable(true); w2.focus(); await w2Focused; await closeWindow(w2, { assertNotWindows: false }); }); }); describe('BrowserWindow.isFocusable()', () => { it('correctly returns whether a window is focusable', async () => { const w2 = new BrowserWindow({ focusable: false }); expect(w2.isFocusable()).to.be.false(); w2.setFocusable(true); expect(w2.isFocusable()).to.be.true(); await closeWindow(w2, { assertNotWindows: false }); }); }); }); describe('sizing', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, width: 400, height: 400 }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.setBounds(bounds[, animate])', () => { it('sets the window bounds with full bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); expectBoundsEqual(w.getBounds(), fullBounds); }); it('sets the window bounds with partial bounds', () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds); const boundsUpdate = { width: 200 }; w.setBounds(boundsUpdate as any); const expectedBounds = { ...fullBounds, ...boundsUpdate }; expectBoundsEqual(w.getBounds(), expectedBounds); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const fullBounds = { x: 440, y: 225, width: 500, height: 400 }; w.setBounds(fullBounds, true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setSize(width, height)', () => { it('sets the window size', async () => { const size = [300, 400]; const resized = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resized; expectBoundsEqual(w.getSize(), size); }); ifit(process.platform === 'darwin')('on macOS', () => { it('emits \'resized\' event after animating', async () => { const size = [300, 400]; w.setSize(size[0], size[1], true); await expect(emittedOnce(w, 'resized')).to.eventually.be.fulfilled(); }); }); }); describe('BrowserWindow.setMinimum/MaximumSize(width, height)', () => { it('sets the maximum and minimum size of the window', () => { expect(w.getMinimumSize()).to.deep.equal([0, 0]); expect(w.getMaximumSize()).to.deep.equal([0, 0]); w.setMinimumSize(100, 100); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [0, 0]); w.setMaximumSize(900, 600); expectBoundsEqual(w.getMinimumSize(), [100, 100]); expectBoundsEqual(w.getMaximumSize(), [900, 600]); }); }); describe('BrowserWindow.setAspectRatio(ratio)', () => { it('resets the behaviour when passing in 0', async () => { const size = [300, 400]; w.setAspectRatio(1 / 2); w.setAspectRatio(0); const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getSize(), size); }); it('doesn\'t change bounds when maximum size is set', () => { w.setMenu(null); w.setMaximumSize(400, 400); // Without https://github.com/electron/electron/pull/29101 // following call would shrink the window to 384x361. // There would be also DCHECK in resize_utils.cc on // debug build. w.setAspectRatio(1.0); expectBoundsEqual(w.getSize(), [400, 400]); }); }); describe('BrowserWindow.setPosition(x, y)', () => { it('sets the window position', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expect(w.getPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setContentSize(width, height)', () => { it('sets the content size', async () => { // NB. The CI server has a very small screen. Attempting to size the window // larger than the screen will limit the window's size to the screen and // cause the test to fail. const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400 }); const size = [456, 567]; w.setContentSize(size[0], size[1]); await new Promise(setImmediate); const after = w.getContentSize(); expect(after).to.deep.equal(size); }); }); describe('BrowserWindow.setContentBounds(bounds)', () => { it('sets the content size and position', async () => { const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); it('works for a frameless window', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300 }); const bounds = { x: 10, y: 10, width: 250, height: 250 }; const resize = emittedOnce(w, 'resize'); w.setContentBounds(bounds); await resize; await delay(); expectBoundsEqual(w.getContentBounds(), bounds); }); }); describe('BrowserWindow.getBackgroundColor()', () => { it('returns default value if no backgroundColor is set', () => { w.destroy(); w = new BrowserWindow({}); expect(w.getBackgroundColor()).to.equal('#FFFFFF'); }); it('returns correct value if backgroundColor is set', () => { const backgroundColor = '#BBAAFF'; w.destroy(); w = new BrowserWindow({ backgroundColor: backgroundColor }); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct value from setBackgroundColor()', () => { const backgroundColor = '#AABBFF'; w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor(backgroundColor); expect(w.getBackgroundColor()).to.equal(backgroundColor); }); it('returns correct color with multiple passed formats', () => { w.destroy(); w = new BrowserWindow({}); w.setBackgroundColor('#AABBFF'); expect(w.getBackgroundColor()).to.equal('#AABBFF'); w.setBackgroundColor('blueviolet'); expect(w.getBackgroundColor()).to.equal('#8A2BE2'); w.setBackgroundColor('rgb(255, 0, 185)'); expect(w.getBackgroundColor()).to.equal('#FF00B9'); w.setBackgroundColor('rgba(245, 40, 145, 0.8)'); expect(w.getBackgroundColor()).to.equal('#F52891'); w.setBackgroundColor('hsl(155, 100%, 50%)'); expect(w.getBackgroundColor()).to.equal('#00FF95'); }); }); describe('BrowserWindow.getNormalBounds()', () => { describe('Normal state', () => { it('checks normal bounds after resize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); it('checks normal bounds after move', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; expectBoundsEqual(w.getNormalBounds(), w.getBounds()); }); }); ifdescribe(process.platform !== 'linux')('Maximized state', () => { it('checks normal bounds when maximized', async () => { const bounds = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and maximize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and maximize', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const maximize = emittedOnce(w, 'maximize'); w.maximize(); await maximize; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('checks normal bounds when unmaximized', async () => { const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('maximize', () => { w.unmaximize(); }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await unmaximize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('correctly checks transparent window maximization state', async () => { w.destroy(); w = new BrowserWindow({ show: false, width: 300, height: 300, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); const unmaximize = emittedOnce(w, 'unmaximize'); w.unmaximize(); await unmaximize; expect(w.isMaximized()).to.equal(false); }); it('returns the correct value for windows with an aspect ratio', async () => { w.destroy(); w = new BrowserWindow({ show: false, fullscreenable: false }); w.setAspectRatio(16 / 11); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; expect(w.isMaximized()).to.equal(true); w.resizable = false; expect(w.isMaximized()).to.equal(true); }); }); ifdescribe(process.platform !== 'linux')('Minimized state', () => { it('checks normal bounds when minimized', async () => { const bounds = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after move and minimize', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('updates normal bounds after resize and minimize', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; const normal = w.getNormalBounds(); expect(original).to.deep.equal(normal); expectBoundsEqual(normal, w.getBounds()); }); it('checks normal bounds when restored', async () => { const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('does not change size for a frameless window with min size', async () => { w.destroy(); w = new BrowserWindow({ show: false, frame: false, width: 300, height: 300, minWidth: 300, minHeight: 300 }); const bounds = w.getBounds(); w.once('minimize', () => { w.restore(); }); const restore = emittedOnce(w, 'restore'); w.show(); w.minimize(); await restore; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); ifdescribe(process.platform === 'win32')('Fullscreen state', () => { it('with properties', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.fullScreen).to.be.true(); }); it('can be changed', () => { w.fullScreen = false; expect(w.fullScreen).to.be.false(); w.fullScreen = true; expect(w.fullScreen).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.show(); w.fullScreen = true; await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.fullScreen = true; await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.once('enter-full-screen', () => { w.fullScreen = false; }); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.show(); w.fullScreen = true; await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); it('with functions', () => { it('can be set with the fullscreen constructor option', () => { w = new BrowserWindow({ fullscreen: true }); expect(w.isFullScreen()).to.be.true(); }); it('can be changed', () => { w.setFullScreen(false); expect(w.isFullScreen()).to.be.false(); w.setFullScreen(true); expect(w.isFullScreen()).to.be.true(); }); it('checks normal bounds when fullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); it('updates normal bounds after resize and fullscreen', async () => { const size = [300, 400]; const resize = emittedOnce(w, 'resize'); w.setSize(size[0], size[1]); await resize; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('updates normal bounds after move and fullscreen', async () => { const pos = [10, 10]; const move = emittedOnce(w, 'move'); w.setPosition(pos[0], pos[1]); await move; const original = w.getBounds(); const fsc = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await fsc; const normal = w.getNormalBounds(); const bounds = w.getBounds(); expect(normal).to.deep.equal(original); expect(normal).to.not.deep.equal(bounds); const close = emittedOnce(w, 'close'); w.close(); await close; }); it('checks normal bounds when unfullscreen\'ed', async () => { const bounds = w.getBounds(); w.show(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expectBoundsEqual(w.getNormalBounds(), bounds); }); }); }); }); }); ifdescribe(process.platform === 'darwin')('tabbed windows', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); describe('BrowserWindow.selectPreviousTab()', () => { it('does not throw', () => { expect(() => { w.selectPreviousTab(); }).to.not.throw(); }); }); describe('BrowserWindow.selectNextTab()', () => { it('does not throw', () => { expect(() => { w.selectNextTab(); }).to.not.throw(); }); }); describe('BrowserWindow.mergeAllWindows()', () => { it('does not throw', () => { expect(() => { w.mergeAllWindows(); }).to.not.throw(); }); }); describe('BrowserWindow.moveTabToNewWindow()', () => { it('does not throw', () => { expect(() => { w.moveTabToNewWindow(); }).to.not.throw(); }); }); describe('BrowserWindow.toggleTabBar()', () => { it('does not throw', () => { expect(() => { w.toggleTabBar(); }).to.not.throw(); }); }); describe('BrowserWindow.addTabbedWindow()', () => { it('does not throw', async () => { const tabbedWindow = new BrowserWindow({}); expect(() => { w.addTabbedWindow(tabbedWindow); }).to.not.throw(); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(2); // w + tabbedWindow await closeWindow(tabbedWindow, { assertNotWindows: false }); expect(BrowserWindow.getAllWindows()).to.have.lengthOf(1); // w }); it('throws when called on itself', () => { expect(() => { w.addTabbedWindow(w); }).to.throw('AddTabbedWindow cannot be called by a window on itself.'); }); }); }); describe('autoHideMenuBar state', () => { afterEach(closeAllWindows); it('for properties', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); w.autoHideMenuBar = true; expect(w.autoHideMenuBar).to.be.true('autoHideMenuBar'); w.autoHideMenuBar = false; expect(w.autoHideMenuBar).to.be.false('autoHideMenuBar'); }); }); it('for functions', () => { it('can be set with autoHideMenuBar constructor option', () => { const w = new BrowserWindow({ show: false, autoHideMenuBar: true }); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); w.setAutoHideMenuBar(true); expect(w.isMenuBarAutoHide()).to.be.true('autoHideMenuBar'); w.setAutoHideMenuBar(false); expect(w.isMenuBarAutoHide()).to.be.false('autoHideMenuBar'); }); }); }); describe('BrowserWindow.capturePage(rect)', () => { afterEach(closeAllWindows); it('returns a Promise with a Buffer', async () => { const w = new BrowserWindow({ show: false }); const image = await w.capturePage({ x: 0, y: 0, width: 100, height: 100 }); expect(image.isEmpty()).to.equal(true); }); it('resolves after the window is hidden', async () => { const w = new BrowserWindow({ show: false }); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const visibleImage = await w.capturePage(); expect(visibleImage.isEmpty()).to.equal(false); w.hide(); const hiddenImage = await w.capturePage(); const isEmpty = process.platform !== 'darwin'; expect(hiddenImage.isEmpty()).to.equal(isEmpty); }); it('resolves after the window is hidden and capturer count is non-zero', async () => { const w = new BrowserWindow({ show: false }); w.webContents.setBackgroundThrottling(false); w.loadFile(path.join(fixtures, 'pages', 'a.html')); await emittedOnce(w, 'ready-to-show'); w.webContents.incrementCapturerCount(); const image = await w.capturePage(); expect(image.isEmpty()).to.equal(false); }); it('preserves transparency', async () => { const w = new BrowserWindow({ show: false, transparent: true }); w.loadFile(path.join(fixtures, 'pages', 'theme-color.html')); await emittedOnce(w, 'ready-to-show'); w.show(); const image = await w.capturePage(); const imgBuffer = image.toPNG(); // Check the 25th byte in the PNG. // Values can be 0,2,3,4, or 6. We want 6, which is RGB + Alpha expect(imgBuffer[25]).to.equal(6); }); it('should increase the capturer count', () => { const w = new BrowserWindow({ show: false }); w.webContents.incrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.true(); w.webContents.decrementCapturerCount(); expect(w.webContents.isBeingCaptured()).to.be.false(); }); }); describe('BrowserWindow.setProgressBar(progress)', () => { let w = null as unknown as BrowserWindow; before(() => { w = new BrowserWindow({ show: false }); }); after(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); it('sets the progress', () => { expect(() => { if (process.platform === 'darwin') { app.dock.setIcon(path.join(fixtures, 'assets', 'logo.png')); } w.setProgressBar(0.5); if (process.platform === 'darwin') { app.dock.setIcon(null as any); } w.setProgressBar(-1); }).to.not.throw(); }); it('sets the progress using "paused" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'paused' }); }).to.not.throw(); }); it('sets the progress using "error" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'error' }); }).to.not.throw(); }); it('sets the progress using "normal" mode', () => { expect(() => { w.setProgressBar(0.5, { mode: 'normal' }); }).to.not.throw(); }); }); describe('BrowserWindow.setAlwaysOnTop(flag, level)', () => { let w = null as unknown as BrowserWindow; afterEach(closeAllWindows); beforeEach(() => { w = new BrowserWindow({ show: true }); }); it('sets the window as always on top', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.setAlwaysOnTop(false); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('resets the windows level on minimize', () => { expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); w.minimize(); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.restore(); expect(w.isAlwaysOnTop()).to.be.true('is not alwaysOnTop'); }); it('causes the right value to be emitted on `always-on-top-changed`', async () => { const alwaysOnTopChanged = emittedOnce(w, 'always-on-top-changed'); expect(w.isAlwaysOnTop()).to.be.false('is alwaysOnTop'); w.setAlwaysOnTop(true); const [, alwaysOnTop] = await alwaysOnTopChanged; expect(alwaysOnTop).to.be.true('is not alwaysOnTop'); }); ifit(process.platform === 'darwin')('honors the alwaysOnTop level of a child window', () => { w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ parent: w }); c.setAlwaysOnTop(true, 'screen-saver'); expect(w.isAlwaysOnTop()).to.be.false(); expect(c.isAlwaysOnTop()).to.be.true('child is not always on top'); expect((c as any)._getAlwaysOnTopLevel()).to.equal('screen-saver'); }); }); describe('preconnect feature', () => { let w = null as unknown as BrowserWindow; let server = null as unknown as http.Server; let url = null as unknown as string; let connections = 0; beforeEach(async () => { connections = 0; server = http.createServer((req, res) => { if (req.url === '/link') { res.setHeader('Content-type', 'text/html'); res.end('<head><link rel="preconnect" href="//example.com" /></head><body>foo</body>'); return; } res.end(); }); server.on('connection', () => { connections++; }); await new Promise<void>(resolve => server.listen(0, '127.0.0.1', () => resolve())); url = `http://127.0.0.1:${(server.address() as AddressInfo).port}`; }); afterEach(async () => { server.close(); await closeWindow(w); w = null as unknown as BrowserWindow; server = null as unknown as http.Server; }); it('calling preconnect() connects to the server', async () => { w = new BrowserWindow({ show: false }); w.webContents.on('did-start-navigation', (event, url) => { w.webContents.session.preconnect({ url, numSockets: 4 }); }); await w.loadURL(url); expect(connections).to.equal(4); }); it('does not preconnect unless requested', async () => { w = new BrowserWindow({ show: false }); await w.loadURL(url); expect(connections).to.equal(1); }); it('parses <link rel=preconnect>', async () => { w = new BrowserWindow({ show: true }); const p = emittedOnce(w.webContents.session, 'preconnect'); w.loadURL(url + '/link'); const [, preconnectUrl, allowCredentials] = await p; expect(preconnectUrl).to.equal('http://example.com/'); expect(allowCredentials).to.be.true('allowCredentials'); }); }); describe('BrowserWindow.setAutoHideCursor(autoHide)', () => { let w = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false }); }); afterEach(async () => { await closeWindow(w); w = null as unknown as BrowserWindow; }); ifit(process.platform === 'darwin')('on macOS', () => { it('allows changing cursor auto-hiding', () => { expect(() => { w.setAutoHideCursor(false); w.setAutoHideCursor(true); }).to.not.throw(); }); }); ifit(process.platform !== 'darwin')('on non-macOS platforms', () => { it('is not available', () => { expect(w.setAutoHideCursor).to.be.undefined('setAutoHideCursor function'); }); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setWindowButtonVisibility()', () => { afterEach(closeAllWindows); it('does not throw', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setWindowButtonVisibility(true); w.setWindowButtonVisibility(false); }).to.not.throw(); }); it('changes window button visibility for normal window', () => { const w = new BrowserWindow({ show: false }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('changes window button visibility for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('changes window button visibility for hiddenInset window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); // Buttons of customButtonsOnHover are always hidden unless hovered. it('does not change window button visibility for customButtonsOnHover window', () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'customButtonsOnHover' }); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(false); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); }); it('correctly updates when entering/exiting fullscreen for hidden style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hidden' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); it('correctly updates when entering/exiting fullscreen for hiddenInset style', async () => { const w = new BrowserWindow({ show: false, frame: false, titleBarStyle: 'hiddenInset' }); expect(w._getWindowButtonVisibility()).to.equal(true); w.setWindowButtonVisibility(false); expect(w._getWindowButtonVisibility()).to.equal(false); const enterFS = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFS; const leaveFS = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFS; w.setWindowButtonVisibility(true); expect(w._getWindowButtonVisibility()).to.equal(true); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setVibrancy(type)', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | childProcess.ChildProcess | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } closeAllWindows(); }); it('allows setting, changing, and removing the vibrancy', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('light'); w.setVibrancy('dark'); w.setVibrancy(null); w.setVibrancy('ultra-dark'); w.setVibrancy('' as any); }).to.not.throw(); }); it('does not crash if vibrancy is set to an invalid value', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setVibrancy('i-am-not-a-valid-vibrancy-type' as any); }).to.not.throw(); }); // TODO(nornagon): disabled due to flakiness. it.skip('Allows setting a transparent window via CSS', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'background-color-transparent'); appProcess = childProcess.spawn(process.execPath, [appPath], { stdio: 'inherit' }); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); ifdescribe(process.platform === 'darwin')('trafficLightPosition', () => { const pos = { x: 10, y: 10 }; afterEach(closeAllWindows); describe('BrowserWindow.getTrafficLightPosition(pos)', () => { it('gets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); it('gets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); expect(w.getTrafficLightPosition()).to.deep.equal(pos); }); }); describe('BrowserWindow.setTrafficLightPosition(pos)', () => { it('sets position property for "hidden" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'hidden', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); it('sets position property for "customButtonsOnHover" titleBarStyle', () => { const w = new BrowserWindow({ show: false, titleBarStyle: 'customButtonsOnHover', trafficLightPosition: pos }); const newPos = { x: 20, y: 20 }; w.setTrafficLightPosition(newPos); expect(w.getTrafficLightPosition()).to.deep.equal(newPos); }); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setAppDetails(options)', () => { afterEach(closeAllWindows); it('supports setting the app details', () => { const w = new BrowserWindow({ show: false }); const iconPath = path.join(fixtures, 'assets', 'icon.ico'); expect(() => { w.setAppDetails({ appId: 'my.app.id' }); w.setAppDetails({ appIconPath: iconPath, appIconIndex: 0 }); w.setAppDetails({ appIconPath: iconPath }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({ relaunchCommand: 'my-app.exe arg1 arg2' }); w.setAppDetails({ relaunchDisplayName: 'My app name' }); w.setAppDetails({ appId: 'my.app.id', appIconPath: iconPath, appIconIndex: 0, relaunchCommand: 'my-app.exe arg1 arg2', relaunchDisplayName: 'My app name' }); w.setAppDetails({}); }).to.not.throw(); expect(() => { (w.setAppDetails as any)(); }).to.throw('Insufficient number of arguments.'); }); }); describe('BrowserWindow.fromId(id)', () => { afterEach(closeAllWindows); it('returns the window with id', () => { const w = new BrowserWindow({ show: false }); expect(BrowserWindow.fromId(w.id)!.id).to.equal(w.id); }); }); describe('Opening a BrowserWindow from a link', () => { let appProcess: childProcess.ChildProcessWithoutNullStreams | undefined; afterEach(() => { if (appProcess && !appProcess.killed) { appProcess.kill(); appProcess = undefined; } }); it('can properly open and load a new window from a link', async () => { const appPath = path.join(__dirname, 'fixtures', 'apps', 'open-new-window-from-link'); appProcess = childProcess.spawn(process.execPath, [appPath]); const [code] = await emittedOnce(appProcess, 'exit'); expect(code).to.equal(0); }); }); describe('BrowserWindow.fromWebContents(webContents)', () => { afterEach(closeAllWindows); it('returns the window with the webContents', () => { const w = new BrowserWindow({ show: false }); const found = BrowserWindow.fromWebContents(w.webContents); expect(found!.id).to.equal(w.id); }); it('returns null for webContents without a BrowserWindow', () => { const contents = (webContents as any).create({}); try { expect(BrowserWindow.fromWebContents(contents)).to.be.null('BrowserWindow.fromWebContents(contents)'); } finally { contents.destroy(); } }); it('returns the correct window for a BrowserView webcontents', async () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); await bv.webContents.loadURL('about:blank'); expect(BrowserWindow.fromWebContents(bv.webContents)!.id).to.equal(w.id); }); it('returns the correct window for a WebView webcontents', async () => { const w = new BrowserWindow({ show: false, webPreferences: { webviewTag: true } }); w.loadURL('data:text/html,<webview src="data:text/html,hi"></webview>'); // NOTE(nornagon): Waiting for 'did-attach-webview' is a workaround for // https://github.com/electron/electron/issues/25413, and is not integral // to the test. const p = emittedOnce(w.webContents, 'did-attach-webview'); const [, webviewContents] = await emittedOnce(app, 'web-contents-created'); expect(BrowserWindow.fromWebContents(webviewContents)!.id).to.equal(w.id); await p; }); it('is usable immediately on browser-window-created', async () => { const w = new BrowserWindow({ show: false }); w.loadURL('about:blank'); w.webContents.executeJavaScript('window.open(""); null'); const [win, winFromWebContents] = await new Promise((resolve) => { app.once('browser-window-created', (e, win) => { resolve([win, BrowserWindow.fromWebContents(win.webContents)]); }); }); expect(winFromWebContents).to.equal(win); }); }); describe('BrowserWindow.openDevTools()', () => { afterEach(closeAllWindows); it('does not crash for frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); w.webContents.openDevTools(); }); }); describe('BrowserWindow.fromBrowserView(browserView)', () => { afterEach(closeAllWindows); it('returns the window with the BrowserView', () => { const w = new BrowserWindow({ show: false }); const bv = new BrowserView(); w.setBrowserView(bv); defer(() => { w.removeBrowserView(bv); (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)!.id).to.equal(w.id); }); it('returns the window when there are multiple BrowserViews', () => { const w = new BrowserWindow({ show: false }); const bv1 = new BrowserView(); w.addBrowserView(bv1); const bv2 = new BrowserView(); w.addBrowserView(bv2); defer(() => { w.removeBrowserView(bv1); w.removeBrowserView(bv2); (bv1.webContents as any).destroy(); (bv2.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv1)!.id).to.equal(w.id); expect(BrowserWindow.fromBrowserView(bv2)!.id).to.equal(w.id); }); it('returns undefined if not attached', () => { const bv = new BrowserView(); defer(() => { (bv.webContents as any).destroy(); }); expect(BrowserWindow.fromBrowserView(bv)).to.be.null('BrowserWindow associated with bv'); }); }); describe('BrowserWindow.setOpacity(opacity)', () => { afterEach(closeAllWindows); ifdescribe(process.platform !== 'linux')(('Windows and Mac'), () => { it('make window with initial opacity', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); expect(w.getOpacity()).to.equal(0.5); }); it('allows setting the opacity', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setOpacity(0.0); expect(w.getOpacity()).to.equal(0.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(0.5); w.setOpacity(1.0); expect(w.getOpacity()).to.equal(1.0); }).to.not.throw(); }); it('clamps opacity to [0.0...1.0]', () => { const w = new BrowserWindow({ show: false, opacity: 0.5 }); w.setOpacity(100); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(-100); expect(w.getOpacity()).to.equal(0.0); }); }); ifdescribe(process.platform === 'linux')(('Linux'), () => { it('sets 1 regardless of parameter', () => { const w = new BrowserWindow({ show: false }); w.setOpacity(0); expect(w.getOpacity()).to.equal(1.0); w.setOpacity(0.5); expect(w.getOpacity()).to.equal(1.0); }); }); }); describe('BrowserWindow.setShape(rects)', () => { afterEach(closeAllWindows); it('allows setting shape', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.setShape([]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }]); w.setShape([{ x: 0, y: 0, width: 100, height: 100 }, { x: 0, y: 200, width: 1000, height: 100 }]); w.setShape([]); }).to.not.throw(); }); }); describe('"useContentSize" option', () => { afterEach(closeAllWindows); it('make window created with content size when used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('make window created with window size when not used', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400 }); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false, width: 400, height: 400, useContentSize: true }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); const size = w.getSize(); expect(size).to.deep.equal([400, 400]); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarStyle" option', () => { const testWindowsOverlay = async (style: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: style, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: true }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRect = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRect.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRect.x).to.be.greaterThan(0); } else { expect(overlayRect.x).to.equal(0); } expect(overlayRect.width).to.be.greaterThan(0); expect(overlayRect.height).to.be.greaterThan(0); const cssOverlayRect = await w.webContents.executeJavaScript('getCssOverlayProperties();'); expect(cssOverlayRect).to.deep.equal(overlayRect); const geometryChange = emittedOnce(ipcMain, 'geometrychange'); w.setBounds({ width: 800 }); const [, newOverlayRect] = await geometryChange; expect(newOverlayRect.width).to.equal(overlayRect.width + 400); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('creates browser window with hidden title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); ifit(process.platform === 'darwin')('creates browser window with hidden inset title bar', () => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hiddenInset' }); const contentSize = w.getContentSize(); expect(contentSize).to.deep.equal([400, 400]); }); it('sets Window Control Overlay with hidden title bar', async () => { await testWindowsOverlay('hidden'); }); ifit(process.platform === 'darwin')('sets Window Control Overlay with hidden inset title bar', async () => { await testWindowsOverlay('hiddenInset'); }); ifdescribe(process.platform === 'win32')('when an invalid titleBarStyle is initially set', () => { let w: BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); }); afterEach(async () => { await closeAllWindows(); }); it('does not crash changing minimizability ', () => { expect(() => { w.setMinimizable(false); }).to.not.throw(); }); it('does not crash changing maximizability', () => { expect(() => { w.setMaximizable(false); }).to.not.throw(); }); }); }); ifdescribe(['win32', 'darwin'].includes(process.platform))('"titleBarOverlay" option', () => { const testWindowsOverlayHeight = async (size: any) => { const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: size } }); const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); if (process.platform === 'darwin') { await w.loadFile(overlayHTML); } else { const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const overlayRectPreMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const overlayRectPostMax = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(overlayRectPreMax.y).to.equal(0); if (process.platform === 'darwin') { expect(overlayRectPreMax.x).to.be.greaterThan(0); } else { expect(overlayRectPreMax.x).to.equal(0); } expect(overlayRectPreMax.width).to.be.greaterThan(0); expect(overlayRectPreMax.height).to.equal(size); // Confirm that maximization only affected the height of the buttons and not the title bar expect(overlayRectPostMax.height).to.equal(size); }; afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('sets Window Control Overlay with title bar height of 40', async () => { await testWindowsOverlayHeight(40); }); }); ifdescribe(process.platform === 'win32')('BrowserWindow.setTitlebarOverlay', () => { afterEach(async () => { await closeAllWindows(); ipcMain.removeAllListeners('geometrychange'); }); it('does not crash when an invalid titleBarStyle was initially set', () => { const win = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { color: '#0000f0', symbolColor: '#ffffff' }, titleBarStyle: 'hiddenInset' }); expect(() => { win.setTitleBarOverlay({ color: '#000000' }); }).to.not.throw(); }); it('correctly updates the height of the overlay', async () => { const testOverlay = async (w: BrowserWindow, size: Number, firstRun: boolean) => { const overlayHTML = path.join(__dirname, 'fixtures', 'pages', 'overlay.html'); const overlayReady = emittedOnce(ipcMain, 'geometrychange'); await w.loadFile(overlayHTML); if (firstRun) { await overlayReady; } const overlayEnabled = await w.webContents.executeJavaScript('navigator.windowControlsOverlay.visible'); expect(overlayEnabled).to.be.true('overlayEnabled'); const { height: preMaxHeight } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); if (!w.isMaximized()) { const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; } expect(w.isMaximized()).to.be.true('not maximized'); const { x, y, width, height } = await w.webContents.executeJavaScript('getJSOverlayProperties()'); expect(x).to.equal(0); expect(y).to.equal(0); expect(width).to.be.greaterThan(0); expect(height).to.equal(size); expect(preMaxHeight).to.equal(size); }; const INITIAL_SIZE = 40; const w = new BrowserWindow({ show: false, width: 400, height: 400, titleBarStyle: 'hidden', webPreferences: { nodeIntegration: true, contextIsolation: false }, titleBarOverlay: { height: INITIAL_SIZE } }); await testOverlay(w, INITIAL_SIZE, true); w.setTitleBarOverlay({ height: INITIAL_SIZE + 10 }); await testOverlay(w, INITIAL_SIZE + 10, false); }); }); ifdescribe(process.platform === 'darwin')('"enableLargerThanScreen" option', () => { afterEach(closeAllWindows); it('can move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, 50); const after = w.getPosition(); expect(after).to.deep.equal([-10, 50]); }); it('cannot move the window behind menu bar', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can move the window behind menu bar if it has no frame', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true, frame: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[0]).to.be.equal(-10); expect(after[1]).to.be.equal(-10); }); it('without it, cannot move the window out of screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); w.setPosition(-10, -10); const after = w.getPosition(); expect(after[1]).to.be.at.least(0); }); it('can set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: true }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expectBoundsEqual(w.getSize(), [size.width, size.height]); }); it('without it, cannot set the window larger than screen', () => { const w = new BrowserWindow({ show: true, enableLargerThanScreen: false }); const size = screen.getPrimaryDisplay().size; size.width += 100; size.height += 100; w.setSize(size.width, size.height); expect(w.getSize()[1]).to.at.most(screen.getPrimaryDisplay().size.height); }); }); ifdescribe(process.platform === 'darwin')('"zoomToPageWidth" option', () => { afterEach(closeAllWindows); it('sets the window width to the page width when used', () => { const w = new BrowserWindow({ show: false, width: 500, height: 400, zoomToPageWidth: true }); w.maximize(); expect(w.getSize()[0]).to.equal(500); }); }); describe('"tabbingIdentifier" option', () => { afterEach(closeAllWindows); it('can be set on a window', () => { expect(() => { /* eslint-disable no-new */ new BrowserWindow({ tabbingIdentifier: 'group1' }); new BrowserWindow({ tabbingIdentifier: 'group2', frame: false }); /* eslint-enable no-new */ }).not.to.throw(); }); }); describe('"webPreferences" option', () => { afterEach(() => { ipcMain.removeAllListeners('answer'); }); afterEach(closeAllWindows); describe('"preload" option', () => { const doesNotLeakSpec = (name: string, webPrefs: { nodeIntegration: boolean, sandbox: boolean, contextIsolation: boolean }) => { it(name, async () => { const w = new BrowserWindow({ webPreferences: { ...webPrefs, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'no-leak.html')); const [, result] = await emittedOnce(ipcMain, 'leak-result'); expect(result).to.have.property('require', 'undefined'); expect(result).to.have.property('exports', 'undefined'); expect(result).to.have.property('windowExports', 'undefined'); expect(result).to.have.property('windowPreload', 'undefined'); expect(result).to.have.property('windowRequire', 'undefined'); }); }; doesNotLeakSpec('does not leak require', { nodeIntegration: false, sandbox: false, contextIsolation: false }); doesNotLeakSpec('does not leak require when sandbox is enabled', { nodeIntegration: false, sandbox: true, contextIsolation: false }); doesNotLeakSpec('does not leak require when context isolation is enabled', { nodeIntegration: false, sandbox: false, contextIsolation: true }); doesNotLeakSpec('does not leak require when context isolation and sandbox are enabled', { nodeIntegration: false, sandbox: true, contextIsolation: true }); it('does not leak any node globals on the window object with nodeIntegration is disabled', async () => { let w = new BrowserWindow({ webPreferences: { contextIsolation: false, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, notIsolated] = await emittedOnce(ipcMain, 'leak-result'); expect(notIsolated).to.have.property('globals'); w.destroy(); w = new BrowserWindow({ webPreferences: { contextIsolation: true, nodeIntegration: false, preload: path.resolve(fixtures, 'module', 'empty.js') }, show: false }); w.loadFile(path.join(fixtures, 'api', 'globals.html')); const [, isolated] = await emittedOnce(ipcMain, 'leak-result'); expect(isolated).to.have.property('globals'); const notIsolatedGlobals = new Set(notIsolated.globals); for (const isolatedGlobal of isolated.globals) { notIsolatedGlobals.delete(isolatedGlobal); } expect([...notIsolatedGlobals]).to.deep.equal([], 'non-isolated renderer should have no additional globals'); }); it('loads the script before other scripts in window', async () => { const preload = path.join(fixtures, 'module', 'set-global.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.eql('preload'); }); it('has synchronous access to all eventual window APIs', async () => { const preload = path.join(fixtures, 'module', 'access-blink-apis.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false, preload } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.be.an('object'); expect(test.atPreload).to.be.an('array'); expect(test.atLoad).to.be.an('array'); expect(test.atPreload).to.deep.equal(test.atLoad, 'should have access to the same window APIs'); }); }); describe('session preload scripts', function () { const preloads = [ path.join(fixtures, 'module', 'set-global-preload-1.js'), path.join(fixtures, 'module', 'set-global-preload-2.js'), path.relative(process.cwd(), path.join(fixtures, 'module', 'set-global-preload-3.js')) ]; const defaultSession = session.defaultSession; beforeEach(() => { expect(defaultSession.getPreloads()).to.deep.equal([]); defaultSession.setPreloads(preloads); }); afterEach(() => { defaultSession.setPreloads([]); }); it('can set multiple session preload script', () => { expect(defaultSession.getPreloads()).to.deep.equal(preloads); }); const generateSpecs = (description: string, sandbox: boolean) => { describe(description, () => { it('loads the script before other scripts in window including normal preloads', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox, preload: path.join(fixtures, 'module', 'get-global-preload.js'), contextIsolation: false } }); w.loadURL('about:blank'); const [, preload1, preload2, preload3] = await emittedOnce(ipcMain, 'vars'); expect(preload1).to.equal('preload-1'); expect(preload2).to.equal('preload-1-2'); expect(preload3).to.be.undefined('preload 3'); }); }); }; generateSpecs('without sandbox', false); generateSpecs('with sandbox', true); }); describe('"additionalArguments" option', () => { it('adds extra args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg'); }); it('adds extra value args to process.argv in the renderer process', async () => { const preload = path.join(fixtures, 'module', 'check-arguments.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, preload, additionalArguments: ['--my-magic-arg=foo'] } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, argv] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--my-magic-arg=foo'); }); }); describe('"node-integration" option', () => { it('disables node integration by default', async () => { const preload = path.join(fixtures, 'module', 'send-later.js'); const w = new BrowserWindow({ show: false, webPreferences: { preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'blank.html')); const [, typeofProcess, typeofBuffer] = await emittedOnce(ipcMain, 'answer'); expect(typeofProcess).to.equal('undefined'); expect(typeofBuffer).to.equal('undefined'); }); }); describe('"sandbox" option', () => { const preload = path.join(path.resolve(__dirname, 'fixtures'), 'module', 'preload-sandbox.js'); let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { switch (request.url) { case '/cross-site': response.end(`<html><body><h1>${request.url}</h1></body></html>`); break; default: throw new Error(`unsupported endpoint: ${request.url}`); } }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('exposes ipcRenderer to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes ipcRenderer to preload script (path has special chars)', async () => { const preloadSpecialChars = path.join(fixtures, 'module', 'preload-sandboxæø åü.js'); const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload: preloadSpecialChars, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test).to.equal('preload'); }); it('exposes "loaded" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload } }); w.loadURL('about:blank'); await emittedOnce(ipcMain, 'process-loaded'); }); it('exposes "exit" event to preload script', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?exit-event'); const pageUrl = 'file://' + htmlPath; w.loadURL(pageUrl); const [, url] = await emittedOnce(ipcMain, 'answer'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); }); it('should open windows in same domain with cross-scripting enabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); const htmlPath = path.join(__dirname, 'fixtures', 'api', 'sandbox.html?window-open'); const pageUrl = 'file://' + htmlPath; const answer = emittedOnce(ipcMain, 'answer'); w.loadURL(pageUrl); const [, { url, frameName, options }] = await emittedOnce(w.webContents, 'did-create-window'); const expectedUrl = process.platform === 'win32' ? 'file:///' + htmlPath.replace(/\\/g, '/') : pageUrl; expect(url).to.equal(expectedUrl); expect(frameName).to.equal('popup!'); expect(options.width).to.equal(500); expect(options.height).to.equal(600); const [, html] = await answer; expect(html).to.equal('<h1>scripting from opener</h1>'); }); it('should open windows in another domain with cross-scripting disabled', async () => { const w = new BrowserWindow({ show: true, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload } } })); w.loadFile( path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'window-open-external' } ); // Wait for a message from the main window saying that it's ready. await emittedOnce(ipcMain, 'opener-loaded'); // Ask the opener to open a popup with window.opener. const expectedPopupUrl = `${serverUrl}/cross-site`; // Set in "sandbox.html". w.webContents.send('open-the-popup', expectedPopupUrl); // The page is going to open a popup that it won't be able to close. // We have to close it from here later. const [, popupWindow] = await emittedOnce(app, 'browser-window-created'); // Ask the popup window for details. const detailsAnswer = emittedOnce(ipcMain, 'child-loaded'); popupWindow.webContents.send('provide-details'); const [, openerIsNull, , locationHref] = await detailsAnswer; expect(openerIsNull).to.be.false('window.opener is null'); expect(locationHref).to.equal(expectedPopupUrl); // Ask the page to access the popup. const touchPopupResult = emittedOnce(ipcMain, 'answer'); w.webContents.send('touch-the-popup'); const [, popupAccessMessage] = await touchPopupResult; // Ask the popup to access the opener. const touchOpenerResult = emittedOnce(ipcMain, 'answer'); popupWindow.webContents.send('touch-the-opener'); const [, openerAccessMessage] = await touchOpenerResult; // We don't need the popup anymore, and its parent page can't close it, // so let's close it from here before we run any checks. await closeWindow(popupWindow, { assertNotWindows: false }); expect(popupAccessMessage).to.be.a('string', 'child\'s .document is accessible from its parent window'); expect(popupAccessMessage).to.match(/^Blocked a frame with origin/); expect(openerAccessMessage).to.be.a('string', 'opener .document is accessible from a popup window'); expect(openerAccessMessage).to.match(/^Blocked a frame with origin/); }); it('should inherit the sandbox setting in opened windows', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [, { argv }] = await emittedOnce(ipcMain, 'answer'); expect(argv).to.include('--enable-sandbox'); }); it('should open windows with the options configured via new-window event listeners', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); it('should set ipc event sender correctly', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); let childWc: WebContents | null = null; w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload, contextIsolation: false } } })); w.webContents.on('did-create-window', (win) => { childWc = win.webContents; expect(w.webContents).to.not.equal(childWc); }); ipcMain.once('parent-ready', function (event) { expect(event.sender).to.equal(w.webContents, 'sender should be the parent'); event.sender.send('verified'); }); ipcMain.once('child-ready', function (event) { expect(childWc).to.not.be.null('child webcontents should be available'); expect(event.sender).to.equal(childWc, 'sender should be the child'); event.sender.send('verified'); }); const done = Promise.all([ 'parent-answer', 'child-answer' ].map(name => emittedOnce(ipcMain, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'verify-ipc-sender' }); await done; }); describe('event handling', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); }); it('works for window events', async () => { const pageTitleUpdated = emittedOnce(w, 'page-title-updated'); w.loadURL('data:text/html,<script>document.title = \'changed\'</script>'); await pageTitleUpdated; }); it('works for stop events', async () => { const done = Promise.all([ 'did-navigate', 'did-fail-load', 'did-stop-loading' ].map(name => emittedOnce(w.webContents, name))); w.loadURL('data:text/html,<script>stop()</script>'); await done; }); it('works for web contents events', async () => { const done = Promise.all([ 'did-finish-load', 'did-frame-finish-load', 'did-navigate-in-page', 'will-navigate', 'did-start-loading', 'did-stop-loading', 'did-frame-finish-load', 'dom-ready' ].map(name => emittedOnce(w.webContents, name))); w.loadFile(path.join(__dirname, 'fixtures', 'api', 'sandbox.html'), { search: 'webcontents-events' }); await done; }); }); it('supports calling preventDefault on new-window events', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true } }); const initialWebContents = webContents.getAllWebContents().map((i) => i.id); w.webContents.once('new-window', (e) => { e.preventDefault(); // We need to give it some time so the windows get properly disposed (at least on OSX). setTimeout(() => { const currentWebContents = webContents.getAllWebContents().map((i) => i.id); try { expect(currentWebContents).to.deep.equal(initialWebContents); done(); } catch (error) { done(e); } }, 100); }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('validates process APIs access in sandboxed renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, contextIsolation: false } }); w.webContents.once('preload-error', (event, preloadPath, error) => { throw error; }); process.env.sandboxmain = 'foo'; w.loadFile(path.join(fixtures, 'api', 'preload.html')); const [, test] = await emittedOnce(ipcMain, 'answer'); expect(test.hasCrash).to.be.true('has crash'); expect(test.hasHang).to.be.true('has hang'); expect(test.heapStatistics).to.be.an('object'); expect(test.blinkMemoryInfo).to.be.an('object'); expect(test.processMemoryInfo).to.be.an('object'); expect(test.systemVersion).to.be.a('string'); expect(test.cpuUsage).to.be.an('object'); expect(test.ioCounters).to.be.an('object'); expect(test.uptime).to.be.a('number'); expect(test.arch).to.equal(process.arch); expect(test.platform).to.equal(process.platform); expect(test.env).to.deep.equal(process.env); expect(test.execPath).to.equal(process.helperExecPath); expect(test.sandboxed).to.be.true('sandboxed'); expect(test.contextIsolated).to.be.false('contextIsolated'); expect(test.type).to.equal('renderer'); expect(test.version).to.equal(process.version); expect(test.versions).to.deep.equal(process.versions); expect(test.contextId).to.be.a('string'); if (process.platform === 'linux' && test.osSandbox) { expect(test.creationTime).to.be.null('creation time'); expect(test.systemMemoryInfo).to.be.null('system memory info'); } else { expect(test.creationTime).to.be.a('number'); expect(test.systemMemoryInfo).to.be.an('object'); } }); it('webview in sandbox renderer', async () => { const w = new BrowserWindow({ show: false, webPreferences: { sandbox: true, preload, webviewTag: true, contextIsolation: false } }); const didAttachWebview = emittedOnce(w.webContents, 'did-attach-webview'); const webviewDomReady = emittedOnce(ipcMain, 'webview-dom-ready'); w.loadFile(path.join(fixtures, 'pages', 'webview-did-attach-event.html')); const [, webContents] = await didAttachWebview; const [, id] = await webviewDomReady; expect(webContents.id).to.equal(id); }); }); describe('child windows', () => { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, // tests relies on preloads in opened windows nodeIntegrationInSubFrames: true, contextIsolation: false } }); }); it('opens window of about:blank with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-blank.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window of same domain with cross-scripting enabled', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-file.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('blocks accessing cross-origin frames', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-cross-origin.html')); const [, content] = await answer; expect(content).to.equal('Blocked a frame with origin "file://" from accessing a cross-origin frame.'); }); it('opens window from <iframe> tags', async () => { const answer = emittedOnce(ipcMain, 'answer'); w.loadFile(path.join(fixtures, 'api', 'native-window-open-iframe.html')); const [, content] = await answer; expect(content).to.equal('Hello'); }); it('opens window with cross-scripting enabled from isolated context', async () => { const w = new BrowserWindow({ show: false, webPreferences: { preload: path.join(fixtures, 'api', 'native-window-open-isolated-preload.js') } }); w.loadFile(path.join(fixtures, 'api', 'native-window-open-isolated.html')); const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('Hello'); }); ifit(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('loads native addons correctly after reload', async () => { w.loadFile(path.join(__dirname, 'fixtures', 'api', 'native-window-open-native-addon.html')); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } w.reload(); { const [, content] = await emittedOnce(ipcMain, 'answer'); expect(content).to.equal('function'); } }); it('<webview> works in a scriptable popup', async () => { const preload = path.join(fixtures, 'api', 'new-window-webview-preload.js'); const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegrationInSubFrames: true, webviewTag: true, contextIsolation: false, preload } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { show: false, webPreferences: { contextIsolation: false, webviewTag: true, nodeIntegrationInSubFrames: true, preload } } })); const webviewLoaded = emittedOnce(ipcMain, 'webview-loaded'); w.loadFile(path.join(fixtures, 'api', 'new-window-webview.html')); await webviewLoaded; }); it('should open windows with the options configured via new-window event listeners', async () => { const preloadPath = path.join(mainFixtures, 'api', 'new-window-preload.js'); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: preloadPath, contextIsolation: false } } })); w.loadFile(path.join(fixtures, 'api', 'new-window.html')); const [[, childWebContents]] = await Promise.all([ emittedOnce(app, 'web-contents-created'), emittedOnce(ipcMain, 'answer') ]); const webPreferences = childWebContents.getLastWebPreferences(); expect(webPreferences.contextIsolation).to.equal(false); }); describe('window.location', () => { const protocols = [ ['foo', path.join(fixtures, 'api', 'window-open-location-change.html')], ['bar', path.join(fixtures, 'api', 'window-open-location-final.html')] ]; beforeEach(() => { for (const [scheme, path] of protocols) { protocol.registerBufferProtocol(scheme, (request, callback) => { callback({ mimeType: 'text/html', data: fs.readFileSync(path) }); }); } }); afterEach(() => { for (const [scheme] of protocols) { protocol.unregisterProtocol(scheme); } }); it('retains the original web preferences when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true, contextIsolation: false } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js'), contextIsolation: false, nodeIntegrationInSubFrames: true } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { nodeIntegration, typeofProcess }] = await emittedOnce(ipcMain, 'answer'); expect(nodeIntegration).to.be.false(); expect(typeofProcess).to.eql('undefined'); }); it('window.opener is not null when window.location is changed to a new origin', async () => { const w = new BrowserWindow({ show: false, webPreferences: { // test relies on preloads in opened window nodeIntegrationInSubFrames: true } }); w.webContents.setWindowOpenHandler(() => ({ action: 'allow', overrideBrowserWindowOptions: { webPreferences: { preload: path.join(mainFixtures, 'api', 'window-open-preload.js') } } })); w.loadFile(path.join(fixtures, 'api', 'window-open-location-open.html')); const [, { windowOpenerIsNull }] = await emittedOnce(ipcMain, 'answer'); expect(windowOpenerIsNull).to.be.false('window.opener is null'); }); }); }); describe('"disableHtmlFullscreenWindowResize" option', () => { it('prevents window from resizing when set', async () => { const w = new BrowserWindow({ show: false, webPreferences: { disableHtmlFullscreenWindowResize: true } }); await w.loadURL('about:blank'); const size = w.getSize(); const enterHtmlFullScreen = emittedOnce(w.webContents, 'enter-html-full-screen'); w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await enterHtmlFullScreen; expect(w.getSize()).to.deep.equal(size); }); }); }); describe('beforeunload handler', function () { let w: BrowserWindow = null as unknown as BrowserWindow; beforeEach(() => { w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); }); afterEach(closeAllWindows); it('returning undefined would not prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-undefined.html')); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('returning false would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('returning empty string would prevent close', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-empty-string.html')); w.close(); const [, proceed] = await emittedOnce(w.webContents, 'before-unload-fired'); expect(proceed).to.equal(false); }); it('emits for each close attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const destroyListener = () => { expect.fail('Close was not prevented'); }; w.webContents.once('destroyed', destroyListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.close(); await emittedOnce(w.webContents, 'before-unload-fired'); w.webContents.removeListener('destroyed', destroyListener); const wait = emittedOnce(w, 'closed'); w.close(); await wait; }); it('emits for each reload attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.reload(); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.reload(); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); w.reload(); await emittedOnce(w.webContents, 'did-finish-load'); }); it('emits for each navigation attempt', async () => { await w.loadFile(path.join(__dirname, 'fixtures', 'api', 'beforeunload-false-prevent3.html')); const navigationListener = () => { expect.fail('Reload was not prevented'); }; w.webContents.once('did-start-navigation', navigationListener); w.webContents.executeJavaScript('installBeforeUnload(2)', true); // The renderer needs to report the status of beforeunload handler // back to main process, so wait for next console message, which means // the SuddenTerminationStatus message have been flushed. await emittedOnce(w.webContents, 'console-message'); w.loadURL('about:blank'); // Chromium does not emit 'before-unload-fired' on WebContents for // navigations, so we have to use other ways to know if beforeunload // is fired. await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.loadURL('about:blank'); await emittedUntil(w.webContents, 'console-message', isBeforeUnload); w.webContents.removeListener('did-start-navigation', navigationListener); await w.loadURL('about:blank'); }); }); describe('document.visibilityState/hidden', () => { afterEach(closeAllWindows); it('visibilityState is initially visible despite window being hidden', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let readyToShow = false; w.once('ready-to-show', () => { readyToShow = true; }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(readyToShow).to.be.false('ready to show'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is hidden', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.hide(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform !== 'win32')('visibilityState changes when window is shown', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.show(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); ifit(process.platform !== 'win32')('visibilityState changes when window is shown inactive', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); if (process.platform === 'darwin') { // See https://github.com/electron/electron/issues/8664 await emittedOnce(w, 'show'); } w.hide(); w.showInactive(); const [, visibilityState] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); }); // TODO(nornagon): figure out why this is failing on windows ifit(process.platform === 'darwin')('visibilityState changes when window is minimized', async () => { const w = new BrowserWindow({ width: 100, height: 100, webPreferences: { nodeIntegration: true, contextIsolation: false } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } w.minimize(); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('hidden'); expect(hidden).to.be.true('hidden'); } }); // FIXME(MarshallOfSound): This test fails locally 100% of the time, on CI it started failing // when we introduced the compositor recycling patch. Should figure out how to fix this it.skip('visibilityState remains visible if backgroundThrottling is disabled', async () => { const w = new BrowserWindow({ show: false, width: 100, height: 100, webPreferences: { backgroundThrottling: false, nodeIntegration: true } }); w.loadFile(path.join(fixtures, 'pages', 'visibilitychange.html')); { const [, visibilityState, hidden] = await emittedOnce(ipcMain, 'pong'); expect(visibilityState).to.equal('visible'); expect(hidden).to.be.false('hidden'); } ipcMain.once('pong', (event, visibilityState, hidden) => { throw new Error(`Unexpected visibility change event. visibilityState: ${visibilityState} hidden: ${hidden}`); }); try { const shown1 = emittedOnce(w, 'show'); w.show(); await shown1; const hidden = emittedOnce(w, 'hide'); w.hide(); await hidden; const shown2 = emittedOnce(w, 'show'); w.show(); await shown2; } finally { ipcMain.removeAllListeners('pong'); } }); }); describe('new-window event', () => { afterEach(closeAllWindows); it('emits when window.open is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName, disposition, options) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when window.open is called with no webPreferences', (done) => { const w = new BrowserWindow({ show: false }); w.webContents.once('new-window', function (e, url, frameName, disposition, options) { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('host'); expect((options as any)['this-is-not-a-standard-feature']).to.equal(true); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'window-open.html')); }); it('emits when link with target is called', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true } }); w.webContents.once('new-window', (e, url, frameName) => { e.preventDefault(); try { expect(url).to.equal('http://host/'); expect(frameName).to.equal('target'); done(); } catch (e) { done(e); } }); w.loadFile(path.join(fixtures, 'pages', 'target-name.html')); }); it('includes all properties', async () => { const w = new BrowserWindow({ show: false }); const p = new Promise<{ url: string, frameName: string, disposition: string, options: BrowserWindowConstructorOptions, additionalFeatures: string[], referrer: Electron.Referrer, postBody: Electron.PostBody }>((resolve) => { w.webContents.once('new-window', (e, url, frameName, disposition, options, additionalFeatures, referrer, postBody) => { e.preventDefault(); resolve({ url, frameName, disposition, options, additionalFeatures, referrer, postBody }); }); }); w.loadURL(`data:text/html,${encodeURIComponent(` <form target="_blank" method="POST" id="form" action="http://example.com/test"> <input type="text" name="post-test-key" value="post-test-value"></input> </form> <script>form.submit()</script> `)}`); const { url, frameName, disposition, options, additionalFeatures, referrer, postBody } = await p; expect(url).to.equal('http://example.com/test'); expect(frameName).to.equal(''); expect(disposition).to.equal('foreground-tab'); expect(options).to.be.an('object').not.null(); expect(referrer.policy).to.equal('strict-origin-when-cross-origin'); expect(referrer.url).to.equal(''); expect(additionalFeatures).to.deep.equal([]); expect(postBody.data).to.have.length(1); expect(postBody.data[0].type).to.equal('rawData'); expect((postBody.data[0] as any).bytes).to.deep.equal(Buffer.from('post-test-key=post-test-value')); expect(postBody.contentType).to.equal('application/x-www-form-urlencoded'); }); }); ifdescribe(process.platform !== 'linux')('max/minimize events', () => { afterEach(closeAllWindows); it('emits an event when window is maximized', async () => { const w = new BrowserWindow({ show: false }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits an event when a transparent window is maximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); w.show(); w.maximize(); await maximize; }); it('emits only one event when frameless window is maximized', () => { const w = new BrowserWindow({ show: false, frame: false }); let emitted = 0; w.on('maximize', () => emitted++); w.show(); w.maximize(); expect(emitted).to.equal(1); }); it('emits an event when window is unmaximized', async () => { const w = new BrowserWindow({ show: false }); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); w.unmaximize(); await unmaximize; }); it('emits an event when a transparent window is unmaximized', async () => { const w = new BrowserWindow({ show: false, frame: false, transparent: true }); const maximize = emittedOnce(w, 'maximize'); const unmaximize = emittedOnce(w, 'unmaximize'); w.show(); w.maximize(); await maximize; w.unmaximize(); await unmaximize; }); it('emits an event when window is minimized', async () => { const w = new BrowserWindow({ show: false }); const minimize = emittedOnce(w, 'minimize'); w.show(); w.minimize(); await minimize; }); }); describe('beginFrameSubscription method', () => { it('does not crash when callback returns nothing', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function () { // This callback might be called twice. if (called) return; called = true; // Pending endFrameSubscription to next tick can reliably reproduce // a crash which happens when nothing is returned in the callback. setTimeout(() => { w.webContents.endFrameSubscription(); done(); }); }); }); }); it('subscribes to frame updates', (done) => { const w = new BrowserWindow({ show: false }); let called = false; w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); w.webContents.on('dom-ready', () => { w.webContents.beginFrameSubscription(function (data) { // This callback might be called twice. if (called) return; called = true; try { expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); }); it('subscribes to frame updates (only dirty rectangle)', (done) => { const w = new BrowserWindow({ show: false }); let called = false; let gotInitialFullSizeFrame = false; const [contentWidth, contentHeight] = w.getContentSize(); w.webContents.on('did-finish-load', () => { w.webContents.beginFrameSubscription(true, (image, rect) => { if (image.isEmpty()) { // Chromium sometimes sends a 0x0 frame at the beginning of the // page load. return; } if (rect.height === contentHeight && rect.width === contentWidth && !gotInitialFullSizeFrame) { // The initial frame is full-size, but we're looking for a call // with just the dirty-rect. The next frame should be a smaller // rect. gotInitialFullSizeFrame = true; return; } // This callback might be called twice. if (called) return; // We asked for just the dirty rectangle, so we expect to receive a // rect smaller than the full size. // TODO(jeremy): this is failing on windows currently; investigate. // assert(rect.width < contentWidth || rect.height < contentHeight) called = true; try { const expectedSize = rect.width * rect.height * 4; expect(image.getBitmap()).to.be.an.instanceOf(Buffer).with.lengthOf(expectedSize); done(); } catch (e) { done(e); } finally { w.webContents.endFrameSubscription(); } }); }); w.loadFile(path.join(fixtures, 'api', 'frame-subscriber.html')); }); it('throws error when subscriber is not well defined', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.webContents.beginFrameSubscription(true, true as any); // TODO(zcbenz): gin is weak at guessing parameter types, we should // upstream native_mate's implementation to gin. }).to.throw('Error processing argument at index 1, conversion failure from '); }); }); describe('savePage method', () => { const savePageDir = path.join(fixtures, 'save_page'); const savePageHtmlPath = path.join(savePageDir, 'save_page.html'); const savePageJsPath = path.join(savePageDir, 'save_page_files', 'test.js'); const savePageCssPath = path.join(savePageDir, 'save_page_files', 'test.css'); afterEach(() => { closeAllWindows(); try { fs.unlinkSync(savePageCssPath); fs.unlinkSync(savePageJsPath); fs.unlinkSync(savePageHtmlPath); fs.rmdirSync(path.join(savePageDir, 'save_page_files')); fs.rmdirSync(savePageDir); } catch {} }); it('should throw when passing relative paths', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await expect( w.webContents.savePage('save_page.html', 'HTMLComplete') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'HTMLOnly') ).to.eventually.be.rejectedWith('Path must be absolute'); await expect( w.webContents.savePage('save_page.html', 'MHTML') ).to.eventually.be.rejectedWith('Path must be absolute'); }); it('should save page to disk with HTMLOnly', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLOnly'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with MHTML', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'MHTML'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.false('js path'); expect(fs.existsSync(savePageCssPath)).to.be.false('css path'); }); it('should save page to disk with HTMLComplete', async () => { const w = new BrowserWindow({ show: false }); await w.loadFile(path.join(fixtures, 'pages', 'save_page', 'index.html')); await w.webContents.savePage(savePageHtmlPath, 'HTMLComplete'); expect(fs.existsSync(savePageHtmlPath)).to.be.true('html path'); expect(fs.existsSync(savePageJsPath)).to.be.true('js path'); expect(fs.existsSync(savePageCssPath)).to.be.true('css path'); }); }); describe('BrowserWindow options argument is optional', () => { afterEach(closeAllWindows); it('should create a window with default size (800x600)', () => { const w = new BrowserWindow(); expect(w.getSize()).to.deep.equal([800, 600]); }); }); describe('BrowserWindow.restore()', () => { afterEach(closeAllWindows); it('should restore the previous window size', () => { const w = new BrowserWindow({ minWidth: 800, width: 800 }); const initialSize = w.getSize(); w.minimize(); w.restore(); expectBoundsEqual(w.getSize(), initialSize); }); it('does not crash when restoring hidden minimized window', () => { const w = new BrowserWindow({}); w.minimize(); w.hide(); w.show(); }); }); // TODO(dsanders11): Enable once maximize event works on Linux again on CI ifdescribe(process.platform !== 'linux')('BrowserWindow.maximize()', () => { afterEach(closeAllWindows); it('should show the window if it is not currently shown', async () => { const w = new BrowserWindow({ show: false }); const hidden = emittedOnce(w, 'hide'); let shown = emittedOnce(w, 'show'); const maximize = emittedOnce(w, 'maximize'); expect(w.isVisible()).to.be.false('visible'); w.maximize(); await maximize; await shown; expect(w.isMaximized()).to.be.true('maximized'); expect(w.isVisible()).to.be.true('visible'); // Even if the window is already maximized w.hide(); await hidden; expect(w.isVisible()).to.be.false('visible'); shown = emittedOnce(w, 'show'); w.maximize(); await shown; expect(w.isVisible()).to.be.true('visible'); }); }); describe('BrowserWindow.unmaximize()', () => { afterEach(closeAllWindows); it('should restore the previous window position', () => { const w = new BrowserWindow(); const initialPosition = w.getPosition(); w.maximize(); w.unmaximize(); expectBoundsEqual(w.getPosition(), initialPosition); }); // TODO(dsanders11): Enable once minimize event works on Linux again. // See https://github.com/electron/electron/issues/28699 ifit(process.platform !== 'linux')('should not restore a minimized window', async () => { const w = new BrowserWindow(); const minimize = emittedOnce(w, 'minimize'); w.minimize(); await minimize; w.unmaximize(); await delay(1000); expect(w.isMinimized()).to.be.true(); }); it('should not change the size or position of a normal window', async () => { const w = new BrowserWindow(); const initialSize = w.getSize(); const initialPosition = w.getPosition(); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getSize(), initialSize); expectBoundsEqual(w.getPosition(), initialPosition); }); ifit(process.platform === 'darwin')('should not change size or position of a window which is functionally maximized', async () => { const { workArea } = screen.getPrimaryDisplay(); const bounds = { x: workArea.x, y: workArea.y, width: workArea.width, height: workArea.height }; const w = new BrowserWindow(bounds); w.unmaximize(); await delay(1000); expectBoundsEqual(w.getBounds(), bounds); }); }); describe('setFullScreen(false)', () => { afterEach(closeAllWindows); // only applicable to windows: https://github.com/electron/electron/issues/6036 ifdescribe(process.platform === 'win32')('on windows', () => { it('should restore a normal visible window from a fullscreen startup state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const shown = emittedOnce(w, 'show'); // start fullscreen and hidden w.setFullScreen(true); w.show(); await shown; const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.true('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); it('should keep window hidden if already in hidden state', async () => { const w = new BrowserWindow({ show: false }); await w.loadURL('about:blank'); const leftFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leftFullScreen; expect(w.isVisible()).to.be.false('visible'); expect(w.isFullScreen()).to.be.false('fullscreen'); }); }); ifdescribe(process.platform === 'darwin')('BrowserWindow.setFullScreen(false) when HTML fullscreen', () => { it('exits HTML fullscreen when window leaves fullscreen', async () => { const w = new BrowserWindow(); await w.loadURL('about:blank'); await w.webContents.executeJavaScript('document.body.webkitRequestFullscreen()', true); await emittedOnce(w, 'enter-full-screen'); // Wait a tick for the full-screen state to 'stick' await delay(); w.setFullScreen(false); await emittedOnce(w, 'leave-html-full-screen'); }); }); }); describe('parent window', () => { afterEach(closeAllWindows); ifit(process.platform === 'darwin')('sheet-begin event emits when window opens a sheet', async () => { const w = new BrowserWindow(); const sheetBegin = emittedOnce(w, 'sheet-begin'); // eslint-disable-next-line no-new new BrowserWindow({ modal: true, parent: w }); await sheetBegin; }); ifit(process.platform === 'darwin')('sheet-end event emits when window has closed a sheet', async () => { const w = new BrowserWindow(); const sheet = new BrowserWindow({ modal: true, parent: w }); const sheetEnd = emittedOnce(w, 'sheet-end'); sheet.close(); await sheetEnd; }); describe('parent option', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.getParentWindow()).to.equal(w); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(w.getChildWindows()).to.deep.equal([c]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); const closed = emittedOnce(c, 'closed'); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); it('closes a grandchild window when a middle child window is destroyed', (done) => { const w = new BrowserWindow(); w.loadFile(path.join(fixtures, 'pages', 'base-page.html')); w.webContents.executeJavaScript('window.open("")'); w.webContents.on('did-create-window', async (window) => { const childWindow = new BrowserWindow({ parent: window }); await delay(); window.close(); childWindow.on('closed', () => { expect(() => { BrowserWindow.getFocusedWindow(); }).to.not.throw(); done(); }); }); }); it('should not affect the show option', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w }); expect(c.isVisible()).to.be.false('child is visible'); expect(c.getParentWindow()!.isVisible()).to.be.false('parent is visible'); }); }); describe('win.setParentWindow(parent)', () => { it('sets parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getParentWindow()).to.be.null('w.parent'); expect(c.getParentWindow()).to.be.null('c.parent'); c.setParentWindow(w); expect(c.getParentWindow()).to.equal(w); c.setParentWindow(null); expect(c.getParentWindow()).to.be.null('c.parent'); }); it('adds window to child windows of parent', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); expect(w.getChildWindows()).to.deep.equal([]); c.setParentWindow(w); expect(w.getChildWindows()).to.deep.equal([c]); c.setParentWindow(null); expect(w.getChildWindows()).to.deep.equal([]); }); it('removes from child windows of parent when window is closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false }); const closed = emittedOnce(c, 'closed'); c.setParentWindow(w); c.close(); await closed; // The child window list is not immediately cleared, so wait a tick until it's ready. await delay(); expect(w.getChildWindows().length).to.equal(0); }); }); describe('modal option', () => { it('does not freeze or crash', async () => { const parentWindow = new BrowserWindow(); const createTwo = async () => { const two = new BrowserWindow({ width: 300, height: 200, parent: parentWindow, modal: true, show: false }); const twoShown = emittedOnce(two, 'show'); two.show(); await twoShown; setTimeout(() => two.close(), 500); await emittedOnce(two, 'closed'); }; const one = new BrowserWindow({ width: 600, height: 400, parent: parentWindow, modal: true, show: false }); const oneShown = emittedOnce(one, 'show'); one.show(); await oneShown; setTimeout(() => one.destroy(), 500); await emittedOnce(one, 'closed'); await createTwo(); }); ifit(process.platform !== 'darwin')('disables parent window', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); expect(w.isEnabled()).to.be.true('w.isEnabled'); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('re-enables an enabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.true('w.isEnabled'); }); ifit(process.platform !== 'darwin')('does not re-enable a disabled parent window when closed', async () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const closed = emittedOnce(c, 'closed'); w.setEnabled(false); c.show(); c.close(); await closed; expect(w.isEnabled()).to.be.false('w.isEnabled'); }); ifit(process.platform !== 'darwin')('disables parent window recursively', () => { const w = new BrowserWindow({ show: false }); const c = new BrowserWindow({ show: false, parent: w, modal: true }); const c2 = new BrowserWindow({ show: false, parent: w, modal: true }); c.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.show(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c.destroy(); expect(w.isEnabled()).to.be.false('w.isEnabled'); c2.destroy(); expect(w.isEnabled()).to.be.true('w.isEnabled'); }); }); }); describe('window states', () => { afterEach(closeAllWindows); it('does not resize frameless windows when states change', () => { const w = new BrowserWindow({ frame: false, width: 300, height: 200, show: false }); w.minimizable = false; w.minimizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.resizable = false; w.resizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.maximizable = false; w.maximizable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.fullScreenable = false; w.fullScreenable = true; expect(w.getSize()).to.deep.equal([300, 200]); w.closable = false; w.closable = true; expect(w.getSize()).to.deep.equal([300, 200]); }); describe('resizable state', () => { it('with properties', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.resizable).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.maximizable).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); w.resizable = false; expect(w.resizable).to.be.false('resizable'); w.resizable = true; expect(w.resizable).to.be.true('resizable'); }); }); it('with functions', () => { it('can be set with resizable constructor option', () => { const w = new BrowserWindow({ show: false, resizable: false }); expect(w.isResizable()).to.be.false('resizable'); if (process.platform === 'darwin') { expect(w.isMaximizable()).to.to.true('maximizable'); } }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isResizable()).to.be.true('resizable'); w.setResizable(false); expect(w.isResizable()).to.be.false('resizable'); w.setResizable(true); expect(w.isResizable()).to.be.true('resizable'); }); }); it('works for a frameless window', () => { const w = new BrowserWindow({ show: false, frame: false }); expect(w.resizable).to.be.true('resizable'); if (process.platform === 'win32') { const w = new BrowserWindow({ show: false, thickFrame: false }); expect(w.resizable).to.be.false('resizable'); } }); // On Linux there is no "resizable" property of a window. ifit(process.platform !== 'linux')('does affect maximizability when disabled and enabled', () => { const w = new BrowserWindow({ show: false }); expect(w.resizable).to.be.true('resizable'); expect(w.maximizable).to.be.true('maximizable'); w.resizable = false; expect(w.maximizable).to.be.false('not maximizable'); w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); ifit(process.platform === 'win32')('works for a window smaller than 64x64', () => { const w = new BrowserWindow({ show: false, frame: false, resizable: false, transparent: true }); w.setContentSize(60, 60); expectBoundsEqual(w.getContentSize(), [60, 60]); w.setContentSize(30, 30); expectBoundsEqual(w.getContentSize(), [30, 30]); w.setContentSize(10, 10); expectBoundsEqual(w.getContentSize(), [10, 10]); }); }); describe('loading main frame state', () => { let server: http.Server = null as unknown as http.Server; let serverUrl: string = null as unknown as string; before((done) => { server = http.createServer((request, response) => { response.end(); }).listen(0, '127.0.0.1', () => { serverUrl = 'http://127.0.0.1:' + (server.address() as AddressInfo).port; done(); }); }); after(() => { server.close(); }); it('is true when the main frame is loading', async () => { const w = new BrowserWindow({ show: false }); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(serverUrl); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); it('is false when only a subframe is loading', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.executeJavaScript(` var iframe = document.createElement('iframe') iframe.src = '${serverUrl}/page2' document.body.appendChild(iframe) `); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); }); it('is true when navigating to pages from the same origin', async () => { const w = new BrowserWindow({ show: false }); const didStopLoading = emittedOnce(w.webContents, 'did-stop-loading'); w.webContents.loadURL(serverUrl); await didStopLoading; expect(w.webContents.isLoadingMainFrame()).to.be.false('isLoadingMainFrame'); const didStartLoading = emittedOnce(w.webContents, 'did-start-loading'); w.webContents.loadURL(`${serverUrl}/page2`); await didStartLoading; expect(w.webContents.isLoadingMainFrame()).to.be.true('isLoadingMainFrame'); }); }); }); ifdescribe(process.platform !== 'linux')('window states (excluding Linux)', () => { // Not implemented on Linux. afterEach(closeAllWindows); describe('movable state', () => { it('with properties', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.movable).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.movable).to.be.true('movable'); w.movable = false; expect(w.movable).to.be.false('movable'); w.movable = true; expect(w.movable).to.be.true('movable'); }); }); it('with functions', () => { it('can be set with movable constructor option', () => { const w = new BrowserWindow({ show: false, movable: false }); expect(w.isMovable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMovable()).to.be.true('movable'); w.setMovable(false); expect(w.isMovable()).to.be.false('movable'); w.setMovable(true); expect(w.isMovable()).to.be.true('movable'); }); }); }); describe('visibleOnAllWorkspaces state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.visibleOnAllWorkspaces).to.be.false(); w.visibleOnAllWorkspaces = true; expect(w.visibleOnAllWorkspaces).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isVisibleOnAllWorkspaces()).to.be.false(); w.setVisibleOnAllWorkspaces(true); expect(w.isVisibleOnAllWorkspaces()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('documentEdited state', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.documentEdited).to.be.false(); w.documentEdited = true; expect(w.documentEdited).to.be.true(); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isDocumentEdited()).to.be.false(); w.setDocumentEdited(true); expect(w.isDocumentEdited()).to.be.true(); }); }); }); ifdescribe(process.platform === 'darwin')('representedFilename', () => { it('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.representedFilename).to.eql(''); w.representedFilename = 'a name'; expect(w.representedFilename).to.eql('a name'); }); }); it('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getRepresentedFilename()).to.eql(''); w.setRepresentedFilename('a name'); expect(w.getRepresentedFilename()).to.eql('a name'); }); }); }); describe('native window title', () => { it('with properties', () => { it('can be set with title constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.title).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.title).to.eql('Electron Test Main'); w.title = 'NEW TITLE'; expect(w.title).to.eql('NEW TITLE'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, title: 'mYtItLe' }); expect(w.getTitle()).to.eql('mYtItLe'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.getTitle()).to.eql('Electron Test Main'); w.setTitle('NEW TITLE'); expect(w.getTitle()).to.eql('NEW TITLE'); }); }); }); describe('minimizable state', () => { it('with properties', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.minimizable).to.be.false('minimizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.minimizable).to.be.true('minimizable'); w.minimizable = false; expect(w.minimizable).to.be.false('minimizable'); w.minimizable = true; expect(w.minimizable).to.be.true('minimizable'); }); }); it('with functions', () => { it('can be set with minimizable constructor option', () => { const w = new BrowserWindow({ show: false, minimizable: false }); expect(w.isMinimizable()).to.be.false('movable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMinimizable()).to.be.true('isMinimizable'); w.setMinimizable(false); expect(w.isMinimizable()).to.be.false('isMinimizable'); w.setMinimizable(true); expect(w.isMinimizable()).to.be.true('isMinimizable'); }); }); }); describe('maximizable state (property)', () => { it('with properties', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.maximizable).to.be.false('maximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.maximizable).to.be.true('maximizable'); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; expect(w.maximizable).to.be.false('maximizable'); w.minimizable = false; expect(w.maximizable).to.be.false('maximizable'); w.closable = false; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; expect(w.maximizable).to.be.true('maximizable'); w.closable = true; expect(w.maximizable).to.be.true('maximizable'); w.fullScreenable = false; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('can be set with maximizable constructor option', () => { const w = new BrowserWindow({ show: false, maximizable: false }); expect(w.isMaximizable()).to.be.false('isMaximizable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); it('is not affected when changing other states', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMinimizable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setClosable(false); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setClosable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); w.setFullScreenable(false); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform === 'win32')('maximizable state', () => { it('with properties', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.maximizable = false; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.false('maximizable'); w.maximizable = true; w.resizable = false; w.resizable = true; expect(w.maximizable).to.be.true('maximizable'); }); }); it('with functions', () => { it('is reset to its former state', () => { const w = new BrowserWindow({ show: false }); w.setMaximizable(false); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.false('isMaximizable'); w.setMaximizable(true); w.setResizable(false); w.setResizable(true); expect(w.isMaximizable()).to.be.true('isMaximizable'); }); }); }); ifdescribe(process.platform !== 'darwin')('menuBarVisible state', () => { describe('with properties', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.menuBarVisible).to.be.true(); w.menuBarVisible = false; expect(w.menuBarVisible).to.be.false(); w.menuBarVisible = true; expect(w.menuBarVisible).to.be.true(); }); }); describe('with functions', () => { it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); w.setMenuBarVisibility(false); expect(w.isMenuBarVisible()).to.be.false('isMenuBarVisible'); w.setMenuBarVisibility(true); expect(w.isMenuBarVisible()).to.be.true('isMenuBarVisible'); }); }); }); ifdescribe(process.platform === 'darwin')('fullscreenable state', () => { it('with functions', () => { it('can be set with fullscreenable constructor option', () => { const w = new BrowserWindow({ show: false, fullscreenable: false }); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); w.setFullScreenable(false); expect(w.isFullScreenable()).to.be.false('isFullScreenable'); w.setFullScreenable(true); expect(w.isFullScreenable()).to.be.true('isFullScreenable'); }); }); }); // fullscreen events are dispatched eagerly and twiddling things too fast can confuse poor Electron ifdescribe(process.platform === 'darwin')('kiosk state', () => { it('with properties', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.kiosk).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.kiosk = true; expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.kiosk = false; expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); it('with functions', () => { it('can be set with a constructor property', () => { const w = new BrowserWindow({ kiosk: true }); expect(w.isKiosk()).to.be.true(); }); it('can be changed ', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setKiosk(true); expect(w.isKiosk()).to.be.true('isKiosk'); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setKiosk(false); expect(w.isKiosk()).to.be.false('isKiosk'); await leaveFullScreen; }); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state with resizable set', () => { it('resizable flag should be set to false and restored', async () => { const w = new BrowserWindow({ resizable: false }); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.false('resizable'); }); it('default resizable flag should be restored after entering/exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.resizable).to.be.false('resizable'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.resizable).to.be.true('resizable'); }); }); ifdescribe(process.platform === 'darwin')('fullscreen state', () => { it('should not cause a crash if called when exiting fullscreen', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; }); it('can be changed with setFullScreen method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); it('handles several transitions starting with fullscreen', async () => { const w = new BrowserWindow({ fullscreen: true, show: true }); expect(w.isFullScreen()).to.be.true('not fullscreen'); w.setFullScreen(false); w.setFullScreen(true); const enterFullScreen = emittedNTimes(w, 'enter-full-screen', 2); await enterFullScreen; expect(w.isFullScreen()).to.be.true('not fullscreen'); await delay(); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several HTML fullscreen transitions', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); await delay(); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await enterFullScreen; await w.webContents.executeJavaScript('document.exitFullscreen()', true); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('is fullscreen'); }); it('handles several transitions in close proximity', async () => { const w = new BrowserWindow(); expect(w.isFullScreen()).to.be.false('is fullscreen'); const enterFS = emittedNTimes(w, 'enter-full-screen', 2); const leaveFS = emittedNTimes(w, 'leave-full-screen', 2); w.setFullScreen(true); w.setFullScreen(false); w.setFullScreen(true); w.setFullScreen(false); await Promise.all([enterFS, leaveFS]); expect(w.isFullScreen()).to.be.false('not fullscreen'); }); it('handles several chromium-initiated transitions in close proximity', async () => { const w = new BrowserWindow(); await w.loadFile(path.join(fixtures, 'pages', 'a.html')); expect(w.isFullScreen()).to.be.false('is fullscreen'); let enterCount = 0; let exitCount = 0; const done = new Promise<void>(resolve => { const checkDone = () => { if (enterCount === 2 && exitCount === 2) resolve(); }; w.webContents.on('enter-html-full-screen', () => { enterCount++; checkDone(); }); w.webContents.on('leave-html-full-screen', () => { exitCount++; checkDone(); }); }); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await w.webContents.executeJavaScript('document.getElementById("div").requestFullscreen()', true); await w.webContents.executeJavaScript('document.exitFullscreen()'); await done; }); it('does not crash when exiting simpleFullScreen (properties)', async () => { const w = new BrowserWindow(); w.setSimpleFullScreen(true); await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('does not crash when exiting simpleFullScreen (functions)', async () => { const w = new BrowserWindow(); w.simpleFullScreen = true; await delay(1000); w.setFullScreen(!w.isFullScreen()); }); it('should not be changed by setKiosk method', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); w.setKiosk(true); await delay(); w.setKiosk(false); expect(w.isFullScreen()).to.be.true('isFullScreen'); const leaveFullScreen = emittedOnce(w, 'leave-full-screen'); w.setFullScreen(false); await leaveFullScreen; expect(w.isFullScreen()).to.be.false('isFullScreen'); }); // FIXME: https://github.com/electron/electron/issues/30140 xit('multiple windows inherit correct fullscreen state', async () => { const w = new BrowserWindow(); const enterFullScreen = emittedOnce(w, 'enter-full-screen'); w.setFullScreen(true); await enterFullScreen; expect(w.isFullScreen()).to.be.true('isFullScreen'); await delay(); const w2 = new BrowserWindow({ show: false }); const enterFullScreen2 = emittedOnce(w2, 'enter-full-screen'); w2.show(); await enterFullScreen2; expect(w2.isFullScreen()).to.be.true('isFullScreen'); }); }); describe('closable state', () => { it('with properties', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.closable).to.be.false('closable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.closable).to.be.true('closable'); w.closable = false; expect(w.closable).to.be.false('closable'); w.closable = true; expect(w.closable).to.be.true('closable'); }); }); it('with functions', () => { it('can be set with closable constructor option', () => { const w = new BrowserWindow({ show: false, closable: false }); expect(w.isClosable()).to.be.false('isClosable'); }); it('can be changed', () => { const w = new BrowserWindow({ show: false }); expect(w.isClosable()).to.be.true('isClosable'); w.setClosable(false); expect(w.isClosable()).to.be.false('isClosable'); w.setClosable(true); expect(w.isClosable()).to.be.true('isClosable'); }); }); }); describe('hasShadow state', () => { it('with properties', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); expect(w.shadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.shadow).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); w.shadow = true; expect(w.shadow).to.be.true('hasShadow'); w.shadow = false; expect(w.shadow).to.be.false('hasShadow'); }); }); describe('with functions', () => { it('returns a boolean on all platforms', () => { const w = new BrowserWindow({ show: false }); const hasShadow = w.hasShadow(); expect(hasShadow).to.be.a('boolean'); }); // On Windows there's no shadow by default & it can't be changed dynamically. it('can be changed with hasShadow option', () => { const hasShadow = process.platform !== 'darwin'; const w = new BrowserWindow({ show: false, hasShadow }); expect(w.hasShadow()).to.equal(hasShadow); }); it('can be changed with setHasShadow method', () => { const w = new BrowserWindow({ show: false }); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); w.setHasShadow(true); expect(w.hasShadow()).to.be.true('hasShadow'); w.setHasShadow(false); expect(w.hasShadow()).to.be.false('hasShadow'); }); }); }); }); describe('window.getMediaSourceId()', () => { afterEach(closeAllWindows); it('returns valid source id', async () => { const w = new BrowserWindow({ show: false }); const shown = emittedOnce(w, 'show'); w.show(); await shown; // Check format 'window:1234:0'. const sourceId = w.getMediaSourceId(); expect(sourceId).to.match(/^window:\d+:\d+$/); }); }); ifdescribe(!process.env.ELECTRON_SKIP_NATIVE_MODULE_TESTS)('window.getNativeWindowHandle()', () => { afterEach(closeAllWindows); it('returns valid handle', () => { const w = new BrowserWindow({ show: false }); // The module's source code is hosted at // https://github.com/electron/node-is-valid-window const isValidWindow = require('is-valid-window'); expect(isValidWindow(w.getNativeWindowHandle())).to.be.true('is valid window'); }); }); ifdescribe(process.platform === 'darwin')('previewFile', () => { afterEach(closeAllWindows); it('opens the path in Quick Look on macOS', () => { const w = new BrowserWindow({ show: false }); expect(() => { w.previewFile(__filename); w.closeFilePreview(); }).to.not.throw(); }); }); describe('contextIsolation option with and without sandbox option', () => { const expectedContextData = { preloadContext: { preloadProperty: 'number', pageProperty: 'undefined', typeofRequire: 'function', typeofProcess: 'object', typeofArrayPush: 'function', typeofFunctionApply: 'function', typeofPreloadExecuteJavaScriptProperty: 'undefined' }, pageContext: { preloadProperty: 'undefined', pageProperty: 'string', typeofRequire: 'undefined', typeofProcess: 'undefined', typeofArrayPush: 'number', typeofFunctionApply: 'boolean', typeofPreloadExecuteJavaScriptProperty: 'number', typeofOpenedWindow: 'object' } }; afterEach(closeAllWindows); it('separates the page context from the Electron/preload context', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await iw.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); iw.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('enables context isolation on child windows', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const browserWindowCreated = emittedOnce(app, 'browser-window-created'); iw.loadFile(path.join(fixtures, 'pages', 'window-open.html')); const [, window] = await browserWindowCreated; expect(window.webContents.getLastWebPreferences().contextIsolation).to.be.true('contextIsolation'); }); it('separates the page context from the Electron/preload context with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const [, data] = await p; expect(data).to.deep.equal(expectedContextData); }); it('recreates the contexts on reload with sandbox on', async () => { const ws = new BrowserWindow({ show: false, webPreferences: { sandbox: true, contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); await ws.loadFile(path.join(fixtures, 'api', 'isolated.html')); const isolatedWorld = emittedOnce(ipcMain, 'isolated-world'); ws.webContents.reload(); const [, data] = await isolatedWorld; expect(data).to.deep.equal(expectedContextData); }); it('supports fetch api', async () => { const fetchWindow = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-fetch-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-fetch-error'); fetchWindow.loadURL('about:blank'); const [, error] = await p; expect(error).to.equal('Failed to fetch'); }); it('doesn\'t break ipc serialization', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-preload.js') } }); const p = emittedOnce(ipcMain, 'isolated-world'); iw.loadURL('about:blank'); iw.webContents.executeJavaScript(` const opened = window.open() openedLocation = opened.location.href opened.close() window.postMessage({openedLocation}, '*') `); const [, data] = await p; expect(data.pageContext.openedLocation).to.equal('about:blank'); }); it('reports process.contextIsolated', async () => { const iw = new BrowserWindow({ show: false, webPreferences: { contextIsolation: true, preload: path.join(fixtures, 'api', 'isolated-process.js') } }); const p = emittedOnce(ipcMain, 'context-isolation'); iw.loadURL('about:blank'); const [, contextIsolation] = await p; expect(contextIsolation).to.be.true('contextIsolation'); }); }); it('reloading does not cause Node.js module API hangs after reload', (done) => { const w = new BrowserWindow({ show: false, webPreferences: { nodeIntegration: true, contextIsolation: false } }); let count = 0; ipcMain.on('async-node-api-done', () => { if (count === 3) { ipcMain.removeAllListeners('async-node-api-done'); done(); } else { count++; w.reload(); } }); w.loadFile(path.join(fixtures, 'pages', 'send-after-node.html')); }); describe('window.webContents.focus()', () => { afterEach(closeAllWindows); it('focuses window', async () => { const w1 = new BrowserWindow({ x: 100, y: 300, width: 300, height: 200 }); w1.loadURL('about:blank'); const w2 = new BrowserWindow({ x: 300, y: 300, width: 300, height: 200 }); w2.loadURL('about:blank'); const w1Focused = emittedOnce(w1, 'focus'); w1.webContents.focus(); await w1Focused; expect(w1.webContents.isFocused()).to.be.true('focuses window'); }); }); ifdescribe(features.isOffscreenRenderingEnabled())('offscreen rendering', () => { let w: BrowserWindow; beforeEach(function () { w = new BrowserWindow({ width: 100, height: 100, show: false, webPreferences: { backgroundThrottling: false, offscreen: true } }); }); afterEach(closeAllWindows); it('creates offscreen window with correct size', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); const [,, data] = await paint; expect(data.constructor.name).to.equal('NativeImage'); expect(data.isEmpty()).to.be.false('data is empty'); const size = data.getSize(); const { scaleFactor } = screen.getPrimaryDisplay(); expect(size.width).to.be.closeTo(100 * scaleFactor, 2); expect(size.height).to.be.closeTo(100 * scaleFactor, 2); }); it('does not crash after navigation', () => { w.webContents.loadURL('about:blank'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); }); describe('window.webContents.isOffscreen()', () => { it('is true for offscreen type', () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); expect(w.webContents.isOffscreen()).to.be.true('isOffscreen'); }); it('is false for regular window', () => { const c = new BrowserWindow({ show: false }); expect(c.webContents.isOffscreen()).to.be.false('isOffscreen'); c.destroy(); }); }); describe('window.webContents.isPainting()', () => { it('returns whether is currently painting', async () => { const paint = emittedOnce(w.webContents, 'paint'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await paint; expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('window.webContents.stopPainting()', () => { it('stops painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); expect(w.webContents.isPainting()).to.be.false('isPainting'); }); }); describe('window.webContents.startPainting()', () => { it('starts painting', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.stopPainting(); w.webContents.startPainting(); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.isPainting()).to.be.true('isPainting'); }); }); describe('frameRate APIs', () => { it('has default frame rate (function)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(60); }); it('has default frame rate (property)', async () => { w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(60); }); it('sets custom frame rate (function)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.setFrameRate(30); await emittedOnce(w.webContents, 'paint'); expect(w.webContents.getFrameRate()).to.equal(30); }); it('sets custom frame rate (property)', async () => { const domReady = emittedOnce(w.webContents, 'dom-ready'); w.loadFile(path.join(fixtures, 'api', 'offscreen-rendering.html')); await domReady; w.webContents.frameRate = 30; await emittedOnce(w.webContents, 'paint'); expect(w.webContents.frameRate).to.equal(30); }); }); }); describe('"transparent" option', () => { afterEach(closeAllWindows); // Only applicable on Windows where transparent windows can't be maximized. ifit(process.platform === 'win32')('can show maximized frameless window', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, frame: false, transparent: true, show: true }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); expect(w.isMaximized()).to.be.true(); // Fails when the transparent HWND is in an invalid maximized state. expect(w.getBounds()).to.deep.equal(display.workArea); const newBounds = { width: 256, height: 256, x: 0, y: 0 }; w.setBounds(newBounds); expect(w.getBounds()).to.deep.equal(newBounds); }); // Linux and arm64 platforms (WOA and macOS) do not return any capture sources ifit(process.platform !== 'linux' && process.arch !== 'arm64')('should not display a visible background', async () => { const display = screen.getPrimaryDisplay(); const backgroundWindow = new BrowserWindow({ ...display.bounds, frame: false, backgroundColor: CHROMA_COLOR_HEX, hasShadow: false }); await backgroundWindow.loadURL('about:blank'); const foregroundWindow = new BrowserWindow({ ...display.bounds, show: true, transparent: true, frame: false, hasShadow: false }); foregroundWindow.loadFile(path.join(__dirname, 'fixtures', 'pages', 'half-background-color.html')); await emittedOnce(foregroundWindow, 'ready-to-show'); const screenCapture = await captureScreen(); const leftHalfColor = getPixelColor(screenCapture, { x: display.size.width / 4, y: display.size.height / 2 }); const rightHalfColor = getPixelColor(screenCapture, { x: display.size.width - (display.size.width / 4), y: display.size.height / 2 }); expect(areColorsSimilar(leftHalfColor, CHROMA_COLOR_HEX)).to.be.true(); expect(areColorsSimilar(rightHalfColor, '#ff0000')).to.be.true(); }); }); describe('"backgroundColor" option', () => { afterEach(closeAllWindows); // Linux/WOA doesn't return any capture sources. ifit(process.platform !== 'linux' && (process.platform !== 'win32' || process.arch !== 'arm64'))('should display the set color', async () => { const display = screen.getPrimaryDisplay(); const w = new BrowserWindow({ ...display.bounds, show: true, backgroundColor: CHROMA_COLOR_HEX }); w.loadURL('about:blank'); await emittedOnce(w, 'ready-to-show'); const screenCapture = await captureScreen(); const centerColor = getPixelColor(screenCapture, { x: display.size.width / 2, y: display.size.height / 2 }); expect(areColorsSimilar(centerColor, CHROMA_COLOR_HEX)).to.be.true(); }); }); });
closed
electron/electron
https://github.com/electron/electron
34,813
[Bug]: Can not print contents of browser window silently in Ubuntu linux
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.3 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version none ### Expected Behavior I want to print the contents of browser window silently on a POS printer. The code attached at Gist section works fine on windows, but doesn't work in Ubuntu. My targeted platform is ubuntu linux 20.04 and above ### Actual Behavior The output at the console for the Gist is : Console ready 🔬 Saving files to temp directory... Saved files to /tmp/tmp-17209-xBE03rN99Kka Electron v18.2.3 started. libva error: /usr/lib/x86_64-linux-gnu/dri/iHD_drv_video.so init failed [19927:0702/212214.938092:ERROR:sandbox_linux.cc(377)] InitializeSandbox() called with multiple threads in process gpu-process. [ { name: 'DCP-7030', displayName: 'DCP-7030', description: 'Brother DCP-7030', status: 5, isDefault: false, options: { copies: '1', 'device-uri': 'usb://Brother/DCP-7030?serial=000D0N969645', finishings: '3', 'job-cancel-after': '10800', 'job-hold-until': 'no-hold', 'job-priority': '50', 'job-sheets': 'none,none', 'marker-change-time': '0', 'number-up': '1', 'printer-commands': 'none', 'printer-info': 'Brother DCP-7030', 'printer-is-accepting-jobs': 'true', 'printer-is-shared': 'true', 'printer-is-temporary': 'false', 'printer-location': 'embeddedSaugat', 'printer-make-and-model': 'Brother DCP-7030, using brlaser v6', 'printer-state': '5', 'printer-state-change-time': '1651417533', 'printer-state-reasons': 'paused', 'printer-type': '4164', 'printer-uri-supported': 'ipp://localhost/printers/DCP-7030', system_driverinfo: 'Brother DCP-7030, using brlaser v6' } }, { name: 'POS80QMS', displayName: 'POS80QMS', description: '80mm printer for QMS Project', status: 3, isDefault: true, options: { copies: '1', 'device-uri': 'usb://Unknown/Printer', finishings: '3', 'job-cancel-after': '10800', 'job-hold-until': 'no-hold', 'job-priority': '50', 'job-sheets': 'none,none', 'marker-change-time': '0', 'number-up': '1', 'printer-commands': 'none', 'printer-info': '80mm printer for QMS Project', 'printer-is-accepting-jobs': 'true', 'printer-is-shared': 'false', 'printer-is-temporary': 'false', 'printer-location': 'holus', 'printer-make-and-model': 'POS-80', 'printer-state': '3', 'printer-state-change-time': '1655307054', 'printer-state-reasons': 'none', 'printer-type': '2248708', 'printer-uri-supported': 'ipp://localhost/printers/POS80QMS', system_driverinfo: 'POS-80' } } ] (node:19895) electron: Deprecation Warning: getPrinters() is deprecated. Use the asynchronous and non-blocking version, getPrintersAsync(), instead. (Use `electron --trace-warnings ...` to show where the warning was created) failed [19895:0702/212216.612479:ERROR:print_view_manager_base.cc(85)] Invalid printer settings The selected printer is not available or not installed correctly. <br> Check your printer or try selecting another printer. Electron exited with code 0. ### Testcase Gist URL https://gist.github.com/saugatdai/5ba400d42e3fa4be66d323b2d826fe50 ### Additional Information My project is not going to production because of this problem. Please help with some solutions and suggestions.
https://github.com/electron/electron/issues/34813
https://github.com/electron/electron/pull/34893
eb8c9452cb38b6bd32bdc92724cc1fb42a3d43dc
05d4966251580cd4ae95479ccbbfdd5e8a70702f
2022-07-02T15:55:59Z
c++
2022-07-19T12:46:08Z
shell/browser/printing/print_view_manager_electron.cc
// Copyright 2020 Microsoft, Inc. All rights reserved. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/printing/print_view_manager_electron.h" #include <utility> #include "build/build_config.h" #include "components/printing/browser/print_to_pdf/pdf_print_utils.h" #include "printing/mojom/print.mojom.h" #include "printing/page_range.h" #include "third_party/abseil-cpp/absl/types/variant.h" #if BUILDFLAG(ENABLE_PRINT_PREVIEW) #include "mojo/public/cpp/bindings/message.h" #endif namespace electron { namespace { #if BUILDFLAG(ENABLE_PRINT_PREVIEW) constexpr char kInvalidUpdatePrintSettingsCall[] = "Invalid UpdatePrintSettings Call"; constexpr char kInvalidSetupScriptedPrintPreviewCall[] = "Invalid SetupScriptedPrintPreview Call"; constexpr char kInvalidShowScriptedPrintPreviewCall[] = "Invalid ShowScriptedPrintPreview Call"; constexpr char kInvalidRequestPrintPreviewCall[] = "Invalid RequestPrintPreview Call"; #endif } // namespace // This file subclasses printing::PrintViewManagerBase // but the implementations are duplicated from // components/printing/browser/print_to_pdf/pdf_print_manager.cc. PrintViewManagerElectron::PrintViewManagerElectron( content::WebContents* web_contents) : printing::PrintViewManagerBase(web_contents), content::WebContentsUserData<PrintViewManagerElectron>(*web_contents) {} PrintViewManagerElectron::~PrintViewManagerElectron() = default; // static void PrintViewManagerElectron::BindPrintManagerHost( mojo::PendingAssociatedReceiver<printing::mojom::PrintManagerHost> receiver, content::RenderFrameHost* rfh) { auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); if (!web_contents) return; auto* print_manager = PrintViewManagerElectron::FromWebContents(web_contents); if (!print_manager) return; print_manager->BindReceiver(std::move(receiver), rfh); } // static std::string PrintViewManagerElectron::PrintResultToString(PrintResult result) { switch (result) { case PRINT_SUCCESS: return std::string(); // no error message case PRINTING_FAILED: return "Printing failed"; case INVALID_PRINTER_SETTINGS: return "Show invalid printer settings error"; case INVALID_MEMORY_HANDLE: return "Invalid memory handle"; case METAFILE_MAP_ERROR: return "Map to shared memory error"; case METAFILE_INVALID_HEADER: return "Invalid metafile header"; case METAFILE_GET_DATA_ERROR: return "Get data from metafile error"; case SIMULTANEOUS_PRINT_ACTIVE: return "The previous printing job hasn't finished"; case PAGE_RANGE_SYNTAX_ERROR: return "Page range syntax error"; case PAGE_RANGE_INVALID_RANGE: return "Page range is invalid (start > end)"; case PAGE_COUNT_EXCEEDED: return "Page range exceeds page count"; default: NOTREACHED(); return "Unknown PrintResult"; } } void PrintViewManagerElectron::PrintToPdf( content::RenderFrameHost* rfh, const std::string& page_ranges, printing::mojom::PrintPagesParamsPtr print_pages_params, PrintToPDFCallback callback) { DCHECK(callback); if (callback_) { std::move(callback).Run(SIMULTANEOUS_PRINT_ACTIVE, base::MakeRefCounted<base::RefCountedString>()); return; } if (!rfh->IsRenderFrameLive()) { std::move(callback).Run(PRINTING_FAILED, base::MakeRefCounted<base::RefCountedString>()); return; } absl::variant<printing::PageRanges, print_to_pdf::PageRangeError> parsed_ranges = print_to_pdf::TextPageRangesToPageRanges(page_ranges); if (absl::holds_alternative<print_to_pdf::PageRangeError>(parsed_ranges)) { PrintResult print_result; switch (absl::get<print_to_pdf::PageRangeError>(parsed_ranges)) { case print_to_pdf::PageRangeError::kSyntaxError: print_result = PAGE_RANGE_SYNTAX_ERROR; break; case print_to_pdf::PageRangeError::kInvalidRange: print_result = PAGE_RANGE_INVALID_RANGE; break; } std::move(callback).Run(print_result, base::MakeRefCounted<base::RefCountedString>()); return; } printing_rfh_ = rfh; print_pages_params->pages = absl::get<printing::PageRanges>(parsed_ranges); auto cookie = print_pages_params->params->document_cookie; set_cookie(cookie); headless_jobs_.emplace_back(cookie); callback_ = std::move(callback); GetPrintRenderFrame(rfh)->PrintWithParams(std::move(print_pages_params)); } void PrintViewManagerElectron::GetDefaultPrintSettings( GetDefaultPrintSettingsCallback callback) { if (printing_rfh_) { LOG(ERROR) << "Scripted print is not supported"; std::move(callback).Run(printing::mojom::PrintParams::New()); } else { PrintViewManagerBase::GetDefaultPrintSettings(std::move(callback)); } } void PrintViewManagerElectron::ScriptedPrint( printing::mojom::ScriptedPrintParamsPtr params, ScriptedPrintCallback callback) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), params->cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::ScriptedPrint(std::move(params), std::move(callback)); return; } auto default_param = printing::mojom::PrintPagesParams::New(); default_param->params = printing::mojom::PrintParams::New(); LOG(ERROR) << "Scripted print is not supported"; std::move(callback).Run(std::move(default_param), /*cancelled*/ false); } void PrintViewManagerElectron::ShowInvalidPrinterSettingsError() { ReleaseJob(INVALID_PRINTER_SETTINGS); } void PrintViewManagerElectron::PrintingFailed( int32_t cookie, printing::mojom::PrintFailureReason reason) { ReleaseJob(reason == printing::mojom::PrintFailureReason::kInvalidPageRange ? PAGE_COUNT_EXCEEDED : PRINTING_FAILED); } #if BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintViewManagerElectron::UpdatePrintSettings( int32_t cookie, base::Value::Dict job_settings, UpdatePrintSettingsCallback callback) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::UpdatePrintSettings(cookie, std::move(job_settings), std::move(callback)); return; } mojo::ReportBadMessage(kInvalidUpdatePrintSettingsCall); } void PrintViewManagerElectron::SetupScriptedPrintPreview( SetupScriptedPrintPreviewCallback callback) { mojo::ReportBadMessage(kInvalidSetupScriptedPrintPreviewCall); } void PrintViewManagerElectron::ShowScriptedPrintPreview( bool source_is_modifiable) { mojo::ReportBadMessage(kInvalidShowScriptedPrintPreviewCall); } void PrintViewManagerElectron::RequestPrintPreview( printing::mojom::RequestPrintPreviewParamsPtr params) { mojo::ReportBadMessage(kInvalidRequestPrintPreviewCall); } void PrintViewManagerElectron::CheckForCancel(int32_t preview_ui_id, int32_t request_id, CheckForCancelCallback callback) { std::move(callback).Run(false); } #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintViewManagerElectron::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { PrintViewManagerBase::RenderFrameDeleted(render_frame_host); if (printing_rfh_ != render_frame_host) return; if (callback_) { std::move(callback_).Run(PRINTING_FAILED, base::MakeRefCounted<base::RefCountedString>()); } Reset(); } void PrintViewManagerElectron::DidGetPrintedPagesCount(int32_t cookie, uint32_t number_pages) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::DidGetPrintedPagesCount(cookie, number_pages); } } void PrintViewManagerElectron::DidPrintDocument( printing::mojom::DidPrintDocumentParamsPtr params, DidPrintDocumentCallback callback) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), params->document_cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::DidPrintDocument(std::move(params), std::move(callback)); return; } auto& content = *params->content; if (!content.metafile_data_region.IsValid()) { ReleaseJob(INVALID_MEMORY_HANDLE); std::move(callback).Run(false); return; } base::ReadOnlySharedMemoryMapping map = content.metafile_data_region.Map(); if (!map.IsValid()) { ReleaseJob(METAFILE_MAP_ERROR); std::move(callback).Run(false); return; } data_ = std::string(static_cast<const char*>(map.memory()), map.size()); headless_jobs_.erase(entry); std::move(callback).Run(true); ReleaseJob(PRINT_SUCCESS); } void PrintViewManagerElectron::Reset() { printing_rfh_ = nullptr; callback_.Reset(); data_.clear(); } void PrintViewManagerElectron::ReleaseJob(PrintResult result) { if (callback_) { DCHECK(result == PRINT_SUCCESS || data_.empty()); std::move(callback_).Run(result, base::RefCountedString::TakeString(&data_)); if (printing_rfh_ && printing_rfh_->IsRenderFrameLive()) { GetPrintRenderFrame(printing_rfh_)->PrintingDone(result == PRINT_SUCCESS); } Reset(); } } WEB_CONTENTS_USER_DATA_KEY_IMPL(PrintViewManagerElectron); } // namespace electron
closed
electron/electron
https://github.com/electron/electron
34,813
[Bug]: Can not print contents of browser window silently in Ubuntu linux
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.2.3 ### What operating system are you using? Ubuntu ### Operating System Version Ubuntu 20.04 ### What arch are you using? x64 ### Last Known Working Electron version none ### Expected Behavior I want to print the contents of browser window silently on a POS printer. The code attached at Gist section works fine on windows, but doesn't work in Ubuntu. My targeted platform is ubuntu linux 20.04 and above ### Actual Behavior The output at the console for the Gist is : Console ready 🔬 Saving files to temp directory... Saved files to /tmp/tmp-17209-xBE03rN99Kka Electron v18.2.3 started. libva error: /usr/lib/x86_64-linux-gnu/dri/iHD_drv_video.so init failed [19927:0702/212214.938092:ERROR:sandbox_linux.cc(377)] InitializeSandbox() called with multiple threads in process gpu-process. [ { name: 'DCP-7030', displayName: 'DCP-7030', description: 'Brother DCP-7030', status: 5, isDefault: false, options: { copies: '1', 'device-uri': 'usb://Brother/DCP-7030?serial=000D0N969645', finishings: '3', 'job-cancel-after': '10800', 'job-hold-until': 'no-hold', 'job-priority': '50', 'job-sheets': 'none,none', 'marker-change-time': '0', 'number-up': '1', 'printer-commands': 'none', 'printer-info': 'Brother DCP-7030', 'printer-is-accepting-jobs': 'true', 'printer-is-shared': 'true', 'printer-is-temporary': 'false', 'printer-location': 'embeddedSaugat', 'printer-make-and-model': 'Brother DCP-7030, using brlaser v6', 'printer-state': '5', 'printer-state-change-time': '1651417533', 'printer-state-reasons': 'paused', 'printer-type': '4164', 'printer-uri-supported': 'ipp://localhost/printers/DCP-7030', system_driverinfo: 'Brother DCP-7030, using brlaser v6' } }, { name: 'POS80QMS', displayName: 'POS80QMS', description: '80mm printer for QMS Project', status: 3, isDefault: true, options: { copies: '1', 'device-uri': 'usb://Unknown/Printer', finishings: '3', 'job-cancel-after': '10800', 'job-hold-until': 'no-hold', 'job-priority': '50', 'job-sheets': 'none,none', 'marker-change-time': '0', 'number-up': '1', 'printer-commands': 'none', 'printer-info': '80mm printer for QMS Project', 'printer-is-accepting-jobs': 'true', 'printer-is-shared': 'false', 'printer-is-temporary': 'false', 'printer-location': 'holus', 'printer-make-and-model': 'POS-80', 'printer-state': '3', 'printer-state-change-time': '1655307054', 'printer-state-reasons': 'none', 'printer-type': '2248708', 'printer-uri-supported': 'ipp://localhost/printers/POS80QMS', system_driverinfo: 'POS-80' } } ] (node:19895) electron: Deprecation Warning: getPrinters() is deprecated. Use the asynchronous and non-blocking version, getPrintersAsync(), instead. (Use `electron --trace-warnings ...` to show where the warning was created) failed [19895:0702/212216.612479:ERROR:print_view_manager_base.cc(85)] Invalid printer settings The selected printer is not available or not installed correctly. <br> Check your printer or try selecting another printer. Electron exited with code 0. ### Testcase Gist URL https://gist.github.com/saugatdai/5ba400d42e3fa4be66d323b2d826fe50 ### Additional Information My project is not going to production because of this problem. Please help with some solutions and suggestions.
https://github.com/electron/electron/issues/34813
https://github.com/electron/electron/pull/34893
eb8c9452cb38b6bd32bdc92724cc1fb42a3d43dc
05d4966251580cd4ae95479ccbbfdd5e8a70702f
2022-07-02T15:55:59Z
c++
2022-07-19T12:46:08Z
shell/browser/printing/print_view_manager_electron.cc
// Copyright 2020 Microsoft, Inc. All rights reserved. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/printing/print_view_manager_electron.h" #include <utility> #include "build/build_config.h" #include "components/printing/browser/print_to_pdf/pdf_print_utils.h" #include "printing/mojom/print.mojom.h" #include "printing/page_range.h" #include "third_party/abseil-cpp/absl/types/variant.h" #if BUILDFLAG(ENABLE_PRINT_PREVIEW) #include "mojo/public/cpp/bindings/message.h" #endif namespace electron { namespace { #if BUILDFLAG(ENABLE_PRINT_PREVIEW) constexpr char kInvalidUpdatePrintSettingsCall[] = "Invalid UpdatePrintSettings Call"; constexpr char kInvalidSetupScriptedPrintPreviewCall[] = "Invalid SetupScriptedPrintPreview Call"; constexpr char kInvalidShowScriptedPrintPreviewCall[] = "Invalid ShowScriptedPrintPreview Call"; constexpr char kInvalidRequestPrintPreviewCall[] = "Invalid RequestPrintPreview Call"; #endif } // namespace // This file subclasses printing::PrintViewManagerBase // but the implementations are duplicated from // components/printing/browser/print_to_pdf/pdf_print_manager.cc. PrintViewManagerElectron::PrintViewManagerElectron( content::WebContents* web_contents) : printing::PrintViewManagerBase(web_contents), content::WebContentsUserData<PrintViewManagerElectron>(*web_contents) {} PrintViewManagerElectron::~PrintViewManagerElectron() = default; // static void PrintViewManagerElectron::BindPrintManagerHost( mojo::PendingAssociatedReceiver<printing::mojom::PrintManagerHost> receiver, content::RenderFrameHost* rfh) { auto* web_contents = content::WebContents::FromRenderFrameHost(rfh); if (!web_contents) return; auto* print_manager = PrintViewManagerElectron::FromWebContents(web_contents); if (!print_manager) return; print_manager->BindReceiver(std::move(receiver), rfh); } // static std::string PrintViewManagerElectron::PrintResultToString(PrintResult result) { switch (result) { case PRINT_SUCCESS: return std::string(); // no error message case PRINTING_FAILED: return "Printing failed"; case INVALID_PRINTER_SETTINGS: return "Show invalid printer settings error"; case INVALID_MEMORY_HANDLE: return "Invalid memory handle"; case METAFILE_MAP_ERROR: return "Map to shared memory error"; case METAFILE_INVALID_HEADER: return "Invalid metafile header"; case METAFILE_GET_DATA_ERROR: return "Get data from metafile error"; case SIMULTANEOUS_PRINT_ACTIVE: return "The previous printing job hasn't finished"; case PAGE_RANGE_SYNTAX_ERROR: return "Page range syntax error"; case PAGE_RANGE_INVALID_RANGE: return "Page range is invalid (start > end)"; case PAGE_COUNT_EXCEEDED: return "Page range exceeds page count"; default: NOTREACHED(); return "Unknown PrintResult"; } } void PrintViewManagerElectron::PrintToPdf( content::RenderFrameHost* rfh, const std::string& page_ranges, printing::mojom::PrintPagesParamsPtr print_pages_params, PrintToPDFCallback callback) { DCHECK(callback); if (callback_) { std::move(callback).Run(SIMULTANEOUS_PRINT_ACTIVE, base::MakeRefCounted<base::RefCountedString>()); return; } if (!rfh->IsRenderFrameLive()) { std::move(callback).Run(PRINTING_FAILED, base::MakeRefCounted<base::RefCountedString>()); return; } absl::variant<printing::PageRanges, print_to_pdf::PageRangeError> parsed_ranges = print_to_pdf::TextPageRangesToPageRanges(page_ranges); if (absl::holds_alternative<print_to_pdf::PageRangeError>(parsed_ranges)) { PrintResult print_result; switch (absl::get<print_to_pdf::PageRangeError>(parsed_ranges)) { case print_to_pdf::PageRangeError::kSyntaxError: print_result = PAGE_RANGE_SYNTAX_ERROR; break; case print_to_pdf::PageRangeError::kInvalidRange: print_result = PAGE_RANGE_INVALID_RANGE; break; } std::move(callback).Run(print_result, base::MakeRefCounted<base::RefCountedString>()); return; } printing_rfh_ = rfh; print_pages_params->pages = absl::get<printing::PageRanges>(parsed_ranges); auto cookie = print_pages_params->params->document_cookie; set_cookie(cookie); headless_jobs_.emplace_back(cookie); callback_ = std::move(callback); GetPrintRenderFrame(rfh)->PrintWithParams(std::move(print_pages_params)); } void PrintViewManagerElectron::GetDefaultPrintSettings( GetDefaultPrintSettingsCallback callback) { if (printing_rfh_) { LOG(ERROR) << "Scripted print is not supported"; std::move(callback).Run(printing::mojom::PrintParams::New()); } else { PrintViewManagerBase::GetDefaultPrintSettings(std::move(callback)); } } void PrintViewManagerElectron::ScriptedPrint( printing::mojom::ScriptedPrintParamsPtr params, ScriptedPrintCallback callback) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), params->cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::ScriptedPrint(std::move(params), std::move(callback)); return; } auto default_param = printing::mojom::PrintPagesParams::New(); default_param->params = printing::mojom::PrintParams::New(); LOG(ERROR) << "Scripted print is not supported"; std::move(callback).Run(std::move(default_param), /*cancelled*/ false); } void PrintViewManagerElectron::ShowInvalidPrinterSettingsError() { ReleaseJob(INVALID_PRINTER_SETTINGS); } void PrintViewManagerElectron::PrintingFailed( int32_t cookie, printing::mojom::PrintFailureReason reason) { ReleaseJob(reason == printing::mojom::PrintFailureReason::kInvalidPageRange ? PAGE_COUNT_EXCEEDED : PRINTING_FAILED); } #if BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintViewManagerElectron::UpdatePrintSettings( int32_t cookie, base::Value::Dict job_settings, UpdatePrintSettingsCallback callback) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::UpdatePrintSettings(cookie, std::move(job_settings), std::move(callback)); return; } mojo::ReportBadMessage(kInvalidUpdatePrintSettingsCall); } void PrintViewManagerElectron::SetupScriptedPrintPreview( SetupScriptedPrintPreviewCallback callback) { mojo::ReportBadMessage(kInvalidSetupScriptedPrintPreviewCall); } void PrintViewManagerElectron::ShowScriptedPrintPreview( bool source_is_modifiable) { mojo::ReportBadMessage(kInvalidShowScriptedPrintPreviewCall); } void PrintViewManagerElectron::RequestPrintPreview( printing::mojom::RequestPrintPreviewParamsPtr params) { mojo::ReportBadMessage(kInvalidRequestPrintPreviewCall); } void PrintViewManagerElectron::CheckForCancel(int32_t preview_ui_id, int32_t request_id, CheckForCancelCallback callback) { std::move(callback).Run(false); } #endif // BUILDFLAG(ENABLE_PRINT_PREVIEW) void PrintViewManagerElectron::RenderFrameDeleted( content::RenderFrameHost* render_frame_host) { PrintViewManagerBase::RenderFrameDeleted(render_frame_host); if (printing_rfh_ != render_frame_host) return; if (callback_) { std::move(callback_).Run(PRINTING_FAILED, base::MakeRefCounted<base::RefCountedString>()); } Reset(); } void PrintViewManagerElectron::DidGetPrintedPagesCount(int32_t cookie, uint32_t number_pages) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::DidGetPrintedPagesCount(cookie, number_pages); } } void PrintViewManagerElectron::DidPrintDocument( printing::mojom::DidPrintDocumentParamsPtr params, DidPrintDocumentCallback callback) { auto entry = std::find(headless_jobs_.begin(), headless_jobs_.end(), params->document_cookie); if (entry == headless_jobs_.end()) { PrintViewManagerBase::DidPrintDocument(std::move(params), std::move(callback)); return; } auto& content = *params->content; if (!content.metafile_data_region.IsValid()) { ReleaseJob(INVALID_MEMORY_HANDLE); std::move(callback).Run(false); return; } base::ReadOnlySharedMemoryMapping map = content.metafile_data_region.Map(); if (!map.IsValid()) { ReleaseJob(METAFILE_MAP_ERROR); std::move(callback).Run(false); return; } data_ = std::string(static_cast<const char*>(map.memory()), map.size()); headless_jobs_.erase(entry); std::move(callback).Run(true); ReleaseJob(PRINT_SUCCESS); } void PrintViewManagerElectron::Reset() { printing_rfh_ = nullptr; callback_.Reset(); data_.clear(); } void PrintViewManagerElectron::ReleaseJob(PrintResult result) { if (callback_) { DCHECK(result == PRINT_SUCCESS || data_.empty()); std::move(callback_).Run(result, base::RefCountedString::TakeString(&data_)); if (printing_rfh_ && printing_rfh_->IsRenderFrameLive()) { GetPrintRenderFrame(printing_rfh_)->PrintingDone(result == PRINT_SUCCESS); } Reset(); } } WEB_CONTENTS_USER_DATA_KEY_IMPL(PrintViewManagerElectron); } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,810
[Bug]: --ozone-platform-hint command line flag ignored
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Setting the `--ozone-platform-hint` flag to `auto` or `wayland` should make electron use wayland (assuming `--enable-features=UseOzonePlatform` is also set) ### Actual Behavior The flag is ignored. ### Testcase Gist URL _No response_ ### Additional Information Using `--ozone-platform=wayland` does work, but then it fails when not running wayland.
https://github.com/electron/electron/issues/33810
https://github.com/electron/electron/pull/34937
9f0e7126c422c12333544de0a20f954addd13061
67eda4bcc81754a973a4455cd6db5ac624f4bfa0
2022-04-17T16:33:59Z
c++
2022-07-21T08:37:54Z
filenames.gni
filenames = { default_app_ts_sources = [ "default_app/default_app.ts", "default_app/main.ts", "default_app/preload.ts", ] default_app_static_sources = [ "default_app/icon.png", "default_app/index.html", "default_app/package.json", "default_app/styles.css", ] default_app_octicon_sources = [ "node_modules/@primer/octicons/build/build.css", "node_modules/@primer/octicons/build/svg/book-24.svg", "node_modules/@primer/octicons/build/svg/code-square-24.svg", "node_modules/@primer/octicons/build/svg/gift-24.svg", "node_modules/@primer/octicons/build/svg/mark-github-16.svg", "node_modules/@primer/octicons/build/svg/star-fill-24.svg", ] lib_sources_linux = [ "shell/browser/browser_linux.cc", "shell/browser/lib/power_observer_linux.cc", "shell/browser/lib/power_observer_linux.h", "shell/browser/linux/unity_service.cc", "shell/browser/linux/unity_service.h", "shell/browser/notifications/linux/libnotify_notification.cc", "shell/browser/notifications/linux/libnotify_notification.h", "shell/browser/notifications/linux/notification_presenter_linux.cc", "shell/browser/notifications/linux/notification_presenter_linux.h", "shell/browser/relauncher_linux.cc", "shell/browser/ui/electron_desktop_window_tree_host_linux.cc", "shell/browser/ui/file_dialog_gtk.cc", "shell/browser/ui/message_box_gtk.cc", "shell/browser/ui/tray_icon_gtk.cc", "shell/browser/ui/tray_icon_gtk.h", "shell/browser/ui/views/client_frame_view_linux.cc", "shell/browser/ui/views/client_frame_view_linux.h", "shell/common/application_info_linux.cc", "shell/common/language_util_linux.cc", "shell/common/node_bindings_linux.cc", "shell/common/node_bindings_linux.h", "shell/common/platform_util_linux.cc", ] lib_sources_linux_x11 = [ "shell/browser/ui/views/global_menu_bar_registrar_x11.cc", "shell/browser/ui/views/global_menu_bar_registrar_x11.h", "shell/browser/ui/views/global_menu_bar_x11.cc", "shell/browser/ui/views/global_menu_bar_x11.h", "shell/browser/ui/x/event_disabler.cc", "shell/browser/ui/x/event_disabler.h", "shell/browser/ui/x/x_window_utils.cc", "shell/browser/ui/x/x_window_utils.h", ] lib_sources_posix = [ "shell/browser/electron_browser_main_parts_posix.cc" ] lib_sources_win = [ "shell/browser/api/electron_api_power_monitor_win.cc", "shell/browser/api/electron_api_system_preferences_win.cc", "shell/browser/browser_win.cc", "shell/browser/native_window_views_win.cc", "shell/browser/notifications/win/notification_presenter_win.cc", "shell/browser/notifications/win/notification_presenter_win.h", "shell/browser/notifications/win/notification_presenter_win7.cc", "shell/browser/notifications/win/notification_presenter_win7.h", "shell/browser/notifications/win/win32_desktop_notifications/common.h", "shell/browser/notifications/win/win32_desktop_notifications/desktop_notification_controller.cc", "shell/browser/notifications/win/win32_desktop_notifications/desktop_notification_controller.h", "shell/browser/notifications/win/win32_desktop_notifications/toast_uia.cc", "shell/browser/notifications/win/win32_desktop_notifications/toast_uia.h", "shell/browser/notifications/win/win32_desktop_notifications/toast.cc", "shell/browser/notifications/win/win32_desktop_notifications/toast.h", "shell/browser/notifications/win/win32_notification.cc", "shell/browser/notifications/win/win32_notification.h", "shell/browser/notifications/win/windows_toast_notification.cc", "shell/browser/notifications/win/windows_toast_notification.h", "shell/browser/relauncher_win.cc", "shell/browser/ui/certificate_trust_win.cc", "shell/browser/ui/file_dialog_win.cc", "shell/browser/ui/message_box_win.cc", "shell/browser/ui/tray_icon_win.cc", "shell/browser/ui/views/electron_views_delegate_win.cc", "shell/browser/ui/views/win_icon_painter.cc", "shell/browser/ui/views/win_icon_painter.h", "shell/browser/ui/views/win_frame_view.cc", "shell/browser/ui/views/win_frame_view.h", "shell/browser/ui/views/win_caption_button.cc", "shell/browser/ui/views/win_caption_button.h", "shell/browser/ui/views/win_caption_button_container.cc", "shell/browser/ui/views/win_caption_button_container.h", "shell/browser/ui/win/dialog_thread.cc", "shell/browser/ui/win/dialog_thread.h", "shell/browser/ui/win/electron_desktop_native_widget_aura.cc", "shell/browser/ui/win/electron_desktop_native_widget_aura.h", "shell/browser/ui/win/electron_desktop_window_tree_host_win.cc", "shell/browser/ui/win/electron_desktop_window_tree_host_win.h", "shell/browser/ui/win/jump_list.cc", "shell/browser/ui/win/jump_list.h", "shell/browser/ui/win/notify_icon_host.cc", "shell/browser/ui/win/notify_icon_host.h", "shell/browser/ui/win/notify_icon.cc", "shell/browser/ui/win/notify_icon.h", "shell/browser/ui/win/taskbar_host.cc", "shell/browser/ui/win/taskbar_host.h", "shell/browser/win/dark_mode.cc", "shell/browser/win/dark_mode.h", "shell/browser/win/scoped_hstring.cc", "shell/browser/win/scoped_hstring.h", "shell/common/api/electron_api_native_image_win.cc", "shell/common/application_info_win.cc", "shell/common/language_util_win.cc", "shell/common/node_bindings_win.cc", "shell/common/node_bindings_win.h", "shell/common/platform_util_win.cc", ] lib_sources_mac = [ "shell/app/electron_main_delegate_mac.h", "shell/app/electron_main_delegate_mac.mm", "shell/browser/api/electron_api_app_mac.mm", "shell/browser/api/electron_api_browser_window_mac.mm", "shell/browser/api/electron_api_menu_mac.h", "shell/browser/api/electron_api_menu_mac.mm", "shell/browser/api/electron_api_native_theme_mac.mm", "shell/browser/api/electron_api_power_monitor_mac.mm", "shell/browser/api/electron_api_push_notifications_mac.mm", "shell/browser/api/electron_api_system_preferences_mac.mm", "shell/browser/api/electron_api_web_contents_mac.mm", "shell/browser/auto_updater_mac.mm", "shell/browser/browser_mac.mm", "shell/browser/electron_browser_main_parts_mac.mm", "shell/browser/mac/dict_util.h", "shell/browser/mac/dict_util.mm", "shell/browser/mac/electron_application_delegate.h", "shell/browser/mac/electron_application_delegate.mm", "shell/browser/mac/electron_application.h", "shell/browser/mac/electron_application.mm", "shell/browser/mac/in_app_purchase_observer.h", "shell/browser/mac/in_app_purchase_observer.mm", "shell/browser/mac/in_app_purchase_product.h", "shell/browser/mac/in_app_purchase_product.mm", "shell/browser/mac/in_app_purchase.h", "shell/browser/mac/in_app_purchase.mm", "shell/browser/native_browser_view_mac.h", "shell/browser/native_browser_view_mac.mm", "shell/browser/native_window_mac.h", "shell/browser/native_window_mac.mm", "shell/browser/notifications/mac/cocoa_notification.h", "shell/browser/notifications/mac/cocoa_notification.mm", "shell/browser/notifications/mac/notification_center_delegate.h", "shell/browser/notifications/mac/notification_center_delegate.mm", "shell/browser/notifications/mac/notification_presenter_mac.h", "shell/browser/notifications/mac/notification_presenter_mac.mm", "shell/browser/relauncher_mac.cc", "shell/browser/ui/certificate_trust_mac.mm", "shell/browser/ui/cocoa/delayed_native_view_host.cc", "shell/browser/ui/cocoa/delayed_native_view_host.h", "shell/browser/ui/cocoa/electron_bundle_mover.h", "shell/browser/ui/cocoa/electron_bundle_mover.mm", "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.h", "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm", "shell/browser/ui/cocoa/electron_menu_controller.h", "shell/browser/ui/cocoa/electron_menu_controller.mm", "shell/browser/ui/cocoa/electron_native_widget_mac.h", "shell/browser/ui/cocoa/electron_native_widget_mac.mm", "shell/browser/ui/cocoa/electron_ns_window_delegate.h", "shell/browser/ui/cocoa/electron_ns_window_delegate.mm", "shell/browser/ui/cocoa/electron_ns_panel.h", "shell/browser/ui/cocoa/electron_ns_panel.mm", "shell/browser/ui/cocoa/electron_ns_window.h", "shell/browser/ui/cocoa/electron_ns_window.mm", "shell/browser/ui/cocoa/electron_preview_item.h", "shell/browser/ui/cocoa/electron_preview_item.mm", "shell/browser/ui/cocoa/electron_touch_bar.h", "shell/browser/ui/cocoa/electron_touch_bar.mm", "shell/browser/ui/cocoa/event_dispatching_window.h", "shell/browser/ui/cocoa/event_dispatching_window.mm", "shell/browser/ui/cocoa/NSColor+Hex.h", "shell/browser/ui/cocoa/NSColor+Hex.mm", "shell/browser/ui/cocoa/NSString+ANSI.h", "shell/browser/ui/cocoa/NSString+ANSI.mm", "shell/browser/ui/cocoa/root_view_mac.h", "shell/browser/ui/cocoa/root_view_mac.mm", "shell/browser/ui/cocoa/views_delegate_mac.h", "shell/browser/ui/cocoa/views_delegate_mac.mm", "shell/browser/ui/cocoa/window_buttons_proxy.h", "shell/browser/ui/cocoa/window_buttons_proxy.mm", "shell/browser/ui/drag_util_mac.mm", "shell/browser/ui/file_dialog_mac.mm", "shell/browser/ui/inspectable_web_contents_view_mac.h", "shell/browser/ui/inspectable_web_contents_view_mac.mm", "shell/browser/ui/message_box_mac.mm", "shell/browser/ui/tray_icon_cocoa.h", "shell/browser/ui/tray_icon_cocoa.mm", "shell/common/api/electron_api_clipboard_mac.mm", "shell/common/api/electron_api_native_image_mac.mm", "shell/common/asar/archive_mac.mm", "shell/common/application_info_mac.mm", "shell/common/language_util_mac.mm", "shell/common/mac/main_application_bundle.h", "shell/common/mac/main_application_bundle.mm", "shell/common/node_bindings_mac.cc", "shell/common/node_bindings_mac.h", "shell/common/platform_util_mac.mm", ] lib_sources_views = [ "shell/browser/api/electron_api_browser_window_views.cc", "shell/browser/api/electron_api_menu_views.cc", "shell/browser/api/electron_api_menu_views.h", "shell/browser/native_browser_view_views.cc", "shell/browser/native_browser_view_views.h", "shell/browser/native_window_views.cc", "shell/browser/native_window_views.h", "shell/browser/ui/drag_util_views.cc", "shell/browser/ui/views/autofill_popup_view.cc", "shell/browser/ui/views/autofill_popup_view.h", "shell/browser/ui/views/electron_views_delegate.cc", "shell/browser/ui/views/electron_views_delegate.h", "shell/browser/ui/views/frameless_view.cc", "shell/browser/ui/views/frameless_view.h", "shell/browser/ui/views/inspectable_web_contents_view_views.cc", "shell/browser/ui/views/inspectable_web_contents_view_views.h", "shell/browser/ui/views/menu_bar.cc", "shell/browser/ui/views/menu_bar.h", "shell/browser/ui/views/menu_delegate.cc", "shell/browser/ui/views/menu_delegate.h", "shell/browser/ui/views/menu_model_adapter.cc", "shell/browser/ui/views/menu_model_adapter.h", "shell/browser/ui/views/native_frame_view.cc", "shell/browser/ui/views/native_frame_view.h", "shell/browser/ui/views/root_view.cc", "shell/browser/ui/views/root_view.h", "shell/browser/ui/views/submenu_button.cc", "shell/browser/ui/views/submenu_button.h", ] lib_sources = [ "shell/app/command_line_args.cc", "shell/app/command_line_args.h", "shell/app/electron_content_client.cc", "shell/app/electron_content_client.h", "shell/app/electron_crash_reporter_client.cc", "shell/app/electron_crash_reporter_client.h", "shell/app/electron_main_delegate.cc", "shell/app/electron_main_delegate.h", "shell/app/uv_task_runner.cc", "shell/app/uv_task_runner.h", "shell/browser/api/electron_api_app.cc", "shell/browser/api/electron_api_app.h", "shell/browser/api/electron_api_auto_updater.cc", "shell/browser/api/electron_api_auto_updater.h", "shell/browser/api/electron_api_base_window.cc", "shell/browser/api/electron_api_base_window.h", "shell/browser/api/electron_api_browser_view.cc", "shell/browser/api/electron_api_browser_view.h", "shell/browser/api/electron_api_browser_window.cc", "shell/browser/api/electron_api_browser_window.h", "shell/browser/api/electron_api_content_tracing.cc", "shell/browser/api/electron_api_cookies.cc", "shell/browser/api/electron_api_cookies.h", "shell/browser/api/electron_api_crash_reporter.cc", "shell/browser/api/electron_api_crash_reporter.h", "shell/browser/api/electron_api_data_pipe_holder.cc", "shell/browser/api/electron_api_data_pipe_holder.h", "shell/browser/api/electron_api_debugger.cc", "shell/browser/api/electron_api_debugger.h", "shell/browser/api/electron_api_dialog.cc", "shell/browser/api/electron_api_download_item.cc", "shell/browser/api/electron_api_download_item.h", "shell/browser/api/electron_api_event.cc", "shell/browser/api/electron_api_event_emitter.cc", "shell/browser/api/electron_api_event_emitter.h", "shell/browser/api/electron_api_global_shortcut.cc", "shell/browser/api/electron_api_global_shortcut.h", "shell/browser/api/electron_api_in_app_purchase.cc", "shell/browser/api/electron_api_in_app_purchase.h", "shell/browser/api/electron_api_menu.cc", "shell/browser/api/electron_api_menu.h", "shell/browser/api/electron_api_native_theme.cc", "shell/browser/api/electron_api_native_theme.h", "shell/browser/api/electron_api_net.cc", "shell/browser/api/electron_api_net_log.cc", "shell/browser/api/electron_api_net_log.h", "shell/browser/api/electron_api_notification.cc", "shell/browser/api/electron_api_notification.h", "shell/browser/api/electron_api_power_monitor.cc", "shell/browser/api/electron_api_power_monitor.h", "shell/browser/api/electron_api_power_save_blocker.cc", "shell/browser/api/electron_api_power_save_blocker.h", "shell/browser/api/electron_api_printing.cc", "shell/browser/api/electron_api_protocol.cc", "shell/browser/api/electron_api_protocol.h", "shell/browser/api/electron_api_push_notifications.cc", "shell/browser/api/electron_api_push_notifications.h", "shell/browser/api/electron_api_safe_storage.cc", "shell/browser/api/electron_api_safe_storage.h", "shell/browser/api/electron_api_screen.cc", "shell/browser/api/electron_api_screen.h", "shell/browser/api/electron_api_service_worker_context.cc", "shell/browser/api/electron_api_service_worker_context.h", "shell/browser/api/electron_api_session.cc", "shell/browser/api/electron_api_session.h", "shell/browser/api/electron_api_system_preferences.cc", "shell/browser/api/electron_api_system_preferences.h", "shell/browser/api/electron_api_tray.cc", "shell/browser/api/electron_api_tray.h", "shell/browser/api/electron_api_url_loader.cc", "shell/browser/api/electron_api_url_loader.h", "shell/browser/api/electron_api_view.cc", "shell/browser/api/electron_api_view.h", "shell/browser/api/electron_api_web_contents.cc", "shell/browser/api/electron_api_web_contents.h", "shell/browser/api/electron_api_web_contents_impl.cc", "shell/browser/api/electron_api_web_contents_view.cc", "shell/browser/api/electron_api_web_contents_view.h", "shell/browser/api/electron_api_web_frame_main.cc", "shell/browser/api/electron_api_web_frame_main.h", "shell/browser/api/electron_api_web_request.cc", "shell/browser/api/electron_api_web_request.h", "shell/browser/api/electron_api_web_view_manager.cc", "shell/browser/api/event.cc", "shell/browser/api/event.h", "shell/browser/api/frame_subscriber.cc", "shell/browser/api/frame_subscriber.h", "shell/browser/api/gpu_info_enumerator.cc", "shell/browser/api/gpu_info_enumerator.h", "shell/browser/api/gpuinfo_manager.cc", "shell/browser/api/gpuinfo_manager.h", "shell/browser/api/message_port.cc", "shell/browser/api/message_port.h", "shell/browser/api/process_metric.cc", "shell/browser/api/process_metric.h", "shell/browser/api/save_page_handler.cc", "shell/browser/api/save_page_handler.h", "shell/browser/api/ui_event.cc", "shell/browser/api/ui_event.h", "shell/browser/auto_updater.cc", "shell/browser/auto_updater.h", "shell/browser/badging/badge_manager.cc", "shell/browser/badging/badge_manager.h", "shell/browser/badging/badge_manager_factory.cc", "shell/browser/badging/badge_manager_factory.h", "shell/browser/bluetooth/electron_bluetooth_delegate.cc", "shell/browser/bluetooth/electron_bluetooth_delegate.h", "shell/browser/browser.cc", "shell/browser/browser.h", "shell/browser/browser_observer.h", "shell/browser/browser_process_impl.cc", "shell/browser/browser_process_impl.h", "shell/browser/child_web_contents_tracker.cc", "shell/browser/child_web_contents_tracker.h", "shell/browser/cookie_change_notifier.cc", "shell/browser/cookie_change_notifier.h", "shell/browser/electron_api_ipc_handler_impl.cc", "shell/browser/electron_api_ipc_handler_impl.h", "shell/browser/electron_autofill_driver.cc", "shell/browser/electron_autofill_driver.h", "shell/browser/electron_autofill_driver_factory.cc", "shell/browser/electron_autofill_driver_factory.h", "shell/browser/electron_browser_client.cc", "shell/browser/electron_browser_client.h", "shell/browser/electron_browser_context.cc", "shell/browser/electron_browser_context.h", "shell/browser/electron_browser_main_parts.cc", "shell/browser/electron_browser_main_parts.h", "shell/browser/electron_download_manager_delegate.cc", "shell/browser/electron_download_manager_delegate.h", "shell/browser/electron_gpu_client.cc", "shell/browser/electron_gpu_client.h", "shell/browser/electron_javascript_dialog_manager.cc", "shell/browser/electron_javascript_dialog_manager.h", "shell/browser/electron_navigation_throttle.cc", "shell/browser/electron_navigation_throttle.h", "shell/browser/electron_permission_manager.cc", "shell/browser/electron_permission_manager.h", "shell/browser/electron_quota_permission_context.cc", "shell/browser/electron_quota_permission_context.h", "shell/browser/electron_speech_recognition_manager_delegate.cc", "shell/browser/electron_speech_recognition_manager_delegate.h", "shell/browser/electron_web_contents_utility_handler_impl.cc", "shell/browser/electron_web_contents_utility_handler_impl.h", "shell/browser/electron_web_ui_controller_factory.cc", "shell/browser/electron_web_ui_controller_factory.h", "shell/browser/event_emitter_mixin.cc", "shell/browser/event_emitter_mixin.h", "shell/browser/extended_web_contents_observer.h", "shell/browser/feature_list.cc", "shell/browser/feature_list.h", "shell/browser/file_select_helper.cc", "shell/browser/file_select_helper.h", "shell/browser/file_select_helper_mac.mm", "shell/browser/font_defaults.cc", "shell/browser/font_defaults.h", "shell/browser/hid/electron_hid_delegate.cc", "shell/browser/hid/electron_hid_delegate.h", "shell/browser/hid/hid_chooser_context.cc", "shell/browser/hid/hid_chooser_context.h", "shell/browser/hid/hid_chooser_context_factory.cc", "shell/browser/hid/hid_chooser_context_factory.h", "shell/browser/hid/hid_chooser_controller.cc", "shell/browser/hid/hid_chooser_controller.h", "shell/browser/javascript_environment.cc", "shell/browser/javascript_environment.h", "shell/browser/lib/bluetooth_chooser.cc", "shell/browser/lib/bluetooth_chooser.h", "shell/browser/login_handler.cc", "shell/browser/login_handler.h", "shell/browser/media/media_capture_devices_dispatcher.cc", "shell/browser/media/media_capture_devices_dispatcher.h", "shell/browser/media/media_device_id_salt.cc", "shell/browser/media/media_device_id_salt.h", "shell/browser/microtasks_runner.cc", "shell/browser/microtasks_runner.h", "shell/browser/native_browser_view.cc", "shell/browser/native_browser_view.h", "shell/browser/native_window.cc", "shell/browser/native_window.h", "shell/browser/native_window_features.cc", "shell/browser/native_window_features.h", "shell/browser/native_window_observer.h", "shell/browser/net/asar/asar_file_validator.cc", "shell/browser/net/asar/asar_file_validator.h", "shell/browser/net/asar/asar_url_loader.cc", "shell/browser/net/asar/asar_url_loader.h", "shell/browser/net/asar/asar_url_loader_factory.cc", "shell/browser/net/asar/asar_url_loader_factory.h", "shell/browser/net/cert_verifier_client.cc", "shell/browser/net/cert_verifier_client.h", "shell/browser/net/electron_url_loader_factory.cc", "shell/browser/net/electron_url_loader_factory.h", "shell/browser/net/network_context_service.cc", "shell/browser/net/network_context_service.h", "shell/browser/net/network_context_service_factory.cc", "shell/browser/net/network_context_service_factory.h", "shell/browser/net/node_stream_loader.cc", "shell/browser/net/node_stream_loader.h", "shell/browser/net/proxying_url_loader_factory.cc", "shell/browser/net/proxying_url_loader_factory.h", "shell/browser/net/proxying_websocket.cc", "shell/browser/net/proxying_websocket.h", "shell/browser/net/resolve_proxy_helper.cc", "shell/browser/net/resolve_proxy_helper.h", "shell/browser/net/system_network_context_manager.cc", "shell/browser/net/system_network_context_manager.h", "shell/browser/net/url_pipe_loader.cc", "shell/browser/net/url_pipe_loader.h", "shell/browser/net/web_request_api_interface.h", "shell/browser/network_hints_handler_impl.cc", "shell/browser/network_hints_handler_impl.h", "shell/browser/notifications/notification.cc", "shell/browser/notifications/notification.h", "shell/browser/notifications/notification_delegate.h", "shell/browser/notifications/notification_presenter.cc", "shell/browser/notifications/notification_presenter.h", "shell/browser/notifications/platform_notification_service.cc", "shell/browser/notifications/platform_notification_service.h", "shell/browser/plugins/plugin_utils.cc", "shell/browser/plugins/plugin_utils.h", "shell/browser/pref_store_delegate.cc", "shell/browser/pref_store_delegate.h", "shell/browser/protocol_registry.cc", "shell/browser/protocol_registry.h", "shell/browser/relauncher.cc", "shell/browser/relauncher.h", "shell/browser/serial/electron_serial_delegate.cc", "shell/browser/serial/electron_serial_delegate.h", "shell/browser/serial/serial_chooser_context.cc", "shell/browser/serial/serial_chooser_context.h", "shell/browser/serial/serial_chooser_context_factory.cc", "shell/browser/serial/serial_chooser_context_factory.h", "shell/browser/serial/serial_chooser_controller.cc", "shell/browser/serial/serial_chooser_controller.h", "shell/browser/session_preferences.cc", "shell/browser/session_preferences.h", "shell/browser/special_storage_policy.cc", "shell/browser/special_storage_policy.h", "shell/browser/ui/accelerator_util.cc", "shell/browser/ui/accelerator_util.h", "shell/browser/ui/autofill_popup.cc", "shell/browser/ui/autofill_popup.h", "shell/browser/ui/certificate_trust.h", "shell/browser/ui/devtools_manager_delegate.cc", "shell/browser/ui/devtools_manager_delegate.h", "shell/browser/ui/devtools_ui.cc", "shell/browser/ui/devtools_ui.h", "shell/browser/ui/drag_util.cc", "shell/browser/ui/drag_util.h", "shell/browser/ui/electron_menu_model.cc", "shell/browser/ui/electron_menu_model.h", "shell/browser/ui/file_dialog.h", "shell/browser/ui/inspectable_web_contents.cc", "shell/browser/ui/inspectable_web_contents.h", "shell/browser/ui/inspectable_web_contents_delegate.h", "shell/browser/ui/inspectable_web_contents_view.h", "shell/browser/ui/inspectable_web_contents_view_delegate.cc", "shell/browser/ui/inspectable_web_contents_view_delegate.h", "shell/browser/ui/message_box.h", "shell/browser/ui/tray_icon.cc", "shell/browser/ui/tray_icon.h", "shell/browser/ui/tray_icon_observer.h", "shell/browser/ui/webui/accessibility_ui.cc", "shell/browser/ui/webui/accessibility_ui.h", "shell/browser/unresponsive_suppressor.cc", "shell/browser/unresponsive_suppressor.h", "shell/browser/web_contents_permission_helper.cc", "shell/browser/web_contents_permission_helper.h", "shell/browser/web_contents_preferences.cc", "shell/browser/web_contents_preferences.h", "shell/browser/web_contents_zoom_controller.cc", "shell/browser/web_contents_zoom_controller.h", "shell/browser/web_view_guest_delegate.cc", "shell/browser/web_view_guest_delegate.h", "shell/browser/web_view_manager.cc", "shell/browser/web_view_manager.h", "shell/browser/window_list.cc", "shell/browser/window_list.h", "shell/browser/window_list_observer.h", "shell/browser/zoom_level_delegate.cc", "shell/browser/zoom_level_delegate.h", "shell/common/api/electron_api_asar.cc", "shell/common/api/electron_api_clipboard.cc", "shell/common/api/electron_api_clipboard.h", "shell/common/api/electron_api_command_line.cc", "shell/common/api/electron_api_environment.cc", "shell/common/api/electron_api_key_weak_map.h", "shell/common/api/electron_api_native_image.cc", "shell/common/api/electron_api_native_image.h", "shell/common/api/electron_api_shell.cc", "shell/common/api/electron_api_testing.cc", "shell/common/api/electron_api_v8_util.cc", "shell/common/api/electron_bindings.cc", "shell/common/api/electron_bindings.h", "shell/common/api/features.cc", "shell/common/api/object_life_monitor.cc", "shell/common/api/object_life_monitor.h", "shell/common/application_info.cc", "shell/common/application_info.h", "shell/common/asar/archive.cc", "shell/common/asar/archive.h", "shell/common/asar/asar_util.cc", "shell/common/asar/asar_util.h", "shell/common/asar/scoped_temporary_file.cc", "shell/common/asar/scoped_temporary_file.h", "shell/common/color_util.cc", "shell/common/color_util.h", "shell/common/crash_keys.cc", "shell/common/crash_keys.h", "shell/common/electron_command_line.cc", "shell/common/electron_command_line.h", "shell/common/electron_constants.cc", "shell/common/electron_constants.h", "shell/common/electron_paths.h", "shell/common/gin_converters/accelerator_converter.cc", "shell/common/gin_converters/accelerator_converter.h", "shell/common/gin_converters/base_converter.h", "shell/common/gin_converters/blink_converter.cc", "shell/common/gin_converters/blink_converter.h", "shell/common/gin_converters/callback_converter.h", "shell/common/gin_converters/content_converter.cc", "shell/common/gin_converters/content_converter.h", "shell/common/gin_converters/file_dialog_converter.cc", "shell/common/gin_converters/file_dialog_converter.h", "shell/common/gin_converters/file_path_converter.h", "shell/common/gin_converters/frame_converter.cc", "shell/common/gin_converters/frame_converter.h", "shell/common/gin_converters/gfx_converter.cc", "shell/common/gin_converters/gfx_converter.h", "shell/common/gin_converters/guid_converter.h", "shell/common/gin_converters/gurl_converter.h", "shell/common/gin_converters/hid_device_info_converter.h", "shell/common/gin_converters/image_converter.cc", "shell/common/gin_converters/image_converter.h", "shell/common/gin_converters/message_box_converter.cc", "shell/common/gin_converters/message_box_converter.h", "shell/common/gin_converters/native_window_converter.h", "shell/common/gin_converters/net_converter.cc", "shell/common/gin_converters/net_converter.h", "shell/common/gin_converters/std_converter.h", "shell/common/gin_converters/time_converter.cc", "shell/common/gin_converters/time_converter.h", "shell/common/gin_converters/value_converter.cc", "shell/common/gin_converters/value_converter.h", "shell/common/gin_helper/arguments.cc", "shell/common/gin_helper/arguments.h", "shell/common/gin_helper/callback.cc", "shell/common/gin_helper/callback.h", "shell/common/gin_helper/cleaned_up_at_exit.cc", "shell/common/gin_helper/cleaned_up_at_exit.h", "shell/common/gin_helper/constructible.h", "shell/common/gin_helper/constructor.h", "shell/common/gin_helper/destroyable.cc", "shell/common/gin_helper/destroyable.h", "shell/common/gin_helper/dictionary.h", "shell/common/gin_helper/error_thrower.cc", "shell/common/gin_helper/error_thrower.h", "shell/common/gin_helper/event_emitter.cc", "shell/common/gin_helper/event_emitter.h", "shell/common/gin_helper/event_emitter_caller.cc", "shell/common/gin_helper/event_emitter_caller.h", "shell/common/gin_helper/function_template.cc", "shell/common/gin_helper/function_template.h", "shell/common/gin_helper/function_template_extensions.h", "shell/common/gin_helper/locker.cc", "shell/common/gin_helper/locker.h", "shell/common/gin_helper/microtasks_scope.cc", "shell/common/gin_helper/microtasks_scope.h", "shell/common/gin_helper/object_template_builder.cc", "shell/common/gin_helper/object_template_builder.h", "shell/common/gin_helper/persistent_dictionary.cc", "shell/common/gin_helper/persistent_dictionary.h", "shell/common/gin_helper/pinnable.h", "shell/common/gin_helper/promise.cc", "shell/common/gin_helper/promise.h", "shell/common/gin_helper/trackable_object.cc", "shell/common/gin_helper/trackable_object.h", "shell/common/gin_helper/wrappable.cc", "shell/common/gin_helper/wrappable.h", "shell/common/gin_helper/wrappable_base.h", "shell/common/heap_snapshot.cc", "shell/common/heap_snapshot.h", "shell/common/key_weak_map.h", "shell/common/keyboard_util.cc", "shell/common/keyboard_util.h", "shell/common/language_util.h", "shell/common/logging.cc", "shell/common/logging.h", "shell/common/mouse_util.cc", "shell/common/mouse_util.h", "shell/common/node_bindings.cc", "shell/common/node_bindings.h", "shell/common/node_includes.h", "shell/common/node_util.cc", "shell/common/node_util.h", "shell/common/options_switches.cc", "shell/common/options_switches.h", "shell/common/platform_util.cc", "shell/common/platform_util.h", "shell/common/platform_util_internal.h", "shell/common/process_util.cc", "shell/common/process_util.h", "shell/common/skia_util.cc", "shell/common/skia_util.h", "shell/common/v8_value_serializer.cc", "shell/common/v8_value_serializer.h", "shell/common/world_ids.h", "shell/renderer/api/context_bridge/object_cache.cc", "shell/renderer/api/context_bridge/object_cache.h", "shell/renderer/api/electron_api_context_bridge.cc", "shell/renderer/api/electron_api_context_bridge.h", "shell/renderer/api/electron_api_crash_reporter_renderer.cc", "shell/renderer/api/electron_api_ipc_renderer.cc", "shell/renderer/api/electron_api_spell_check_client.cc", "shell/renderer/api/electron_api_spell_check_client.h", "shell/renderer/api/electron_api_web_frame.cc", "shell/renderer/browser_exposed_renderer_interfaces.cc", "shell/renderer/browser_exposed_renderer_interfaces.h", "shell/renderer/content_settings_observer.cc", "shell/renderer/content_settings_observer.h", "shell/renderer/electron_api_service_impl.cc", "shell/renderer/electron_api_service_impl.h", "shell/renderer/electron_autofill_agent.cc", "shell/renderer/electron_autofill_agent.h", "shell/renderer/electron_render_frame_observer.cc", "shell/renderer/electron_render_frame_observer.h", "shell/renderer/electron_renderer_client.cc", "shell/renderer/electron_renderer_client.h", "shell/renderer/electron_renderer_pepper_host_factory.cc", "shell/renderer/electron_renderer_pepper_host_factory.h", "shell/renderer/electron_sandboxed_renderer_client.cc", "shell/renderer/electron_sandboxed_renderer_client.h", "shell/renderer/guest_view_container.cc", "shell/renderer/guest_view_container.h", "shell/renderer/renderer_client_base.cc", "shell/renderer/renderer_client_base.h", "shell/renderer/web_worker_observer.cc", "shell/renderer/web_worker_observer.h", "shell/utility/electron_content_utility_client.cc", "shell/utility/electron_content_utility_client.h", ] lib_sources_extensions = [ "shell/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.cc", "shell/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.h", "shell/browser/extensions/api/management/electron_management_api_delegate.cc", "shell/browser/extensions/api/management/electron_management_api_delegate.h", "shell/browser/extensions/api/resources_private/resources_private_api.cc", "shell/browser/extensions/api/resources_private/resources_private_api.h", "shell/browser/extensions/api/runtime/electron_runtime_api_delegate.cc", "shell/browser/extensions/api/runtime/electron_runtime_api_delegate.h", "shell/browser/extensions/api/streams_private/streams_private_api.cc", "shell/browser/extensions/api/streams_private/streams_private_api.h", "shell/browser/extensions/api/tabs/tabs_api.cc", "shell/browser/extensions/api/tabs/tabs_api.h", "shell/browser/extensions/electron_browser_context_keyed_service_factories.cc", "shell/browser/extensions/electron_browser_context_keyed_service_factories.h", "shell/browser/extensions/electron_component_extension_resource_manager.cc", "shell/browser/extensions/electron_component_extension_resource_manager.h", "shell/browser/extensions/electron_display_info_provider.cc", "shell/browser/extensions/electron_display_info_provider.h", "shell/browser/extensions/electron_extension_host_delegate.cc", "shell/browser/extensions/electron_extension_host_delegate.h", "shell/browser/extensions/electron_extension_loader.cc", "shell/browser/extensions/electron_extension_loader.h", "shell/browser/extensions/electron_extension_message_filter.cc", "shell/browser/extensions/electron_extension_message_filter.h", "shell/browser/extensions/electron_extension_system_factory.cc", "shell/browser/extensions/electron_extension_system_factory.h", "shell/browser/extensions/electron_extension_system.cc", "shell/browser/extensions/electron_extension_system.h", "shell/browser/extensions/electron_extension_web_contents_observer.cc", "shell/browser/extensions/electron_extension_web_contents_observer.h", "shell/browser/extensions/electron_extensions_api_client.cc", "shell/browser/extensions/electron_extensions_api_client.h", "shell/browser/extensions/electron_extensions_browser_api_provider.cc", "shell/browser/extensions/electron_extensions_browser_api_provider.h", "shell/browser/extensions/electron_extensions_browser_client.cc", "shell/browser/extensions/electron_extensions_browser_client.h", "shell/browser/extensions/electron_kiosk_delegate.cc", "shell/browser/extensions/electron_kiosk_delegate.h", "shell/browser/extensions/electron_messaging_delegate.cc", "shell/browser/extensions/electron_messaging_delegate.h", "shell/browser/extensions/electron_navigation_ui_data.cc", "shell/browser/extensions/electron_navigation_ui_data.h", "shell/browser/extensions/electron_process_manager_delegate.cc", "shell/browser/extensions/electron_process_manager_delegate.h", "shell/common/extensions/electron_extensions_api_provider.cc", "shell/common/extensions/electron_extensions_api_provider.h", "shell/common/extensions/electron_extensions_client.cc", "shell/common/extensions/electron_extensions_client.h", "shell/common/gin_converters/extension_converter.cc", "shell/common/gin_converters/extension_converter.h", "shell/renderer/extensions/electron_extensions_dispatcher_delegate.cc", "shell/renderer/extensions/electron_extensions_dispatcher_delegate.h", "shell/renderer/extensions/electron_extensions_renderer_client.cc", "shell/renderer/extensions/electron_extensions_renderer_client.h", ] framework_sources = [ "shell/app/electron_library_main.h", "shell/app/electron_library_main.mm", ] login_helper_sources = [ "shell/app/electron_login_helper.mm" ] }
closed
electron/electron
https://github.com/electron/electron
33,810
[Bug]: --ozone-platform-hint command line flag ignored
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Setting the `--ozone-platform-hint` flag to `auto` or `wayland` should make electron use wayland (assuming `--enable-features=UseOzonePlatform` is also set) ### Actual Behavior The flag is ignored. ### Testcase Gist URL _No response_ ### Additional Information Using `--ozone-platform=wayland` does work, but then it fails when not running wayland.
https://github.com/electron/electron/issues/33810
https://github.com/electron/electron/pull/34937
9f0e7126c422c12333544de0a20f954addd13061
67eda4bcc81754a973a4455cd6db5ac624f4bfa0
2022-04-17T16:33:59Z
c++
2022-07-21T08:37:54Z
shell/browser/electron_browser_main_parts.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_main_parts.h" #include <memory> #include <string> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/icon_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/key_storage_config_linux.h" #include "components/os_crypt/os_crypt.h" #include "content/browser/browser_main_loop.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/device_service.h" #include "content/public/browser/first_party_sets_handler.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "media/base/localized_strings.h" #include "services/network/public/cpp/features.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/electron_main_delegate.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/browser.h" #include "shell/browser/browser_process_impl.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_web_ui_controller_factory.h" #include "shell/browser/feature_list.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_helper/trackable_object.h" #include "shell/common/logging.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/idle/idle.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_switches.h" #if defined(USE_AURA) #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/wm/core/wm_state.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "base/threading/thread_task_runner_handle.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h" #include "electron/electron_gtk_stubs.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/gfx/color_utils.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/linux_ui_factory.h" #include "ui/ozone/public/ozone_platform.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/l10n/l10n_util_win.h" #include "ui/display/win/dpi.h" #include "ui/gfx/system_fonts_win.h" #include "ui/strings/grit/app_locale_settings.h" #endif #if BUILDFLAG(IS_MAC) #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "shell/browser/ui/cocoa/views_delegate_mac.h" #else #include "shell/browser/ui/views/electron_views_delegate.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #endif namespace electron { namespace { template <typename T> void Erase(T* container, typename T::iterator iter) { container->erase(iter); } #if BUILDFLAG(IS_WIN) // gfx::Font callbacks void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) { l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override, &font_adjustment->font_scale); font_adjustment->font_scale *= display::win::GetAccessibilityFontScale(); } int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } #endif std::u16string MediaStringProvider(media::MessageId id) { switch (id) { case media::DEFAULT_AUDIO_DEVICE_NAME: return u"Default"; #if BUILDFLAG(IS_WIN) case media::COMMUNICATIONS_AUDIO_DEVICE_NAME: return u"Communications"; #endif default: return std::u16string(); } } #if BUILDFLAG(IS_LINUX) // GTK does not provide a way to check if current theme is dark, so we compare // the text and background luminosity to get a result. // This trick comes from FireFox. void UpdateDarkThemeSetting() { float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel")); float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel")); bool is_dark = fg > bg; // Pass it to NativeUi theme, which is used by the nativeTheme module and most // places in Electron. ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark); // Pass it to Web Theme, to make "prefers-color-scheme" media query work. ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark); } #endif } // namespace #if BUILDFLAG(IS_LINUX) class DarkThemeObserver : public ui::NativeThemeObserver { public: DarkThemeObserver() = default; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override { UpdateDarkThemeSetting(); } }; #endif // static ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr; ElectronBrowserMainParts::ElectronBrowserMainParts() : fake_browser_process_(std::make_unique<BrowserProcessImpl>()), browser_(std::make_unique<Browser>()), node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) { DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts"; self_ = this; } ElectronBrowserMainParts::~ElectronBrowserMainParts() = default; // static ElectronBrowserMainParts* ElectronBrowserMainParts::Get() { DCHECK(self_); return self_; } bool ElectronBrowserMainParts::SetExitCode(int code) { if (!exit_code_) return false; content::BrowserMainLoop::GetInstance()->SetResultCode(code); *exit_code_ = code; return true; } int ElectronBrowserMainParts::GetExitCode() const { return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT); } int ElectronBrowserMainParts::PreEarlyInitialization() { field_trial_list_ = std::make_unique<base::FieldTrialList>(nullptr); #if BUILDFLAG(IS_POSIX) HandleSIGCHLD(); #endif #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::PreEarlyInitialization(); #endif #if BUILDFLAG(IS_MAC) screen_ = std::make_unique<display::ScopedNativeScreen>(); #endif return GetExitCode(); } void ElectronBrowserMainParts::PostEarlyInitialization() { // A workaround was previously needed because there was no ThreadTaskRunner // set. If this check is failing we may need to re-add that workaround DCHECK(base::ThreadTaskRunnerHandle::IsSet()); // The ProxyResolverV8 has setup a complete V8 environment, in order to // avoid conflicts we only initialize our V8 environment after that. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); v8::HandleScope scope(js_env_->isolate()); node_bindings_->Initialize(); // Create the global environment. node::Environment* env = node_bindings_->CreateEnvironment( js_env_->context(), js_env_->platform()); node_env_ = std::make_unique<NodeEnvironment>(env); env->set_trace_sync_io(env->options()->trace_sync_io); // We do not want to crash the main process on unhandled rejections. env->options()->unhandled_rejections = "warn"; // Add Electron extended APIs. electron_bindings_->BindTo(js_env_->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // Wrap the uv loop with global env. node_bindings_->set_uv_env(env); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line // switches at that point. Lets reinitialize it here to pick up the // command-line changes. base::FeatureList::ClearInstanceForTesting(); InitializeFeatureList(); // Initialize field trials. InitializeFieldTrials(); // Reinitialize logging now that the app has had a chance to set the app name // and/or user data directory. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ false); // Initialize after user script environment creation. fake_browser_process_->PostEarlyInitialization(); } int ElectronBrowserMainParts::PreCreateThreads() { #if defined(USE_AURA) if (!display::Screen::GetScreen()) { screen_ = views::CreateDesktopScreen(); } #endif if (!views::LayoutProvider::Get()) layout_provider_ = std::make_unique<views::LayoutProvider>(); auto* command_line = base::CommandLine::ForCurrentProcess(); std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); #if BUILDFLAG(IS_MAC) // The browser process only wants to support the language Cocoa will use, // so force the app locale to be overridden with that value. This must // happen before the ResourceBundle is loaded if (locale.empty()) l10n_util::OverrideLocaleWithCocoaLocale(); #elif BUILDFLAG(IS_LINUX) // l10n_util::GetApplicationLocaleInternal uses g_get_language_names(), // which keys off of getenv("LC_ALL"). // We must set this env first to make ui::ResourceBundle accept the custom // locale. auto env = base::Environment::Create(); absl::optional<std::string> lc_all; if (!locale.empty()) { std::string str; if (env->GetVar("LC_ALL", &str)) lc_all.emplace(std::move(str)); env->SetVar("LC_ALL", locale.c_str()); } #endif // Load resources bundle according to locale. std::string loaded_locale = LoadResourceBundle(locale); // Initialize the app locale. std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale); ElectronBrowserClient::SetApplicationLocale(app_locale); fake_browser_process_->SetApplicationLocale(app_locale); #if BUILDFLAG(IS_LINUX) // Reset to the original LC_ALL since we should not be changing it. if (!locale.empty()) { if (lc_all) env->SetVar("LC_ALL", *lc_all); else env->UnSetVar("LC_ALL"); } #endif // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); #if BUILDFLAG(IS_MAC) ui::InitIdleMonitor(); #endif fake_browser_process_->PreCreateThreads(); // Notify observers. Browser::Get()->PreCreateThreads(); return 0; } void ElectronBrowserMainParts::PostCreateThreads() { content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); } void ElectronBrowserMainParts::PostDestroyThreads() { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_browser_client_.reset(); extensions::ExtensionsBrowserClient::Set(nullptr); #endif #if BUILDFLAG(IS_LINUX) device::BluetoothAdapterFactory::Shutdown(); bluez::DBusBluezManagerWrapperLinux::Shutdown(); #endif fake_browser_process_->PostDestroyThreads(); } void ElectronBrowserMainParts::ToolkitInitialized() { #if BUILDFLAG(IS_LINUX) auto linux_ui = ui::CreateLinuxUi(); DCHECK(ui::LinuxInputMethodContextFactory::instance()); // Try loading gtk symbols used by Electron. electron::InitializeElectron_gtk(gtk::GetLibGtk()); if (!electron::IsElectron_gtkInitialized()) { electron::UninitializeElectron_gtk(); } electron::InitializeElectron_gdk_pixbuf(gtk::GetLibGdkPixbuf()); CHECK(electron::IsElectron_gdk_pixbufInitialized()) << "Failed to initialize libgdk_pixbuf-2.0.so.0"; // Chromium does not respect GTK dark theme setting, but they may change // in future and this code might be no longer needed. Check the Chromium // issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=998903 UpdateDarkThemeSetting(); // Update the native theme when GTK theme changes. The GetNativeTheme // here returns a NativeThemeGtk, which monitors GTK settings. dark_theme_observer_ = std::make_unique<DarkThemeObserver>(); linux_ui->GetNativeTheme(nullptr)->AddObserver(dark_theme_observer_.get()); ui::LinuxUi::SetInstance(std::move(linux_ui)); // Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager // implementation). Start observing them once it's initialized. ui::CursorFactory::GetInstance()->ObserveThemeChanges(); #endif #if defined(USE_AURA) wm_state_ = std::make_unique<wm::WMState>(); #endif #if BUILDFLAG(IS_WIN) gfx::win::SetAdjustFontCallback(&AdjustUIFont); gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize); #endif #if BUILDFLAG(IS_MAC) views_delegate_ = std::make_unique<ViewsDelegateMac>(); #else views_delegate_ = std::make_unique<ViewsDelegate>(); #endif } int ElectronBrowserMainParts::PreMainMessageLoopRun() { // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareEmbedThread(); node_bindings_->StartPolling(); // url::Add*Scheme are not threadsafe, this helps prevent data races. url::LockSchemeRegistries(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_client_ = std::make_unique<ElectronExtensionsClient>(); extensions::ExtensionsClient::Set(extensions_client_.get()); // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient. extensions_browser_client_ = std::make_unique<ElectronExtensionsBrowserClient>(); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt(); extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt(); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckServiceFactory::GetInstance(); #endif content::WebUIControllerFactory::RegisterFactory( ElectronWebUIControllerFactory::GetInstance()); auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) { // --remote-debugging-pipe auto on_disconnect = base::BindOnce([]() { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); })); }); content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler( std::move(on_disconnect)); } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { // --remote-debugging-port DevToolsManagerDelegate::StartHttpHandler(); } #if !BUILDFLAG(IS_MAC) // The corresponding call in macOS is in ElectronApplicationDelegate. Browser::Get()->WillFinishLaunching(); Browser::Get()->DidFinishLaunching(base::Value::Dict()); #endif // Notify observers that main thread message loop was initialized. Browser::Get()->PreMainMessageLoopRun(); return GetExitCode(); } void ElectronBrowserMainParts::WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) { js_env_->OnMessageLoopCreated(); exit_code_ = content::RESULT_CODE_NORMAL_EXIT; Browser::Get()->SetMainMessageLoopQuitClosure( run_loop->QuitWhenIdleClosure()); } void ElectronBrowserMainParts::PostCreateMainMessageLoop() { #if BUILDFLAG(IS_LINUX) auto shutdown_cb = base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop( std::move(shutdown_cb)); bluez::DBusBluezManagerWrapperLinux::Initialize(); // Set up crypt config. This needs to be done before anything starts the // network service, as the raw encryption key needs to be shared with the // network service for encrypted cookie storage. std::string app_name = electron::Browser::Get()->GetName(); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::unique_ptr<os_crypt::Config> config = std::make_unique<os_crypt::Config>(); // Forward to os_crypt the flag to use a specific password store. config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore); config->product_name = app_name; config->application_name = app_name; config->main_thread_runner = base::ThreadTaskRunnerHandle::Get(); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1 config->should_use_preference = command_line.HasSwitch(::switches::kEnableEncryptionSelection); base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path); OSCrypt::SetConfig(std::move(config)); #endif #if BUILDFLAG(IS_POSIX) // Exit in response to SIGINT, SIGTERM, etc. InstallShutdownSignalHandlers( base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())), content::GetUIThreadTaskRunner({})); #endif } void ElectronBrowserMainParts::PostMainMessageLoopRun() { #if BUILDFLAG(IS_MAC) FreeAppDelegate(); #endif // Shutdown the DownloadManager before destroying Node to prevent // DownloadItem callbacks from crashing. for (auto& iter : ElectronBrowserContext::browser_context_map()) { auto* download_manager = iter.second.get()->GetDownloadManager(); if (download_manager) { download_manager->Shutdown(); } } // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. node_env_->env()->set_trace_sync_io(false); js_env_->OnMessageLoopDestroying(); node::Stop(node_env_->env()); node_env_.reset(); auto default_context_key = ElectronBrowserContext::PartitionKey("", false); std::unique_ptr<ElectronBrowserContext> default_context = std::move( ElectronBrowserContext::browser_context_map()[default_context_key]); ElectronBrowserContext::browser_context_map().clear(); default_context.reset(); fake_browser_process_->PostMainMessageLoopRun(); content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler(); #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun(); #endif } #if !BUILDFLAG(IS_MAC) void ElectronBrowserMainParts::PreCreateMainMessageLoop() { PreCreateMainMessageLoopCommon(); } #endif void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() { #if BUILDFLAG(IS_MAC) InitializeMainNib(); RegisterURLHandler(); #endif media::SetLocalizedStringProvider(MediaStringProvider); #if BUILDFLAG(IS_WIN) auto* local_state = g_browser_process->local_state(); DCHECK(local_state); bool os_crypt_init = OSCrypt::Init(local_state); DCHECK(os_crypt_init); #endif } device::mojom::GeolocationControl* ElectronBrowserMainParts::GetGeolocationControl() { if (!geolocation_control_) { content::GetDeviceService().BindGeolocationControl( geolocation_control_.BindNewPipeAndPassReceiver()); } return geolocation_control_.get(); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserMainParts::GetGeolocationManager() { return geolocation_manager_.get(); } #endif IconManager* ElectronBrowserMainParts::GetIconManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!icon_manager_.get()) icon_manager_ = std::make_unique<IconManager>(); return icon_manager_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,810
[Bug]: --ozone-platform-hint command line flag ignored
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Setting the `--ozone-platform-hint` flag to `auto` or `wayland` should make electron use wayland (assuming `--enable-features=UseOzonePlatform` is also set) ### Actual Behavior The flag is ignored. ### Testcase Gist URL _No response_ ### Additional Information Using `--ozone-platform=wayland` does work, but then it fails when not running wayland.
https://github.com/electron/electron/issues/33810
https://github.com/electron/electron/pull/34937
9f0e7126c422c12333544de0a20f954addd13061
67eda4bcc81754a973a4455cd6db5ac624f4bfa0
2022-04-17T16:33:59Z
c++
2022-07-21T08:37:54Z
shell/browser/electron_browser_main_parts.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_MAIN_PARTS_H_ #define ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_MAIN_PARTS_H_ #include <memory> #include <string> #include "base/callback.h" #include "base/timer/timer.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_main_parts.h" #include "electron/buildflags/buildflags.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/geolocation_control.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/display/screen.h" #include "ui/views/layout/layout_provider.h" class BrowserProcessImpl; class IconManager; namespace base { class FieldTrialList; } #if defined(USE_AURA) namespace wm { class WMState; } namespace display { class Screen; } #endif namespace device { class GeolocationManager; } namespace electron { class Browser; class ElectronBindings; class JavascriptEnvironment; class NodeBindings; class NodeEnvironment; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) class ElectronExtensionsClient; class ElectronExtensionsBrowserClient; #endif #if defined(TOOLKIT_VIEWS) class ViewsDelegate; #endif #if BUILDFLAG(IS_MAC) class ViewsDelegateMac; #endif #if BUILDFLAG(IS_LINUX) class DarkThemeObserver; #endif class ElectronBrowserMainParts : public content::BrowserMainParts { public: ElectronBrowserMainParts(); ~ElectronBrowserMainParts() override; // disable copy ElectronBrowserMainParts(const ElectronBrowserMainParts&) = delete; ElectronBrowserMainParts& operator=(const ElectronBrowserMainParts&) = delete; static ElectronBrowserMainParts* Get(); // Sets the exit code, will fail if the message loop is not ready. bool SetExitCode(int code); // Gets the exit code int GetExitCode() const; // Returns the connection to GeolocationControl which can be // used to enable the location services once per client. device::mojom::GeolocationControl* GetGeolocationControl(); #if BUILDFLAG(IS_MAC) device::GeolocationManager* GetGeolocationManager(); #endif // Returns handle to the class responsible for extracting file icons. IconManager* GetIconManager(); Browser* browser() { return browser_.get(); } BrowserProcessImpl* browser_process() { return fake_browser_process_.get(); } protected: // content::BrowserMainParts: int PreEarlyInitialization() override; void PostEarlyInitialization() override; int PreCreateThreads() override; void ToolkitInitialized() override; int PreMainMessageLoopRun() override; void WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) override; void PostCreateMainMessageLoop() override; void PostMainMessageLoopRun() override; void PreCreateMainMessageLoop() override; void PostCreateThreads() override; void PostDestroyThreads() override; private: void PreCreateMainMessageLoopCommon(); #if BUILDFLAG(IS_POSIX) // Set signal handlers. void HandleSIGCHLD(); void InstallShutdownSignalHandlers( base::OnceCallback<void()> shutdown_callback, const scoped_refptr<base::SingleThreadTaskRunner>& task_runner); #endif #if BUILDFLAG(IS_MAC) void FreeAppDelegate(); void RegisterURLHandler(); void InitializeMainNib(); #endif #if BUILDFLAG(IS_MAC) std::unique_ptr<ViewsDelegateMac> views_delegate_; #else std::unique_ptr<ViewsDelegate> views_delegate_; #endif #if defined(USE_AURA) std::unique_ptr<wm::WMState> wm_state_; std::unique_ptr<display::Screen> screen_; #endif #if BUILDFLAG(IS_LINUX) // Used to notify the native theme of changes to dark mode. std::unique_ptr<DarkThemeObserver> dark_theme_observer_; #endif std::unique_ptr<views::LayoutProvider> layout_provider_; // A fake BrowserProcess object that used to feed the source code from chrome. std::unique_ptr<BrowserProcessImpl> fake_browser_process_; // A place to remember the exit code once the message loop is ready. // Before then, we just exit() without any intermediate steps. absl::optional<int> exit_code_; std::unique_ptr<JavascriptEnvironment> js_env_; std::unique_ptr<Browser> browser_; std::unique_ptr<NodeBindings> node_bindings_; std::unique_ptr<ElectronBindings> electron_bindings_; std::unique_ptr<NodeEnvironment> node_env_; std::unique_ptr<IconManager> icon_manager_; std::unique_ptr<base::FieldTrialList> field_trial_list_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) std::unique_ptr<ElectronExtensionsClient> extensions_client_; std::unique_ptr<ElectronExtensionsBrowserClient> extensions_browser_client_; #endif mojo::Remote<device::mojom::GeolocationControl> geolocation_control_; #if BUILDFLAG(IS_MAC) std::unique_ptr<device::GeolocationManager> geolocation_manager_; std::unique_ptr<display::ScopedNativeScreen> screen_; #endif static ElectronBrowserMainParts* self_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_MAIN_PARTS_H_
closed
electron/electron
https://github.com/electron/electron
33,810
[Bug]: --ozone-platform-hint command line flag ignored
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Setting the `--ozone-platform-hint` flag to `auto` or `wayland` should make electron use wayland (assuming `--enable-features=UseOzonePlatform` is also set) ### Actual Behavior The flag is ignored. ### Testcase Gist URL _No response_ ### Additional Information Using `--ozone-platform=wayland` does work, but then it fails when not running wayland.
https://github.com/electron/electron/issues/33810
https://github.com/electron/electron/pull/34937
9f0e7126c422c12333544de0a20f954addd13061
67eda4bcc81754a973a4455cd6db5ac624f4bfa0
2022-04-17T16:33:59Z
c++
2022-07-21T08:37:54Z
shell/browser/electron_browser_main_parts_linux.cc
closed
electron/electron
https://github.com/electron/electron
33,810
[Bug]: --ozone-platform-hint command line flag ignored
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Setting the `--ozone-platform-hint` flag to `auto` or `wayland` should make electron use wayland (assuming `--enable-features=UseOzonePlatform` is also set) ### Actual Behavior The flag is ignored. ### Testcase Gist URL _No response_ ### Additional Information Using `--ozone-platform=wayland` does work, but then it fails when not running wayland.
https://github.com/electron/electron/issues/33810
https://github.com/electron/electron/pull/34937
9f0e7126c422c12333544de0a20f954addd13061
67eda4bcc81754a973a4455cd6db5ac624f4bfa0
2022-04-17T16:33:59Z
c++
2022-07-21T08:37:54Z
filenames.gni
filenames = { default_app_ts_sources = [ "default_app/default_app.ts", "default_app/main.ts", "default_app/preload.ts", ] default_app_static_sources = [ "default_app/icon.png", "default_app/index.html", "default_app/package.json", "default_app/styles.css", ] default_app_octicon_sources = [ "node_modules/@primer/octicons/build/build.css", "node_modules/@primer/octicons/build/svg/book-24.svg", "node_modules/@primer/octicons/build/svg/code-square-24.svg", "node_modules/@primer/octicons/build/svg/gift-24.svg", "node_modules/@primer/octicons/build/svg/mark-github-16.svg", "node_modules/@primer/octicons/build/svg/star-fill-24.svg", ] lib_sources_linux = [ "shell/browser/browser_linux.cc", "shell/browser/lib/power_observer_linux.cc", "shell/browser/lib/power_observer_linux.h", "shell/browser/linux/unity_service.cc", "shell/browser/linux/unity_service.h", "shell/browser/notifications/linux/libnotify_notification.cc", "shell/browser/notifications/linux/libnotify_notification.h", "shell/browser/notifications/linux/notification_presenter_linux.cc", "shell/browser/notifications/linux/notification_presenter_linux.h", "shell/browser/relauncher_linux.cc", "shell/browser/ui/electron_desktop_window_tree_host_linux.cc", "shell/browser/ui/file_dialog_gtk.cc", "shell/browser/ui/message_box_gtk.cc", "shell/browser/ui/tray_icon_gtk.cc", "shell/browser/ui/tray_icon_gtk.h", "shell/browser/ui/views/client_frame_view_linux.cc", "shell/browser/ui/views/client_frame_view_linux.h", "shell/common/application_info_linux.cc", "shell/common/language_util_linux.cc", "shell/common/node_bindings_linux.cc", "shell/common/node_bindings_linux.h", "shell/common/platform_util_linux.cc", ] lib_sources_linux_x11 = [ "shell/browser/ui/views/global_menu_bar_registrar_x11.cc", "shell/browser/ui/views/global_menu_bar_registrar_x11.h", "shell/browser/ui/views/global_menu_bar_x11.cc", "shell/browser/ui/views/global_menu_bar_x11.h", "shell/browser/ui/x/event_disabler.cc", "shell/browser/ui/x/event_disabler.h", "shell/browser/ui/x/x_window_utils.cc", "shell/browser/ui/x/x_window_utils.h", ] lib_sources_posix = [ "shell/browser/electron_browser_main_parts_posix.cc" ] lib_sources_win = [ "shell/browser/api/electron_api_power_monitor_win.cc", "shell/browser/api/electron_api_system_preferences_win.cc", "shell/browser/browser_win.cc", "shell/browser/native_window_views_win.cc", "shell/browser/notifications/win/notification_presenter_win.cc", "shell/browser/notifications/win/notification_presenter_win.h", "shell/browser/notifications/win/notification_presenter_win7.cc", "shell/browser/notifications/win/notification_presenter_win7.h", "shell/browser/notifications/win/win32_desktop_notifications/common.h", "shell/browser/notifications/win/win32_desktop_notifications/desktop_notification_controller.cc", "shell/browser/notifications/win/win32_desktop_notifications/desktop_notification_controller.h", "shell/browser/notifications/win/win32_desktop_notifications/toast_uia.cc", "shell/browser/notifications/win/win32_desktop_notifications/toast_uia.h", "shell/browser/notifications/win/win32_desktop_notifications/toast.cc", "shell/browser/notifications/win/win32_desktop_notifications/toast.h", "shell/browser/notifications/win/win32_notification.cc", "shell/browser/notifications/win/win32_notification.h", "shell/browser/notifications/win/windows_toast_notification.cc", "shell/browser/notifications/win/windows_toast_notification.h", "shell/browser/relauncher_win.cc", "shell/browser/ui/certificate_trust_win.cc", "shell/browser/ui/file_dialog_win.cc", "shell/browser/ui/message_box_win.cc", "shell/browser/ui/tray_icon_win.cc", "shell/browser/ui/views/electron_views_delegate_win.cc", "shell/browser/ui/views/win_icon_painter.cc", "shell/browser/ui/views/win_icon_painter.h", "shell/browser/ui/views/win_frame_view.cc", "shell/browser/ui/views/win_frame_view.h", "shell/browser/ui/views/win_caption_button.cc", "shell/browser/ui/views/win_caption_button.h", "shell/browser/ui/views/win_caption_button_container.cc", "shell/browser/ui/views/win_caption_button_container.h", "shell/browser/ui/win/dialog_thread.cc", "shell/browser/ui/win/dialog_thread.h", "shell/browser/ui/win/electron_desktop_native_widget_aura.cc", "shell/browser/ui/win/electron_desktop_native_widget_aura.h", "shell/browser/ui/win/electron_desktop_window_tree_host_win.cc", "shell/browser/ui/win/electron_desktop_window_tree_host_win.h", "shell/browser/ui/win/jump_list.cc", "shell/browser/ui/win/jump_list.h", "shell/browser/ui/win/notify_icon_host.cc", "shell/browser/ui/win/notify_icon_host.h", "shell/browser/ui/win/notify_icon.cc", "shell/browser/ui/win/notify_icon.h", "shell/browser/ui/win/taskbar_host.cc", "shell/browser/ui/win/taskbar_host.h", "shell/browser/win/dark_mode.cc", "shell/browser/win/dark_mode.h", "shell/browser/win/scoped_hstring.cc", "shell/browser/win/scoped_hstring.h", "shell/common/api/electron_api_native_image_win.cc", "shell/common/application_info_win.cc", "shell/common/language_util_win.cc", "shell/common/node_bindings_win.cc", "shell/common/node_bindings_win.h", "shell/common/platform_util_win.cc", ] lib_sources_mac = [ "shell/app/electron_main_delegate_mac.h", "shell/app/electron_main_delegate_mac.mm", "shell/browser/api/electron_api_app_mac.mm", "shell/browser/api/electron_api_browser_window_mac.mm", "shell/browser/api/electron_api_menu_mac.h", "shell/browser/api/electron_api_menu_mac.mm", "shell/browser/api/electron_api_native_theme_mac.mm", "shell/browser/api/electron_api_power_monitor_mac.mm", "shell/browser/api/electron_api_push_notifications_mac.mm", "shell/browser/api/electron_api_system_preferences_mac.mm", "shell/browser/api/electron_api_web_contents_mac.mm", "shell/browser/auto_updater_mac.mm", "shell/browser/browser_mac.mm", "shell/browser/electron_browser_main_parts_mac.mm", "shell/browser/mac/dict_util.h", "shell/browser/mac/dict_util.mm", "shell/browser/mac/electron_application_delegate.h", "shell/browser/mac/electron_application_delegate.mm", "shell/browser/mac/electron_application.h", "shell/browser/mac/electron_application.mm", "shell/browser/mac/in_app_purchase_observer.h", "shell/browser/mac/in_app_purchase_observer.mm", "shell/browser/mac/in_app_purchase_product.h", "shell/browser/mac/in_app_purchase_product.mm", "shell/browser/mac/in_app_purchase.h", "shell/browser/mac/in_app_purchase.mm", "shell/browser/native_browser_view_mac.h", "shell/browser/native_browser_view_mac.mm", "shell/browser/native_window_mac.h", "shell/browser/native_window_mac.mm", "shell/browser/notifications/mac/cocoa_notification.h", "shell/browser/notifications/mac/cocoa_notification.mm", "shell/browser/notifications/mac/notification_center_delegate.h", "shell/browser/notifications/mac/notification_center_delegate.mm", "shell/browser/notifications/mac/notification_presenter_mac.h", "shell/browser/notifications/mac/notification_presenter_mac.mm", "shell/browser/relauncher_mac.cc", "shell/browser/ui/certificate_trust_mac.mm", "shell/browser/ui/cocoa/delayed_native_view_host.cc", "shell/browser/ui/cocoa/delayed_native_view_host.h", "shell/browser/ui/cocoa/electron_bundle_mover.h", "shell/browser/ui/cocoa/electron_bundle_mover.mm", "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.h", "shell/browser/ui/cocoa/electron_inspectable_web_contents_view.mm", "shell/browser/ui/cocoa/electron_menu_controller.h", "shell/browser/ui/cocoa/electron_menu_controller.mm", "shell/browser/ui/cocoa/electron_native_widget_mac.h", "shell/browser/ui/cocoa/electron_native_widget_mac.mm", "shell/browser/ui/cocoa/electron_ns_window_delegate.h", "shell/browser/ui/cocoa/electron_ns_window_delegate.mm", "shell/browser/ui/cocoa/electron_ns_panel.h", "shell/browser/ui/cocoa/electron_ns_panel.mm", "shell/browser/ui/cocoa/electron_ns_window.h", "shell/browser/ui/cocoa/electron_ns_window.mm", "shell/browser/ui/cocoa/electron_preview_item.h", "shell/browser/ui/cocoa/electron_preview_item.mm", "shell/browser/ui/cocoa/electron_touch_bar.h", "shell/browser/ui/cocoa/electron_touch_bar.mm", "shell/browser/ui/cocoa/event_dispatching_window.h", "shell/browser/ui/cocoa/event_dispatching_window.mm", "shell/browser/ui/cocoa/NSColor+Hex.h", "shell/browser/ui/cocoa/NSColor+Hex.mm", "shell/browser/ui/cocoa/NSString+ANSI.h", "shell/browser/ui/cocoa/NSString+ANSI.mm", "shell/browser/ui/cocoa/root_view_mac.h", "shell/browser/ui/cocoa/root_view_mac.mm", "shell/browser/ui/cocoa/views_delegate_mac.h", "shell/browser/ui/cocoa/views_delegate_mac.mm", "shell/browser/ui/cocoa/window_buttons_proxy.h", "shell/browser/ui/cocoa/window_buttons_proxy.mm", "shell/browser/ui/drag_util_mac.mm", "shell/browser/ui/file_dialog_mac.mm", "shell/browser/ui/inspectable_web_contents_view_mac.h", "shell/browser/ui/inspectable_web_contents_view_mac.mm", "shell/browser/ui/message_box_mac.mm", "shell/browser/ui/tray_icon_cocoa.h", "shell/browser/ui/tray_icon_cocoa.mm", "shell/common/api/electron_api_clipboard_mac.mm", "shell/common/api/electron_api_native_image_mac.mm", "shell/common/asar/archive_mac.mm", "shell/common/application_info_mac.mm", "shell/common/language_util_mac.mm", "shell/common/mac/main_application_bundle.h", "shell/common/mac/main_application_bundle.mm", "shell/common/node_bindings_mac.cc", "shell/common/node_bindings_mac.h", "shell/common/platform_util_mac.mm", ] lib_sources_views = [ "shell/browser/api/electron_api_browser_window_views.cc", "shell/browser/api/electron_api_menu_views.cc", "shell/browser/api/electron_api_menu_views.h", "shell/browser/native_browser_view_views.cc", "shell/browser/native_browser_view_views.h", "shell/browser/native_window_views.cc", "shell/browser/native_window_views.h", "shell/browser/ui/drag_util_views.cc", "shell/browser/ui/views/autofill_popup_view.cc", "shell/browser/ui/views/autofill_popup_view.h", "shell/browser/ui/views/electron_views_delegate.cc", "shell/browser/ui/views/electron_views_delegate.h", "shell/browser/ui/views/frameless_view.cc", "shell/browser/ui/views/frameless_view.h", "shell/browser/ui/views/inspectable_web_contents_view_views.cc", "shell/browser/ui/views/inspectable_web_contents_view_views.h", "shell/browser/ui/views/menu_bar.cc", "shell/browser/ui/views/menu_bar.h", "shell/browser/ui/views/menu_delegate.cc", "shell/browser/ui/views/menu_delegate.h", "shell/browser/ui/views/menu_model_adapter.cc", "shell/browser/ui/views/menu_model_adapter.h", "shell/browser/ui/views/native_frame_view.cc", "shell/browser/ui/views/native_frame_view.h", "shell/browser/ui/views/root_view.cc", "shell/browser/ui/views/root_view.h", "shell/browser/ui/views/submenu_button.cc", "shell/browser/ui/views/submenu_button.h", ] lib_sources = [ "shell/app/command_line_args.cc", "shell/app/command_line_args.h", "shell/app/electron_content_client.cc", "shell/app/electron_content_client.h", "shell/app/electron_crash_reporter_client.cc", "shell/app/electron_crash_reporter_client.h", "shell/app/electron_main_delegate.cc", "shell/app/electron_main_delegate.h", "shell/app/uv_task_runner.cc", "shell/app/uv_task_runner.h", "shell/browser/api/electron_api_app.cc", "shell/browser/api/electron_api_app.h", "shell/browser/api/electron_api_auto_updater.cc", "shell/browser/api/electron_api_auto_updater.h", "shell/browser/api/electron_api_base_window.cc", "shell/browser/api/electron_api_base_window.h", "shell/browser/api/electron_api_browser_view.cc", "shell/browser/api/electron_api_browser_view.h", "shell/browser/api/electron_api_browser_window.cc", "shell/browser/api/electron_api_browser_window.h", "shell/browser/api/electron_api_content_tracing.cc", "shell/browser/api/electron_api_cookies.cc", "shell/browser/api/electron_api_cookies.h", "shell/browser/api/electron_api_crash_reporter.cc", "shell/browser/api/electron_api_crash_reporter.h", "shell/browser/api/electron_api_data_pipe_holder.cc", "shell/browser/api/electron_api_data_pipe_holder.h", "shell/browser/api/electron_api_debugger.cc", "shell/browser/api/electron_api_debugger.h", "shell/browser/api/electron_api_dialog.cc", "shell/browser/api/electron_api_download_item.cc", "shell/browser/api/electron_api_download_item.h", "shell/browser/api/electron_api_event.cc", "shell/browser/api/electron_api_event_emitter.cc", "shell/browser/api/electron_api_event_emitter.h", "shell/browser/api/electron_api_global_shortcut.cc", "shell/browser/api/electron_api_global_shortcut.h", "shell/browser/api/electron_api_in_app_purchase.cc", "shell/browser/api/electron_api_in_app_purchase.h", "shell/browser/api/electron_api_menu.cc", "shell/browser/api/electron_api_menu.h", "shell/browser/api/electron_api_native_theme.cc", "shell/browser/api/electron_api_native_theme.h", "shell/browser/api/electron_api_net.cc", "shell/browser/api/electron_api_net_log.cc", "shell/browser/api/electron_api_net_log.h", "shell/browser/api/electron_api_notification.cc", "shell/browser/api/electron_api_notification.h", "shell/browser/api/electron_api_power_monitor.cc", "shell/browser/api/electron_api_power_monitor.h", "shell/browser/api/electron_api_power_save_blocker.cc", "shell/browser/api/electron_api_power_save_blocker.h", "shell/browser/api/electron_api_printing.cc", "shell/browser/api/electron_api_protocol.cc", "shell/browser/api/electron_api_protocol.h", "shell/browser/api/electron_api_push_notifications.cc", "shell/browser/api/electron_api_push_notifications.h", "shell/browser/api/electron_api_safe_storage.cc", "shell/browser/api/electron_api_safe_storage.h", "shell/browser/api/electron_api_screen.cc", "shell/browser/api/electron_api_screen.h", "shell/browser/api/electron_api_service_worker_context.cc", "shell/browser/api/electron_api_service_worker_context.h", "shell/browser/api/electron_api_session.cc", "shell/browser/api/electron_api_session.h", "shell/browser/api/electron_api_system_preferences.cc", "shell/browser/api/electron_api_system_preferences.h", "shell/browser/api/electron_api_tray.cc", "shell/browser/api/electron_api_tray.h", "shell/browser/api/electron_api_url_loader.cc", "shell/browser/api/electron_api_url_loader.h", "shell/browser/api/electron_api_view.cc", "shell/browser/api/electron_api_view.h", "shell/browser/api/electron_api_web_contents.cc", "shell/browser/api/electron_api_web_contents.h", "shell/browser/api/electron_api_web_contents_impl.cc", "shell/browser/api/electron_api_web_contents_view.cc", "shell/browser/api/electron_api_web_contents_view.h", "shell/browser/api/electron_api_web_frame_main.cc", "shell/browser/api/electron_api_web_frame_main.h", "shell/browser/api/electron_api_web_request.cc", "shell/browser/api/electron_api_web_request.h", "shell/browser/api/electron_api_web_view_manager.cc", "shell/browser/api/event.cc", "shell/browser/api/event.h", "shell/browser/api/frame_subscriber.cc", "shell/browser/api/frame_subscriber.h", "shell/browser/api/gpu_info_enumerator.cc", "shell/browser/api/gpu_info_enumerator.h", "shell/browser/api/gpuinfo_manager.cc", "shell/browser/api/gpuinfo_manager.h", "shell/browser/api/message_port.cc", "shell/browser/api/message_port.h", "shell/browser/api/process_metric.cc", "shell/browser/api/process_metric.h", "shell/browser/api/save_page_handler.cc", "shell/browser/api/save_page_handler.h", "shell/browser/api/ui_event.cc", "shell/browser/api/ui_event.h", "shell/browser/auto_updater.cc", "shell/browser/auto_updater.h", "shell/browser/badging/badge_manager.cc", "shell/browser/badging/badge_manager.h", "shell/browser/badging/badge_manager_factory.cc", "shell/browser/badging/badge_manager_factory.h", "shell/browser/bluetooth/electron_bluetooth_delegate.cc", "shell/browser/bluetooth/electron_bluetooth_delegate.h", "shell/browser/browser.cc", "shell/browser/browser.h", "shell/browser/browser_observer.h", "shell/browser/browser_process_impl.cc", "shell/browser/browser_process_impl.h", "shell/browser/child_web_contents_tracker.cc", "shell/browser/child_web_contents_tracker.h", "shell/browser/cookie_change_notifier.cc", "shell/browser/cookie_change_notifier.h", "shell/browser/electron_api_ipc_handler_impl.cc", "shell/browser/electron_api_ipc_handler_impl.h", "shell/browser/electron_autofill_driver.cc", "shell/browser/electron_autofill_driver.h", "shell/browser/electron_autofill_driver_factory.cc", "shell/browser/electron_autofill_driver_factory.h", "shell/browser/electron_browser_client.cc", "shell/browser/electron_browser_client.h", "shell/browser/electron_browser_context.cc", "shell/browser/electron_browser_context.h", "shell/browser/electron_browser_main_parts.cc", "shell/browser/electron_browser_main_parts.h", "shell/browser/electron_download_manager_delegate.cc", "shell/browser/electron_download_manager_delegate.h", "shell/browser/electron_gpu_client.cc", "shell/browser/electron_gpu_client.h", "shell/browser/electron_javascript_dialog_manager.cc", "shell/browser/electron_javascript_dialog_manager.h", "shell/browser/electron_navigation_throttle.cc", "shell/browser/electron_navigation_throttle.h", "shell/browser/electron_permission_manager.cc", "shell/browser/electron_permission_manager.h", "shell/browser/electron_quota_permission_context.cc", "shell/browser/electron_quota_permission_context.h", "shell/browser/electron_speech_recognition_manager_delegate.cc", "shell/browser/electron_speech_recognition_manager_delegate.h", "shell/browser/electron_web_contents_utility_handler_impl.cc", "shell/browser/electron_web_contents_utility_handler_impl.h", "shell/browser/electron_web_ui_controller_factory.cc", "shell/browser/electron_web_ui_controller_factory.h", "shell/browser/event_emitter_mixin.cc", "shell/browser/event_emitter_mixin.h", "shell/browser/extended_web_contents_observer.h", "shell/browser/feature_list.cc", "shell/browser/feature_list.h", "shell/browser/file_select_helper.cc", "shell/browser/file_select_helper.h", "shell/browser/file_select_helper_mac.mm", "shell/browser/font_defaults.cc", "shell/browser/font_defaults.h", "shell/browser/hid/electron_hid_delegate.cc", "shell/browser/hid/electron_hid_delegate.h", "shell/browser/hid/hid_chooser_context.cc", "shell/browser/hid/hid_chooser_context.h", "shell/browser/hid/hid_chooser_context_factory.cc", "shell/browser/hid/hid_chooser_context_factory.h", "shell/browser/hid/hid_chooser_controller.cc", "shell/browser/hid/hid_chooser_controller.h", "shell/browser/javascript_environment.cc", "shell/browser/javascript_environment.h", "shell/browser/lib/bluetooth_chooser.cc", "shell/browser/lib/bluetooth_chooser.h", "shell/browser/login_handler.cc", "shell/browser/login_handler.h", "shell/browser/media/media_capture_devices_dispatcher.cc", "shell/browser/media/media_capture_devices_dispatcher.h", "shell/browser/media/media_device_id_salt.cc", "shell/browser/media/media_device_id_salt.h", "shell/browser/microtasks_runner.cc", "shell/browser/microtasks_runner.h", "shell/browser/native_browser_view.cc", "shell/browser/native_browser_view.h", "shell/browser/native_window.cc", "shell/browser/native_window.h", "shell/browser/native_window_features.cc", "shell/browser/native_window_features.h", "shell/browser/native_window_observer.h", "shell/browser/net/asar/asar_file_validator.cc", "shell/browser/net/asar/asar_file_validator.h", "shell/browser/net/asar/asar_url_loader.cc", "shell/browser/net/asar/asar_url_loader.h", "shell/browser/net/asar/asar_url_loader_factory.cc", "shell/browser/net/asar/asar_url_loader_factory.h", "shell/browser/net/cert_verifier_client.cc", "shell/browser/net/cert_verifier_client.h", "shell/browser/net/electron_url_loader_factory.cc", "shell/browser/net/electron_url_loader_factory.h", "shell/browser/net/network_context_service.cc", "shell/browser/net/network_context_service.h", "shell/browser/net/network_context_service_factory.cc", "shell/browser/net/network_context_service_factory.h", "shell/browser/net/node_stream_loader.cc", "shell/browser/net/node_stream_loader.h", "shell/browser/net/proxying_url_loader_factory.cc", "shell/browser/net/proxying_url_loader_factory.h", "shell/browser/net/proxying_websocket.cc", "shell/browser/net/proxying_websocket.h", "shell/browser/net/resolve_proxy_helper.cc", "shell/browser/net/resolve_proxy_helper.h", "shell/browser/net/system_network_context_manager.cc", "shell/browser/net/system_network_context_manager.h", "shell/browser/net/url_pipe_loader.cc", "shell/browser/net/url_pipe_loader.h", "shell/browser/net/web_request_api_interface.h", "shell/browser/network_hints_handler_impl.cc", "shell/browser/network_hints_handler_impl.h", "shell/browser/notifications/notification.cc", "shell/browser/notifications/notification.h", "shell/browser/notifications/notification_delegate.h", "shell/browser/notifications/notification_presenter.cc", "shell/browser/notifications/notification_presenter.h", "shell/browser/notifications/platform_notification_service.cc", "shell/browser/notifications/platform_notification_service.h", "shell/browser/plugins/plugin_utils.cc", "shell/browser/plugins/plugin_utils.h", "shell/browser/pref_store_delegate.cc", "shell/browser/pref_store_delegate.h", "shell/browser/protocol_registry.cc", "shell/browser/protocol_registry.h", "shell/browser/relauncher.cc", "shell/browser/relauncher.h", "shell/browser/serial/electron_serial_delegate.cc", "shell/browser/serial/electron_serial_delegate.h", "shell/browser/serial/serial_chooser_context.cc", "shell/browser/serial/serial_chooser_context.h", "shell/browser/serial/serial_chooser_context_factory.cc", "shell/browser/serial/serial_chooser_context_factory.h", "shell/browser/serial/serial_chooser_controller.cc", "shell/browser/serial/serial_chooser_controller.h", "shell/browser/session_preferences.cc", "shell/browser/session_preferences.h", "shell/browser/special_storage_policy.cc", "shell/browser/special_storage_policy.h", "shell/browser/ui/accelerator_util.cc", "shell/browser/ui/accelerator_util.h", "shell/browser/ui/autofill_popup.cc", "shell/browser/ui/autofill_popup.h", "shell/browser/ui/certificate_trust.h", "shell/browser/ui/devtools_manager_delegate.cc", "shell/browser/ui/devtools_manager_delegate.h", "shell/browser/ui/devtools_ui.cc", "shell/browser/ui/devtools_ui.h", "shell/browser/ui/drag_util.cc", "shell/browser/ui/drag_util.h", "shell/browser/ui/electron_menu_model.cc", "shell/browser/ui/electron_menu_model.h", "shell/browser/ui/file_dialog.h", "shell/browser/ui/inspectable_web_contents.cc", "shell/browser/ui/inspectable_web_contents.h", "shell/browser/ui/inspectable_web_contents_delegate.h", "shell/browser/ui/inspectable_web_contents_view.h", "shell/browser/ui/inspectable_web_contents_view_delegate.cc", "shell/browser/ui/inspectable_web_contents_view_delegate.h", "shell/browser/ui/message_box.h", "shell/browser/ui/tray_icon.cc", "shell/browser/ui/tray_icon.h", "shell/browser/ui/tray_icon_observer.h", "shell/browser/ui/webui/accessibility_ui.cc", "shell/browser/ui/webui/accessibility_ui.h", "shell/browser/unresponsive_suppressor.cc", "shell/browser/unresponsive_suppressor.h", "shell/browser/web_contents_permission_helper.cc", "shell/browser/web_contents_permission_helper.h", "shell/browser/web_contents_preferences.cc", "shell/browser/web_contents_preferences.h", "shell/browser/web_contents_zoom_controller.cc", "shell/browser/web_contents_zoom_controller.h", "shell/browser/web_view_guest_delegate.cc", "shell/browser/web_view_guest_delegate.h", "shell/browser/web_view_manager.cc", "shell/browser/web_view_manager.h", "shell/browser/window_list.cc", "shell/browser/window_list.h", "shell/browser/window_list_observer.h", "shell/browser/zoom_level_delegate.cc", "shell/browser/zoom_level_delegate.h", "shell/common/api/electron_api_asar.cc", "shell/common/api/electron_api_clipboard.cc", "shell/common/api/electron_api_clipboard.h", "shell/common/api/electron_api_command_line.cc", "shell/common/api/electron_api_environment.cc", "shell/common/api/electron_api_key_weak_map.h", "shell/common/api/electron_api_native_image.cc", "shell/common/api/electron_api_native_image.h", "shell/common/api/electron_api_shell.cc", "shell/common/api/electron_api_testing.cc", "shell/common/api/electron_api_v8_util.cc", "shell/common/api/electron_bindings.cc", "shell/common/api/electron_bindings.h", "shell/common/api/features.cc", "shell/common/api/object_life_monitor.cc", "shell/common/api/object_life_monitor.h", "shell/common/application_info.cc", "shell/common/application_info.h", "shell/common/asar/archive.cc", "shell/common/asar/archive.h", "shell/common/asar/asar_util.cc", "shell/common/asar/asar_util.h", "shell/common/asar/scoped_temporary_file.cc", "shell/common/asar/scoped_temporary_file.h", "shell/common/color_util.cc", "shell/common/color_util.h", "shell/common/crash_keys.cc", "shell/common/crash_keys.h", "shell/common/electron_command_line.cc", "shell/common/electron_command_line.h", "shell/common/electron_constants.cc", "shell/common/electron_constants.h", "shell/common/electron_paths.h", "shell/common/gin_converters/accelerator_converter.cc", "shell/common/gin_converters/accelerator_converter.h", "shell/common/gin_converters/base_converter.h", "shell/common/gin_converters/blink_converter.cc", "shell/common/gin_converters/blink_converter.h", "shell/common/gin_converters/callback_converter.h", "shell/common/gin_converters/content_converter.cc", "shell/common/gin_converters/content_converter.h", "shell/common/gin_converters/file_dialog_converter.cc", "shell/common/gin_converters/file_dialog_converter.h", "shell/common/gin_converters/file_path_converter.h", "shell/common/gin_converters/frame_converter.cc", "shell/common/gin_converters/frame_converter.h", "shell/common/gin_converters/gfx_converter.cc", "shell/common/gin_converters/gfx_converter.h", "shell/common/gin_converters/guid_converter.h", "shell/common/gin_converters/gurl_converter.h", "shell/common/gin_converters/hid_device_info_converter.h", "shell/common/gin_converters/image_converter.cc", "shell/common/gin_converters/image_converter.h", "shell/common/gin_converters/message_box_converter.cc", "shell/common/gin_converters/message_box_converter.h", "shell/common/gin_converters/native_window_converter.h", "shell/common/gin_converters/net_converter.cc", "shell/common/gin_converters/net_converter.h", "shell/common/gin_converters/std_converter.h", "shell/common/gin_converters/time_converter.cc", "shell/common/gin_converters/time_converter.h", "shell/common/gin_converters/value_converter.cc", "shell/common/gin_converters/value_converter.h", "shell/common/gin_helper/arguments.cc", "shell/common/gin_helper/arguments.h", "shell/common/gin_helper/callback.cc", "shell/common/gin_helper/callback.h", "shell/common/gin_helper/cleaned_up_at_exit.cc", "shell/common/gin_helper/cleaned_up_at_exit.h", "shell/common/gin_helper/constructible.h", "shell/common/gin_helper/constructor.h", "shell/common/gin_helper/destroyable.cc", "shell/common/gin_helper/destroyable.h", "shell/common/gin_helper/dictionary.h", "shell/common/gin_helper/error_thrower.cc", "shell/common/gin_helper/error_thrower.h", "shell/common/gin_helper/event_emitter.cc", "shell/common/gin_helper/event_emitter.h", "shell/common/gin_helper/event_emitter_caller.cc", "shell/common/gin_helper/event_emitter_caller.h", "shell/common/gin_helper/function_template.cc", "shell/common/gin_helper/function_template.h", "shell/common/gin_helper/function_template_extensions.h", "shell/common/gin_helper/locker.cc", "shell/common/gin_helper/locker.h", "shell/common/gin_helper/microtasks_scope.cc", "shell/common/gin_helper/microtasks_scope.h", "shell/common/gin_helper/object_template_builder.cc", "shell/common/gin_helper/object_template_builder.h", "shell/common/gin_helper/persistent_dictionary.cc", "shell/common/gin_helper/persistent_dictionary.h", "shell/common/gin_helper/pinnable.h", "shell/common/gin_helper/promise.cc", "shell/common/gin_helper/promise.h", "shell/common/gin_helper/trackable_object.cc", "shell/common/gin_helper/trackable_object.h", "shell/common/gin_helper/wrappable.cc", "shell/common/gin_helper/wrappable.h", "shell/common/gin_helper/wrappable_base.h", "shell/common/heap_snapshot.cc", "shell/common/heap_snapshot.h", "shell/common/key_weak_map.h", "shell/common/keyboard_util.cc", "shell/common/keyboard_util.h", "shell/common/language_util.h", "shell/common/logging.cc", "shell/common/logging.h", "shell/common/mouse_util.cc", "shell/common/mouse_util.h", "shell/common/node_bindings.cc", "shell/common/node_bindings.h", "shell/common/node_includes.h", "shell/common/node_util.cc", "shell/common/node_util.h", "shell/common/options_switches.cc", "shell/common/options_switches.h", "shell/common/platform_util.cc", "shell/common/platform_util.h", "shell/common/platform_util_internal.h", "shell/common/process_util.cc", "shell/common/process_util.h", "shell/common/skia_util.cc", "shell/common/skia_util.h", "shell/common/v8_value_serializer.cc", "shell/common/v8_value_serializer.h", "shell/common/world_ids.h", "shell/renderer/api/context_bridge/object_cache.cc", "shell/renderer/api/context_bridge/object_cache.h", "shell/renderer/api/electron_api_context_bridge.cc", "shell/renderer/api/electron_api_context_bridge.h", "shell/renderer/api/electron_api_crash_reporter_renderer.cc", "shell/renderer/api/electron_api_ipc_renderer.cc", "shell/renderer/api/electron_api_spell_check_client.cc", "shell/renderer/api/electron_api_spell_check_client.h", "shell/renderer/api/electron_api_web_frame.cc", "shell/renderer/browser_exposed_renderer_interfaces.cc", "shell/renderer/browser_exposed_renderer_interfaces.h", "shell/renderer/content_settings_observer.cc", "shell/renderer/content_settings_observer.h", "shell/renderer/electron_api_service_impl.cc", "shell/renderer/electron_api_service_impl.h", "shell/renderer/electron_autofill_agent.cc", "shell/renderer/electron_autofill_agent.h", "shell/renderer/electron_render_frame_observer.cc", "shell/renderer/electron_render_frame_observer.h", "shell/renderer/electron_renderer_client.cc", "shell/renderer/electron_renderer_client.h", "shell/renderer/electron_renderer_pepper_host_factory.cc", "shell/renderer/electron_renderer_pepper_host_factory.h", "shell/renderer/electron_sandboxed_renderer_client.cc", "shell/renderer/electron_sandboxed_renderer_client.h", "shell/renderer/guest_view_container.cc", "shell/renderer/guest_view_container.h", "shell/renderer/renderer_client_base.cc", "shell/renderer/renderer_client_base.h", "shell/renderer/web_worker_observer.cc", "shell/renderer/web_worker_observer.h", "shell/utility/electron_content_utility_client.cc", "shell/utility/electron_content_utility_client.h", ] lib_sources_extensions = [ "shell/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.cc", "shell/browser/extensions/api/cryptotoken_private/cryptotoken_private_api.h", "shell/browser/extensions/api/management/electron_management_api_delegate.cc", "shell/browser/extensions/api/management/electron_management_api_delegate.h", "shell/browser/extensions/api/resources_private/resources_private_api.cc", "shell/browser/extensions/api/resources_private/resources_private_api.h", "shell/browser/extensions/api/runtime/electron_runtime_api_delegate.cc", "shell/browser/extensions/api/runtime/electron_runtime_api_delegate.h", "shell/browser/extensions/api/streams_private/streams_private_api.cc", "shell/browser/extensions/api/streams_private/streams_private_api.h", "shell/browser/extensions/api/tabs/tabs_api.cc", "shell/browser/extensions/api/tabs/tabs_api.h", "shell/browser/extensions/electron_browser_context_keyed_service_factories.cc", "shell/browser/extensions/electron_browser_context_keyed_service_factories.h", "shell/browser/extensions/electron_component_extension_resource_manager.cc", "shell/browser/extensions/electron_component_extension_resource_manager.h", "shell/browser/extensions/electron_display_info_provider.cc", "shell/browser/extensions/electron_display_info_provider.h", "shell/browser/extensions/electron_extension_host_delegate.cc", "shell/browser/extensions/electron_extension_host_delegate.h", "shell/browser/extensions/electron_extension_loader.cc", "shell/browser/extensions/electron_extension_loader.h", "shell/browser/extensions/electron_extension_message_filter.cc", "shell/browser/extensions/electron_extension_message_filter.h", "shell/browser/extensions/electron_extension_system_factory.cc", "shell/browser/extensions/electron_extension_system_factory.h", "shell/browser/extensions/electron_extension_system.cc", "shell/browser/extensions/electron_extension_system.h", "shell/browser/extensions/electron_extension_web_contents_observer.cc", "shell/browser/extensions/electron_extension_web_contents_observer.h", "shell/browser/extensions/electron_extensions_api_client.cc", "shell/browser/extensions/electron_extensions_api_client.h", "shell/browser/extensions/electron_extensions_browser_api_provider.cc", "shell/browser/extensions/electron_extensions_browser_api_provider.h", "shell/browser/extensions/electron_extensions_browser_client.cc", "shell/browser/extensions/electron_extensions_browser_client.h", "shell/browser/extensions/electron_kiosk_delegate.cc", "shell/browser/extensions/electron_kiosk_delegate.h", "shell/browser/extensions/electron_messaging_delegate.cc", "shell/browser/extensions/electron_messaging_delegate.h", "shell/browser/extensions/electron_navigation_ui_data.cc", "shell/browser/extensions/electron_navigation_ui_data.h", "shell/browser/extensions/electron_process_manager_delegate.cc", "shell/browser/extensions/electron_process_manager_delegate.h", "shell/common/extensions/electron_extensions_api_provider.cc", "shell/common/extensions/electron_extensions_api_provider.h", "shell/common/extensions/electron_extensions_client.cc", "shell/common/extensions/electron_extensions_client.h", "shell/common/gin_converters/extension_converter.cc", "shell/common/gin_converters/extension_converter.h", "shell/renderer/extensions/electron_extensions_dispatcher_delegate.cc", "shell/renderer/extensions/electron_extensions_dispatcher_delegate.h", "shell/renderer/extensions/electron_extensions_renderer_client.cc", "shell/renderer/extensions/electron_extensions_renderer_client.h", ] framework_sources = [ "shell/app/electron_library_main.h", "shell/app/electron_library_main.mm", ] login_helper_sources = [ "shell/app/electron_login_helper.mm" ] }
closed
electron/electron
https://github.com/electron/electron
33,810
[Bug]: --ozone-platform-hint command line flag ignored
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Setting the `--ozone-platform-hint` flag to `auto` or `wayland` should make electron use wayland (assuming `--enable-features=UseOzonePlatform` is also set) ### Actual Behavior The flag is ignored. ### Testcase Gist URL _No response_ ### Additional Information Using `--ozone-platform=wayland` does work, but then it fails when not running wayland.
https://github.com/electron/electron/issues/33810
https://github.com/electron/electron/pull/34937
9f0e7126c422c12333544de0a20f954addd13061
67eda4bcc81754a973a4455cd6db5ac624f4bfa0
2022-04-17T16:33:59Z
c++
2022-07-21T08:37:54Z
shell/browser/electron_browser_main_parts.cc
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/electron_browser_main_parts.h" #include <memory> #include <string> #include <utility> #include "base/base_switches.h" #include "base/command_line.h" #include "base/feature_list.h" #include "base/metrics/field_trial.h" #include "base/path_service.h" #include "base/run_loop.h" #include "base/strings/string_number_conversions.h" #include "base/strings/utf_string_conversions.h" #include "chrome/browser/icon_manager.h" #include "chrome/common/chrome_paths.h" #include "chrome/common/chrome_switches.h" #include "components/os_crypt/key_storage_config_linux.h" #include "components/os_crypt/os_crypt.h" #include "content/browser/browser_main_loop.h" // nogncheck #include "content/public/browser/browser_thread.h" #include "content/public/browser/child_process_security_policy.h" #include "content/public/browser/device_service.h" #include "content/public/browser/first_party_sets_handler.h" #include "content/public/browser/web_ui_controller_factory.h" #include "content/public/common/content_features.h" #include "content/public/common/content_switches.h" #include "content/public/common/result_codes.h" #include "electron/buildflags/buildflags.h" #include "electron/fuses.h" #include "media/base/localized_strings.h" #include "services/network/public/cpp/features.h" #include "services/tracing/public/cpp/stack_sampling/tracing_sampler_profiler.h" #include "shell/app/electron_main_delegate.h" #include "shell/browser/api/electron_api_app.h" #include "shell/browser/browser.h" #include "shell/browser/browser_process_impl.h" #include "shell/browser/electron_browser_client.h" #include "shell/browser/electron_browser_context.h" #include "shell/browser/electron_web_ui_controller_factory.h" #include "shell/browser/feature_list.h" #include "shell/browser/javascript_environment.h" #include "shell/browser/media/media_capture_devices_dispatcher.h" #include "shell/browser/ui/devtools_manager_delegate.h" #include "shell/common/api/electron_bindings.h" #include "shell/common/application_info.h" #include "shell/common/electron_paths.h" #include "shell/common/gin_helper/trackable_object.h" #include "shell/common/logging.h" #include "shell/common/node_bindings.h" #include "shell/common/node_includes.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/base/idle/idle.h" #include "ui/base/l10n/l10n_util.h" #include "ui/base/ui_base_switches.h" #if defined(USE_AURA) #include "ui/display/display.h" #include "ui/display/screen.h" #include "ui/views/widget/desktop_aura/desktop_screen.h" #include "ui/wm/core/wm_state.h" #endif #if BUILDFLAG(IS_LINUX) #include "base/environment.h" #include "base/threading/thread_task_runner_handle.h" #include "device/bluetooth/bluetooth_adapter_factory.h" #include "device/bluetooth/dbus/dbus_bluez_manager_wrapper_linux.h" #include "electron/electron_gtk_stubs.h" #include "ui/base/cursor/cursor_factory.h" #include "ui/base/ime/linux/linux_input_method_context_factory.h" #include "ui/gfx/color_utils.h" #include "ui/gtk/gtk_compat.h" // nogncheck #include "ui/gtk/gtk_util.h" // nogncheck #include "ui/linux/linux_ui.h" #include "ui/linux/linux_ui_factory.h" #include "ui/ozone/public/ozone_platform.h" #endif #if BUILDFLAG(IS_WIN) #include "ui/base/l10n/l10n_util_win.h" #include "ui/display/win/dpi.h" #include "ui/gfx/system_fonts_win.h" #include "ui/strings/grit/app_locale_settings.h" #endif #if BUILDFLAG(IS_MAC) #include "services/device/public/cpp/geolocation/geolocation_manager.h" #include "shell/browser/ui/cocoa/views_delegate_mac.h" #else #include "shell/browser/ui/views/electron_views_delegate.h" #endif #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #include "components/keyed_service/content/browser_context_dependency_manager.h" #include "extensions/browser/browser_context_keyed_service_factories.h" #include "extensions/common/extension_api.h" #include "shell/browser/extensions/electron_browser_context_keyed_service_factories.h" #include "shell/browser/extensions/electron_extensions_browser_client.h" #include "shell/common/extensions/electron_extensions_client.h" #endif // BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) #include "chrome/browser/spellchecker/spellcheck_factory.h" // nogncheck #endif namespace electron { namespace { template <typename T> void Erase(T* container, typename T::iterator iter) { container->erase(iter); } #if BUILDFLAG(IS_WIN) // gfx::Font callbacks void AdjustUIFont(gfx::win::FontAdjustment* font_adjustment) { l10n_util::NeedOverrideDefaultUIFont(&font_adjustment->font_family_override, &font_adjustment->font_scale); font_adjustment->font_scale *= display::win::GetAccessibilityFontScale(); } int GetMinimumFontSize() { int min_font_size; base::StringToInt(l10n_util::GetStringUTF16(IDS_MINIMUM_UI_FONT_SIZE), &min_font_size); return min_font_size; } #endif std::u16string MediaStringProvider(media::MessageId id) { switch (id) { case media::DEFAULT_AUDIO_DEVICE_NAME: return u"Default"; #if BUILDFLAG(IS_WIN) case media::COMMUNICATIONS_AUDIO_DEVICE_NAME: return u"Communications"; #endif default: return std::u16string(); } } #if BUILDFLAG(IS_LINUX) // GTK does not provide a way to check if current theme is dark, so we compare // the text and background luminosity to get a result. // This trick comes from FireFox. void UpdateDarkThemeSetting() { float bg = color_utils::GetRelativeLuminance(gtk::GetBgColor("GtkLabel")); float fg = color_utils::GetRelativeLuminance(gtk::GetFgColor("GtkLabel")); bool is_dark = fg > bg; // Pass it to NativeUi theme, which is used by the nativeTheme module and most // places in Electron. ui::NativeTheme::GetInstanceForNativeUi()->set_use_dark_colors(is_dark); // Pass it to Web Theme, to make "prefers-color-scheme" media query work. ui::NativeTheme::GetInstanceForWeb()->set_use_dark_colors(is_dark); } #endif } // namespace #if BUILDFLAG(IS_LINUX) class DarkThemeObserver : public ui::NativeThemeObserver { public: DarkThemeObserver() = default; // ui::NativeThemeObserver: void OnNativeThemeUpdated(ui::NativeTheme* observed_theme) override { UpdateDarkThemeSetting(); } }; #endif // static ElectronBrowserMainParts* ElectronBrowserMainParts::self_ = nullptr; ElectronBrowserMainParts::ElectronBrowserMainParts() : fake_browser_process_(std::make_unique<BrowserProcessImpl>()), browser_(std::make_unique<Browser>()), node_bindings_( NodeBindings::Create(NodeBindings::BrowserEnvironment::kBrowser)), electron_bindings_( std::make_unique<ElectronBindings>(node_bindings_->uv_loop())) { DCHECK(!self_) << "Cannot have two ElectronBrowserMainParts"; self_ = this; } ElectronBrowserMainParts::~ElectronBrowserMainParts() = default; // static ElectronBrowserMainParts* ElectronBrowserMainParts::Get() { DCHECK(self_); return self_; } bool ElectronBrowserMainParts::SetExitCode(int code) { if (!exit_code_) return false; content::BrowserMainLoop::GetInstance()->SetResultCode(code); *exit_code_ = code; return true; } int ElectronBrowserMainParts::GetExitCode() const { return exit_code_.value_or(content::RESULT_CODE_NORMAL_EXIT); } int ElectronBrowserMainParts::PreEarlyInitialization() { field_trial_list_ = std::make_unique<base::FieldTrialList>(nullptr); #if BUILDFLAG(IS_POSIX) HandleSIGCHLD(); #endif #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::PreEarlyInitialization(); #endif #if BUILDFLAG(IS_MAC) screen_ = std::make_unique<display::ScopedNativeScreen>(); #endif return GetExitCode(); } void ElectronBrowserMainParts::PostEarlyInitialization() { // A workaround was previously needed because there was no ThreadTaskRunner // set. If this check is failing we may need to re-add that workaround DCHECK(base::ThreadTaskRunnerHandle::IsSet()); // The ProxyResolverV8 has setup a complete V8 environment, in order to // avoid conflicts we only initialize our V8 environment after that. js_env_ = std::make_unique<JavascriptEnvironment>(node_bindings_->uv_loop()); v8::HandleScope scope(js_env_->isolate()); node_bindings_->Initialize(); // Create the global environment. node::Environment* env = node_bindings_->CreateEnvironment( js_env_->context(), js_env_->platform()); node_env_ = std::make_unique<NodeEnvironment>(env); env->set_trace_sync_io(env->options()->trace_sync_io); // We do not want to crash the main process on unhandled rejections. env->options()->unhandled_rejections = "warn"; // Add Electron extended APIs. electron_bindings_->BindTo(js_env_->isolate(), env->process_object()); // Load everything. node_bindings_->LoadEnvironment(env); // Wrap the uv loop with global env. node_bindings_->set_uv_env(env); // We already initialized the feature list in PreEarlyInitialization(), but // the user JS script would not have had a chance to alter the command-line // switches at that point. Lets reinitialize it here to pick up the // command-line changes. base::FeatureList::ClearInstanceForTesting(); InitializeFeatureList(); // Initialize field trials. InitializeFieldTrials(); // Reinitialize logging now that the app has had a chance to set the app name // and/or user data directory. logging::InitElectronLogging(*base::CommandLine::ForCurrentProcess(), /* is_preinit = */ false); // Initialize after user script environment creation. fake_browser_process_->PostEarlyInitialization(); } int ElectronBrowserMainParts::PreCreateThreads() { #if defined(USE_AURA) if (!display::Screen::GetScreen()) { screen_ = views::CreateDesktopScreen(); } #endif if (!views::LayoutProvider::Get()) layout_provider_ = std::make_unique<views::LayoutProvider>(); auto* command_line = base::CommandLine::ForCurrentProcess(); std::string locale = command_line->GetSwitchValueASCII(::switches::kLang); #if BUILDFLAG(IS_MAC) // The browser process only wants to support the language Cocoa will use, // so force the app locale to be overridden with that value. This must // happen before the ResourceBundle is loaded if (locale.empty()) l10n_util::OverrideLocaleWithCocoaLocale(); #elif BUILDFLAG(IS_LINUX) // l10n_util::GetApplicationLocaleInternal uses g_get_language_names(), // which keys off of getenv("LC_ALL"). // We must set this env first to make ui::ResourceBundle accept the custom // locale. auto env = base::Environment::Create(); absl::optional<std::string> lc_all; if (!locale.empty()) { std::string str; if (env->GetVar("LC_ALL", &str)) lc_all.emplace(std::move(str)); env->SetVar("LC_ALL", locale.c_str()); } #endif // Load resources bundle according to locale. std::string loaded_locale = LoadResourceBundle(locale); // Initialize the app locale. std::string app_locale = l10n_util::GetApplicationLocale(loaded_locale); ElectronBrowserClient::SetApplicationLocale(app_locale); fake_browser_process_->SetApplicationLocale(app_locale); #if BUILDFLAG(IS_LINUX) // Reset to the original LC_ALL since we should not be changing it. if (!locale.empty()) { if (lc_all) env->SetVar("LC_ALL", *lc_all); else env->UnSetVar("LC_ALL"); } #endif // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); // Force MediaCaptureDevicesDispatcher to be created on UI thread. MediaCaptureDevicesDispatcher::GetInstance(); #if BUILDFLAG(IS_MAC) ui::InitIdleMonitor(); #endif fake_browser_process_->PreCreateThreads(); // Notify observers. Browser::Get()->PreCreateThreads(); return 0; } void ElectronBrowserMainParts::PostCreateThreads() { content::GetIOThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce(&tracing::TracingSamplerProfiler::CreateOnChildThread)); } void ElectronBrowserMainParts::PostDestroyThreads() { #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_browser_client_.reset(); extensions::ExtensionsBrowserClient::Set(nullptr); #endif #if BUILDFLAG(IS_LINUX) device::BluetoothAdapterFactory::Shutdown(); bluez::DBusBluezManagerWrapperLinux::Shutdown(); #endif fake_browser_process_->PostDestroyThreads(); } void ElectronBrowserMainParts::ToolkitInitialized() { #if BUILDFLAG(IS_LINUX) auto linux_ui = ui::CreateLinuxUi(); DCHECK(ui::LinuxInputMethodContextFactory::instance()); // Try loading gtk symbols used by Electron. electron::InitializeElectron_gtk(gtk::GetLibGtk()); if (!electron::IsElectron_gtkInitialized()) { electron::UninitializeElectron_gtk(); } electron::InitializeElectron_gdk_pixbuf(gtk::GetLibGdkPixbuf()); CHECK(electron::IsElectron_gdk_pixbufInitialized()) << "Failed to initialize libgdk_pixbuf-2.0.so.0"; // Chromium does not respect GTK dark theme setting, but they may change // in future and this code might be no longer needed. Check the Chromium // issue to keep updated: // https://bugs.chromium.org/p/chromium/issues/detail?id=998903 UpdateDarkThemeSetting(); // Update the native theme when GTK theme changes. The GetNativeTheme // here returns a NativeThemeGtk, which monitors GTK settings. dark_theme_observer_ = std::make_unique<DarkThemeObserver>(); linux_ui->GetNativeTheme(nullptr)->AddObserver(dark_theme_observer_.get()); ui::LinuxUi::SetInstance(std::move(linux_ui)); // Cursor theme changes are tracked by LinuxUI (via a CursorThemeManager // implementation). Start observing them once it's initialized. ui::CursorFactory::GetInstance()->ObserveThemeChanges(); #endif #if defined(USE_AURA) wm_state_ = std::make_unique<wm::WMState>(); #endif #if BUILDFLAG(IS_WIN) gfx::win::SetAdjustFontCallback(&AdjustUIFont); gfx::win::SetGetMinimumFontSizeCallback(&GetMinimumFontSize); #endif #if BUILDFLAG(IS_MAC) views_delegate_ = std::make_unique<ViewsDelegateMac>(); #else views_delegate_ = std::make_unique<ViewsDelegate>(); #endif } int ElectronBrowserMainParts::PreMainMessageLoopRun() { // Run user's main script before most things get initialized, so we can have // a chance to setup everything. node_bindings_->PrepareEmbedThread(); node_bindings_->StartPolling(); // url::Add*Scheme are not threadsafe, this helps prevent data races. url::LockSchemeRegistries(); #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) extensions_client_ = std::make_unique<ElectronExtensionsClient>(); extensions::ExtensionsClient::Set(extensions_client_.get()); // BrowserContextKeyedAPIServiceFactories require an ExtensionsBrowserClient. extensions_browser_client_ = std::make_unique<ElectronExtensionsBrowserClient>(); extensions::ExtensionsBrowserClient::Set(extensions_browser_client_.get()); extensions::EnsureBrowserContextKeyedServiceFactoriesBuilt(); extensions::electron::EnsureBrowserContextKeyedServiceFactoriesBuilt(); #endif #if BUILDFLAG(ENABLE_BUILTIN_SPELLCHECKER) SpellcheckServiceFactory::GetInstance(); #endif content::WebUIControllerFactory::RegisterFactory( ElectronWebUIControllerFactory::GetInstance()); auto* command_line = base::CommandLine::ForCurrentProcess(); if (command_line->HasSwitch(switches::kRemoteDebuggingPipe)) { // --remote-debugging-pipe auto on_disconnect = base::BindOnce([]() { content::GetUIThreadTaskRunner({})->PostTask( FROM_HERE, base::BindOnce([]() { Browser::Get()->Quit(); })); }); content::DevToolsAgentHost::StartRemoteDebuggingPipeHandler( std::move(on_disconnect)); } else if (command_line->HasSwitch(switches::kRemoteDebuggingPort)) { // --remote-debugging-port DevToolsManagerDelegate::StartHttpHandler(); } #if !BUILDFLAG(IS_MAC) // The corresponding call in macOS is in ElectronApplicationDelegate. Browser::Get()->WillFinishLaunching(); Browser::Get()->DidFinishLaunching(base::Value::Dict()); #endif // Notify observers that main thread message loop was initialized. Browser::Get()->PreMainMessageLoopRun(); return GetExitCode(); } void ElectronBrowserMainParts::WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) { js_env_->OnMessageLoopCreated(); exit_code_ = content::RESULT_CODE_NORMAL_EXIT; Browser::Get()->SetMainMessageLoopQuitClosure( run_loop->QuitWhenIdleClosure()); } void ElectronBrowserMainParts::PostCreateMainMessageLoop() { #if BUILDFLAG(IS_LINUX) auto shutdown_cb = base::BindOnce(base::RunLoop::QuitCurrentWhenIdleClosureDeprecated()); ui::OzonePlatform::GetInstance()->PostCreateMainMessageLoop( std::move(shutdown_cb)); bluez::DBusBluezManagerWrapperLinux::Initialize(); // Set up crypt config. This needs to be done before anything starts the // network service, as the raw encryption key needs to be shared with the // network service for encrypted cookie storage. std::string app_name = electron::Browser::Get()->GetName(); const base::CommandLine& command_line = *base::CommandLine::ForCurrentProcess(); std::unique_ptr<os_crypt::Config> config = std::make_unique<os_crypt::Config>(); // Forward to os_crypt the flag to use a specific password store. config->store = command_line.GetSwitchValueASCII(::switches::kPasswordStore); config->product_name = app_name; config->application_name = app_name; config->main_thread_runner = base::ThreadTaskRunnerHandle::Get(); // c.f. // https://source.chromium.org/chromium/chromium/src/+/master:chrome/common/chrome_switches.cc;l=689;drc=9d82515060b9b75fa941986f5db7390299669ef1 config->should_use_preference = command_line.HasSwitch(::switches::kEnableEncryptionSelection); base::PathService::Get(DIR_SESSION_DATA, &config->user_data_path); OSCrypt::SetConfig(std::move(config)); #endif #if BUILDFLAG(IS_POSIX) // Exit in response to SIGINT, SIGTERM, etc. InstallShutdownSignalHandlers( base::BindOnce(&Browser::Quit, base::Unretained(Browser::Get())), content::GetUIThreadTaskRunner({})); #endif } void ElectronBrowserMainParts::PostMainMessageLoopRun() { #if BUILDFLAG(IS_MAC) FreeAppDelegate(); #endif // Shutdown the DownloadManager before destroying Node to prevent // DownloadItem callbacks from crashing. for (auto& iter : ElectronBrowserContext::browser_context_map()) { auto* download_manager = iter.second.get()->GetDownloadManager(); if (download_manager) { download_manager->Shutdown(); } } // Destroy node platform after all destructors_ are executed, as they may // invoke Node/V8 APIs inside them. node_env_->env()->set_trace_sync_io(false); js_env_->OnMessageLoopDestroying(); node::Stop(node_env_->env()); node_env_.reset(); auto default_context_key = ElectronBrowserContext::PartitionKey("", false); std::unique_ptr<ElectronBrowserContext> default_context = std::move( ElectronBrowserContext::browser_context_map()[default_context_key]); ElectronBrowserContext::browser_context_map().clear(); default_context.reset(); fake_browser_process_->PostMainMessageLoopRun(); content::DevToolsAgentHost::StopRemoteDebuggingPipeHandler(); #if BUILDFLAG(IS_LINUX) ui::OzonePlatform::GetInstance()->PostMainMessageLoopRun(); #endif } #if !BUILDFLAG(IS_MAC) void ElectronBrowserMainParts::PreCreateMainMessageLoop() { PreCreateMainMessageLoopCommon(); } #endif void ElectronBrowserMainParts::PreCreateMainMessageLoopCommon() { #if BUILDFLAG(IS_MAC) InitializeMainNib(); RegisterURLHandler(); #endif media::SetLocalizedStringProvider(MediaStringProvider); #if BUILDFLAG(IS_WIN) auto* local_state = g_browser_process->local_state(); DCHECK(local_state); bool os_crypt_init = OSCrypt::Init(local_state); DCHECK(os_crypt_init); #endif } device::mojom::GeolocationControl* ElectronBrowserMainParts::GetGeolocationControl() { if (!geolocation_control_) { content::GetDeviceService().BindGeolocationControl( geolocation_control_.BindNewPipeAndPassReceiver()); } return geolocation_control_.get(); } #if BUILDFLAG(IS_MAC) device::GeolocationManager* ElectronBrowserMainParts::GetGeolocationManager() { return geolocation_manager_.get(); } #endif IconManager* ElectronBrowserMainParts::GetIconManager() { DCHECK_CURRENTLY_ON(content::BrowserThread::UI); if (!icon_manager_.get()) icon_manager_ = std::make_unique<IconManager>(); return icon_manager_.get(); } } // namespace electron
closed
electron/electron
https://github.com/electron/electron
33,810
[Bug]: --ozone-platform-hint command line flag ignored
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Setting the `--ozone-platform-hint` flag to `auto` or `wayland` should make electron use wayland (assuming `--enable-features=UseOzonePlatform` is also set) ### Actual Behavior The flag is ignored. ### Testcase Gist URL _No response_ ### Additional Information Using `--ozone-platform=wayland` does work, but then it fails when not running wayland.
https://github.com/electron/electron/issues/33810
https://github.com/electron/electron/pull/34937
9f0e7126c422c12333544de0a20f954addd13061
67eda4bcc81754a973a4455cd6db5ac624f4bfa0
2022-04-17T16:33:59Z
c++
2022-07-21T08:37:54Z
shell/browser/electron_browser_main_parts.h
// Copyright (c) 2013 GitHub, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #ifndef ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_MAIN_PARTS_H_ #define ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_MAIN_PARTS_H_ #include <memory> #include <string> #include "base/callback.h" #include "base/timer/timer.h" #include "content/public/browser/browser_context.h" #include "content/public/browser/browser_main_parts.h" #include "electron/buildflags/buildflags.h" #include "mojo/public/cpp/bindings/remote.h" #include "services/device/public/mojom/geolocation_control.mojom.h" #include "third_party/abseil-cpp/absl/types/optional.h" #include "ui/display/screen.h" #include "ui/views/layout/layout_provider.h" class BrowserProcessImpl; class IconManager; namespace base { class FieldTrialList; } #if defined(USE_AURA) namespace wm { class WMState; } namespace display { class Screen; } #endif namespace device { class GeolocationManager; } namespace electron { class Browser; class ElectronBindings; class JavascriptEnvironment; class NodeBindings; class NodeEnvironment; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) class ElectronExtensionsClient; class ElectronExtensionsBrowserClient; #endif #if defined(TOOLKIT_VIEWS) class ViewsDelegate; #endif #if BUILDFLAG(IS_MAC) class ViewsDelegateMac; #endif #if BUILDFLAG(IS_LINUX) class DarkThemeObserver; #endif class ElectronBrowserMainParts : public content::BrowserMainParts { public: ElectronBrowserMainParts(); ~ElectronBrowserMainParts() override; // disable copy ElectronBrowserMainParts(const ElectronBrowserMainParts&) = delete; ElectronBrowserMainParts& operator=(const ElectronBrowserMainParts&) = delete; static ElectronBrowserMainParts* Get(); // Sets the exit code, will fail if the message loop is not ready. bool SetExitCode(int code); // Gets the exit code int GetExitCode() const; // Returns the connection to GeolocationControl which can be // used to enable the location services once per client. device::mojom::GeolocationControl* GetGeolocationControl(); #if BUILDFLAG(IS_MAC) device::GeolocationManager* GetGeolocationManager(); #endif // Returns handle to the class responsible for extracting file icons. IconManager* GetIconManager(); Browser* browser() { return browser_.get(); } BrowserProcessImpl* browser_process() { return fake_browser_process_.get(); } protected: // content::BrowserMainParts: int PreEarlyInitialization() override; void PostEarlyInitialization() override; int PreCreateThreads() override; void ToolkitInitialized() override; int PreMainMessageLoopRun() override; void WillRunMainMessageLoop( std::unique_ptr<base::RunLoop>& run_loop) override; void PostCreateMainMessageLoop() override; void PostMainMessageLoopRun() override; void PreCreateMainMessageLoop() override; void PostCreateThreads() override; void PostDestroyThreads() override; private: void PreCreateMainMessageLoopCommon(); #if BUILDFLAG(IS_POSIX) // Set signal handlers. void HandleSIGCHLD(); void InstallShutdownSignalHandlers( base::OnceCallback<void()> shutdown_callback, const scoped_refptr<base::SingleThreadTaskRunner>& task_runner); #endif #if BUILDFLAG(IS_MAC) void FreeAppDelegate(); void RegisterURLHandler(); void InitializeMainNib(); #endif #if BUILDFLAG(IS_MAC) std::unique_ptr<ViewsDelegateMac> views_delegate_; #else std::unique_ptr<ViewsDelegate> views_delegate_; #endif #if defined(USE_AURA) std::unique_ptr<wm::WMState> wm_state_; std::unique_ptr<display::Screen> screen_; #endif #if BUILDFLAG(IS_LINUX) // Used to notify the native theme of changes to dark mode. std::unique_ptr<DarkThemeObserver> dark_theme_observer_; #endif std::unique_ptr<views::LayoutProvider> layout_provider_; // A fake BrowserProcess object that used to feed the source code from chrome. std::unique_ptr<BrowserProcessImpl> fake_browser_process_; // A place to remember the exit code once the message loop is ready. // Before then, we just exit() without any intermediate steps. absl::optional<int> exit_code_; std::unique_ptr<JavascriptEnvironment> js_env_; std::unique_ptr<Browser> browser_; std::unique_ptr<NodeBindings> node_bindings_; std::unique_ptr<ElectronBindings> electron_bindings_; std::unique_ptr<NodeEnvironment> node_env_; std::unique_ptr<IconManager> icon_manager_; std::unique_ptr<base::FieldTrialList> field_trial_list_; #if BUILDFLAG(ENABLE_ELECTRON_EXTENSIONS) std::unique_ptr<ElectronExtensionsClient> extensions_client_; std::unique_ptr<ElectronExtensionsBrowserClient> extensions_browser_client_; #endif mojo::Remote<device::mojom::GeolocationControl> geolocation_control_; #if BUILDFLAG(IS_MAC) std::unique_ptr<device::GeolocationManager> geolocation_manager_; std::unique_ptr<display::ScopedNativeScreen> screen_; #endif static ElectronBrowserMainParts* self_; }; } // namespace electron #endif // ELECTRON_SHELL_BROWSER_ELECTRON_BROWSER_MAIN_PARTS_H_
closed
electron/electron
https://github.com/electron/electron
33,810
[Bug]: --ozone-platform-hint command line flag ignored
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 18.0.3 ### What operating system are you using? Other Linux ### Operating System Version Arch Linux ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior Setting the `--ozone-platform-hint` flag to `auto` or `wayland` should make electron use wayland (assuming `--enable-features=UseOzonePlatform` is also set) ### Actual Behavior The flag is ignored. ### Testcase Gist URL _No response_ ### Additional Information Using `--ozone-platform=wayland` does work, but then it fails when not running wayland.
https://github.com/electron/electron/issues/33810
https://github.com/electron/electron/pull/34937
9f0e7126c422c12333544de0a20f954addd13061
67eda4bcc81754a973a4455cd6db5ac624f4bfa0
2022-04-17T16:33:59Z
c++
2022-07-21T08:37:54Z
shell/browser/electron_browser_main_parts_linux.cc
closed
electron/electron
https://github.com/electron/electron
34,887
Web Serial API removed and added events are never called
### Preflight Checklist - [X] I have read the [Contributing Guidelines](https://github.com/electron/electron/blob/main/CONTRIBUTING.md) for this project. - [X] I agree to follow the [Code of Conduct](https://github.com/electron/electron/blob/main/CODE_OF_CONDUCT.md) that this project adheres to. - [X] I have searched the [issue tracker](https://www.github.com/electron/electron/issues) for a bug report that matches the one I want to file, without success. ### Electron Version 19.0.8 ### What operating system are you using? macOS ### Operating System Version macOS Monterey 12.4 ### What arch are you using? x64 ### Last Known Working Electron version _No response_ ### Expected Behavior I want to update UI when picking a port if a serial port is plugged in or unplugged. Test Steps: 1, Click button to call `navigator.serial.requestPort()` 2, Show a modal to show port list in the `select-serial-port` event handler 3, Plug in or unplug a device to check the `serial-port-added` and `serial-port-removed` events ``` modal.webContents.session.on('select-serial-port', (event, portList, webContents, callback) => { //Add listeners to handle ports being added or removed before the callback for `select-serial-port` //is called. modal.webContents.session.on('serial-port-added', (event, port) => { console.log('serial-port-added FIRED WITH', port) //Optionally update portList to add the new port }) modal.webContents.session.on('serial-port-removed', (event, port) => { console.log('serial-port-removed FIRED WITH', port) //Optionally update portList to remove the port }) // modal.webContents.openDevTools(); modal.webContents.send('update-list', portList); modal.show(); event.preventDefault(); ipcMain.once('serial-port', (_event, portId = '') => { callback(portId); modal.hide(); }); }); ``` ### Actual Behavior But the `select-serial-port` and `select-serial-removed` events never called. Did I use these api in a wrong way? ### Testcase Gist URL https://gist.github.com/0bbeeaa1c9e8f5affb6b59663870616e ### Additional Information _No response_
https://github.com/electron/electron/issues/34887
https://github.com/electron/electron/pull/34958
aeba6ca973c8ed8a8b75cceb4e0dde33f3595850
648c9934c01c12ea082a18fdf690c37e3112ce12
2022-07-12T03:31:13Z
c++
2022-07-25T14:50:19Z
shell/browser/serial/electron_serial_delegate.cc
// Copyright (c) 2020 Microsoft, Inc. // Use of this source code is governed by the MIT license that can be // found in the LICENSE file. #include "shell/browser/serial/electron_serial_delegate.h" #include <utility> #include "base/feature_list.h" #include "content/public/browser/web_contents.h" #include "shell/browser/api/electron_api_web_contents.h" #include "shell/browser/serial/serial_chooser_context.h" #include "shell/browser/serial/serial_chooser_context_factory.h" #include "shell/browser/serial/serial_chooser_controller.h" #include "shell/browser/web_contents_permission_helper.h" namespace electron { SerialChooserContext* GetChooserContext(content::RenderFrameHost* frame) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame); auto* browser_context = web_contents->GetBrowserContext(); return SerialChooserContextFactory::GetForBrowserContext(browser_context); } ElectronSerialDelegate::ElectronSerialDelegate() = default; ElectronSerialDelegate::~ElectronSerialDelegate() = default; std::unique_ptr<content::SerialChooser> ElectronSerialDelegate::RunChooser( content::RenderFrameHost* frame, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback) { SerialChooserController* controller = ControllerForFrame(frame); if (controller) { DeleteControllerForFrame(frame); } AddControllerForFrame(frame, std::move(filters), std::move(callback)); // Return a nullptr because the return value isn't used for anything, eg // there is no mechanism to cancel navigator.serial.requestPort(). The return // value is simply used in Chromium to cleanup the chooser UI once the serial // service is destroyed. return nullptr; } bool ElectronSerialDelegate::CanRequestPortPermission( content::RenderFrameHost* frame) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame); auto* permission_helper = WebContentsPermissionHelper::FromWebContents(web_contents); return permission_helper->CheckSerialAccessPermission( web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin()); } bool ElectronSerialDelegate::HasPortPermission( content::RenderFrameHost* frame, const device::mojom::SerialPortInfo& port) { auto* web_contents = content::WebContents::FromRenderFrameHost(frame); auto* browser_context = web_contents->GetBrowserContext(); auto* chooser_context = SerialChooserContextFactory::GetForBrowserContext(browser_context); return chooser_context->HasPortPermission( web_contents->GetPrimaryMainFrame()->GetLastCommittedOrigin(), port, frame); } device::mojom::SerialPortManager* ElectronSerialDelegate::GetPortManager( content::RenderFrameHost* frame) { return GetChooserContext(frame)->GetPortManager(); } void ElectronSerialDelegate::AddObserver(content::RenderFrameHost* frame, Observer* observer) { return GetChooserContext(frame)->AddPortObserver(observer); } void ElectronSerialDelegate::RemoveObserver(content::RenderFrameHost* frame, Observer* observer) { SerialChooserContext* serial_chooser_context = GetChooserContext(frame); if (serial_chooser_context) { return serial_chooser_context->RemovePortObserver(observer); } } void ElectronSerialDelegate::RevokePortPermissionWebInitiated( content::RenderFrameHost* frame, const base::UnguessableToken& token) { // TODO(nornagon/jkleinsc): pass this on to the chooser context } const device::mojom::SerialPortInfo* ElectronSerialDelegate::GetPortInfo( content::RenderFrameHost* frame, const base::UnguessableToken& token) { // TODO(nornagon/jkleinsc): pass this on to the chooser context return nullptr; } SerialChooserController* ElectronSerialDelegate::ControllerForFrame( content::RenderFrameHost* render_frame_host) { auto mapping = controller_map_.find(render_frame_host); return mapping == controller_map_.end() ? nullptr : mapping->second.get(); } SerialChooserController* ElectronSerialDelegate::AddControllerForFrame( content::RenderFrameHost* render_frame_host, std::vector<blink::mojom::SerialPortFilterPtr> filters, content::SerialChooser::Callback callback) { auto* web_contents = content::WebContents::FromRenderFrameHost(render_frame_host); auto controller = std::make_unique<SerialChooserController>( render_frame_host, std::move(filters), std::move(callback), web_contents, weak_factory_.GetWeakPtr()); controller_map_.insert( std::make_pair(render_frame_host, std::move(controller))); return ControllerForFrame(render_frame_host); } void ElectronSerialDelegate::DeleteControllerForFrame( content::RenderFrameHost* render_frame_host) { controller_map_.erase(render_frame_host); } } // namespace electron