Lightweight native Discord client for Windows, Linux and macOS, written in Rust. No Electron, no browser engine.
Rust desktop-appdiscorddiscord-clienteguielectron-alternativelightweightlinuxmacosnative-apprustwindows
Type AltGr characters entered as Ctrl + Alt on Windows (#34)
VRonGitHube0d3b7626aa6
diff --git a/Cargo.lock b/Cargo.lockindex 64a9e04..b296ebc 100644--- a/Cargo.lock+++ b/Cargo.lock@@ -1844,8 +1844,6 @@ dependencies = [[[package]]name = "egui-winit"version = "0.29.1"-source = "registry+https://github.com/rust-lang/crates.io-index"-checksum = "0a9c430f4f816340e8e8c1b20eec274186b1be6bc4c7dfc467ed50d57abc36c6"dependencies = ["accesskit_winit","ahash",diff --git a/Cargo.toml b/Cargo.tomlindex c841bb3..a03ae2a 100644--- a/Cargo.toml+++ b/Cargo.toml@@ -23,6 +23,9 @@ davey = { path = "crates/voice/vendor/davey" }hpke-rs = { path = "crates/voice/vendor/hpke-rs" }# egui_glow 0.29.1 with text shaded like Chrome's (see crates/vendor/egui_glow/src/painter.rs).egui_glow = { path = "crates/vendor/egui_glow" }+# egui-winit 0.29.1 that keeps text typed with AltGr as Ctrl + Alt on Windows+# (see on_keyboard_input in crates/vendor/egui-winit/src/lib.rs).+egui-winit = { path = "crates/vendor/egui-winit" }# epaint 0.29.1 with text laid out like a browser: sizes and glyph advances not# rounded to whole pixels, GPOS kerning, and shaped, right-to-left Arabic and# Hebrew (see crates/vendor/epaint/src/text).diff --git a/crates/vendor/egui-winit/Cargo.toml b/crates/vendor/egui-winit/Cargo.tomlnew file mode 100644index 0000000..b2e9b4f--- /dev/null+++ b/crates/vendor/egui-winit/Cargo.toml@@ -0,0 +1,303 @@+# THIS FILE IS AUTOMATICALLY GENERATED BY CARGO+#+# When uploading crates to the registry Cargo will automatically+# "normalize" Cargo.toml files for maximal compatibility+# with all versions of Cargo and also rewrite `path` dependencies+# to registry (e.g., crates.io) dependencies.+#+# If you are reading this file be aware that the original Cargo.toml+# will likely look very different (and much more reasonable).+# See Cargo.toml.orig for the original contents.++[package]+edition = "2021"+rust-version = "1.76"+name = "egui-winit"+version = "0.29.1"+authors = ["Emil Ernerfeldt <[email protected]>"]+include = [+ "../LICENSE-APACHE",+ "../LICENSE-MIT",+ "**/*.rs",+ "Cargo.toml",+]+description = "Bindings for using egui with winit"+homepage = "https://github.com/emilk/egui/tree/master/crates/egui-winit"+readme = "README.md"+keywords = [+ "winit",+ "egui",+ "gui",+ "gamedev",+]+categories = [+ "gui",+ "game-development",+]+license = "MIT OR Apache-2.0"+repository = "https://github.com/emilk/egui/tree/master/crates/egui-winit"++[package.metadata.docs.rs]+all-features = true+rustdoc-args = ["--generate-link-to-definition"]++[dependencies.accesskit_winit]+version = "0.22"+optional = true++[dependencies.ahash]+version = "0.8.11"+features = [+ "no-rng",+ "std",+]+default-features = false++[dependencies.document-features]+version = " 0.2.8"+optional = true++[dependencies.egui]+version = "0.29.1"+features = ["log"]+default-features = false++[dependencies.log]+version = "0.4"+features = ["std"]++[dependencies.puffin]+version = "0.19"+optional = true++[dependencies.raw-window-handle]+version = "0.6.0"++[dependencies.serde]+version = "1"+features = ["derive"]+optional = true++[dependencies.web-time]+version = "1.1.0"++[dependencies.webbrowser]+version = "1.0.0"+optional = true++[dependencies.winit]+version = "0.30.5"+default-features = false++[features]+accesskit = [+ "accesskit_winit",+ "egui/accesskit",+]+android-game-activity = ["winit/android-game-activity"]+android-native-activity = ["winit/android-native-activity"]+bytemuck = ["egui/bytemuck"]+clipboard = [+ "arboard",+ "smithay-clipboard",+]+default = [+ "clipboard",+ "links",+ "wayland",+ "winit/default",+ "x11",+]+links = ["webbrowser"]+puffin = [+ "dep:puffin",+ "egui/puffin",+]+serde = [+ "egui/serde",+ "dep:serde",+]+wayland = [+ "winit/wayland",+ "bytemuck",+]+x11 = [+ "winit/x11",+ "bytemuck",+]++[target."cfg(any(target_os=\"linux\", target_os=\"dragonfly\", target_os=\"freebsd\", target_os=\"netbsd\", target_os=\"openbsd\"))".dependencies.smithay-clipboard]+version = "0.7.2"+optional = true++[target."cfg(any(target_os=\"linux\", target_os=\"dragonfly\", target_os=\"freebsd\", target_os=\"netbsd\", target_os=\"openbsd\"))".dependencies.wayland-cursor]+version = "0.31.1"+optional = true+default-features = false++[target."cfg(not(target_os = \"android\"))".dependencies.arboard]+version = "3.3"+optional = true+default-features = false++[lints.clippy]+as_ptr_cast_mut = "warn"+await_holding_lock = "warn"+bool_to_int_with_if = "warn"+char_lit_as_u8 = "warn"+checked_conversions = "warn"+clear_with_drain = "warn"+cloned_instead_of_copied = "warn"+dbg_macro = "warn"+debug_assert_with_mut_call = "warn"+derive_partial_eq_without_eq = "warn"+disallowed_macros = "warn"+disallowed_methods = "warn"+disallowed_names = "warn"+disallowed_script_idents = "warn"+disallowed_types = "warn"+doc_link_with_quotes = "warn"+doc_markdown = "warn"+empty_enum = "warn"+enum_glob_use = "warn"+equatable_if_let = "warn"+exit = "warn"+expl_impl_clone_on_copy = "warn"+explicit_deref_methods = "warn"+explicit_into_iter_loop = "warn"+explicit_iter_loop = "warn"+fallible_impl_from = "warn"+filter_map_next = "warn"+flat_map_option = "warn"+float_cmp_const = "warn"+fn_params_excessive_bools = "warn"+fn_to_numeric_cast_any = "warn"+from_iter_instead_of_collect = "warn"+get_unwrap = "warn"+if_let_mutex = "warn"+implicit_clone = "warn"+implied_bounds_in_impls = "warn"+imprecise_flops = "warn"+index_refutable_slice = "warn"+inefficient_to_string = "warn"+infinite_loop = "warn"+into_iter_without_iter = "warn"+invalid_upcast_comparisons = "warn"+iter_not_returning_iterator = "warn"+iter_on_empty_collections = "warn"+iter_on_single_items = "warn"+iter_over_hash_type = "allow"+iter_without_into_iter = "warn"+large_digit_groups = "warn"+large_include_file = "warn"+large_stack_arrays = "warn"+large_stack_frames = "warn"+large_types_passed_by_value = "warn"+let_underscore_untyped = "allow"+let_unit_value = "warn"+linkedlist = "warn"+lossy_float_literal = "warn"+macro_use_imports = "warn"+manual_assert = "warn"+manual_clamp = "warn"+manual_instant_elapsed = "warn"+manual_let_else = "warn"+manual_ok_or = "warn"+manual_range_contains = "allow"+manual_string_new = "warn"+map_err_ignore = "warn"+map_flatten = "warn"+map_unwrap_or = "warn"+match_bool = "warn"+match_on_vec_items = "warn"+match_same_arms = "warn"+match_wild_err_arm = "warn"+match_wildcard_for_single_variants = "warn"+mem_forget = "warn"+mismatched_target_os = "warn"+mismatching_type_param_order = "warn"+missing_assert_message = "allow"+missing_enforced_import_renames = "warn"+missing_errors_doc = "warn"+missing_safety_doc = "warn"+mut_mut = "warn"+mutex_integer = "warn"+needless_borrow = "warn"+needless_continue = "warn"+needless_for_each = "warn"+needless_pass_by_ref_mut = "warn"+needless_pass_by_value = "warn"+negative_feature_names = "warn"+nonstandard_macro_braces = "warn"+option_option = "warn"+path_buf_push_overwrite = "warn"+print_stderr = "warn"+ptr_as_ptr = "warn"+ptr_cast_constness = "warn"+pub_without_shorthand = "warn"+rc_mutex = "warn"+readonly_write_lock = "warn"+redundant_type_annotations = "warn"+ref_option_ref = "warn"+ref_patterns = "warn"+rest_pat_in_fully_bound_structs = "warn"+same_functions_in_if_condition = "warn"+self_named_module_files = "allow"+semicolon_if_nothing_returned = "warn"+should_panic_without_expect = "allow"+significant_drop_tightening = "allow"+single_match_else = "warn"+str_to_string = "warn"+string_add = "warn"+string_add_assign = "warn"+string_lit_as_bytes = "warn"+string_lit_chars_any = "warn"+string_to_string = "warn"+suspicious_command_arg_space = "warn"+suspicious_xor_used_as_pow = "warn"+todo = "warn"+too_many_lines = "allow"+trailing_empty_array = "warn"+trait_duplication_in_bounds = "warn"+tuple_array_conversions = "warn"+unchecked_duration_subtraction = "warn"+undocumented_unsafe_blocks = "warn"+unimplemented = "warn"+uninhabited_references = "warn"+uninlined_format_args = "warn"+unnecessary_box_returns = "warn"+unnecessary_safety_doc = "warn"+unnecessary_struct_initialization = "warn"+unnecessary_wraps = "warn"+unnested_or_patterns = "warn"+unused_peekable = "warn"+unused_rounding = "warn"+unused_self = "warn"+unwrap_used = "allow"+use_self = "warn"+useless_transmute = "warn"+verbose_file_reads = "warn"+wildcard_dependencies = "warn"+wildcard_imports = "warn"+zero_sized_map_values = "warn"++[lints.rust]+elided_lifetimes_in_paths = "warn"+future_incompatible = "warn"+nonstandard_style = "warn"+rust_2018_idioms = "warn"+rust_2021_prelude_collisions = "warn"+semicolon_in_expressions_from_macros = "warn"+trivial_casts = "allow"+trivial_numeric_casts = "warn"+unsafe_code = "deny"+unsafe_op_in_unsafe_fn = "warn"+unused_extern_crates = "warn"+unused_import_braces = "warn"+unused_lifetimes = "warn"+unused_qualifications = "allow"++[lints.rustdoc]+all = "warn"+broken_intra_doc_links = "warn"+missing_crate_level_docs = "warn"diff --git a/crates/vendor/egui-winit/Cargo.toml.orig b/crates/vendor/egui-winit/Cargo.toml.orignew file mode 100644index 0000000..f8a11ec--- /dev/null+++ b/crates/vendor/egui-winit/Cargo.toml.orig@@ -0,0 +1,90 @@+[package]+name = "egui-winit"+version.workspace = true+authors = ["Emil Ernerfeldt <[email protected]>"]+description = "Bindings for using egui with winit"+edition.workspace = true+rust-version.workspace = true+homepage = "https://github.com/emilk/egui/tree/master/crates/egui-winit"+license.workspace = true+readme = "README.md"+repository = "https://github.com/emilk/egui/tree/master/crates/egui-winit"+categories = ["gui", "game-development"]+keywords = ["winit", "egui", "gui", "gamedev"]+include = ["../LICENSE-APACHE", "../LICENSE-MIT", "**/*.rs", "Cargo.toml"]++[lints]+workspace = true++[package.metadata.docs.rs]+all-features = true+rustdoc-args = ["--generate-link-to-definition"]++[features]+default = ["clipboard", "links", "wayland", "winit/default", "x11"]++## Enable platform accessibility API implementations through [AccessKit](https://accesskit.dev/).+accesskit = ["accesskit_winit", "egui/accesskit"]++# Allow crates to choose an android-activity backend via Winit+# - It's important that most applications should not have to depend on android-activity directly, and can+# rely on Winit to pull in a suitable version (unlike most Rust crates, any version conflicts won't link)+# - It's also important that we don't impose an android-activity backend by taking this choice away from applications.+## Enable the `game-activity` backend via Winit on Android+android-game-activity = ["winit/android-game-activity"]+## Enable the `native-activity` backend via Winit on Android+android-native-activity = ["winit/android-native-activity"]++## [`bytemuck`](https://docs.rs/bytemuck) enables you to cast [`egui::epaint::Vertex`], [`egui::Vec2`] etc to `&[u8]`.+bytemuck = ["egui/bytemuck"]++## Enable cut/copy/paste to OS clipboard.+## If disabled a clipboard will be simulated so you can still copy/paste within the egui app.+clipboard = ["arboard", "smithay-clipboard"]++## Enable opening links in a browser when an egui hyperlink is clicked.+links = ["webbrowser"]++## Enable profiling with the [`puffin`](https://docs.rs/puffin) crate.+puffin = ["dep:puffin", "egui/puffin"]++## Allow serialization of [`WindowSettings`] using [`serde`](https://docs.rs/serde).+serde = ["egui/serde", "dep:serde"]++## Enables Wayland support.+wayland = ["winit/wayland", "bytemuck"]++## Enables compiling for x11.+x11 = ["winit/x11", "bytemuck"]++[dependencies]+egui = { workspace = true, default-features = false, features = ["log"] }++ahash.workspace = true+log.workspace = true+raw-window-handle.workspace = true+web-time.workspace = true+winit = { workspace = true, default-features = false }++#! ### Optional dependencies++# feature accesskit+accesskit_winit = { version = "0.22", optional = true }++## Enable this when generating docs.+document-features = { workspace = true, optional = true }++puffin = { workspace = true, optional = true }+serde = { workspace = true, optional = true }+webbrowser = { version = "1.0.0", optional = true }++[target.'cfg(any(target_os="linux", target_os="dragonfly", target_os="freebsd", target_os="netbsd", target_os="openbsd"))'.dependencies]+smithay-clipboard = { version = "0.7.2", optional = true }++# The wayland-cursor normally selected doesn't properly enable all the features it uses+# and thus doesn't compile as it is used in egui-winit. This is fixed upstream, so force+# a slightly newer version. Remove this when winit upgrades past this version.+wayland-cursor = { version = "0.31.1", default-features = false, optional = true }++[target.'cfg(not(target_os = "android"))'.dependencies]+arboard = { version = "3.3", optional = true, default-features = false }diff --git a/crates/vendor/egui-winit/LICENSE-APACHE b/crates/vendor/egui-winit/LICENSE-APACHEnew file mode 100644index 0000000..d645695--- /dev/null+++ b/crates/vendor/egui-winit/LICENSE-APACHE@@ -0,0 +1,202 @@++ Apache License+ Version 2.0, January 2004+ http://www.apache.org/licenses/++ TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION++ 1. Definitions.++ "License" shall mean the terms and conditions for use, reproduction,+ and distribution as defined by Sections 1 through 9 of this document.++ "Licensor" shall mean the copyright owner or entity authorized by+ the copyright owner that is granting the License.++ "Legal Entity" shall mean the union of the acting entity and all+ other entities that control, are controlled by, or are under common+ control with that entity. For the purposes of this definition,+ "control" means (i) the power, direct or indirect, to cause the+ direction or management of such entity, whether by contract or+ otherwise, or (ii) ownership of fifty percent (50%) or more of the+ outstanding shares, or (iii) beneficial ownership of such entity.++ "You" (or "Your") shall mean an individual or Legal Entity+ exercising permissions granted by this License.++ "Source" form shall mean the preferred form for making modifications,+ including but not limited to software source code, documentation+ source, and configuration files.++ "Object" form shall mean any form resulting from mechanical+ transformation or translation of a Source form, including but+ not limited to compiled object code, generated documentation,+ and conversions to other media types.++ "Work" shall mean the work of authorship, whether in Source or+ Object form, made available under the License, as indicated by a+ copyright notice that is included in or attached to the work+ (an example is provided in the Appendix below).++ "Derivative Works" shall mean any work, whether in Source or Object+ form, that is based on (or derived from) the Work and for which the+ editorial revisions, annotations, elaborations, or other modifications+ represent, as a whole, an original work of authorship. For the purposes+ of this License, Derivative Works shall not include works that remain+ separable from, or merely link (or bind by name) to the interfaces of,+ the Work and Derivative Works thereof.++ "Contribution" shall mean any work of authorship, including+ the original version of the Work and any modifications or additions+ to that Work or Derivative Works thereof, that is intentionally+ submitted to Licensor for inclusion in the Work by the copyright owner+ or by an individual or Legal Entity authorized to submit on behalf of+ the copyright owner. For the purposes of this definition, "submitted"+ means any form of electronic, verbal, or written communication sent+ to the Licensor or its representatives, including but not limited to+ communication on electronic mailing lists, source code control systems,+ and issue tracking systems that are managed by, or on behalf of, the+ Licensor for the purpose of discussing and improving the Work, but+ excluding communication that is conspicuously marked or otherwise+ designated in writing by the copyright owner as "Not a Contribution."++ "Contributor" shall mean Licensor and any individual or Legal Entity+ on behalf of whom a Contribution has been received by Licensor and+ subsequently incorporated within the Work.++ 2. Grant of Copyright License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ copyright license to reproduce, prepare Derivative Works of,+ publicly display, publicly perform, sublicense, and distribute the+ Work and such Derivative Works in Source or Object form.++ 3. Grant of Patent License. Subject to the terms and conditions of+ this License, each Contributor hereby grants to You a perpetual,+ worldwide, non-exclusive, no-charge, royalty-free, irrevocable+ (except as stated in this section) patent license to make, have made,+ use, offer to sell, sell, import, and otherwise transfer the Work,+ where such license applies only to those patent claims licensable+ by such Contributor that are necessarily infringed by their+ Contribution(s) alone or by combination of their Contribution(s)+ with the Work to which such Contribution(s) was submitted. If You+ institute patent litigation against any entity (including a+ cross-claim or counterclaim in a lawsuit) alleging that the Work+ or a Contribution incorporated within the Work constitutes direct+ or contributory patent infringement, then any patent licenses+ granted to You under this License for that Work shall terminate+ as of the date such litigation is filed.++ 4. Redistribution. You may reproduce and distribute copies of the+ Work or Derivative Works thereof in any medium, with or without+ modifications, and in Source or Object form, provided that You+ meet the following conditions:++ (a) You must give any other recipients of the Work or+ Derivative Works a copy of this License; and++ (b) You must cause any modified files to carry prominent notices+ stating that You changed the files; and++ (c) You must retain, in the Source form of any Derivative Works+ that You distribute, all copyright, patent, trademark, and+ attribution notices from the Source form of the Work,+ excluding those notices that do not pertain to any part of+ the Derivative Works; and++ (d) If the Work includes a "NOTICE" text file as part of its+ distribution, then any Derivative Works that You distribute must+ include a readable copy of the attribution notices contained+ within such NOTICE file, excluding those notices that do not+ pertain to any part of the Derivative Works, in at least one+ of the following places: within a NOTICE text file distributed+ as part of the Derivative Works; within the Source form or+ documentation, if provided along with the Derivative Works; or,+ within a display generated by the Derivative Works, if and+ wherever such third-party notices normally appear. The contents+ of the NOTICE file are for informational purposes only and+ do not modify the License. You may add Your own attribution+ notices within Derivative Works that You distribute, alongside+ or as an addendum to the NOTICE text from the Work, provided+ that such additional attribution notices cannot be construed+ as modifying the License.++ You may add Your own copyright statement to Your modifications and+ may provide additional or different license terms and conditions+ for use, reproduction, or distribution of Your modifications, or+ for any such Derivative Works as a whole, provided Your use,+ reproduction, and distribution of the Work otherwise complies with+ the conditions stated in this License.++ 5. Submission of Contributions. Unless You explicitly state otherwise,+ any Contribution intentionally submitted for inclusion in the Work+ by You to the Licensor shall be under the terms and conditions of+ this License, without any additional terms or conditions.+ Notwithstanding the above, nothing herein shall supersede or modify+ the terms of any separate license agreement you may have executed+ with Licensor regarding such Contributions.++ 6. Trademarks. This License does not grant permission to use the trade+ names, trademarks, service marks, or product names of the Licensor,+ except as required for reasonable and customary use in describing the+ origin of the Work and reproducing the content of the NOTICE file.++ 7. Disclaimer of Warranty. Unless required by applicable law or+ agreed to in writing, Licensor provides the Work (and each+ Contributor provides its Contributions) on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or+ implied, including, without limitation, any warranties or conditions+ of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A+ PARTICULAR PURPOSE. You are solely responsible for determining the+ appropriateness of using or redistributing the Work and assume any+ risks associated with Your exercise of permissions under this License.++ 8. Limitation of Liability. In no event and under no legal theory,+ whether in tort (including negligence), contract, or otherwise,+ unless required by applicable law (such as deliberate and grossly+ negligent acts) or agreed to in writing, shall any Contributor be+ liable to You for damages, including any direct, indirect, special,+ incidental, or consequential damages of any character arising as a+ result of this License or out of the use or inability to use the+ Work (including but not limited to damages for loss of goodwill,+ work stoppage, computer failure or malfunction, or any and all+ other commercial damages or losses), even if such Contributor+ has been advised of the possibility of such damages.++ 9. Accepting Warranty or Additional Liability. While redistributing+ the Work or Derivative Works thereof, You may choose to offer,+ and charge a fee for, acceptance of support, warranty, indemnity,+ or other liability obligations and/or rights consistent with this+ License. However, in accepting such obligations, You may act only+ on Your own behalf and on Your sole responsibility, not on behalf+ of any other Contributor, and only if You agree to indemnify,+ defend, and hold each Contributor harmless for any liability+ incurred by, or claims asserted against, such Contributor by reason+ of your accepting any such warranty or additional liability.++ END OF TERMS AND CONDITIONS++ APPENDIX: How to apply the Apache License to your work.++ To apply the Apache License to your work, attach the following+ boilerplate notice, with the fields enclosed by brackets "[]"+ replaced with your own identifying information. (Don't include+ the brackets!) The text should be enclosed in the appropriate+ comment syntax for the file format. We also recommend that a+ file or class name and description of purpose be included on the+ same "printed page" as the copyright notice for easier+ identification within third-party archives.++ Copyright [yyyy] [name of copyright owner]++ Licensed under the Apache License, Version 2.0 (the "License");+ you may not use this file except in compliance with the License.+ You may obtain a copy of the License at++ http://www.apache.org/licenses/LICENSE-2.0++ Unless required by applicable law or agreed to in writing, software+ distributed under the License is distributed on an "AS IS" BASIS,+ WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.+ See the License for the specific language governing permissions and+ limitations under the License.diff --git a/crates/vendor/egui-winit/LICENSE-MIT b/crates/vendor/egui-winit/LICENSE-MITnew file mode 100644index 0000000..673ea5f--- /dev/null+++ b/crates/vendor/egui-winit/LICENSE-MIT@@ -0,0 +1,25 @@+Copyright (c) 2018-2021 Emil Ernerfeldt <[email protected]>++Permission is hereby granted, free of charge, to any+person obtaining a copy of this software and associated+documentation files (the "Software"), to deal in the+Software without restriction, including without+limitation the rights to use, copy, modify, merge,+publish, distribute, sublicense, and/or sell copies of+the Software, and to permit persons to whom the Software+is furnished to do so, subject to the following+conditions:++The above copyright notice and this permission notice+shall be included in all copies or substantial portions+of the Software.++THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF+ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED+TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A+PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT+SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY+CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION+OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR+IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER+DEALINGS IN THE SOFTWARE.diff --git a/crates/vendor/egui-winit/README.md b/crates/vendor/egui-winit/README.mdnew file mode 100644index 0000000..2386416--- /dev/null+++ b/crates/vendor/egui-winit/README.md@@ -0,0 +1,10 @@+# egui-winit++[](https://crates.io/crates/egui-winit)+[](https://docs.rs/egui-winit)++++This crates provides bindings between [`egui`](https://github.com/emilk/egui) and [`winit`](https://crates.io/crates/winit).++The library translates winit events to egui, handled copy/paste, updates the cursor, open links clicked in egui, etc.diff --git a/crates/vendor/egui-winit/src/clipboard.rs b/crates/vendor/egui-winit/src/clipboard.rsnew file mode 100644index 0000000..44e3840--- /dev/null+++ b/crates/vendor/egui-winit/src/clipboard.rs@@ -0,0 +1,157 @@+use raw_window_handle::RawDisplayHandle;++/// Handles interfacing with the OS clipboard.+///+/// If the "clipboard" feature is off, or we cannot connect to the OS clipboard,+/// then a fallback clipboard that just works within the same app is used instead.+pub struct Clipboard {+ #[cfg(all(feature = "arboard", not(target_os = "android")))]+ arboard: Option<arboard::Clipboard>,++ #[cfg(all(+ any(+ target_os = "linux",+ target_os = "dragonfly",+ target_os = "freebsd",+ target_os = "netbsd",+ target_os = "openbsd"+ ),+ feature = "smithay-clipboard"+ ))]+ smithay: Option<smithay_clipboard::Clipboard>,++ /// Fallback manual clipboard.+ clipboard: String,+}++impl Clipboard {+ /// Construct a new instance+ pub fn new(_raw_display_handle: Option<RawDisplayHandle>) -> Self {+ Self {+ #[cfg(all(feature = "arboard", not(target_os = "android")))]+ arboard: init_arboard(),++ #[cfg(all(+ any(+ target_os = "linux",+ target_os = "dragonfly",+ target_os = "freebsd",+ target_os = "netbsd",+ target_os = "openbsd"+ ),+ feature = "smithay-clipboard"+ ))]+ smithay: init_smithay_clipboard(_raw_display_handle),++ clipboard: Default::default(),+ }+ }++ pub fn get(&mut self) -> Option<String> {+ #[cfg(all(+ any(+ target_os = "linux",+ target_os = "dragonfly",+ target_os = "freebsd",+ target_os = "netbsd",+ target_os = "openbsd"+ ),+ feature = "smithay-clipboard"+ ))]+ if let Some(clipboard) = &mut self.smithay {+ return match clipboard.load() {+ Ok(text) => Some(text),+ Err(err) => {+ log::error!("smithay paste error: {err}");+ None+ }+ };+ }++ #[cfg(all(feature = "arboard", not(target_os = "android")))]+ if let Some(clipboard) = &mut self.arboard {+ return match clipboard.get_text() {+ Ok(text) => Some(text),+ Err(err) => {+ log::error!("arboard paste error: {err}");+ None+ }+ };+ }++ Some(self.clipboard.clone())+ }++ pub fn set(&mut self, text: String) {+ #[cfg(all(+ any(+ target_os = "linux",+ target_os = "dragonfly",+ target_os = "freebsd",+ target_os = "netbsd",+ target_os = "openbsd"+ ),+ feature = "smithay-clipboard"+ ))]+ if let Some(clipboard) = &mut self.smithay {+ clipboard.store(text);+ return;+ }++ #[cfg(all(feature = "arboard", not(target_os = "android")))]+ if let Some(clipboard) = &mut self.arboard {+ if let Err(err) = clipboard.set_text(text) {+ log::error!("arboard copy/cut error: {err}");+ }+ return;+ }++ self.clipboard = text;+ }+}++#[cfg(all(feature = "arboard", not(target_os = "android")))]+fn init_arboard() -> Option<arboard::Clipboard> {+ crate::profile_function!();++ log::trace!("Initializing arboard clipboard…");+ match arboard::Clipboard::new() {+ Ok(clipboard) => Some(clipboard),+ Err(err) => {+ log::warn!("Failed to initialize arboard clipboard: {err}");+ None+ }+ }+}++#[cfg(all(+ any(+ target_os = "linux",+ target_os = "dragonfly",+ target_os = "freebsd",+ target_os = "netbsd",+ target_os = "openbsd"+ ),+ feature = "smithay-clipboard"+))]+fn init_smithay_clipboard(+ raw_display_handle: Option<RawDisplayHandle>,+) -> Option<smithay_clipboard::Clipboard> {+ #![allow(clippy::undocumented_unsafe_blocks)]++ crate::profile_function!();++ if let Some(RawDisplayHandle::Wayland(display)) = raw_display_handle {+ log::trace!("Initializing smithay clipboard…");+ #[allow(unsafe_code)]+ Some(unsafe { smithay_clipboard::Clipboard::new(display.display.as_ptr()) })+ } else {+ #[cfg(feature = "wayland")]+ log::debug!("Cannot init smithay clipboard without a Wayland display handle");+ #[cfg(not(feature = "wayland"))]+ log::debug!(+ "Cannot init smithay clipboard: the 'wayland' feature of 'egui-winit' is not enabled"+ );+ None+ }+}diff --git a/crates/vendor/egui-winit/src/lib.rs b/crates/vendor/egui-winit/src/lib.rsnew file mode 100644index 0000000..8aca55d--- /dev/null+++ b/crates/vendor/egui-winit/src/lib.rs@@ -0,0 +1,1897 @@+//! [`egui`] bindings for [`winit`](https://github.com/rust-windowing/winit).+//!+//! The library translates winit events to egui, handled copy/paste,+//! updates the cursor, open links clicked in egui, etc.+//!+//! ## Feature flags+#![cfg_attr(feature = "document-features", doc = document_features::document_features!())]+//!++#![allow(clippy::manual_range_contains)]++#[cfg(feature = "accesskit")]+pub use accesskit_winit;+pub use egui;+#[cfg(feature = "accesskit")]+use egui::accesskit;+use egui::{Pos2, Rect, Theme, Vec2, ViewportBuilder, ViewportCommand, ViewportId, ViewportInfo};+pub use winit;++pub mod clipboard;+mod window_settings;++pub use window_settings::WindowSettings;++use ahash::HashSet;+use raw_window_handle::HasDisplayHandle;++#[allow(unused_imports)]+pub(crate) use profiling_scopes::{profile_function, profile_scope};++use winit::{+ dpi::{PhysicalPosition, PhysicalSize},+ event::ElementState,+ event_loop::ActiveEventLoop,+ window::{CursorGrabMode, Window, WindowButtons, WindowLevel},+};++pub fn screen_size_in_pixels(window: &Window) -> egui::Vec2 {+ let size = window.inner_size();+ egui::vec2(size.width as f32, size.height as f32)+}++/// Calculate the `pixels_per_point` for a given window, given the current egui zoom factor+pub fn pixels_per_point(egui_ctx: &egui::Context, window: &Window) -> f32 {+ let native_pixels_per_point = window.scale_factor() as f32;+ let egui_zoom_factor = egui_ctx.zoom_factor();+ egui_zoom_factor * native_pixels_per_point+}++// ----------------------------------------------------------------------------++#[must_use]+#[derive(Clone, Copy, Debug, Default)]+pub struct EventResponse {+ /// If true, egui consumed this event, i.e. wants exclusive use of this event+ /// (e.g. a mouse click on an egui window, or entering text into a text field).+ ///+ /// For instance, if you use egui for a game, you should only+ /// pass on the events to your game when [`Self::consumed`] is `false`.+ ///+ /// Note that egui uses `tab` to move focus between elements, so this will always be `true` for tabs.+ pub consumed: bool,++ /// Do we need an egui refresh because of this event?+ pub repaint: bool,+}++// ----------------------------------------------------------------------------++/// Handles the integration between egui and a winit Window.+///+/// Instantiate one of these per viewport/window.+pub struct State {+ /// Shared clone.+ egui_ctx: egui::Context,++ viewport_id: ViewportId,+ start_time: web_time::Instant,+ egui_input: egui::RawInput,+ pointer_pos_in_points: Option<egui::Pos2>,+ any_pointer_button_down: bool,+ current_cursor_icon: Option<egui::CursorIcon>,++ clipboard: clipboard::Clipboard,++ /// If `true`, mouse inputs will be treated as touches.+ /// Useful for debugging touch support in egui.+ ///+ /// Creates duplicate touches, if real touch inputs are coming.+ simulate_touch_screen: bool,++ /// Is Some(…) when a touch is being translated to a pointer.+ ///+ /// Only one touch will be interpreted as pointer at any time.+ pointer_touch_id: Option<u64>,++ /// track ime state+ has_sent_ime_enabled: bool,++ #[cfg(feature = "accesskit")]+ accesskit: Option<accesskit_winit::Adapter>,++ allow_ime: bool,+ ime_rect_px: Option<egui::Rect>,+}++impl State {+ /// Construct a new instance+ pub fn new(+ egui_ctx: egui::Context,+ viewport_id: ViewportId,+ display_target: &dyn HasDisplayHandle,+ native_pixels_per_point: Option<f32>,+ theme: Option<winit::window::Theme>,+ max_texture_side: Option<usize>,+ ) -> Self {+ crate::profile_function!();++ let egui_input = egui::RawInput {+ focused: false, // winit will tell us when we have focus+ ..Default::default()+ };++ let mut slf = Self {+ egui_ctx,+ viewport_id,+ start_time: web_time::Instant::now(),+ egui_input,+ pointer_pos_in_points: None,+ any_pointer_button_down: false,+ current_cursor_icon: None,++ clipboard: clipboard::Clipboard::new(+ display_target.display_handle().ok().map(|h| h.as_raw()),+ ),++ simulate_touch_screen: false,+ pointer_touch_id: None,++ has_sent_ime_enabled: false,++ #[cfg(feature = "accesskit")]+ accesskit: None,++ allow_ime: false,+ ime_rect_px: None,+ };++ slf.egui_input+ .viewports+ .entry(ViewportId::ROOT)+ .or_default()+ .native_pixels_per_point = native_pixels_per_point;+ slf.egui_input.system_theme = theme.map(to_egui_theme);++ if let Some(max_texture_side) = max_texture_side {+ slf.set_max_texture_side(max_texture_side);+ }+ slf+ }++ #[cfg(feature = "accesskit")]+ pub fn init_accesskit<T: From<accesskit_winit::Event> + Send>(+ &mut self,+ window: &Window,+ event_loop_proxy: winit::event_loop::EventLoopProxy<T>,+ ) {+ crate::profile_function!();++ self.accesskit = Some(accesskit_winit::Adapter::with_event_loop_proxy(+ window,+ event_loop_proxy,+ ));+ }++ /// Call this once a graphics context has been created to update the maximum texture dimensions+ /// that egui will use.+ pub fn set_max_texture_side(&mut self, max_texture_side: usize) {+ self.egui_input.max_texture_side = Some(max_texture_side);+ }++ /// Fetches text from the clipboard and returns it.+ pub fn clipboard_text(&mut self) -> Option<String> {+ self.clipboard.get()+ }++ /// Places the text onto the clipboard.+ pub fn set_clipboard_text(&mut self, text: String) {+ self.clipboard.set(text);+ }++ /// Returns [`false`] or the last value that [`Window::set_ime_allowed()`] was called with, used for debouncing.+ pub fn allow_ime(&self) -> bool {+ self.allow_ime+ }++ /// Set the last value that [`Window::set_ime_allowed()`] was called with.+ pub fn set_allow_ime(&mut self, allow: bool) {+ self.allow_ime = allow;+ }++ #[inline]+ pub fn egui_ctx(&self) -> &egui::Context {+ &self.egui_ctx+ }++ /// The current input state.+ /// This is changed by [`Self::on_window_event`] and cleared by [`Self::take_egui_input`].+ #[inline]+ pub fn egui_input(&self) -> &egui::RawInput {+ &self.egui_input+ }++ /// The current input state.+ /// This is changed by [`Self::on_window_event`] and cleared by [`Self::take_egui_input`].+ #[inline]+ pub fn egui_input_mut(&mut self) -> &mut egui::RawInput {+ &mut self.egui_input+ }++ /// Prepare for a new frame by extracting the accumulated input,+ ///+ /// as well as setting [the time](egui::RawInput::time) and [screen rectangle](egui::RawInput::screen_rect).+ ///+ /// You need to set [`egui::RawInput::viewports`] yourself though.+ /// Use [`update_viewport_info`] to update the info for each+ /// viewport.+ pub fn take_egui_input(&mut self, window: &Window) -> egui::RawInput {+ crate::profile_function!();++ self.egui_input.time = Some(self.start_time.elapsed().as_secs_f64());++ // On Windows, a minimized window will have 0 width and height.+ // See: https://github.com/rust-windowing/winit/issues/208+ // This solves an issue where egui window positions would be changed when minimizing on Windows.+ let screen_size_in_pixels = screen_size_in_pixels(window);+ let screen_size_in_points =+ screen_size_in_pixels / pixels_per_point(&self.egui_ctx, window);++ self.egui_input.screen_rect = (screen_size_in_points.x > 0.0+ && screen_size_in_points.y > 0.0)+ .then(|| Rect::from_min_size(Pos2::ZERO, screen_size_in_points));++ // Tell egui which viewport is now active:+ self.egui_input.viewport_id = self.viewport_id;++ self.egui_input+ .viewports+ .entry(self.viewport_id)+ .or_default()+ .native_pixels_per_point = Some(window.scale_factor() as f32);++ self.egui_input.take()+ }++ /// Call this when there is a new event.+ ///+ /// The result can be found in [`Self::egui_input`] and be extracted with [`Self::take_egui_input`].+ pub fn on_window_event(+ &mut self,+ window: &Window,+ event: &winit::event::WindowEvent,+ ) -> EventResponse {+ crate::profile_function!(short_window_event_description(event));++ #[cfg(feature = "accesskit")]+ if let Some(accesskit) = self.accesskit.as_mut() {+ accesskit.process_event(window, event);+ }++ use winit::event::WindowEvent;+ match event {+ WindowEvent::ScaleFactorChanged { scale_factor, .. } => {+ let native_pixels_per_point = *scale_factor as f32;++ self.egui_input+ .viewports+ .entry(self.viewport_id)+ .or_default()+ .native_pixels_per_point = Some(native_pixels_per_point);++ EventResponse {+ repaint: true,+ consumed: false,+ }+ }+ WindowEvent::MouseInput { state, button, .. } => {+ self.on_mouse_button_input(*state, *button);+ EventResponse {+ repaint: true,+ consumed: self.egui_ctx.wants_pointer_input(),+ }+ }+ WindowEvent::MouseWheel { delta, .. } => {+ self.on_mouse_wheel(window, *delta);+ EventResponse {+ repaint: true,+ consumed: self.egui_ctx.wants_pointer_input(),+ }+ }+ WindowEvent::CursorMoved { position, .. } => {+ self.on_cursor_moved(window, *position);+ EventResponse {+ repaint: true,+ consumed: self.egui_ctx.is_using_pointer(),+ }+ }+ WindowEvent::CursorLeft { .. } => {+ self.pointer_pos_in_points = None;+ self.egui_input.events.push(egui::Event::PointerGone);+ EventResponse {+ repaint: true,+ consumed: false,+ }+ }+ // WindowEvent::TouchpadPressure {device_id, pressure, stage, .. } => {} // TODO(emilk)+ WindowEvent::Touch(touch) => {+ self.on_touch(window, touch);+ let consumed = match touch.phase {+ winit::event::TouchPhase::Started+ | winit::event::TouchPhase::Ended+ | winit::event::TouchPhase::Cancelled => self.egui_ctx.wants_pointer_input(),+ winit::event::TouchPhase::Moved => self.egui_ctx.is_using_pointer(),+ };+ EventResponse {+ repaint: true,+ consumed,+ }+ }++ WindowEvent::Ime(ime) => {+ if cfg!(target_os = "linux") {+ // We ignore IME events on linux, because of https://github.com/emilk/egui/issues/5008+ } else {+ // on Mac even Cmd-C is pressed during ime, a `c` is pushed to Preedit.+ // So no need to check is_mac_cmd.+ //+ // How winit produce `Ime::Enabled` and `Ime::Disabled` differs in MacOS+ // and Windows.+ //+ // - On Windows, before and after each Commit will produce an Enable/Disabled+ // event.+ // - On MacOS, only when user explicit enable/disable ime. No Disabled+ // after Commit.+ //+ // We use input_method_editor_started to manually insert CompositionStart+ // between Commits.+ match ime {+ winit::event::Ime::Enabled => {+ self.ime_event_enable();+ }+ winit::event::Ime::Preedit(text, Some(_cursor)) => {+ self.ime_event_enable();+ self.egui_input+ .events+ .push(egui::Event::Ime(egui::ImeEvent::Preedit(text.clone())));+ }+ winit::event::Ime::Commit(text) => {+ self.egui_input+ .events+ .push(egui::Event::Ime(egui::ImeEvent::Commit(text.clone())));+ self.ime_event_disable();+ }+ winit::event::Ime::Disabled | winit::event::Ime::Preedit(_, None) => {+ self.ime_event_disable();+ }+ };+ }++ EventResponse {+ repaint: true,+ consumed: self.egui_ctx.wants_keyboard_input(),+ }+ }+ WindowEvent::KeyboardInput {+ event,+ is_synthetic,+ ..+ } => {+ // Winit generates fake "synthetic" KeyboardInput events when the focus+ // is changed to the window, or away from it. Synthetic key presses+ // represent no real key presses and should be ignored.+ // See https://github.com/rust-windowing/winit/issues/3543+ if *is_synthetic && event.state == ElementState::Pressed {+ EventResponse {+ repaint: true,+ consumed: false,+ }+ } else {+ self.on_keyboard_input(event);++ // When pressing the Tab key, egui focuses the first focusable element, hence Tab always consumes.+ let consumed = self.egui_ctx.wants_keyboard_input()+ || event.logical_key+ == winit::keyboard::Key::Named(winit::keyboard::NamedKey::Tab);+ EventResponse {+ repaint: true,+ consumed,+ }+ }+ }+ WindowEvent::Focused(focused) => {+ self.egui_input.focused = *focused;+ self.egui_input+ .events+ .push(egui::Event::WindowFocused(*focused));+ EventResponse {+ repaint: true,+ consumed: false,+ }+ }+ WindowEvent::ThemeChanged(winit_theme) => {+ self.egui_input.system_theme = Some(to_egui_theme(*winit_theme));+ EventResponse {+ repaint: true,+ consumed: false,+ }+ }+ WindowEvent::HoveredFile(path) => {+ self.egui_input.hovered_files.push(egui::HoveredFile {+ path: Some(path.clone()),+ ..Default::default()+ });+ EventResponse {+ repaint: true,+ consumed: false,+ }+ }+ WindowEvent::HoveredFileCancelled => {+ self.egui_input.hovered_files.clear();+ EventResponse {+ repaint: true,+ consumed: false,+ }+ }+ WindowEvent::DroppedFile(path) => {+ self.egui_input.hovered_files.clear();+ self.egui_input.dropped_files.push(egui::DroppedFile {+ path: Some(path.clone()),+ ..Default::default()+ });+ EventResponse {+ repaint: true,+ consumed: false,+ }+ }+ WindowEvent::ModifiersChanged(state) => {+ let state = state.state();++ let alt = state.alt_key();+ let ctrl = state.control_key();+ let shift = state.shift_key();+ let super_ = state.super_key();++ self.egui_input.modifiers.alt = alt;+ self.egui_input.modifiers.ctrl = ctrl;+ self.egui_input.modifiers.shift = shift;+ self.egui_input.modifiers.mac_cmd = cfg!(target_os = "macos") && super_;+ self.egui_input.modifiers.command = if cfg!(target_os = "macos") {+ super_+ } else {+ ctrl+ };++ EventResponse {+ repaint: true,+ consumed: false,+ }+ }++ // Things that may require repaint:+ WindowEvent::RedrawRequested+ | WindowEvent::CursorEntered { .. }+ | WindowEvent::Destroyed+ | WindowEvent::Occluded(_)+ | WindowEvent::Resized(_)+ | WindowEvent::Moved(_)+ | WindowEvent::TouchpadPressure { .. }+ | WindowEvent::CloseRequested => EventResponse {+ repaint: true,+ consumed: false,+ },++ // Things we completely ignore:+ WindowEvent::ActivationTokenDone { .. }+ | WindowEvent::AxisMotion { .. }+ | WindowEvent::DoubleTapGesture { .. }+ | WindowEvent::RotationGesture { .. }+ | WindowEvent::PanGesture { .. } => EventResponse {+ repaint: false,+ consumed: false,+ },++ WindowEvent::PinchGesture { delta, .. } => {+ // Positive delta values indicate magnification (zooming in).+ // Negative delta values indicate shrinking (zooming out).+ let zoom_factor = (*delta as f32).exp();+ self.egui_input.events.push(egui::Event::Zoom(zoom_factor));+ EventResponse {+ repaint: true,+ consumed: self.egui_ctx.wants_pointer_input(),+ }+ }+ }+ }++ pub fn ime_event_enable(&mut self) {+ if !self.has_sent_ime_enabled {+ self.egui_input+ .events+ .push(egui::Event::Ime(egui::ImeEvent::Enabled));+ self.has_sent_ime_enabled = true;+ }+ }++ pub fn ime_event_disable(&mut self) {+ self.egui_input+ .events+ .push(egui::Event::Ime(egui::ImeEvent::Disabled));+ self.has_sent_ime_enabled = false;+ }++ pub fn on_mouse_motion(&mut self, delta: (f64, f64)) {+ self.egui_input.events.push(egui::Event::MouseMoved(Vec2 {+ x: delta.0 as f32,+ y: delta.1 as f32,+ }));+ }++ /// Call this when there is a new [`accesskit::ActionRequest`].+ ///+ /// The result can be found in [`Self::egui_input`] and be extracted with [`Self::take_egui_input`].+ #[cfg(feature = "accesskit")]+ pub fn on_accesskit_action_request(&mut self, request: accesskit::ActionRequest) {+ self.egui_input+ .events+ .push(egui::Event::AccessKitActionRequest(request));+ }++ fn on_mouse_button_input(+ &mut self,+ state: winit::event::ElementState,+ button: winit::event::MouseButton,+ ) {+ if let Some(pos) = self.pointer_pos_in_points {+ if let Some(button) = translate_mouse_button(button) {+ let pressed = state == winit::event::ElementState::Pressed;++ self.egui_input.events.push(egui::Event::PointerButton {+ pos,+ button,+ pressed,+ modifiers: self.egui_input.modifiers,+ });++ if self.simulate_touch_screen {+ if pressed {+ self.any_pointer_button_down = true;++ self.egui_input.events.push(egui::Event::Touch {+ device_id: egui::TouchDeviceId(0),+ id: egui::TouchId(0),+ phase: egui::TouchPhase::Start,+ pos,+ force: None,+ });+ } else {+ self.any_pointer_button_down = false;++ self.egui_input.events.push(egui::Event::PointerGone);++ self.egui_input.events.push(egui::Event::Touch {+ device_id: egui::TouchDeviceId(0),+ id: egui::TouchId(0),+ phase: egui::TouchPhase::End,+ pos,+ force: None,+ });+ };+ }+ }+ }+ }++ fn on_cursor_moved(+ &mut self,+ window: &Window,+ pos_in_pixels: winit::dpi::PhysicalPosition<f64>,+ ) {+ let pixels_per_point = pixels_per_point(&self.egui_ctx, window);++ let pos_in_points = egui::pos2(+ pos_in_pixels.x as f32 / pixels_per_point,+ pos_in_pixels.y as f32 / pixels_per_point,+ );+ self.pointer_pos_in_points = Some(pos_in_points);++ if self.simulate_touch_screen {+ if self.any_pointer_button_down {+ self.egui_input+ .events+ .push(egui::Event::PointerMoved(pos_in_points));++ self.egui_input.events.push(egui::Event::Touch {+ device_id: egui::TouchDeviceId(0),+ id: egui::TouchId(0),+ phase: egui::TouchPhase::Move,+ pos: pos_in_points,+ force: None,+ });+ }+ } else {+ self.egui_input+ .events+ .push(egui::Event::PointerMoved(pos_in_points));+ }+ }++ fn on_touch(&mut self, window: &Window, touch: &winit::event::Touch) {+ let pixels_per_point = pixels_per_point(&self.egui_ctx, window);++ // Emit touch event+ self.egui_input.events.push(egui::Event::Touch {+ device_id: egui::TouchDeviceId(egui::epaint::util::hash(touch.device_id)),+ id: egui::TouchId::from(touch.id),+ phase: match touch.phase {+ winit::event::TouchPhase::Started => egui::TouchPhase::Start,+ winit::event::TouchPhase::Moved => egui::TouchPhase::Move,+ winit::event::TouchPhase::Ended => egui::TouchPhase::End,+ winit::event::TouchPhase::Cancelled => egui::TouchPhase::Cancel,+ },+ pos: egui::pos2(+ touch.location.x as f32 / pixels_per_point,+ touch.location.y as f32 / pixels_per_point,+ ),+ force: match touch.force {+ Some(winit::event::Force::Normalized(force)) => Some(force as f32),+ Some(winit::event::Force::Calibrated {+ force,+ max_possible_force,+ ..+ }) => Some((force / max_possible_force) as f32),+ None => None,+ },+ });+ // If we're not yet translating a touch or we're translating this very+ // touch …+ if self.pointer_touch_id.is_none() || self.pointer_touch_id.unwrap_or_default() == touch.id+ {+ // … emit PointerButton resp. PointerMoved events to emulate mouse+ match touch.phase {+ winit::event::TouchPhase::Started => {+ self.pointer_touch_id = Some(touch.id);+ // First move the pointer to the right location+ self.on_cursor_moved(window, touch.location);+ self.on_mouse_button_input(+ winit::event::ElementState::Pressed,+ winit::event::MouseButton::Left,+ );+ }+ winit::event::TouchPhase::Moved => {+ self.on_cursor_moved(window, touch.location);+ }+ winit::event::TouchPhase::Ended => {+ self.pointer_touch_id = None;+ self.on_mouse_button_input(+ winit::event::ElementState::Released,+ winit::event::MouseButton::Left,+ );+ // The pointer should vanish completely to not get any+ // hover effects+ self.pointer_pos_in_points = None;+ self.egui_input.events.push(egui::Event::PointerGone);+ }+ winit::event::TouchPhase::Cancelled => {+ self.pointer_touch_id = None;+ self.pointer_pos_in_points = None;+ self.egui_input.events.push(egui::Event::PointerGone);+ }+ }+ }+ }++ fn on_mouse_wheel(&mut self, window: &Window, delta: winit::event::MouseScrollDelta) {+ let pixels_per_point = pixels_per_point(&self.egui_ctx, window);++ {+ let (unit, delta) = match delta {+ winit::event::MouseScrollDelta::LineDelta(x, y) => {+ (egui::MouseWheelUnit::Line, egui::vec2(x, y))+ }+ winit::event::MouseScrollDelta::PixelDelta(winit::dpi::PhysicalPosition {+ x,+ y,+ }) => (+ egui::MouseWheelUnit::Point,+ egui::vec2(x as f32, y as f32) / pixels_per_point,+ ),+ };+ let modifiers = self.egui_input.modifiers;+ self.egui_input.events.push(egui::Event::MouseWheel {+ unit,+ delta,+ modifiers,+ });+ }+ }++ fn on_keyboard_input(&mut self, event: &winit::event::KeyEvent) {+ let winit::event::KeyEvent {+ // Represents the position of a key independent of the currently active layout.+ //+ // It also uniquely identifies the physical key (i.e. it's mostly synonymous with a scancode).+ // The most prevalent use case for this is games. For example the default keys for the player+ // to move around might be the W, A, S, and D keys on a US layout. The position of these keys+ // is more important than their label, so they should map to Z, Q, S, and D on an "AZERTY"+ // layout. (This value is `KeyCode::KeyW` for the Z key on an AZERTY layout.)+ physical_key,++ // Represents the results of a keymap, i.e. what character a certain key press represents.+ // When telling users "Press Ctrl-F to find", this is where we should+ // look for the "F" key, because they may have a dvorak layout on+ // a qwerty keyboard, and so the logical "F" character may not be located on the physical `KeyCode::KeyF` position.+ logical_key,++ text,++ state,++ location: _, // e.g. is it on the numpad?+ repeat: _, // egui will figure this out for us+ ..+ } = event;++ let pressed = *state == winit::event::ElementState::Pressed;++ let physical_key = if let winit::keyboard::PhysicalKey::Code(keycode) = *physical_key {+ key_from_key_code(keycode)+ } else {+ None+ };++ let logical_key = key_from_winit_key(logical_key);++ // Helpful logging to enable when adding new key support+ log::trace!(+ "logical {:?} -> {:?}, physical {:?} -> {:?}",+ event.logical_key,+ logical_key,+ event.physical_key,+ physical_key+ );++ // "Logical OR physical key" is a fallback mechanism for keyboard layouts without Latin characters: it lets them+ // emit events as if the corresponding keys from the Latin layout were pressed. In this case, clipboard shortcuts+ // are mapped to the physical keys that normally contain C, X, V, etc.+ // See also: https://github.com/emilk/egui/issues/3653+ if let Some(active_key) = logical_key.or(physical_key) {+ if pressed {+ if is_cut_command(self.egui_input.modifiers, active_key) {+ self.egui_input.events.push(egui::Event::Cut);+ return;+ } else if is_copy_command(self.egui_input.modifiers, active_key) {+ self.egui_input.events.push(egui::Event::Copy);+ return;+ } else if is_paste_command(self.egui_input.modifiers, active_key) {+ if let Some(contents) = self.clipboard.get() {+ let contents = contents.replace("\r\n", "\n");+ if !contents.is_empty() {+ self.egui_input.events.push(egui::Event::Paste(contents));+ }+ }+ return;+ }+ }++ self.egui_input.events.push(egui::Event::Key {+ key: active_key,+ physical_key,+ pressed,+ repeat: false, // egui will fill this in for us!+ modifiers: self.egui_input.modifiers,+ });+ }++ if let Some(text) = &text {+ // Make sure there is text, and that it is not control characters+ // (e.g. delete is sent as "\u{f728}" on macOS).+ if !text.is_empty() && text.chars().all(is_printable_char) {+ // On some platforms we get here when the user presses Cmd-C (copy), ctrl-W, etc.+ // We need to ignore these characters that are side-effects of commands.+ // Also make sure the key is pressed (not released). On Linux, text might+ // contain some data even when the key is released.+ //+ // RustCord: except on Windows with Ctrl and Alt both held. Windows+ // reports AltGr as Ctrl + Alt, and keyboards without an AltGr key+ // type its characters with Ctrl + Alt (Ctrl + Alt + Q is @ on the+ // Spanish layouts). Shortcuts never produce a printable character+ // there, so one that arrives is typed text.+ let alt_gr = cfg!(windows) && self.egui_input.modifiers.ctrl && self.egui_input.modifiers.alt;+ let is_cmd = !alt_gr+ && (self.egui_input.modifiers.ctrl+ || self.egui_input.modifiers.command+ || self.egui_input.modifiers.mac_cmd);+ if pressed && !is_cmd {+ self.egui_input+ .events+ .push(egui::Event::Text(text.to_string()));+ }+ }+ }+ }++ /// Call with the output given by `egui`.+ ///+ /// This will, if needed:+ /// * update the cursor+ /// * copy text to the clipboard+ /// * open any clicked urls+ /// * update the IME+ /// *+ pub fn handle_platform_output(+ &mut self,+ window: &Window,+ platform_output: egui::PlatformOutput,+ ) {+ crate::profile_function!();++ let egui::PlatformOutput {+ cursor_icon,+ open_url,+ copied_text,+ events: _, // handled elsewhere+ mutable_text_under_cursor: _, // only used in eframe web+ ime,+ #[cfg(feature = "accesskit")]+ accesskit_update,+ num_completed_passes: _, // `egui::Context::run` handles this+ request_discard_reasons: _, // `egui::Context::run` handles this+ } = platform_output;++ self.set_cursor_icon(window, cursor_icon);++ if let Some(open_url) = open_url {+ open_url_in_browser(&open_url.url);+ }++ if !copied_text.is_empty() {+ self.clipboard.set(copied_text);+ }++ let allow_ime = ime.is_some();+ if self.allow_ime != allow_ime {+ self.allow_ime = allow_ime;+ crate::profile_scope!("set_ime_allowed");+ window.set_ime_allowed(allow_ime);+ }++ if let Some(ime) = ime {+ let pixels_per_point = pixels_per_point(&self.egui_ctx, window);+ let ime_rect_px = pixels_per_point * ime.rect;+ if self.ime_rect_px != Some(ime_rect_px)+ || self.egui_ctx.input(|i| !i.events.is_empty())+ {+ self.ime_rect_px = Some(ime_rect_px);+ crate::profile_scope!("set_ime_cursor_area");+ window.set_ime_cursor_area(+ winit::dpi::PhysicalPosition {+ x: ime_rect_px.min.x,+ y: ime_rect_px.min.y,+ },+ winit::dpi::PhysicalSize {+ width: ime_rect_px.width(),+ height: ime_rect_px.height(),+ },+ );+ }+ } else {+ self.ime_rect_px = None;+ }++ #[cfg(feature = "accesskit")]+ if let Some(accesskit) = self.accesskit.as_mut() {+ if let Some(update) = accesskit_update {+ crate::profile_scope!("accesskit");+ accesskit.update_if_active(|| update);+ }+ }+ }++ fn set_cursor_icon(&mut self, window: &Window, cursor_icon: egui::CursorIcon) {+ if self.current_cursor_icon == Some(cursor_icon) {+ // Prevent flickering near frame boundary when Windows OS tries to control cursor icon for window resizing.+ // On other platforms: just early-out to save CPU.+ return;+ }++ let is_pointer_in_window = self.pointer_pos_in_points.is_some();+ if is_pointer_in_window {+ self.current_cursor_icon = Some(cursor_icon);++ if let Some(winit_cursor_icon) = translate_cursor(cursor_icon) {+ window.set_cursor_visible(true);+ window.set_cursor(winit_cursor_icon);+ } else {+ window.set_cursor_visible(false);+ }+ } else {+ // Remember to set the cursor again once the cursor returns to the screen:+ self.current_cursor_icon = None;+ }+ }+}++fn to_egui_theme(theme: winit::window::Theme) -> Theme {+ match theme {+ winit::window::Theme::Dark => Theme::Dark,+ winit::window::Theme::Light => Theme::Light,+ }+}++pub fn inner_rect_in_points(window: &Window, pixels_per_point: f32) -> Option<Rect> {+ let inner_pos_px = window.inner_position().ok()?;+ let inner_pos_px = egui::pos2(inner_pos_px.x as f32, inner_pos_px.y as f32);++ let inner_size_px = window.inner_size();+ let inner_size_px = egui::vec2(inner_size_px.width as f32, inner_size_px.height as f32);++ let inner_rect_px = egui::Rect::from_min_size(inner_pos_px, inner_size_px);++ Some(inner_rect_px / pixels_per_point)+}++pub fn outer_rect_in_points(window: &Window, pixels_per_point: f32) -> Option<Rect> {+ let outer_pos_px = window.outer_position().ok()?;+ let outer_pos_px = egui::pos2(outer_pos_px.x as f32, outer_pos_px.y as f32);++ let outer_size_px = window.outer_size();+ let outer_size_px = egui::vec2(outer_size_px.width as f32, outer_size_px.height as f32);++ let outer_rect_px = egui::Rect::from_min_size(outer_pos_px, outer_size_px);++ Some(outer_rect_px / pixels_per_point)+}++/// Update the given viewport info with the current state of the window.+///+/// Call before [`State::take_egui_input`].+///+/// If this is called right after window creation, `is_init` should be `true`, otherwise `false`.+pub fn update_viewport_info(+ viewport_info: &mut ViewportInfo,+ egui_ctx: &egui::Context,+ window: &Window,+ is_init: bool,+) {+ crate::profile_function!();++ let pixels_per_point = pixels_per_point(egui_ctx, window);++ let has_a_position = match window.is_minimized() {+ Some(true) => false,+ Some(false) | None => true,+ };++ let inner_rect = if has_a_position {+ inner_rect_in_points(window, pixels_per_point)+ } else {+ None+ };++ let outer_rect = if has_a_position {+ outer_rect_in_points(window, pixels_per_point)+ } else {+ None+ };++ let monitor_size = {+ crate::profile_scope!("monitor_size");+ if let Some(monitor) = window.current_monitor() {+ let size = monitor.size().to_logical::<f32>(pixels_per_point.into());+ Some(egui::vec2(size.width, size.height))+ } else {+ None+ }+ };++ viewport_info.title = Some(window.title());+ viewport_info.native_pixels_per_point = Some(window.scale_factor() as f32);++ viewport_info.monitor_size = monitor_size;+ viewport_info.inner_rect = inner_rect;+ viewport_info.outer_rect = outer_rect;++ if is_init || !cfg!(target_os = "macos") {+ // Asking for minimized/maximized state at runtime leads to a deadlock on Mac when running+ // `cargo run -p custom_window_frame`.+ // See https://github.com/emilk/egui/issues/3494+ viewport_info.maximized = Some(window.is_maximized());+ viewport_info.minimized = Some(window.is_minimized().unwrap_or(false));+ }++ viewport_info.fullscreen = Some(window.fullscreen().is_some());+ viewport_info.focused = Some(window.has_focus());+}++fn open_url_in_browser(_url: &str) {+ #[cfg(feature = "webbrowser")]+ if let Err(err) = webbrowser::open(_url) {+ log::warn!("Failed to open url: {}", err);+ }++ #[cfg(not(feature = "webbrowser"))]+ {+ log::warn!("Cannot open url - feature \"links\" not enabled.");+ }+}++/// Winit sends special keys (backspace, delete, F1, …) as characters.+/// Ignore those.+/// We also ignore '\r', '\n', '\t'.+/// Newlines are handled by the `Key::Enter` event.+fn is_printable_char(chr: char) -> bool {+ let is_in_private_use_area = '\u{e000}' <= chr && chr <= '\u{f8ff}'+ || '\u{f0000}' <= chr && chr <= '\u{ffffd}'+ || '\u{100000}' <= chr && chr <= '\u{10fffd}';++ !is_in_private_use_area && !chr.is_ascii_control()+}++fn is_cut_command(modifiers: egui::Modifiers, keycode: egui::Key) -> bool {+ keycode == egui::Key::Cut+ || (modifiers.command && keycode == egui::Key::X)+ || (cfg!(target_os = "windows") && modifiers.shift && keycode == egui::Key::Delete)+}++fn is_copy_command(modifiers: egui::Modifiers, keycode: egui::Key) -> bool {+ keycode == egui::Key::Copy+ || (modifiers.command && keycode == egui::Key::C)+ || (cfg!(target_os = "windows") && modifiers.ctrl && keycode == egui::Key::Insert)+}++fn is_paste_command(modifiers: egui::Modifiers, keycode: egui::Key) -> bool {+ keycode == egui::Key::Paste+ || (modifiers.command && keycode == egui::Key::V)+ || (cfg!(target_os = "windows") && modifiers.shift && keycode == egui::Key::Insert)+}++fn translate_mouse_button(button: winit::event::MouseButton) -> Option<egui::PointerButton> {+ match button {+ winit::event::MouseButton::Left => Some(egui::PointerButton::Primary),+ winit::event::MouseButton::Right => Some(egui::PointerButton::Secondary),+ winit::event::MouseButton::Middle => Some(egui::PointerButton::Middle),+ winit::event::MouseButton::Back => Some(egui::PointerButton::Extra1),+ winit::event::MouseButton::Forward => Some(egui::PointerButton::Extra2),+ winit::event::MouseButton::Other(_) => None,+ }+}++fn key_from_winit_key(key: &winit::keyboard::Key) -> Option<egui::Key> {+ match key {+ winit::keyboard::Key::Named(named_key) => key_from_named_key(*named_key),+ winit::keyboard::Key::Character(str) => egui::Key::from_name(str.as_str()),+ winit::keyboard::Key::Unidentified(_) | winit::keyboard::Key::Dead(_) => None,+ }+}++fn key_from_named_key(named_key: winit::keyboard::NamedKey) -> Option<egui::Key> {+ use egui::Key;+ use winit::keyboard::NamedKey;++ Some(match named_key {+ NamedKey::Enter => Key::Enter,+ NamedKey::Tab => Key::Tab,+ NamedKey::ArrowDown => Key::ArrowDown,+ NamedKey::ArrowLeft => Key::ArrowLeft,+ NamedKey::ArrowRight => Key::ArrowRight,+ NamedKey::ArrowUp => Key::ArrowUp,+ NamedKey::End => Key::End,+ NamedKey::Home => Key::Home,+ NamedKey::PageDown => Key::PageDown,+ NamedKey::PageUp => Key::PageUp,+ NamedKey::Backspace => Key::Backspace,+ NamedKey::Delete => Key::Delete,+ NamedKey::Insert => Key::Insert,+ NamedKey::Escape => Key::Escape,+ NamedKey::Cut => Key::Cut,+ NamedKey::Copy => Key::Copy,+ NamedKey::Paste => Key::Paste,++ NamedKey::Space => Key::Space,++ NamedKey::F1 => Key::F1,+ NamedKey::F2 => Key::F2,+ NamedKey::F3 => Key::F3,+ NamedKey::F4 => Key::F4,+ NamedKey::F5 => Key::F5,+ NamedKey::F6 => Key::F6,+ NamedKey::F7 => Key::F7,+ NamedKey::F8 => Key::F8,+ NamedKey::F9 => Key::F9,+ NamedKey::F10 => Key::F10,+ NamedKey::F11 => Key::F11,+ NamedKey::F12 => Key::F12,+ NamedKey::F13 => Key::F13,+ NamedKey::F14 => Key::F14,+ NamedKey::F15 => Key::F15,+ NamedKey::F16 => Key::F16,+ NamedKey::F17 => Key::F17,+ NamedKey::F18 => Key::F18,+ NamedKey::F19 => Key::F19,+ NamedKey::F20 => Key::F20,+ NamedKey::F21 => Key::F21,+ NamedKey::F22 => Key::F22,+ NamedKey::F23 => Key::F23,+ NamedKey::F24 => Key::F24,+ NamedKey::F25 => Key::F25,+ NamedKey::F26 => Key::F26,+ NamedKey::F27 => Key::F27,+ NamedKey::F28 => Key::F28,+ NamedKey::F29 => Key::F29,+ NamedKey::F30 => Key::F30,+ NamedKey::F31 => Key::F31,+ NamedKey::F32 => Key::F32,+ NamedKey::F33 => Key::F33,+ NamedKey::F34 => Key::F34,+ NamedKey::F35 => Key::F35,+ _ => {+ log::trace!("Unknown key: {named_key:?}");+ return None;+ }+ })+}++fn key_from_key_code(key: winit::keyboard::KeyCode) -> Option<egui::Key> {+ use egui::Key;+ use winit::keyboard::KeyCode;++ Some(match key {+ KeyCode::ArrowDown => Key::ArrowDown,+ KeyCode::ArrowLeft => Key::ArrowLeft,+ KeyCode::ArrowRight => Key::ArrowRight,+ KeyCode::ArrowUp => Key::ArrowUp,++ KeyCode::Escape => Key::Escape,+ KeyCode::Tab => Key::Tab,+ KeyCode::Backspace => Key::Backspace,+ KeyCode::Enter | KeyCode::NumpadEnter => Key::Enter,++ KeyCode::Insert => Key::Insert,+ KeyCode::Delete => Key::Delete,+ KeyCode::Home => Key::Home,+ KeyCode::End => Key::End,+ KeyCode::PageUp => Key::PageUp,+ KeyCode::PageDown => Key::PageDown,++ // Punctuation+ KeyCode::Space => Key::Space,+ KeyCode::Comma => Key::Comma,+ KeyCode::Period => Key::Period,+ // KeyCode::Colon => Key::Colon, // NOTE: there is no physical colon key on an american keyboard+ KeyCode::Semicolon => Key::Semicolon,+ KeyCode::Backslash => Key::Backslash,+ KeyCode::Slash | KeyCode::NumpadDivide => Key::Slash,+ KeyCode::BracketLeft => Key::OpenBracket,+ KeyCode::BracketRight => Key::CloseBracket,+ KeyCode::Backquote => Key::Backtick,+ KeyCode::Quote => Key::Quote,++ KeyCode::Cut => Key::Cut,+ KeyCode::Copy => Key::Copy,+ KeyCode::Paste => Key::Paste,+ KeyCode::Minus | KeyCode::NumpadSubtract => Key::Minus,+ KeyCode::NumpadAdd => Key::Plus,+ KeyCode::Equal => Key::Equals,++ KeyCode::Digit0 | KeyCode::Numpad0 => Key::Num0,+ KeyCode::Digit1 | KeyCode::Numpad1 => Key::Num1,+ KeyCode::Digit2 | KeyCode::Numpad2 => Key::Num2,+ KeyCode::Digit3 | KeyCode::Numpad3 => Key::Num3,+ KeyCode::Digit4 | KeyCode::Numpad4 => Key::Num4,+ KeyCode::Digit5 | KeyCode::Numpad5 => Key::Num5,+ KeyCode::Digit6 | KeyCode::Numpad6 => Key::Num6,+ KeyCode::Digit7 | KeyCode::Numpad7 => Key::Num7,+ KeyCode::Digit8 | KeyCode::Numpad8 => Key::Num8,+ KeyCode::Digit9 | KeyCode::Numpad9 => Key::Num9,++ KeyCode::KeyA => Key::A,+ KeyCode::KeyB => Key::B,+ KeyCode::KeyC => Key::C,+ KeyCode::KeyD => Key::D,+ KeyCode::KeyE => Key::E,+ KeyCode::KeyF => Key::F,+ KeyCode::KeyG => Key::G,+ KeyCode::KeyH => Key::H,+ KeyCode::KeyI => Key::I,+ KeyCode::KeyJ => Key::J,+ KeyCode::KeyK => Key::K,+ KeyCode::KeyL => Key::L,+ KeyCode::KeyM => Key::M,+ KeyCode::KeyN => Key::N,+ KeyCode::KeyO => Key::O,+ KeyCode::KeyP => Key::P,+ KeyCode::KeyQ => Key::Q,+ KeyCode::KeyR => Key::R,+ KeyCode::KeyS => Key::S,+ KeyCode::KeyT => Key::T,+ KeyCode::KeyU => Key::U,+ KeyCode::KeyV => Key::V,+ KeyCode::KeyW => Key::W,+ KeyCode::KeyX => Key::X,+ KeyCode::KeyY => Key::Y,+ KeyCode::KeyZ => Key::Z,++ KeyCode::F1 => Key::F1,+ KeyCode::F2 => Key::F2,+ KeyCode::F3 => Key::F3,+ KeyCode::F4 => Key::F4,+ KeyCode::F5 => Key::F5,+ KeyCode::F6 => Key::F6,+ KeyCode::F7 => Key::F7,+ KeyCode::F8 => Key::F8,+ KeyCode::F9 => Key::F9,+ KeyCode::F10 => Key::F10,+ KeyCode::F11 => Key::F11,+ KeyCode::F12 => Key::F12,+ KeyCode::F13 => Key::F13,+ KeyCode::F14 => Key::F14,+ KeyCode::F15 => Key::F15,+ KeyCode::F16 => Key::F16,+ KeyCode::F17 => Key::F17,+ KeyCode::F18 => Key::F18,+ KeyCode::F19 => Key::F19,+ KeyCode::F20 => Key::F20,+ KeyCode::F21 => Key::F21,+ KeyCode::F22 => Key::F22,+ KeyCode::F23 => Key::F23,+ KeyCode::F24 => Key::F24,+ KeyCode::F25 => Key::F25,+ KeyCode::F26 => Key::F26,+ KeyCode::F27 => Key::F27,+ KeyCode::F28 => Key::F28,+ KeyCode::F29 => Key::F29,+ KeyCode::F30 => Key::F30,+ KeyCode::F31 => Key::F31,+ KeyCode::F32 => Key::F32,+ KeyCode::F33 => Key::F33,+ KeyCode::F34 => Key::F34,+ KeyCode::F35 => Key::F35,++ _ => {+ return None;+ }+ })+}++fn translate_cursor(cursor_icon: egui::CursorIcon) -> Option<winit::window::CursorIcon> {+ match cursor_icon {+ egui::CursorIcon::None => None,++ egui::CursorIcon::Alias => Some(winit::window::CursorIcon::Alias),+ egui::CursorIcon::AllScroll => Some(winit::window::CursorIcon::AllScroll),+ egui::CursorIcon::Cell => Some(winit::window::CursorIcon::Cell),+ egui::CursorIcon::ContextMenu => Some(winit::window::CursorIcon::ContextMenu),+ egui::CursorIcon::Copy => Some(winit::window::CursorIcon::Copy),+ egui::CursorIcon::Crosshair => Some(winit::window::CursorIcon::Crosshair),+ egui::CursorIcon::Default => Some(winit::window::CursorIcon::Default),+ egui::CursorIcon::Grab => Some(winit::window::CursorIcon::Grab),+ egui::CursorIcon::Grabbing => Some(winit::window::CursorIcon::Grabbing),+ egui::CursorIcon::Help => Some(winit::window::CursorIcon::Help),+ egui::CursorIcon::Move => Some(winit::window::CursorIcon::Move),+ egui::CursorIcon::NoDrop => Some(winit::window::CursorIcon::NoDrop),+ egui::CursorIcon::NotAllowed => Some(winit::window::CursorIcon::NotAllowed),+ egui::CursorIcon::PointingHand => Some(winit::window::CursorIcon::Pointer),+ egui::CursorIcon::Progress => Some(winit::window::CursorIcon::Progress),++ egui::CursorIcon::ResizeHorizontal => Some(winit::window::CursorIcon::EwResize),+ egui::CursorIcon::ResizeNeSw => Some(winit::window::CursorIcon::NeswResize),+ egui::CursorIcon::ResizeNwSe => Some(winit::window::CursorIcon::NwseResize),+ egui::CursorIcon::ResizeVertical => Some(winit::window::CursorIcon::NsResize),++ egui::CursorIcon::ResizeEast => Some(winit::window::CursorIcon::EResize),+ egui::CursorIcon::ResizeSouthEast => Some(winit::window::CursorIcon::SeResize),+ egui::CursorIcon::ResizeSouth => Some(winit::window::CursorIcon::SResize),+ egui::CursorIcon::ResizeSouthWest => Some(winit::window::CursorIcon::SwResize),+ egui::CursorIcon::ResizeWest => Some(winit::window::CursorIcon::WResize),+ egui::CursorIcon::ResizeNorthWest => Some(winit::window::CursorIcon::NwResize),+ egui::CursorIcon::ResizeNorth => Some(winit::window::CursorIcon::NResize),+ egui::CursorIcon::ResizeNorthEast => Some(winit::window::CursorIcon::NeResize),+ egui::CursorIcon::ResizeColumn => Some(winit::window::CursorIcon::ColResize),+ egui::CursorIcon::ResizeRow => Some(winit::window::CursorIcon::RowResize),++ egui::CursorIcon::Text => Some(winit::window::CursorIcon::Text),+ egui::CursorIcon::VerticalText => Some(winit::window::CursorIcon::VerticalText),+ egui::CursorIcon::Wait => Some(winit::window::CursorIcon::Wait),+ egui::CursorIcon::ZoomIn => Some(winit::window::CursorIcon::ZoomIn),+ egui::CursorIcon::ZoomOut => Some(winit::window::CursorIcon::ZoomOut),+ }+}++// Helpers for egui Viewports+// ---------------------------------------------------------------------------+#[derive(PartialEq, Eq, Hash, Debug)]+pub enum ActionRequested {+ Screenshot,+ Cut,+ Copy,+ Paste,+}++pub fn process_viewport_commands(+ egui_ctx: &egui::Context,+ info: &mut ViewportInfo,+ commands: impl IntoIterator<Item = ViewportCommand>,+ window: &Window,+ actions_requested: &mut HashSet<ActionRequested>,+) {+ for command in commands {+ process_viewport_command(egui_ctx, window, command, info, actions_requested);+ }+}++fn process_viewport_command(+ egui_ctx: &egui::Context,+ window: &Window,+ command: ViewportCommand,+ info: &mut ViewportInfo,+ actions_requested: &mut HashSet<ActionRequested>,+) {+ crate::profile_function!();++ use winit::window::ResizeDirection;++ log::trace!("Processing ViewportCommand::{command:?}");++ let pixels_per_point = pixels_per_point(egui_ctx, window);++ match command {+ ViewportCommand::Close => {+ info.events.push(egui::ViewportEvent::Close);+ }+ ViewportCommand::CancelClose => {+ // Need to be handled elsewhere+ }+ ViewportCommand::StartDrag => {+ // If `.has_focus()` is not checked on x11 the input will be permanently taken until the app is killed!+ if window.has_focus() {+ if let Err(err) = window.drag_window() {+ log::warn!("{command:?}: {err}");+ }+ }+ }+ ViewportCommand::InnerSize(size) => {+ let width_px = pixels_per_point * size.x.max(1.0);+ let height_px = pixels_per_point * size.y.max(1.0);+ let requested_size = PhysicalSize::new(width_px, height_px);+ if let Some(_returned_inner_size) = window.request_inner_size(requested_size) {+ // On platforms where the size is entirely controlled by the user the+ // applied size will be returned immediately, resize event in such case+ // may not be generated.+ // e.g. Linux++ // On platforms where resizing is disallowed by the windowing system, the current+ // inner size is returned immediately, and the user one is ignored.+ // e.g. Android, iOS, …++ // However, comparing the results is prone to numerical errors+ // because the linux backend converts physical to logical and back again.+ // So let's just assume it worked:++ info.inner_rect = inner_rect_in_points(window, pixels_per_point);+ info.outer_rect = outer_rect_in_points(window, pixels_per_point);+ } else {+ // e.g. macOS, Windows+ // The request went to the display system,+ // and the actual size will be delivered later with the [`WindowEvent::Resized`].+ }+ }+ ViewportCommand::BeginResize(direction) => {+ if let Err(err) = window.drag_resize_window(match direction {+ egui::viewport::ResizeDirection::North => ResizeDirection::North,+ egui::viewport::ResizeDirection::South => ResizeDirection::South,+ egui::viewport::ResizeDirection::East => ResizeDirection::East,+ egui::viewport::ResizeDirection::West => ResizeDirection::West,+ egui::viewport::ResizeDirection::NorthEast => ResizeDirection::NorthEast,+ egui::viewport::ResizeDirection::SouthEast => ResizeDirection::SouthEast,+ egui::viewport::ResizeDirection::NorthWest => ResizeDirection::NorthWest,+ egui::viewport::ResizeDirection::SouthWest => ResizeDirection::SouthWest,+ }) {+ log::warn!("{command:?}: {err}");+ }+ }+ ViewportCommand::Title(title) => {+ window.set_title(&title);+ }+ ViewportCommand::Transparent(v) => window.set_transparent(v),+ ViewportCommand::Visible(v) => window.set_visible(v),+ ViewportCommand::OuterPosition(pos) => {+ window.set_outer_position(PhysicalPosition::new(+ pixels_per_point * pos.x,+ pixels_per_point * pos.y,+ ));+ }+ ViewportCommand::MinInnerSize(s) => {+ window.set_min_inner_size((s.is_finite() && s != Vec2::ZERO).then_some(+ PhysicalSize::new(pixels_per_point * s.x, pixels_per_point * s.y),+ ));+ }+ ViewportCommand::MaxInnerSize(s) => {+ window.set_max_inner_size((s.is_finite() && s != Vec2::INFINITY).then_some(+ PhysicalSize::new(pixels_per_point * s.x, pixels_per_point * s.y),+ ));+ }+ ViewportCommand::ResizeIncrements(s) => {+ window.set_resize_increments(+ s.map(|s| PhysicalSize::new(pixels_per_point * s.x, pixels_per_point * s.y)),+ );+ }+ ViewportCommand::Resizable(v) => window.set_resizable(v),+ ViewportCommand::EnableButtons {+ close,+ minimized,+ maximize,+ } => window.set_enabled_buttons(+ if close {+ WindowButtons::CLOSE+ } else {+ WindowButtons::empty()+ } | if minimized {+ WindowButtons::MINIMIZE+ } else {+ WindowButtons::empty()+ } | if maximize {+ WindowButtons::MAXIMIZE+ } else {+ WindowButtons::empty()+ },+ ),+ ViewportCommand::Minimized(v) => {+ window.set_minimized(v);+ info.minimized = Some(v);+ }+ ViewportCommand::Maximized(v) => {+ window.set_maximized(v);+ info.maximized = Some(v);+ }+ ViewportCommand::Fullscreen(v) => {+ window.set_fullscreen(v.then_some(winit::window::Fullscreen::Borderless(None)));+ }+ ViewportCommand::Decorations(v) => window.set_decorations(v),+ ViewportCommand::WindowLevel(l) => window.set_window_level(match l {+ egui::viewport::WindowLevel::AlwaysOnBottom => WindowLevel::AlwaysOnBottom,+ egui::viewport::WindowLevel::AlwaysOnTop => WindowLevel::AlwaysOnTop,+ egui::viewport::WindowLevel::Normal => WindowLevel::Normal,+ }),+ ViewportCommand::Icon(icon) => {+ let winit_icon = icon.and_then(|icon| to_winit_icon(&icon));+ window.set_window_icon(winit_icon);+ }+ ViewportCommand::IMERect(rect) => {+ window.set_ime_cursor_area(+ PhysicalPosition::new(pixels_per_point * rect.min.x, pixels_per_point * rect.min.y),+ PhysicalSize::new(+ pixels_per_point * rect.size().x,+ pixels_per_point * rect.size().y,+ ),+ );+ }+ ViewportCommand::IMEAllowed(v) => window.set_ime_allowed(v),+ ViewportCommand::IMEPurpose(p) => window.set_ime_purpose(match p {+ egui::viewport::IMEPurpose::Password => winit::window::ImePurpose::Password,+ egui::viewport::IMEPurpose::Terminal => winit::window::ImePurpose::Terminal,+ egui::viewport::IMEPurpose::Normal => winit::window::ImePurpose::Normal,+ }),+ ViewportCommand::Focus => {+ if !window.has_focus() {+ window.focus_window();+ }+ }+ ViewportCommand::RequestUserAttention(a) => {+ window.request_user_attention(match a {+ egui::UserAttentionType::Reset => None,+ egui::UserAttentionType::Critical => {+ Some(winit::window::UserAttentionType::Critical)+ }+ egui::UserAttentionType::Informational => {+ Some(winit::window::UserAttentionType::Informational)+ }+ });+ }+ ViewportCommand::SetTheme(t) => window.set_theme(match t {+ egui::SystemTheme::Light => Some(winit::window::Theme::Light),+ egui::SystemTheme::Dark => Some(winit::window::Theme::Dark),+ egui::SystemTheme::SystemDefault => None,+ }),+ ViewportCommand::ContentProtected(v) => window.set_content_protected(v),+ ViewportCommand::CursorPosition(pos) => {+ if let Err(err) = window.set_cursor_position(PhysicalPosition::new(+ pixels_per_point * pos.x,+ pixels_per_point * pos.y,+ )) {+ log::warn!("{command:?}: {err}");+ }+ }+ ViewportCommand::CursorGrab(o) => {+ if let Err(err) = window.set_cursor_grab(match o {+ egui::viewport::CursorGrab::None => CursorGrabMode::None,+ egui::viewport::CursorGrab::Confined => CursorGrabMode::Confined,+ egui::viewport::CursorGrab::Locked => CursorGrabMode::Locked,+ }) {+ log::warn!("{command:?}: {err}");+ }+ }+ ViewportCommand::CursorVisible(v) => window.set_cursor_visible(v),+ ViewportCommand::MousePassthrough(passthrough) => {+ if let Err(err) = window.set_cursor_hittest(!passthrough) {+ log::warn!("{command:?}: {err}");+ }+ }+ ViewportCommand::Screenshot => {+ actions_requested.insert(ActionRequested::Screenshot);+ }+ ViewportCommand::RequestCut => {+ actions_requested.insert(ActionRequested::Cut);+ }+ ViewportCommand::RequestCopy => {+ actions_requested.insert(ActionRequested::Copy);+ }+ ViewportCommand::RequestPaste => {+ actions_requested.insert(ActionRequested::Paste);+ }+ }+}++/// Build and intitlaize a window.+///+/// Wrapper around `create_winit_window_builder` and `apply_viewport_builder_to_window`.+///+/// # Errors+/// Possible causes of error include denied permission, incompatible system, and lack of memory.+pub fn create_window(+ egui_ctx: &egui::Context,+ event_loop: &ActiveEventLoop,+ viewport_builder: &ViewportBuilder,+) -> Result<Window, winit::error::OsError> {+ crate::profile_function!();++ let window_attributes =+ create_winit_window_attributes(egui_ctx, event_loop, viewport_builder.clone());+ let window = event_loop.create_window(window_attributes)?;+ apply_viewport_builder_to_window(egui_ctx, &window, viewport_builder);+ Ok(window)+}++pub fn create_winit_window_attributes(+ egui_ctx: &egui::Context,+ event_loop: &ActiveEventLoop,+ viewport_builder: ViewportBuilder,+) -> winit::window::WindowAttributes {+ crate::profile_function!();++ // We set sizes and positions in egui:s own ui points, which depends on the egui+ // zoom_factor and the native pixels per point, so we need to know that here.+ // We don't know what monitor the window will appear on though, but+ // we'll try to fix that after the window is created in the call to `apply_viewport_builder_to_window`.+ let native_pixels_per_point = event_loop+ .primary_monitor()+ .or_else(|| event_loop.available_monitors().next())+ .map_or_else(+ || {+ log::debug!("Failed to find a monitor - assuming native_pixels_per_point of 1.0");+ 1.0+ },+ |m| m.scale_factor() as f32,+ );+ let zoom_factor = egui_ctx.zoom_factor();+ let pixels_per_point = zoom_factor * native_pixels_per_point;++ let ViewportBuilder {+ title,+ position,+ inner_size,+ min_inner_size,+ max_inner_size,+ fullscreen,+ maximized,+ resizable,+ transparent,+ decorations,+ icon,+ active,+ visible,+ close_button,+ minimize_button,+ maximize_button,+ window_level,++ // macOS:+ fullsize_content_view: _fullsize_content_view,+ title_shown: _title_shown,+ titlebar_buttons_shown: _titlebar_buttons_shown,+ titlebar_shown: _titlebar_shown,++ // Windows:+ drag_and_drop: _drag_and_drop,+ taskbar: _taskbar,++ // wayland:+ app_id: _app_id,++ // x11+ window_type: _window_type,++ mouse_passthrough: _, // handled in `apply_viewport_builder_to_window`+ clamp_size_to_monitor_size: _, // Handled in `viewport_builder` in `epi_integration.rs`+ } = viewport_builder;++ let mut window_attributes = winit::window::WindowAttributes::default()+ .with_title(title.unwrap_or_else(|| "egui window".to_owned()))+ .with_transparent(transparent.unwrap_or(false))+ .with_decorations(decorations.unwrap_or(true))+ .with_resizable(resizable.unwrap_or(true))+ .with_visible(visible.unwrap_or(true))+ .with_maximized(if cfg!(target_os = "ios") {+ true+ } else {+ maximized.unwrap_or(false)+ })+ .with_window_level(match window_level.unwrap_or_default() {+ egui::viewport::WindowLevel::AlwaysOnBottom => WindowLevel::AlwaysOnBottom,+ egui::viewport::WindowLevel::AlwaysOnTop => WindowLevel::AlwaysOnTop,+ egui::viewport::WindowLevel::Normal => WindowLevel::Normal,+ })+ .with_fullscreen(+ fullscreen.and_then(|e| e.then_some(winit::window::Fullscreen::Borderless(None))),+ )+ .with_enabled_buttons({+ let mut buttons = WindowButtons::empty();+ if minimize_button.unwrap_or(true) {+ buttons |= WindowButtons::MINIMIZE;+ }+ if maximize_button.unwrap_or(true) {+ buttons |= WindowButtons::MAXIMIZE;+ }+ if close_button.unwrap_or(true) {+ buttons |= WindowButtons::CLOSE;+ }+ buttons+ })+ .with_active(active.unwrap_or(true));++ #[cfg(not(target_os = "ios"))]+ if let Some(size) = inner_size {+ window_attributes = window_attributes.with_inner_size(PhysicalSize::new(+ pixels_per_point * size.x,+ pixels_per_point * size.y,+ ));+ }++ #[cfg(not(target_os = "ios"))]+ if let Some(size) = min_inner_size {+ window_attributes = window_attributes.with_min_inner_size(PhysicalSize::new(+ pixels_per_point * size.x,+ pixels_per_point * size.y,+ ));+ }++ #[cfg(not(target_os = "ios"))]+ if let Some(size) = max_inner_size {+ window_attributes = window_attributes.with_max_inner_size(PhysicalSize::new(+ pixels_per_point * size.x,+ pixels_per_point * size.y,+ ));+ }++ #[cfg(not(target_os = "ios"))]+ if let Some(pos) = position {+ window_attributes = window_attributes.with_position(PhysicalPosition::new(+ pixels_per_point * pos.x,+ pixels_per_point * pos.y,+ ));+ }+ #[cfg(target_os = "ios")]+ {+ // Unused:+ _ = pixels_per_point;+ _ = position;+ _ = inner_size;+ _ = min_inner_size;+ _ = max_inner_size;+ }++ if let Some(icon) = icon {+ let winit_icon = to_winit_icon(&icon);+ window_attributes = window_attributes.with_window_icon(winit_icon);+ }++ #[cfg(all(feature = "wayland", target_os = "linux"))]+ if let Some(app_id) = _app_id {+ use winit::platform::wayland::WindowAttributesExtWayland as _;+ window_attributes = window_attributes.with_name(app_id, "");+ }++ #[cfg(all(feature = "x11", target_os = "linux"))]+ {+ if let Some(window_type) = _window_type {+ use winit::platform::x11::WindowAttributesExtX11 as _;+ use winit::platform::x11::WindowType;+ window_attributes = window_attributes.with_x11_window_type(vec![match window_type {+ egui::X11WindowType::Normal => WindowType::Normal,+ egui::X11WindowType::Utility => WindowType::Utility,+ egui::X11WindowType::Dock => WindowType::Dock,+ egui::X11WindowType::Desktop => WindowType::Desktop,+ egui::X11WindowType::Toolbar => WindowType::Toolbar,+ egui::X11WindowType::Menu => WindowType::Menu,+ egui::X11WindowType::Splash => WindowType::Splash,+ egui::X11WindowType::Dialog => WindowType::Dialog,+ egui::X11WindowType::DropdownMenu => WindowType::DropdownMenu,+ egui::X11WindowType::PopupMenu => WindowType::PopupMenu,+ egui::X11WindowType::Tooltip => WindowType::Tooltip,+ egui::X11WindowType::Notification => WindowType::Notification,+ egui::X11WindowType::Combo => WindowType::Combo,+ egui::X11WindowType::Dnd => WindowType::Dnd,+ }]);+ }+ }++ #[cfg(target_os = "windows")]+ {+ use winit::platform::windows::WindowAttributesExtWindows as _;+ if let Some(enable) = _drag_and_drop {+ window_attributes = window_attributes.with_drag_and_drop(enable);+ }+ if let Some(show) = _taskbar {+ window_attributes = window_attributes.with_skip_taskbar(!show);+ }+ }++ #[cfg(target_os = "macos")]+ {+ use winit::platform::macos::WindowAttributesExtMacOS as _;+ window_attributes = window_attributes+ .with_title_hidden(!_title_shown.unwrap_or(true))+ .with_titlebar_buttons_hidden(!_titlebar_buttons_shown.unwrap_or(true))+ .with_titlebar_transparent(!_titlebar_shown.unwrap_or(true))+ .with_fullsize_content_view(_fullsize_content_view.unwrap_or(false));+ }++ window_attributes+}++fn to_winit_icon(icon: &egui::IconData) -> Option<winit::window::Icon> {+ if icon.is_empty() {+ None+ } else {+ crate::profile_function!();+ match winit::window::Icon::from_rgba(icon.rgba.clone(), icon.width, icon.height) {+ Ok(winit_icon) => Some(winit_icon),+ Err(err) => {+ log::warn!("Invalid IconData: {err}");+ None+ }+ }+ }+}++/// Applies what `create_winit_window_builder` couldn't+pub fn apply_viewport_builder_to_window(+ egui_ctx: &egui::Context,+ window: &Window,+ builder: &ViewportBuilder,+) {+ if let Some(mouse_passthrough) = builder.mouse_passthrough {+ if let Err(err) = window.set_cursor_hittest(!mouse_passthrough) {+ log::warn!("set_cursor_hittest failed: {err}");+ }+ }++ {+ // In `create_winit_window_builder` we didn't know+ // on what monitor the window would appear, so we didn't know+ // how to translate egui ui point to native physical pixels.+ // Now we do know:++ let pixels_per_point = pixels_per_point(egui_ctx, window);++ if let Some(size) = builder.inner_size {+ if window+ .request_inner_size(PhysicalSize::new(+ pixels_per_point * size.x,+ pixels_per_point * size.y,+ ))+ .is_some()+ {+ log::debug!("Failed to set window size");+ }+ }+ if let Some(size) = builder.min_inner_size {+ window.set_min_inner_size(Some(PhysicalSize::new(+ pixels_per_point * size.x,+ pixels_per_point * size.y,+ )));+ }+ if let Some(size) = builder.max_inner_size {+ window.set_max_inner_size(Some(PhysicalSize::new(+ pixels_per_point * size.x,+ pixels_per_point * size.y,+ )));+ }+ if let Some(pos) = builder.position {+ let pos = PhysicalPosition::new(pixels_per_point * pos.x, pixels_per_point * pos.y);+ window.set_outer_position(pos);+ }+ }+}++// ---------------------------------------------------------------------------++/// Short and fast description of a device event.+/// Useful for logging and profiling.+pub fn short_device_event_description(event: &winit::event::DeviceEvent) -> &'static str {+ use winit::event::DeviceEvent;++ match event {+ DeviceEvent::Added { .. } => "DeviceEvent::Added",+ DeviceEvent::Removed { .. } => "DeviceEvent::Removed",+ DeviceEvent::MouseMotion { .. } => "DeviceEvent::MouseMotion",+ DeviceEvent::MouseWheel { .. } => "DeviceEvent::MouseWheel",+ DeviceEvent::Motion { .. } => "DeviceEvent::Motion",+ DeviceEvent::Button { .. } => "DeviceEvent::Button",+ DeviceEvent::Key { .. } => "DeviceEvent::Key",+ }+}++/// Short and fast description of a window event.+/// Useful for logging and profiling.+pub fn short_window_event_description(event: &winit::event::WindowEvent) -> &'static str {+ use winit::event::WindowEvent;++ match event {+ WindowEvent::ActivationTokenDone { .. } => "WindowEvent::ActivationTokenDone",+ WindowEvent::Resized { .. } => "WindowEvent::Resized",+ WindowEvent::Moved { .. } => "WindowEvent::Moved",+ WindowEvent::CloseRequested { .. } => "WindowEvent::CloseRequested",+ WindowEvent::Destroyed { .. } => "WindowEvent::Destroyed",+ WindowEvent::DroppedFile { .. } => "WindowEvent::DroppedFile",+ WindowEvent::HoveredFile { .. } => "WindowEvent::HoveredFile",+ WindowEvent::HoveredFileCancelled { .. } => "WindowEvent::HoveredFileCancelled",+ WindowEvent::Focused { .. } => "WindowEvent::Focused",+ WindowEvent::KeyboardInput { .. } => "WindowEvent::KeyboardInput",+ WindowEvent::ModifiersChanged { .. } => "WindowEvent::ModifiersChanged",+ WindowEvent::Ime { .. } => "WindowEvent::Ime",+ WindowEvent::CursorMoved { .. } => "WindowEvent::CursorMoved",+ WindowEvent::CursorEntered { .. } => "WindowEvent::CursorEntered",+ WindowEvent::CursorLeft { .. } => "WindowEvent::CursorLeft",+ WindowEvent::MouseWheel { .. } => "WindowEvent::MouseWheel",+ WindowEvent::MouseInput { .. } => "WindowEvent::MouseInput",+ WindowEvent::PinchGesture { .. } => "WindowEvent::PinchGesture",+ WindowEvent::RedrawRequested { .. } => "WindowEvent::RedrawRequested",+ WindowEvent::DoubleTapGesture { .. } => "WindowEvent::DoubleTapGesture",+ WindowEvent::RotationGesture { .. } => "WindowEvent::RotationGesture",+ WindowEvent::TouchpadPressure { .. } => "WindowEvent::TouchpadPressure",+ WindowEvent::AxisMotion { .. } => "WindowEvent::AxisMotion",+ WindowEvent::Touch { .. } => "WindowEvent::Touch",+ WindowEvent::ScaleFactorChanged { .. } => "WindowEvent::ScaleFactorChanged",+ WindowEvent::ThemeChanged { .. } => "WindowEvent::ThemeChanged",+ WindowEvent::Occluded { .. } => "WindowEvent::Occluded",+ WindowEvent::PanGesture { .. } => "WindowEvent::PanGesture",+ }+}++// ---------------------------------------------------------------------------++mod profiling_scopes {+ #![allow(unused_macros)]+ #![allow(unused_imports)]++ /// Profiling macro for feature "puffin"+ macro_rules! profile_function {+ ($($arg: tt)*) => {+ #[cfg(feature = "puffin")]+ #[cfg(not(target_arch = "wasm32"))] // Disabled on web because of the coarse 1ms clock resolution there.+ puffin::profile_function!($($arg)*);+ };+ }+ pub(crate) use profile_function;++ /// Profiling macro for feature "puffin"+ macro_rules! profile_scope {+ ($($arg: tt)*) => {+ #[cfg(feature = "puffin")]+ #[cfg(not(target_arch = "wasm32"))] // Disabled on web because of the coarse 1ms clock resolution there.+ puffin::profile_scope!($($arg)*);+ };+ }+ pub(crate) use profile_scope;+}diff --git a/crates/vendor/egui-winit/src/window_settings.rs b/crates/vendor/egui-winit/src/window_settings.rsnew file mode 100644index 0000000..627d881--- /dev/null+++ b/crates/vendor/egui-winit/src/window_settings.rs@@ -0,0 +1,213 @@+use egui::ViewportBuilder;++/// Can be used to store native window settings (position and size).+#[derive(Clone, Copy, Debug, Default)]+#[cfg_attr(feature = "serde", derive(serde::Deserialize, serde::Serialize))]+#[cfg_attr(feature = "serde", serde(default))]+pub struct WindowSettings {+ /// Position of window content in physical pixels.+ inner_position_pixels: Option<egui::Pos2>,++ /// Position of window frame/titlebar in physical pixels.+ outer_position_pixels: Option<egui::Pos2>,++ fullscreen: bool,++ /// Inner size of window in logical pixels+ inner_size_points: Option<egui::Vec2>,+}++impl WindowSettings {+ pub fn from_window(egui_zoom_factor: f32, window: &winit::window::Window) -> Self {+ let inner_size_points = window+ .inner_size()+ .to_logical::<f32>(egui_zoom_factor as f64 * window.scale_factor());++ let inner_position_pixels = window+ .inner_position()+ .ok()+ .map(|p| egui::pos2(p.x as f32, p.y as f32));++ let outer_position_pixels = window+ .outer_position()+ .ok()+ .map(|p| egui::pos2(p.x as f32, p.y as f32));++ Self {+ inner_position_pixels,+ outer_position_pixels,++ fullscreen: window.fullscreen().is_some(),++ inner_size_points: Some(egui::vec2(+ inner_size_points.width,+ inner_size_points.height,+ )),+ }+ }++ pub fn inner_size_points(&self) -> Option<egui::Vec2> {+ self.inner_size_points+ }++ pub fn initialize_viewport_builder(+ &self,+ egui_zoom_factor: f32,+ event_loop: &winit::event_loop::ActiveEventLoop,+ mut viewport_builder: ViewportBuilder,+ ) -> ViewportBuilder {+ crate::profile_function!();++ // `WindowBuilder::with_position` expects inner position in Macos, and outer position elsewhere+ // See [`winit::window::WindowBuilder::with_position`] for details.+ let pos_px = if cfg!(target_os = "macos") {+ self.inner_position_pixels+ } else {+ self.outer_position_pixels+ };+ if let Some(pos) = pos_px {+ let monitor_scale_factor = if let Some(inner_size_points) = self.inner_size_points {+ find_active_monitor(egui_zoom_factor, event_loop, inner_size_points, &pos)+ .map_or(1.0, |monitor| monitor.scale_factor() as f32)+ } else {+ 1.0+ };++ let scaled_pos = pos / (egui_zoom_factor * monitor_scale_factor);+ viewport_builder = viewport_builder.with_position(scaled_pos);+ }++ if let Some(inner_size_points) = self.inner_size_points {+ viewport_builder = viewport_builder+ .with_inner_size(inner_size_points)+ .with_fullscreen(self.fullscreen);+ }++ viewport_builder+ }++ pub fn initialize_window(&self, window: &winit::window::Window) {+ if cfg!(target_os = "macos") {+ // Mac sometimes has problems restoring the window to secondary monitors+ // using only `WindowBuilder::with_position`, so we need this extra step:+ if let Some(pos) = self.outer_position_pixels {+ window.set_outer_position(winit::dpi::PhysicalPosition { x: pos.x, y: pos.y });+ }+ }+ }++ pub fn clamp_size_to_sane_values(&mut self, largest_monitor_size_points: egui::Vec2) {+ use egui::NumExt as _;++ if let Some(size) = &mut self.inner_size_points {+ // Prevent ridiculously small windows:+ let min_size = egui::Vec2::splat(64.0);+ *size = size.at_least(min_size);++ // Make sure we don't try to create a window larger than the largest monitor+ // because on Linux that can lead to a crash.+ *size = size.at_most(largest_monitor_size_points);+ }+ }++ pub fn clamp_position_to_monitors(+ &mut self,+ egui_zoom_factor: f32,+ event_loop: &winit::event_loop::ActiveEventLoop,+ ) {+ // If the app last ran on two monitors and only one is now connected, then+ // the given position is invalid.+ // If this happens on Mac, the window is clamped into valid area.+ // If this happens on Windows, the window becomes invisible to the user 🤦♂️+ // So on Windows we clamp the position to the monitor it is on.+ if !cfg!(target_os = "windows") {+ return;+ }++ let Some(inner_size_points) = self.inner_size_points else {+ return;+ };++ if let Some(pos_px) = &mut self.inner_position_pixels {+ clamp_pos_to_monitors(egui_zoom_factor, event_loop, inner_size_points, pos_px);+ }+ if let Some(pos_px) = &mut self.outer_position_pixels {+ clamp_pos_to_monitors(egui_zoom_factor, event_loop, inner_size_points, pos_px);+ }+ }+}++fn find_active_monitor(+ egui_zoom_factor: f32,+ event_loop: &winit::event_loop::ActiveEventLoop,+ window_size_pts: egui::Vec2,+ position_px: &egui::Pos2,+) -> Option<winit::monitor::MonitorHandle> {+ crate::profile_function!();++ let monitors = event_loop.available_monitors();++ // default to primary monitor, in case the correct monitor was disconnected.+ let Some(mut active_monitor) = event_loop+ .primary_monitor()+ .or_else(|| event_loop.available_monitors().next())+ else {+ return None; // no monitors 🤷+ };++ for monitor in monitors {+ let window_size_px = window_size_pts * (egui_zoom_factor * monitor.scale_factor() as f32);+ let monitor_x_range = (monitor.position().x - window_size_px.x as i32)+ ..(monitor.position().x + monitor.size().width as i32);+ let monitor_y_range = (monitor.position().y - window_size_px.y as i32)+ ..(monitor.position().y + monitor.size().height as i32);++ if monitor_x_range.contains(&(position_px.x as i32))+ && monitor_y_range.contains(&(position_px.y as i32))+ {+ active_monitor = monitor;+ }+ }++ Some(active_monitor)+}++fn clamp_pos_to_monitors(+ egui_zoom_factor: f32,+ event_loop: &winit::event_loop::ActiveEventLoop,+ window_size_pts: egui::Vec2,+ position_px: &mut egui::Pos2,+) {+ crate::profile_function!();++ let Some(active_monitor) =+ find_active_monitor(egui_zoom_factor, event_loop, window_size_pts, position_px)+ else {+ return; // no monitors 🤷+ };++ let mut window_size_px =+ window_size_pts * (egui_zoom_factor * active_monitor.scale_factor() as f32);+ // Add size of title bar. This is 32 px by default in Win 10/11.+ if cfg!(target_os = "windows") {+ window_size_px += egui::Vec2::new(+ 0.0,+ 32.0 * egui_zoom_factor * active_monitor.scale_factor() as f32,+ );+ }+ let monitor_position = egui::Pos2::new(+ active_monitor.position().x as f32,+ active_monitor.position().y as f32,+ );+ let monitor_size_px = egui::Vec2::new(+ active_monitor.size().width as f32,+ active_monitor.size().height as f32,+ );++ // Window size cannot be negative or the subsequent `clamp` will panic.+ let window_size = (monitor_size_px - window_size_px).max(egui::Vec2::ZERO);+ // To get the maximum position, we get the rightmost corner of the display, then+ // subtract the size of the window to get the bottom right most value window.position+ // can have.+ *position_px = position_px.clamp(monitor_position, monitor_position + window_size);+}