diff --git a/Cargo.lock b/Cargo.lock
index e26e401..81dbf40 100644
--- a/Cargo.lock
+++ b/Cargo.lock
@@ -2009,12 +2009,10 @@ dependencies = [
[[package]]
name = "iced_glyphon"
version = "0.6.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "41c3bb56f1820ca252bc1d0994ece33d233a55657c0c263ea7cb16895adbde82"
dependencies = [
"cosmic-text",
"etagere",
- "lru 0.12.5",
+ "lru",
"rustc-hash 2.1.1",
"wgpu",
]
@@ -2413,12 +2411,6 @@ version = "0.4.27"
source = "registry+https://github.com/rust-lang/crates.io-index"
checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
-[[package]]
-name = "lru"
-version = "0.12.5"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "234cf4f4a04dc1f57e24b96cc0cd600cf2af460d4161ac5ecdd0af8e1f3b2a38"
-
[[package]]
name = "lru"
version = "0.16.3"
@@ -3565,7 +3557,7 @@ dependencies = [
"indoc",
"itertools 0.14.0",
"kasuari",
- "lru 0.16.3",
+ "lru",
"strum",
"thiserror 2.0.17",
"unicode-segmentation",
diff --git a/Cargo.toml b/Cargo.toml
index b6388ba..96c2136 100644
--- a/Cargo.toml
+++ b/Cargo.toml
@@ -107,4 +107,10 @@ strip = true
[profile.bench]
opt-level = 3
-debug = false
\ No newline at end of file
+debug = false
+
+# Security fix for RUSTSEC-2026-0002: IterMut violates Stacked Borrows
+# Patch vulnerable lru 0.12.5 by replacing iced_glyphon with patched version
+# The patched version updates lru from 0.12.1 to 0.16.3 which includes the security fix
+[patch.crates-io]
+iced_glyphon = { path = "vendor/iced_glyphon" }
\ No newline at end of file
diff --git a/SECURITY-FIX-RUSTSEC-2026-0002.md b/SECURITY-FIX-RUSTSEC-2026-0002.md
new file mode 100644
index 0000000..2536d4b
--- /dev/null
+++ b/SECURITY-FIX-RUSTSEC-2026-0002.md
@@ -0,0 +1,85 @@
+# Security Fix: RUSTSEC-2026-0002
+
+## Summary
+
+Fixed a soundness vulnerability in the `lru` crate (version 0.12.5) used as a transitive dependency through `iced_glyphon`.
+
+## Vulnerability Details
+
+- **Advisory**: RUSTSEC-2026-0002
+- **Package**: `lru`
+- **Affected Versions**: 0.9.0 to 0.16.2 (inclusive)
+- **Patched Version**: 0.16.3+
+- **Severity**: Unsound (memory safety issue)
+- **Issue**: `IterMut` violates Stacked Borrows by invalidating internal pointer
+
+### Technical Description
+
+The `IterMut` iterator implementation in the vulnerable lru versions temporarily creates an exclusive reference (`&mut`) to the key when dereferencing the internal node pointer. This invalidates the shared pointer (`&`) held by the internal `HashMap`, violating Rust's Stacked Borrows rules and potentially causing undefined behavior.
+
+## Dependency Chain
+
+```
+rustirc v0.3.8
+└── rustirc-gui v0.3.8
+ └── iced v0.13.1
+ └── iced_wgpu v0.13.5
+ └── iced_glyphon v0.6.0
+ └── lru v0.12.5 ← VULNERABLE
+```
+
+## Solution Implemented
+
+Since `iced_glyphon` v0.6.0 depends on `lru ^0.12.1` and there's no newer version of `iced_glyphon` available that uses the patched lru, we implemented a vendor patch:
+
+1. **Downloaded** `iced_glyphon` v0.6.0 source code
+2. **Modified** `Cargo.toml` to update lru dependency from `0.12.1` to `0.16.3`
+3. **Vendored** the patched version in `vendor/iced_glyphon/`
+4. **Applied** Cargo patch in workspace `Cargo.toml`:
+ ```toml
+ [patch.crates-io]
+ iced_glyphon = { path = "vendor/iced_glyphon" }
+ ```
+
+## Verification
+
+Before fix:
+```
+lru v0.12.5 ← Vulnerable
+└── iced_glyphon v0.6.0
+```
+
+After fix:
+```
+lru v0.16.3 ← Patched
+└── iced_glyphon v0.6.0 (vendored)
+```
+
+## Testing
+
+- ✅ Clean build successful
+- ✅ All tests passing
+- ✅ Clippy clean (no warnings)
+- ✅ No vulnerable lru versions in dependency tree
+
+## Future Maintenance
+
+This vendor patch can be removed when:
+- `iced_glyphon` releases a version with lru 0.16.3+
+- Upgrading to iced 0.14+ (which may use different text rendering)
+- Switching to `cryoglyph` (iced-rs fork with updated dependencies)
+
+## References
+
+- RustSec Advisory: https://rustsec.org/advisories/RUSTSEC-2026-0002
+- GitHub Advisory: https://github.com/advisories/GHSA-rhfx-m35p-ff5j
+- lru-rs Fix PR: https://github.com/jeromefroe/lru-rs/pull/224
+- Affected Package: https://crates.io/crates/lru/0.12.5
+- Patched Package: https://crates.io/crates/lru/0.16.3
+
+## Files Modified
+
+- `Cargo.toml`: Added `[patch.crates-io]` section
+- `Cargo.lock`: Updated lru dependency to 0.16.3
+- `vendor/`: Added patched iced_glyphon source
+- `vendor/README.md`: Documentation for vendored dependencies
diff --git a/vendor/README.md b/vendor/README.md
new file mode 100644
index 0000000..7c7da40
--- /dev/null
+++ b/vendor/README.md
@@ -0,0 +1,22 @@
+# Vendored Dependencies
+
+This directory contains vendored copies of dependencies that have been patched for security or compatibility reasons.
+
+## iced_glyphon
+
+**Reason**: Security patch for RUSTSEC-2026-0002
+**Original version**: 0.6.0
+**Issue**: The original iced_glyphon 0.6.0 depends on lru 0.12.5, which contains a soundness bug where `IterMut` violates Stacked Borrows by invalidating internal pointers.
+
+**Changes made**:
+- Updated `lru` dependency from 0.12.1 to 0.16.3 in Cargo.toml
+
+**Affected versions**: lru 0.9.0 - 0.16.2
+**Fixed version**: lru 0.16.3+
+
+**Upstream tracking**:
+- RustSec Advisory: https://rustsec.org/advisories/RUSTSEC-2026-0002
+- lru-rs PR #224: https://github.com/jeromefroe/lru-rs/pull/224
+- iced_glyphon issue: https://github.com/hecrj/glyphon (no newer version available yet)
+
+**Future**: This patch can be removed once iced_glyphon releases a version that depends on lru 0.16.3 or higher, or when upgrading to iced 0.14+ which may use a different text rendering backend.
diff --git a/vendor/iced_glyphon/.cargo_vcs_info.json b/vendor/iced_glyphon/.cargo_vcs_info.json
new file mode 100644
index 0000000..56451a4
--- /dev/null
+++ b/vendor/iced_glyphon/.cargo_vcs_info.json
@@ -0,0 +1,6 @@
+{
+ "git": {
+ "sha1": "647575039c86faf21518c3064f9dde2dacf16db7"
+ },
+ "path_in_vcs": ""
+}
\ No newline at end of file
diff --git a/vendor/iced_glyphon/.github/FUNDING.yml b/vendor/iced_glyphon/.github/FUNDING.yml
new file mode 100644
index 0000000..d55a828
--- /dev/null
+++ b/vendor/iced_glyphon/.github/FUNDING.yml
@@ -0,0 +1 @@
+github: [grovesNL]
diff --git a/vendor/iced_glyphon/.github/workflows/ci.yml b/vendor/iced_glyphon/.github/workflows/ci.yml
new file mode 100644
index 0000000..7e39b36
--- /dev/null
+++ b/vendor/iced_glyphon/.github/workflows/ci.yml
@@ -0,0 +1,21 @@
+name: CI
+
+on:
+ push:
+ branches: [main]
+ pull_request:
+ branches: [main]
+
+env:
+ CARGO_TERM_COLOR: always
+
+jobs:
+ build:
+ runs-on: ubuntu-latest
+
+ steps:
+ - uses: actions/checkout@v3
+ - name: Build
+ run: cargo build --verbose
+ - name: Run tests
+ run: cargo test --verbose
diff --git a/vendor/iced_glyphon/.gitignore b/vendor/iced_glyphon/.gitignore
new file mode 100644
index 0000000..004ae20
--- /dev/null
+++ b/vendor/iced_glyphon/.gitignore
@@ -0,0 +1,3 @@
+/target
+.vscode
+Cargo.lock
diff --git a/vendor/iced_glyphon/Cargo.toml b/vendor/iced_glyphon/Cargo.toml
new file mode 100644
index 0000000..f4d31c0
--- /dev/null
+++ b/vendor/iced_glyphon/Cargo.toml
@@ -0,0 +1,62 @@
+# 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"
+name = "iced_glyphon"
+version = "0.6.0"
+build = false
+autobins = false
+autoexamples = false
+autotests = false
+autobenches = false
+description = "Fast, simple 2D text rendering for wgpu"
+homepage = "https://github.com/hecrj/glyphon.git"
+readme = "README.md"
+license = "MIT OR Apache-2.0 OR Zlib"
+repository = "https://github.com/hecrj/glyphon"
+
+[lib]
+name = "iced_glyphon"
+path = "src/lib.rs"
+
+[[example]]
+name = "hello-world"
+path = "examples/hello-world.rs"
+
+[dependencies.cosmic-text]
+version = "0.12"
+
+[dependencies.etagere]
+version = "0.2.10"
+
+[dependencies.lru]
+version = "0.16.3"
+default-features = false
+
+[dependencies.rustc-hash]
+version = "2.0"
+
+[dependencies.wgpu]
+version = "0.19"
+features = ["wgsl"]
+default-features = false
+
+[dev-dependencies.pollster]
+version = "0.3.0"
+
+[dev-dependencies.wgpu]
+version = "0.19"
+default-features = true
+
+[dev-dependencies.winit]
+version = "0.29.10"
+features = ["rwh_05"]
diff --git a/vendor/iced_glyphon/LICENSE-APACHE b/vendor/iced_glyphon/LICENSE-APACHE
new file mode 100644
index 0000000..16fe87b
--- /dev/null
+++ b/vendor/iced_glyphon/LICENSE-APACHE
@@ -0,0 +1,201 @@
+ 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/vendor/iced_glyphon/LICENSE-MIT b/vendor/iced_glyphon/LICENSE-MIT
new file mode 100644
index 0000000..31aa793
--- /dev/null
+++ b/vendor/iced_glyphon/LICENSE-MIT
@@ -0,0 +1,23 @@
+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/vendor/iced_glyphon/LICENSE-ZLIB b/vendor/iced_glyphon/LICENSE-ZLIB
new file mode 100644
index 0000000..480c61e
--- /dev/null
+++ b/vendor/iced_glyphon/LICENSE-ZLIB
@@ -0,0 +1,15 @@
+This software is provided 'as-is', without any express or implied
+warranty. In no event will the authors be held liable for any damages
+arising from the use of this software.
+
+Permission is granted to anyone to use this software for any purpose,
+including commercial applications, and to alter it and redistribute it
+freely, subject to the following restrictions:
+
+1. The origin of this software must not be misrepresented; you must not
+ claim that you wrote the original software. If you use this software
+ in a product, an acknowledgment in the product documentation would be
+ appreciated but is not required.
+2. Altered source versions must be plainly marked as such, and must not be
+ misrepresented as being the original software.
+3. This notice may not be removed or altered from any source distribution.
diff --git a/vendor/iced_glyphon/README.md b/vendor/iced_glyphon/README.md
new file mode 100644
index 0000000..d0e2bf3
--- /dev/null
+++ b/vendor/iced_glyphon/README.md
@@ -0,0 +1,29 @@
+
+ 🧊🦅 iced_glyphon 🦁🧊
+
+
+ Fast, simple 2D text rendering for
wgpu
+
+
+
+
+## What is this?
+
+This is a temporary fork of [`glyphon`] used by [`iced`] until [this `wgpu` issue] is fixed.
+
+[`glyphon`]: https://github.com/grovesNL/glyphon
+[`iced`]: https://github.com/iced-rs/iced
+[this `wgpu` issue]: https://github.com/gfx-rs/wgpu/issues/5756
+
+## License
+
+This project is licensed under either [Apache License, Version 2.0](LICENSE-APACHE), [zlib License](LICENSE-ZLIB), or [MIT License](LICENSE-MIT), at your option.
+
+## Contribution
+
+Unless you explicitly state otherwise, any contribution intentionally submitted for inclusion in this project by you, as defined in the Apache 2.0 license, shall be triple licensed as above, without any additional terms or conditions.
diff --git a/vendor/iced_glyphon/examples/Inter-Bold.ttf b/vendor/iced_glyphon/examples/Inter-Bold.ttf
new file mode 100644
index 0000000..76a215c
Binary files /dev/null and b/vendor/iced_glyphon/examples/Inter-Bold.ttf differ
diff --git a/vendor/iced_glyphon/examples/hello-world.rs b/vendor/iced_glyphon/examples/hello-world.rs
new file mode 100644
index 0000000..c977c6e
--- /dev/null
+++ b/vendor/iced_glyphon/examples/hello-world.rs
@@ -0,0 +1,176 @@
+use glyphon::{
+ Attrs, Buffer, Cache, Color, Family, FontSystem, Metrics, Resolution, Shaping, SwashCache,
+ TextArea, TextAtlas, TextBounds, TextRenderer, Viewport,
+};
+use wgpu::{
+ CommandEncoderDescriptor, CompositeAlphaMode, DeviceDescriptor, Features, Instance,
+ InstanceDescriptor, Limits, LoadOp, MultisampleState, Operations, PresentMode,
+ RenderPassColorAttachment, RenderPassDescriptor, RequestAdapterOptions, SurfaceConfiguration,
+ TextureFormat, TextureUsages, TextureViewDescriptor,
+};
+use winit::{
+ dpi::LogicalSize,
+ event::{Event, WindowEvent},
+ event_loop::EventLoop,
+ window::WindowBuilder,
+};
+
+use std::sync::Arc;
+
+fn main() {
+ pollster::block_on(run());
+}
+
+async fn run() {
+ // Set up window
+ let (width, height) = (800, 600);
+ let event_loop = EventLoop::new().unwrap();
+ let window = Arc::new(
+ WindowBuilder::new()
+ .with_inner_size(LogicalSize::new(width as f64, height as f64))
+ .with_title("glyphon hello world")
+ .build(&event_loop)
+ .unwrap(),
+ );
+ let size = window.inner_size();
+ let scale_factor = window.scale_factor();
+
+ // Set up surface
+ let instance = Instance::new(InstanceDescriptor::default());
+ let adapter = instance
+ .request_adapter(&RequestAdapterOptions::default())
+ .await
+ .unwrap();
+ let (device, queue) = adapter
+ .request_device(
+ &DeviceDescriptor {
+ label: None,
+ required_features: Features::empty(),
+ required_limits: Limits::downlevel_defaults(),
+ },
+ None,
+ )
+ .await
+ .unwrap();
+
+ let surface = instance
+ .create_surface(window.clone())
+ .expect("Create surface");
+ let swapchain_format = TextureFormat::Bgra8UnormSrgb;
+ let mut config = SurfaceConfiguration {
+ usage: TextureUsages::RENDER_ATTACHMENT,
+ format: swapchain_format,
+ width: size.width,
+ height: size.height,
+ present_mode: PresentMode::Fifo,
+ alpha_mode: CompositeAlphaMode::Opaque,
+ view_formats: vec![],
+ desired_maximum_frame_latency: 2,
+ };
+ surface.configure(&device, &config);
+
+ // Set up text renderer
+ let mut font_system = FontSystem::new();
+ let mut swash_cache = SwashCache::new();
+ let cache = Cache::new(&device);
+ let mut viewport = Viewport::new(&device, &cache);
+ let mut atlas = TextAtlas::new(&device, &queue, &cache, swapchain_format);
+ let mut text_renderer =
+ TextRenderer::new(&mut atlas, &device, MultisampleState::default(), None);
+ let mut buffer = Buffer::new(&mut font_system, Metrics::new(30.0, 42.0));
+
+ let physical_width = (width as f64 * scale_factor) as f32;
+ let physical_height = (height as f64 * scale_factor) as f32;
+
+ buffer.set_size(
+ &mut font_system,
+ Some(physical_width),
+ Some(physical_height),
+ );
+ buffer.set_text(&mut font_system, "Hello world! 👋\nThis is rendered with 🦅 glyphon 🦁\nThe text below should be partially clipped.\na b c d e f g h i j k l m n o p q r s t u v w x y z", Attrs::new().family(Family::SansSerif), Shaping::Advanced);
+ buffer.shape_until_scroll(&mut font_system, false);
+
+ event_loop
+ .run(move |event, target| {
+ if let Event::WindowEvent {
+ window_id: _,
+ event,
+ } = event
+ {
+ match event {
+ WindowEvent::Resized(size) => {
+ config.width = size.width;
+ config.height = size.height;
+ surface.configure(&device, &config);
+ window.request_redraw();
+ }
+ WindowEvent::RedrawRequested => {
+ let mut encoder = device
+ .create_command_encoder(&CommandEncoderDescriptor { label: None });
+
+ viewport.update(
+ &queue,
+ Resolution {
+ width: config.width,
+ height: config.height,
+ },
+ );
+
+ text_renderer
+ .prepare(
+ &device,
+ &queue,
+ &mut encoder,
+ &mut font_system,
+ &mut atlas,
+ &viewport,
+ [TextArea {
+ buffer: &buffer,
+ left: 10.0,
+ top: 10.0,
+ scale: 1.0,
+ bounds: TextBounds {
+ left: 0,
+ top: 0,
+ right: 600,
+ bottom: 160,
+ },
+ default_color: Color::rgb(255, 255, 255),
+ }],
+ &mut swash_cache,
+ )
+ .unwrap();
+
+ let frame = surface.get_current_texture().unwrap();
+ let view = frame.texture.create_view(&TextureViewDescriptor::default());
+ {
+ let mut pass = encoder.begin_render_pass(&RenderPassDescriptor {
+ label: None,
+ color_attachments: &[Some(RenderPassColorAttachment {
+ view: &view,
+ resolve_target: None,
+ ops: Operations {
+ load: LoadOp::Clear(wgpu::Color::BLACK),
+ store: wgpu::StoreOp::Store,
+ },
+ })],
+ depth_stencil_attachment: None,
+ timestamp_writes: None,
+ occlusion_query_set: None,
+ });
+
+ text_renderer.render(&atlas, &viewport, &mut pass).unwrap();
+ }
+
+ queue.submit(Some(encoder.finish()));
+ frame.present();
+
+ atlas.trim();
+ }
+ WindowEvent::CloseRequested => target.exit(),
+ _ => {}
+ }
+ }
+ })
+ .unwrap();
+}
diff --git a/vendor/iced_glyphon/examples/ligature.txt b/vendor/iced_glyphon/examples/ligature.txt
new file mode 100644
index 0000000..8164b4a
--- /dev/null
+++ b/vendor/iced_glyphon/examples/ligature.txt
@@ -0,0 +1,6 @@
+fi ffi 🐕🦺 fi ffi
+fi تما 🐕🦺 ffi تما
+ffi fi 🐕🦺 ffi fi
+تما تما 🐕🦺 تما
+تما ffi 🐕🦺 تما fi تما
+تما تما 🐕🦺 تما
diff --git a/vendor/iced_glyphon/examples/mono.txt b/vendor/iced_glyphon/examples/mono.txt
new file mode 100644
index 0000000..33889df
--- /dev/null
+++ b/vendor/iced_glyphon/examples/mono.txt
@@ -0,0 +1,213 @@
+https://www.cl.cam.ac.uk/~mgk25/ucs/examples/UTF-8-demo.txt
+
+UTF-8 encoded sample plain-text file
+‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾‾
+
+Markus Kuhn [ˈmaʳkʊs kuːn] — 2002-07-25 CC BY
+
+
+The ASCII compatible UTF-8 encoding used in this plain-text file
+is defined in Unicode, ISO 10646-1, and RFC 2279.
+
+
+Using Unicode/UTF-8, you can write in emails and source code things such as
+
+Mathematics and sciences:
+
+ ∮ E⋅da = Q, n → ∞, ∑ f(i) = ∏ g(i), ⎧⎡⎛┌─────┐⎞⎤⎫
+ ⎪⎢⎜│a²+b³ ⎟⎥⎪
+ ∀x∈ℝ: ⌈x⌉ = −⌊−x⌋, α ∧ ¬β = ¬(¬α ∨ β), ⎪⎢⎜│───── ⎟⎥⎪
+ ⎪⎢⎜⎷ c₈ ⎟⎥⎪
+ ℕ ⊆ ℕ₀ ⊂ ℤ ⊂ ℚ ⊂ ℝ ⊂ ℂ, ⎨⎢⎜ ⎟⎥⎬
+ ⎪⎢⎜ ∞ ⎟⎥⎪
+ ⊥ < a ≠ b ≡ c ≤ d ≪ ⊤ ⇒ (⟦A⟧ ⇔ ⟪B⟫), ⎪⎢⎜ ⎲ ⎟⎥⎪
+ ⎪⎢⎜ ⎳aⁱ-bⁱ⎟⎥⎪
+ 2H₂ + O₂ ⇌ 2H₂O, R = 4.7 kΩ, ⌀ 200 mm ⎩⎣⎝i=1 ⎠⎦⎭
+
+Linguistics and dictionaries:
+
+ ði ıntəˈnæʃənəl fəˈnɛtık əsoʊsiˈeıʃn
+ Y [ˈʏpsilɔn], Yen [jɛn], Yoga [ˈjoːgɑ]
+
+APL:
+
+ ((V⍳V)=⍳⍴V)/V←,V ⌷←⍳→⍴∆∇⊃‾⍎⍕⌈
+
+Nicer typography in plain text files:
+
+ ╔══════════════════════════════════════════╗
+ ║ ║
+ ║ • ‘single’ and “double” quotes ║
+ ║ ║
+ ║ • Curly apostrophes: “We’ve been here” ║
+ ║ ║
+ ║ • Latin-1 apostrophe and accents: '´` ║
+ ║ ║
+ ║ • ‚deutsche‘ „Anführungszeichen“ ║
+ ║ ║
+ ║ • †, ‡, ‰, •, 3–4, —, −5/+5, ™, … ║
+ ║ ║
+ ║ • ASCII safety test: 1lI|, 0OD, 8B ║
+ ║ ╭─────────╮ ║
+ ║ • the euro symbol: │ 14.95 € │ ║
+ ║ ╰─────────╯ ║
+ ╚══════════════════════════════════════════╝
+
+Combining characters:
+
+ STARGΛ̊TE SG-1, a = v̇ = r̈, a⃑ ⊥ b⃑
+
+Greek (in Polytonic):
+
+ The Greek anthem:
+
+ Σὲ γνωρίζω ἀπὸ τὴν κόψη
+ τοῦ σπαθιοῦ τὴν τρομερή,
+ σὲ γνωρίζω ἀπὸ τὴν ὄψη
+ ποὺ μὲ βία μετράει τὴ γῆ.
+
+ ᾿Απ᾿ τὰ κόκκαλα βγαλμένη
+ τῶν ῾Ελλήνων τὰ ἱερά
+ καὶ σὰν πρῶτα ἀνδρειωμένη
+ χαῖρε, ὦ χαῖρε, ᾿Ελευθεριά!
+
+ From a speech of Demosthenes in the 4th century BC:
+
+ Οὐχὶ ταὐτὰ παρίσταταί μοι γιγνώσκειν, ὦ ἄνδρες ᾿Αθηναῖοι,
+ ὅταν τ᾿ εἰς τὰ πράγματα ἀποβλέψω καὶ ὅταν πρὸς τοὺς
+ λόγους οὓς ἀκούω· τοὺς μὲν γὰρ λόγους περὶ τοῦ
+ τιμωρήσασθαι Φίλιππον ὁρῶ γιγνομένους, τὰ δὲ πράγματ᾿
+ εἰς τοῦτο προήκοντα, ὥσθ᾿ ὅπως μὴ πεισόμεθ᾿ αὐτοὶ
+ πρότερον κακῶς σκέψασθαι δέον. οὐδέν οὖν ἄλλο μοι δοκοῦσιν
+ οἱ τὰ τοιαῦτα λέγοντες ἢ τὴν ὑπόθεσιν, περὶ ἧς βουλεύεσθαι,
+ οὐχὶ τὴν οὖσαν παριστάντες ὑμῖν ἁμαρτάνειν. ἐγὼ δέ, ὅτι μέν
+ ποτ᾿ ἐξῆν τῇ πόλει καὶ τὰ αὑτῆς ἔχειν ἀσφαλῶς καὶ Φίλιππον
+ τιμωρήσασθαι, καὶ μάλ᾿ ἀκριβῶς οἶδα· ἐπ᾿ ἐμοῦ γάρ, οὐ πάλαι
+ γέγονεν ταῦτ᾿ ἀμφότερα· νῦν μέντοι πέπεισμαι τοῦθ᾿ ἱκανὸν
+ προλαβεῖν ἡμῖν εἶναι τὴν πρώτην, ὅπως τοὺς συμμάχους
+ σώσομεν. ἐὰν γὰρ τοῦτο βεβαίως ὑπάρξῃ, τότε καὶ περὶ τοῦ
+ τίνα τιμωρήσεταί τις καὶ ὃν τρόπον ἐξέσται σκοπεῖν· πρὶν δὲ
+ τὴν ἀρχὴν ὀρθῶς ὑποθέσθαι, μάταιον ἡγοῦμαι περὶ τῆς
+ τελευτῆς ὁντινοῦν ποιεῖσθαι λόγον.
+
+ Δημοσθένους, Γ´ ᾿Ολυνθιακὸς
+
+Georgian:
+
+ From a Unicode conference invitation:
+
+ გთხოვთ ახლავე გაიაროთ რეგისტრაცია Unicode-ის მეათე საერთაშორისო
+ კონფერენციაზე დასასწრებად, რომელიც გაიმართება 10-12 მარტს,
+ ქ. მაინცში, გერმანიაში. კონფერენცია შეჰკრებს ერთად მსოფლიოს
+ ექსპერტებს ისეთ დარგებში როგორიცაა ინტერნეტი და Unicode-ი,
+ ინტერნაციონალიზაცია და ლოკალიზაცია, Unicode-ის გამოყენება
+ ოპერაციულ სისტემებსა, და გამოყენებით პროგრამებში, შრიფტებში,
+ ტექსტების დამუშავებასა და მრავალენოვან კომპიუტერულ სისტემებში.
+
+Russian:
+
+ From a Unicode conference invitation:
+
+ Зарегистрируйтесь сейчас на Десятую Международную Конференцию по
+ Unicode, которая состоится 10-12 марта 1997 года в Майнце в Германии.
+ Конференция соберет широкий круг экспертов по вопросам глобального
+ Интернета и Unicode, локализации и интернационализации, воплощению и
+ применению Unicode в различных операционных системах и программных
+ приложениях, шрифтах, верстке и многоязычных компьютерных системах.
+
+Thai (UCS Level 2):
+
+ Excerpt from a poetry on The Romance of The Three Kingdoms (a Chinese
+ classic 'San Gua'):
+
+ [----------------------------|------------------------]
+ ๏ แผ่นดินฮั่นเสื่อมโทรมแสนสังเวช พระปกเกศกองบู๊กู้ขึ้นใหม่
+ สิบสองกษัตริย์ก่อนหน้าแลถัดไป สององค์ไซร้โง่เขลาเบาปัญญา
+ ทรงนับถือขันทีเป็นที่พึ่ง บ้านเมืองจึงวิปริตเป็นนักหนา
+ โฮจิ๋นเรียกทัพทั่วหัวเมืองมา หมายจะฆ่ามดชั่วตัวสำคัญ
+ เหมือนขับไสไล่เสือจากเคหา รับหมาป่าเข้ามาเลยอาสัญ
+ ฝ่ายอ้องอุ้นยุแยกให้แตกกัน ใช้สาวนั้นเป็นชนวนชื่นชวนใจ
+ พลันลิฉุยกุยกีกลับก่อเหตุ ช่างอาเพศจริงหนาฟ้าร้องไห้
+ ต้องรบราฆ่าฟันจนบรรลัย ฤๅหาใครค้ำชูกู้บรรลังก์ ฯ
+
+ (The above is a two-column text. If combining characters are handled
+ correctly, the lines of the second column should be aligned with the
+ | character above.)
+
+Ethiopian:
+
+ Proverbs in the Amharic language:
+
+ ሰማይ አይታረስ ንጉሥ አይከሰስ።
+ ብላ ካለኝ እንደአባቴ በቆመጠኝ።
+ ጌጥ ያለቤቱ ቁምጥና ነው።
+ ደሀ በሕልሙ ቅቤ ባይጠጣ ንጣት በገደለው።
+ የአፍ ወለምታ በቅቤ አይታሽም።
+ አይጥ በበላ ዳዋ ተመታ።
+ ሲተረጉሙ ይደረግሙ።
+ ቀስ በቀስ፥ ዕንቁላል በእግሩ ይሄዳል።
+ ድር ቢያብር አንበሳ ያስር።
+ ሰው እንደቤቱ እንጅ እንደ ጉረቤቱ አይተዳደርም።
+ እግዜር የከፈተውን ጉሮሮ ሳይዘጋው አይድርም።
+ የጎረቤት ሌባ፥ ቢያዩት ይስቅ ባያዩት ያጠልቅ።
+ ሥራ ከመፍታት ልጄን ላፋታት።
+ ዓባይ ማደሪያ የለው፥ ግንድ ይዞ ይዞራል።
+ የእስላም አገሩ መካ የአሞራ አገሩ ዋርካ።
+ ተንጋሎ ቢተፉ ተመልሶ ባፉ።
+ ወዳጅህ ማር ቢሆን ጨርስህ አትላሰው።
+ እግርህን በፍራሽህ ልክ ዘርጋ።
+
+Runes:
+
+ ᚻᛖ ᚳᚹᚫᚦ ᚦᚫᛏ ᚻᛖ ᛒᚢᛞᛖ ᚩᚾ ᚦᚫᛗ ᛚᚪᚾᛞᛖ ᚾᚩᚱᚦᚹᛖᚪᚱᛞᚢᛗ ᚹᛁᚦ ᚦᚪ ᚹᛖᛥᚫ
+
+ (Old English, which transcribed into Latin reads 'He cwaeth that he
+ bude thaem lande northweardum with tha Westsae.' and means 'He said
+ that he lived in the northern land near the Western Sea.')
+
+Braille:
+
+ ⡌⠁⠧⠑ ⠼⠁⠒ ⡍⠜⠇⠑⠹⠰⠎ ⡣⠕⠌
+
+ ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠙⠑⠁⠙⠒ ⠞⠕ ⠃⠑⠛⠔ ⠺⠊⠹⠲ ⡹⠻⠑ ⠊⠎ ⠝⠕ ⠙⠳⠃⠞
+ ⠱⠁⠞⠑⠧⠻ ⠁⠃⠳⠞ ⠹⠁⠞⠲ ⡹⠑ ⠗⠑⠛⠊⠌⠻ ⠕⠋ ⠙⠊⠎ ⠃⠥⠗⠊⠁⠇ ⠺⠁⠎
+ ⠎⠊⠛⠝⠫ ⠃⠹ ⠹⠑ ⠊⠇⠻⠛⠹⠍⠁⠝⠂ ⠹⠑ ⠊⠇⠻⠅⠂ ⠹⠑ ⠥⠝⠙⠻⠞⠁⠅⠻⠂
+ ⠁⠝⠙ ⠹⠑ ⠡⠊⠑⠋ ⠍⠳⠗⠝⠻⠲ ⡎⠊⠗⠕⠕⠛⠑ ⠎⠊⠛⠝⠫ ⠊⠞⠲ ⡁⠝⠙
+ ⡎⠊⠗⠕⠕⠛⠑⠰⠎ ⠝⠁⠍⠑ ⠺⠁⠎ ⠛⠕⠕⠙ ⠥⠏⠕⠝ ⠰⡡⠁⠝⠛⠑⠂ ⠋⠕⠗ ⠁⠝⠹⠹⠔⠛ ⠙⠑
+ ⠡⠕⠎⠑ ⠞⠕ ⠏⠥⠞ ⠙⠊⠎ ⠙⠁⠝⠙ ⠞⠕⠲
+
+ ⡕⠇⠙ ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲
+
+ ⡍⠔⠙⠖ ⡊ ⠙⠕⠝⠰⠞ ⠍⠑⠁⠝ ⠞⠕ ⠎⠁⠹ ⠹⠁⠞ ⡊ ⠅⠝⠪⠂ ⠕⠋ ⠍⠹
+ ⠪⠝ ⠅⠝⠪⠇⠫⠛⠑⠂ ⠱⠁⠞ ⠹⠻⠑ ⠊⠎ ⠏⠜⠞⠊⠊⠥⠇⠜⠇⠹ ⠙⠑⠁⠙ ⠁⠃⠳⠞
+ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲ ⡊ ⠍⠊⠣⠞ ⠙⠁⠧⠑ ⠃⠑⠲ ⠔⠊⠇⠔⠫⠂ ⠍⠹⠎⠑⠇⠋⠂ ⠞⠕
+ ⠗⠑⠛⠜⠙ ⠁ ⠊⠕⠋⠋⠔⠤⠝⠁⠊⠇ ⠁⠎ ⠹⠑ ⠙⠑⠁⠙⠑⠌ ⠏⠊⠑⠊⠑ ⠕⠋ ⠊⠗⠕⠝⠍⠕⠝⠛⠻⠹
+ ⠔ ⠹⠑ ⠞⠗⠁⠙⠑⠲ ⡃⠥⠞ ⠹⠑ ⠺⠊⠎⠙⠕⠍ ⠕⠋ ⠳⠗ ⠁⠝⠊⠑⠌⠕⠗⠎
+ ⠊⠎ ⠔ ⠹⠑ ⠎⠊⠍⠊⠇⠑⠆ ⠁⠝⠙ ⠍⠹ ⠥⠝⠙⠁⠇⠇⠪⠫ ⠙⠁⠝⠙⠎
+ ⠩⠁⠇⠇ ⠝⠕⠞ ⠙⠊⠌⠥⠗⠃ ⠊⠞⠂ ⠕⠗ ⠹⠑ ⡊⠳⠝⠞⠗⠹⠰⠎ ⠙⠕⠝⠑ ⠋⠕⠗⠲ ⡹⠳
+ ⠺⠊⠇⠇ ⠹⠻⠑⠋⠕⠗⠑ ⠏⠻⠍⠊⠞ ⠍⠑ ⠞⠕ ⠗⠑⠏⠑⠁⠞⠂ ⠑⠍⠏⠙⠁⠞⠊⠊⠁⠇⠇⠹⠂ ⠹⠁⠞
+ ⡍⠜⠇⠑⠹ ⠺⠁⠎ ⠁⠎ ⠙⠑⠁⠙ ⠁⠎ ⠁ ⠙⠕⠕⠗⠤⠝⠁⠊⠇⠲
+
+ (The first couple of paragraphs of "A Christmas Carol" by Dickens)
+
+Compact font selection example text:
+
+ ABCDEFGHIJKLMNOPQRSTUVWXYZ /0123456789
+ abcdefghijklmnopqrstuvwxyz £©µÀÆÖÞßéöÿ
+ –—‘“”„†•…‰™œŠŸž€ ΑΒΓΔΩαβγδω АБВГДабвгд
+ ∀∂∈ℝ∧∪≡∞ ↑↗↨↻⇣ ┐┼╔╘░►☺♀ fi�⑀₂ἠḂӥẄɐː⍎אԱა
+
+Greetings in various languages:
+
+ Hello world, Καλημέρα κόσμε, コンニチハ
+
+Box drawing alignment tests: █
+ ▉
+ ╔══╦══╗ ┌──┬──┐ ╭──┬──╮ ╭──┬──╮ ┏━━┳━━┓ ┎┒┏┑ ╷ ╻ ┏┯┓ ┌┰┐ ▊ ╱╲╱╲╳╳╳
+ ║┌─╨─┐║ │╔═╧═╗│ │╒═╪═╕│ │╓─╁─╖│ ┃┌─╂─┐┃ ┗╃╄┙ ╶┼╴╺╋╸┠┼┨ ┝╋┥ ▋ ╲╱╲╱╳╳╳
+ ║│╲ ╱│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╿ │┃ ┍╅╆┓ ╵ ╹ ┗┷┛ └┸┘ ▌ ╱╲╱╲╳╳╳
+ ╠╡ ╳ ╞╣ ├╢ ╟┤ ├┼─┼─┼┤ ├╫─╂─╫┤ ┣┿╾┼╼┿┫ ┕┛┖┚ ┌┄┄┐ ╎ ┏┅┅┓ ┋ ▍ ╲╱╲╱╳╳╳
+ ║│╱ ╲│║ │║ ║│ ││ │ ││ │║ ┃ ║│ ┃│ ╽ │┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▎
+ ║└─╥─┘║ │╚═╤═╝│ │╘═╪═╛│ │╙─╀─╜│ ┃└─╂─┘┃ ░░▒▒▓▓██ ┊ ┆ ╎ ╏ ┇ ┋ ▏
+ ╚══╩══╝ └──┴──┘ ╰──┴──╯ ╰──┴──╯ ┗━━┻━━┛ ▗▄▖▛▀▜ └╌╌┘ ╎ ┗╍╍┛ ┋ ▁▂▃▄▅▆▇█
+ ▝▀▘▙▄▟
diff --git a/vendor/iced_glyphon/src/cache.rs b/vendor/iced_glyphon/src/cache.rs
new file mode 100644
index 0000000..a73924f
--- /dev/null
+++ b/vendor/iced_glyphon/src/cache.rs
@@ -0,0 +1,248 @@
+use crate::{GlyphToRender, Params};
+
+use wgpu::{
+ BindGroup, BindGroupDescriptor, BindGroupEntry, BindGroupLayout, BindGroupLayoutEntry,
+ BindingResource, BindingType, BlendState, Buffer, BufferBindingType, ColorTargetState,
+ ColorWrites, DepthStencilState, Device, FilterMode, FragmentState, MultisampleState,
+ PipelineLayout, PipelineLayoutDescriptor, PrimitiveState, PrimitiveTopology, RenderPipeline,
+ RenderPipelineDescriptor, Sampler, SamplerBindingType, SamplerDescriptor, ShaderModule,
+ ShaderModuleDescriptor, ShaderSource, ShaderStages, TextureFormat, TextureSampleType,
+ TextureView, TextureViewDimension, VertexFormat, VertexState,
+};
+
+use std::borrow::Cow;
+use std::mem;
+use std::num::NonZeroU64;
+use std::ops::Deref;
+use std::sync::{Arc, RwLock};
+
+#[derive(Debug, Clone)]
+pub struct Cache(Arc);
+
+#[derive(Debug)]
+struct Inner {
+ sampler: Sampler,
+ shader: ShaderModule,
+ vertex_buffers: [wgpu::VertexBufferLayout<'static>; 1],
+ atlas_layout: BindGroupLayout,
+ uniforms_layout: BindGroupLayout,
+ pipeline_layout: PipelineLayout,
+ cache: RwLock<
+ Vec<(
+ TextureFormat,
+ MultisampleState,
+ Option,
+ Arc,
+ )>,
+ >,
+}
+
+impl Cache {
+ pub fn new(device: &Device) -> Self {
+ let sampler = device.create_sampler(&SamplerDescriptor {
+ label: Some("glyphon sampler"),
+ min_filter: FilterMode::Nearest,
+ mag_filter: FilterMode::Nearest,
+ mipmap_filter: FilterMode::Nearest,
+ lod_min_clamp: 0f32,
+ lod_max_clamp: 0f32,
+ ..Default::default()
+ });
+
+ let shader = device.create_shader_module(ShaderModuleDescriptor {
+ label: Some("glyphon shader"),
+ source: ShaderSource::Wgsl(Cow::Borrowed(include_str!("shader.wgsl"))),
+ });
+
+ let vertex_buffer_layout = wgpu::VertexBufferLayout {
+ array_stride: mem::size_of::() as wgpu::BufferAddress,
+ step_mode: wgpu::VertexStepMode::Instance,
+ attributes: &[
+ wgpu::VertexAttribute {
+ format: VertexFormat::Sint32x2,
+ offset: 0,
+ shader_location: 0,
+ },
+ wgpu::VertexAttribute {
+ format: VertexFormat::Uint32,
+ offset: mem::size_of::() as u64 * 2,
+ shader_location: 1,
+ },
+ wgpu::VertexAttribute {
+ format: VertexFormat::Uint32,
+ offset: mem::size_of::() as u64 * 3,
+ shader_location: 2,
+ },
+ wgpu::VertexAttribute {
+ format: VertexFormat::Uint32,
+ offset: mem::size_of::() as u64 * 4,
+ shader_location: 3,
+ },
+ wgpu::VertexAttribute {
+ format: VertexFormat::Uint32,
+ offset: mem::size_of::() as u64 * 5,
+ shader_location: 4,
+ },
+ wgpu::VertexAttribute {
+ format: VertexFormat::Float32,
+ offset: mem::size_of::() as u64 * 6,
+ shader_location: 5,
+ },
+ ],
+ };
+
+ let atlas_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ entries: &[
+ BindGroupLayoutEntry {
+ binding: 0,
+ visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
+ ty: BindingType::Texture {
+ multisampled: false,
+ view_dimension: TextureViewDimension::D2,
+ sample_type: TextureSampleType::Float { filterable: true },
+ },
+ count: None,
+ },
+ BindGroupLayoutEntry {
+ binding: 1,
+ visibility: ShaderStages::VERTEX | ShaderStages::FRAGMENT,
+ ty: BindingType::Texture {
+ multisampled: false,
+ view_dimension: TextureViewDimension::D2,
+ sample_type: TextureSampleType::Float { filterable: true },
+ },
+ count: None,
+ },
+ BindGroupLayoutEntry {
+ binding: 2,
+ visibility: ShaderStages::FRAGMENT,
+ ty: BindingType::Sampler(SamplerBindingType::Filtering),
+ count: None,
+ },
+ ],
+ label: Some("glyphon atlas bind group layout"),
+ });
+
+ let uniforms_layout = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor {
+ entries: &[BindGroupLayoutEntry {
+ binding: 0,
+ visibility: ShaderStages::VERTEX,
+ ty: BindingType::Buffer {
+ ty: BufferBindingType::Uniform,
+ has_dynamic_offset: false,
+ min_binding_size: NonZeroU64::new(mem::size_of::() as u64),
+ },
+ count: None,
+ }],
+ label: Some("glyphon uniforms bind group layout"),
+ });
+
+ let pipeline_layout = device.create_pipeline_layout(&PipelineLayoutDescriptor {
+ label: None,
+ bind_group_layouts: &[&atlas_layout, &uniforms_layout],
+ push_constant_ranges: &[],
+ });
+
+ Self(Arc::new(Inner {
+ sampler,
+ shader,
+ vertex_buffers: [vertex_buffer_layout],
+ uniforms_layout,
+ atlas_layout,
+ pipeline_layout,
+ cache: RwLock::new(Vec::new()),
+ }))
+ }
+
+ pub(crate) fn create_atlas_bind_group(
+ &self,
+ device: &Device,
+ color_atlas: &TextureView,
+ mask_atlas: &TextureView,
+ ) -> BindGroup {
+ device.create_bind_group(&BindGroupDescriptor {
+ layout: &self.0.atlas_layout,
+ entries: &[
+ BindGroupEntry {
+ binding: 0,
+ resource: BindingResource::TextureView(color_atlas),
+ },
+ BindGroupEntry {
+ binding: 1,
+ resource: BindingResource::TextureView(mask_atlas),
+ },
+ BindGroupEntry {
+ binding: 2,
+ resource: BindingResource::Sampler(&self.0.sampler),
+ },
+ ],
+ label: Some("glyphon atlas bind group"),
+ })
+ }
+
+ pub(crate) fn create_uniforms_bind_group(&self, device: &Device, buffer: &Buffer) -> BindGroup {
+ device.create_bind_group(&BindGroupDescriptor {
+ layout: &self.0.uniforms_layout,
+ entries: &[BindGroupEntry {
+ binding: 0,
+ resource: buffer.as_entire_binding(),
+ }],
+ label: Some("glyphon uniforms bind group"),
+ })
+ }
+
+ pub(crate) fn get_or_create_pipeline(
+ &self,
+ device: &Device,
+ format: TextureFormat,
+ multisample: MultisampleState,
+ depth_stencil: Option,
+ ) -> Arc {
+ let Inner {
+ cache,
+ pipeline_layout,
+ shader,
+ vertex_buffers,
+ ..
+ } = self.0.deref();
+
+ let mut cache = cache.write().expect("Write pipeline cache");
+
+ cache
+ .iter()
+ .find(|(fmt, ms, ds, _)| fmt == &format && ms == &multisample && ds == &depth_stencil)
+ .map(|(_, _, _, p)| Arc::clone(p))
+ .unwrap_or_else(|| {
+ let pipeline = Arc::new(device.create_render_pipeline(&RenderPipelineDescriptor {
+ label: Some("glyphon pipeline"),
+ layout: Some(pipeline_layout),
+ vertex: VertexState {
+ module: shader,
+ entry_point: "vs_main",
+ buffers: vertex_buffers,
+ },
+ fragment: Some(FragmentState {
+ module: shader,
+ entry_point: "fs_main",
+ targets: &[Some(ColorTargetState {
+ format,
+ blend: Some(BlendState::ALPHA_BLENDING),
+ write_mask: ColorWrites::default(),
+ })],
+ }),
+ primitive: PrimitiveState {
+ topology: PrimitiveTopology::TriangleStrip,
+ ..PrimitiveState::default()
+ },
+ depth_stencil: depth_stencil.clone(),
+ multisample,
+ multiview: None,
+ }));
+
+ cache.push((format, multisample, depth_stencil, pipeline.clone()));
+
+ pipeline
+ })
+ .clone()
+ }
+}
diff --git a/vendor/iced_glyphon/src/error.rs b/vendor/iced_glyphon/src/error.rs
new file mode 100644
index 0000000..5bc30a6
--- /dev/null
+++ b/vendor/iced_glyphon/src/error.rs
@@ -0,0 +1,44 @@
+use std::{
+ error::Error,
+ fmt::{self, Display, Formatter},
+};
+
+/// An error that occurred while preparing text for rendering.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum PrepareError {
+ AtlasFull,
+}
+
+impl Display for PrepareError {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ write!(f, "Prepare error: glyph texture atlas is full")
+ }
+}
+
+impl Error for PrepareError {}
+
+/// An error that occurred while rendering text.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub enum RenderError {
+ RemovedFromAtlas,
+ ScreenResolutionChanged,
+}
+
+impl Display for RenderError {
+ fn fmt(&self, f: &mut Formatter) -> fmt::Result {
+ match self {
+ RenderError::RemovedFromAtlas => {
+ write!(
+ f,
+ "Render error: glyph no longer exists within the texture atlas"
+ )
+ }
+ RenderError::ScreenResolutionChanged => write!(
+ f,
+ "Render error: screen resolution changed since last `prepare` call"
+ ),
+ }
+ }
+}
+
+impl Error for RenderError {}
diff --git a/vendor/iced_glyphon/src/lib.rs b/vendor/iced_glyphon/src/lib.rs
new file mode 100644
index 0000000..3b31120
--- /dev/null
+++ b/vendor/iced_glyphon/src/lib.rs
@@ -0,0 +1,120 @@
+//! Glyphon provides a simple way to render 2D text with [wgpu], [cosmic-text] and [etagere].
+//!
+//! [wpgu]: https://github.com/gfx-rs/wgpu
+//! [cosmic-text]: https://github.com/pop-os/cosmic-text
+//! [etagere]: https://github.com/nical/etagere
+
+mod cache;
+mod error;
+mod text_atlas;
+mod text_render;
+mod viewport;
+
+pub use cache::Cache;
+pub use error::{PrepareError, RenderError};
+pub use text_atlas::{ColorMode, TextAtlas};
+pub use text_render::TextRenderer;
+pub use viewport::Viewport;
+
+use text_render::ContentType;
+
+// Re-export all top-level types from `cosmic-text` for convenience.
+#[doc(no_inline)]
+pub use cosmic_text::{
+ self, fontdb, Action, Affinity, Attrs, AttrsList, AttrsOwned, Buffer, BufferLine, CacheKey,
+ Color, Command, Cursor, Edit, Editor, Family, FamilyOwned, Font, FontSystem, LayoutCursor,
+ LayoutGlyph, LayoutLine, LayoutRun, LayoutRunIter, Metrics, ShapeGlyph, ShapeLine, ShapeSpan,
+ ShapeWord, Shaping, Stretch, Style, SubpixelBin, SwashCache, SwashContent, SwashImage, Weight,
+ Wrap,
+};
+
+use etagere::AllocId;
+
+pub(crate) enum GpuCacheStatus {
+ InAtlas {
+ x: u16,
+ y: u16,
+ content_type: ContentType,
+ },
+ SkipRasterization,
+}
+
+pub(crate) struct GlyphDetails {
+ width: u16,
+ height: u16,
+ gpu_cache: GpuCacheStatus,
+ atlas_id: Option,
+ top: i16,
+ left: i16,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy, Debug)]
+pub(crate) struct GlyphToRender {
+ pos: [i32; 2],
+ dim: [u16; 2],
+ uv: [u16; 2],
+ color: u32,
+ content_type_with_srgb: [u16; 2],
+ depth: f32,
+}
+
+/// The screen resolution to use when rendering text.
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct Resolution {
+ /// The width of the screen in pixels.
+ pub width: u32,
+ /// The height of the screen in pixels.
+ pub height: u32,
+}
+
+#[repr(C)]
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub(crate) struct Params {
+ screen_resolution: Resolution,
+ _pad: [u32; 2],
+}
+
+/// Controls the visible area of the text. Any text outside of the visible area will be clipped.
+#[derive(Clone, Copy, Debug, Eq, PartialEq)]
+pub struct TextBounds {
+ /// The position of the left edge of the visible area.
+ pub left: i32,
+ /// The position of the top edge of the visible area.
+ pub top: i32,
+ /// The position of the right edge of the visible area.
+ pub right: i32,
+ /// The position of the bottom edge of the visible area.
+ pub bottom: i32,
+}
+
+/// The default visible area doesn't clip any text.
+impl Default for TextBounds {
+ fn default() -> Self {
+ Self {
+ left: i32::MIN,
+ top: i32::MIN,
+ right: i32::MAX,
+ bottom: i32::MAX,
+ }
+ }
+}
+
+/// A text area containing text to be rendered along with its overflow behavior.
+#[derive(Clone)]
+pub struct TextArea<'a> {
+ /// The buffer containing the text to be rendered.
+ pub buffer: &'a Buffer,
+ /// The left edge of the buffer.
+ pub left: f32,
+ /// The top edge of the buffer.
+ pub top: f32,
+ /// The scaling to apply to the buffer.
+ pub scale: f32,
+ /// The visible bounds of the text area. This is used to clip the text and doesn't have to
+ /// match the `left` and `top` values.
+ pub bounds: TextBounds,
+ // The default color of the text area.
+ pub default_color: Color,
+}
diff --git a/vendor/iced_glyphon/src/shader.wgsl b/vendor/iced_glyphon/src/shader.wgsl
new file mode 100644
index 0000000..1813a66
--- /dev/null
+++ b/vendor/iced_glyphon/src/shader.wgsl
@@ -0,0 +1,128 @@
+struct VertexInput {
+ @builtin(vertex_index) vertex_idx: u32,
+ @location(0) pos: vec2,
+ @location(1) dim: u32,
+ @location(2) uv: u32,
+ @location(3) color: u32,
+ @location(4) content_type_with_srgb: u32,
+ @location(5) depth: f32,
+}
+
+struct VertexOutput {
+ @invariant @builtin(position) position: vec4,
+ @location(0) color: vec4,
+ @location(1) uv: vec2,
+ @location(2) @interpolate(flat) content_type: u32,
+};
+
+struct Params {
+ screen_resolution: vec2,
+ _pad: vec2,
+};
+
+@group(0) @binding(0)
+var color_atlas_texture: texture_2d;
+
+@group(0) @binding(1)
+var mask_atlas_texture: texture_2d;
+
+@group(0) @binding(2)
+var atlas_sampler: sampler;
+
+@group(1) @binding(0)
+var params: Params;
+
+fn srgb_to_linear(c: f32) -> f32 {
+ if c <= 0.04045 {
+ return c / 12.92;
+ } else {
+ return pow((c + 0.055) / 1.055, 2.4);
+ }
+}
+
+@vertex
+fn vs_main(in_vert: VertexInput) -> VertexOutput {
+ var pos = in_vert.pos;
+ let width = in_vert.dim & 0xffffu;
+ let height = (in_vert.dim & 0xffff0000u) >> 16u;
+ let color = in_vert.color;
+ var uv = vec2(in_vert.uv & 0xffffu, (in_vert.uv & 0xffff0000u) >> 16u);
+ let v = in_vert.vertex_idx;
+
+ let corner_position = vec2(
+ in_vert.vertex_idx & 1u,
+ (in_vert.vertex_idx >> 1u) & 1u,
+ );
+
+ let corner_offset = vec2(width, height) * corner_position;
+
+ uv = uv + corner_offset;
+ pos = pos + vec2(corner_offset);
+
+ var vert_output: VertexOutput;
+
+ vert_output.position = vec4(
+ 2.0 * vec2(pos) / vec2(params.screen_resolution) - 1.0,
+ in_vert.depth,
+ 1.0,
+ );
+
+ vert_output.position.y *= -1.0;
+
+ let content_type = in_vert.content_type_with_srgb & 0xffffu;
+ let srgb = (in_vert.content_type_with_srgb & 0xffff0000u) >> 16u;
+
+ switch srgb {
+ case 0u: {
+ vert_output.color = vec4(
+ f32((color & 0x00ff0000u) >> 16u) / 255.0,
+ f32((color & 0x0000ff00u) >> 8u) / 255.0,
+ f32(color & 0x000000ffu) / 255.0,
+ f32((color & 0xff000000u) >> 24u) / 255.0,
+ );
+ }
+ case 1u: {
+ vert_output.color = vec4(
+ srgb_to_linear(f32((color & 0x00ff0000u) >> 16u) / 255.0),
+ srgb_to_linear(f32((color & 0x0000ff00u) >> 8u) / 255.0),
+ srgb_to_linear(f32(color & 0x000000ffu) / 255.0),
+ f32((color & 0xff000000u) >> 24u) / 255.0,
+ );
+ }
+ default: {}
+ }
+
+ var dim: vec2 = vec2(0u);
+ switch content_type {
+ case 0u: {
+ dim = textureDimensions(color_atlas_texture);
+ break;
+ }
+ case 1u: {
+ dim = textureDimensions(mask_atlas_texture);
+ break;
+ }
+ default: {}
+ }
+
+ vert_output.content_type = content_type;
+
+ vert_output.uv = vec2(uv) / vec2(dim);
+
+ return vert_output;
+}
+
+@fragment
+fn fs_main(in_frag: VertexOutput) -> @location(0) vec4 {
+ switch in_frag.content_type {
+ case 0u: {
+ return textureSampleLevel(color_atlas_texture, atlas_sampler, in_frag.uv, 0.0);
+ }
+ case 1u: {
+ return vec4(in_frag.color.rgb, in_frag.color.a * textureSampleLevel(mask_atlas_texture, atlas_sampler, in_frag.uv, 0.0).x);
+ }
+ default: {
+ return vec4(0.0);
+ }
+ }
+}
diff --git a/vendor/iced_glyphon/src/text_atlas.rs b/vendor/iced_glyphon/src/text_atlas.rs
new file mode 100644
index 0000000..1cabbc4
--- /dev/null
+++ b/vendor/iced_glyphon/src/text_atlas.rs
@@ -0,0 +1,360 @@
+use crate::{
+ text_render::ContentType, Cache, CacheKey, FontSystem, GlyphDetails, GpuCacheStatus, SwashCache,
+};
+use etagere::{size2, Allocation, BucketedAtlasAllocator};
+use lru::LruCache;
+use rustc_hash::FxHasher;
+use std::{collections::HashSet, hash::BuildHasherDefault, sync::Arc};
+use wgpu::{
+ BindGroup, DepthStencilState, Device, Extent3d, ImageCopyTexture, ImageDataLayout,
+ MultisampleState, Origin3d, Queue, RenderPipeline, Texture, TextureAspect, TextureDescriptor,
+ TextureDimension, TextureFormat, TextureUsages, TextureView, TextureViewDescriptor,
+};
+
+type Hasher = BuildHasherDefault;
+
+#[allow(dead_code)]
+pub(crate) struct InnerAtlas {
+ pub kind: Kind,
+ pub texture: Texture,
+ pub texture_view: TextureView,
+ pub packer: BucketedAtlasAllocator,
+ pub size: u32,
+ pub glyph_cache: LruCache,
+ pub glyphs_in_use: HashSet,
+ pub max_texture_dimension_2d: u32,
+}
+
+impl InnerAtlas {
+ const INITIAL_SIZE: u32 = 256;
+
+ fn new(device: &Device, _queue: &Queue, kind: Kind) -> Self {
+ let max_texture_dimension_2d = device.limits().max_texture_dimension_2d;
+ let size = Self::INITIAL_SIZE.min(max_texture_dimension_2d);
+
+ let packer = BucketedAtlasAllocator::new(size2(size as i32, size as i32));
+
+ // Create a texture to use for our atlas
+ let texture = device.create_texture(&TextureDescriptor {
+ label: Some("glyphon atlas"),
+ size: Extent3d {
+ width: size,
+ height: size,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: TextureDimension::D2,
+ format: kind.texture_format(),
+ usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+
+ let texture_view = texture.create_view(&TextureViewDescriptor::default());
+
+ let glyph_cache = LruCache::unbounded_with_hasher(Hasher::default());
+ let glyphs_in_use = HashSet::with_hasher(Hasher::default());
+
+ Self {
+ kind,
+ texture,
+ texture_view,
+ packer,
+ size,
+ glyph_cache,
+ glyphs_in_use,
+ max_texture_dimension_2d,
+ }
+ }
+
+ pub(crate) fn try_allocate(&mut self, width: usize, height: usize) -> Option {
+ let size = size2(width as i32, height as i32);
+
+ loop {
+ let allocation = self.packer.allocate(size);
+
+ if allocation.is_some() {
+ return allocation;
+ }
+
+ // Try to free least recently used allocation
+ let (mut key, mut value) = self.glyph_cache.peek_lru()?;
+
+ // Find a glyph with an actual size
+ while value.atlas_id.is_none() {
+ // All sized glyphs are in use, cache is full
+ if self.glyphs_in_use.contains(key) {
+ return None;
+ }
+
+ let _ = self.glyph_cache.pop_lru();
+
+ (key, value) = self.glyph_cache.peek_lru()?;
+ }
+
+ // All sized glyphs are in use, cache is full
+ if self.glyphs_in_use.contains(key) {
+ return None;
+ }
+
+ let (_, value) = self.glyph_cache.pop_lru().unwrap();
+ self.packer.deallocate(value.atlas_id.unwrap());
+ }
+ }
+
+ pub fn num_channels(&self) -> usize {
+ self.kind.num_channels()
+ }
+
+ pub(crate) fn promote(&mut self, glyph: CacheKey) {
+ self.glyph_cache.promote(&glyph);
+ self.glyphs_in_use.insert(glyph);
+ }
+
+ pub(crate) fn put(&mut self, glyph: CacheKey, details: GlyphDetails) {
+ self.glyph_cache.put(glyph, details);
+ self.glyphs_in_use.insert(glyph);
+ }
+
+ pub(crate) fn grow(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ font_system: &mut FontSystem,
+ cache: &mut SwashCache,
+ ) -> bool {
+ if self.size >= self.max_texture_dimension_2d {
+ return false;
+ }
+
+ // Grow each dimension by a factor of 2. The growth factor was chosen to match the growth
+ // factor of `Vec`.`
+ const GROWTH_FACTOR: u32 = 2;
+ let new_size = (self.size * GROWTH_FACTOR).min(self.max_texture_dimension_2d);
+
+ self.packer.grow(size2(new_size as i32, new_size as i32));
+
+ // Create a texture to use for our atlas
+ self.texture = device.create_texture(&TextureDescriptor {
+ label: Some("glyphon atlas"),
+ size: Extent3d {
+ width: new_size,
+ height: new_size,
+ depth_or_array_layers: 1,
+ },
+ mip_level_count: 1,
+ sample_count: 1,
+ dimension: TextureDimension::D2,
+ format: self.kind.texture_format(),
+ usage: TextureUsages::TEXTURE_BINDING | TextureUsages::COPY_DST,
+ view_formats: &[],
+ });
+
+ // Re-upload glyphs
+ for (&cache_key, glyph) in &self.glyph_cache {
+ let (x, y) = match glyph.gpu_cache {
+ GpuCacheStatus::InAtlas { x, y, .. } => (x, y),
+ GpuCacheStatus::SkipRasterization => continue,
+ };
+
+ let image = cache.get_image_uncached(font_system, cache_key).unwrap();
+
+ let width = image.placement.width as usize;
+ let height = image.placement.height as usize;
+
+ queue.write_texture(
+ ImageCopyTexture {
+ texture: &self.texture,
+ mip_level: 0,
+ origin: Origin3d {
+ x: x as u32,
+ y: y as u32,
+ z: 0,
+ },
+ aspect: TextureAspect::All,
+ },
+ &image.data,
+ ImageDataLayout {
+ offset: 0,
+ bytes_per_row: Some(width as u32 * self.kind.num_channels() as u32),
+ rows_per_image: None,
+ },
+ Extent3d {
+ width: width as u32,
+ height: height as u32,
+ depth_or_array_layers: 1,
+ },
+ );
+ }
+
+ self.texture_view = self.texture.create_view(&TextureViewDescriptor::default());
+ self.size = new_size;
+
+ true
+ }
+
+ fn trim(&mut self) {
+ self.glyphs_in_use.clear();
+ }
+}
+
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub(crate) enum Kind {
+ Mask,
+ Color { srgb: bool },
+}
+
+impl Kind {
+ fn num_channels(self) -> usize {
+ match self {
+ Kind::Mask => 1,
+ Kind::Color { .. } => 4,
+ }
+ }
+
+ fn texture_format(self) -> wgpu::TextureFormat {
+ match self {
+ Kind::Mask => TextureFormat::R8Unorm,
+ Kind::Color { srgb } => {
+ if srgb {
+ TextureFormat::Rgba8UnormSrgb
+ } else {
+ TextureFormat::Rgba8Unorm
+ }
+ }
+ }
+ }
+}
+
+/// The color mode of an [`Atlas`].
+#[derive(Debug, Clone, Copy, PartialEq, Eq)]
+pub enum ColorMode {
+ /// Accurate color management.
+ ///
+ /// This mode will use a proper sRGB texture for colored glyphs. This will
+ /// produce physically accurate color blending when rendering.
+ Accurate,
+
+ /// Web color management.
+ ///
+ /// This mode reproduces the color management strategy used in the Web and
+ /// implemented by browsers.
+ ///
+ /// This entails storing glyphs colored using the sRGB color space in a
+ /// linear RGB texture. Blending will not be physically accurate, but will
+ /// produce the same results as most UI toolkits.
+ ///
+ /// This mode should be used to render to a linear RGB texture containing
+ /// sRGB colors.
+ Web,
+}
+
+/// An atlas containing a cache of rasterized glyphs that can be rendered.
+pub struct TextAtlas {
+ cache: Cache,
+ pub(crate) bind_group: BindGroup,
+ pub(crate) color_atlas: InnerAtlas,
+ pub(crate) mask_atlas: InnerAtlas,
+ pub(crate) format: TextureFormat,
+ pub(crate) color_mode: ColorMode,
+}
+
+impl TextAtlas {
+ /// Creates a new [`TextAtlas`].
+ pub fn new(device: &Device, queue: &Queue, cache: &Cache, format: TextureFormat) -> Self {
+ Self::with_color_mode(device, queue, cache, format, ColorMode::Accurate)
+ }
+
+ /// Creates a new [`TextAtlas`] with the given [`ColorMode`].
+ pub fn with_color_mode(
+ device: &Device,
+ queue: &Queue,
+ cache: &Cache,
+ format: TextureFormat,
+ color_mode: ColorMode,
+ ) -> Self {
+ let color_atlas = InnerAtlas::new(
+ device,
+ queue,
+ Kind::Color {
+ srgb: match color_mode {
+ ColorMode::Accurate => true,
+ ColorMode::Web => false,
+ },
+ },
+ );
+ let mask_atlas = InnerAtlas::new(device, queue, Kind::Mask);
+
+ let bind_group = cache.create_atlas_bind_group(
+ device,
+ &color_atlas.texture_view,
+ &mask_atlas.texture_view,
+ );
+
+ Self {
+ cache: cache.clone(),
+ bind_group,
+ color_atlas,
+ mask_atlas,
+ format,
+ color_mode,
+ }
+ }
+
+ pub fn trim(&mut self) {
+ self.mask_atlas.trim();
+ self.color_atlas.trim();
+ }
+
+ pub(crate) fn grow(
+ &mut self,
+ device: &wgpu::Device,
+ queue: &wgpu::Queue,
+ font_system: &mut FontSystem,
+ cache: &mut SwashCache,
+ content_type: ContentType,
+ ) -> bool {
+ let did_grow = match content_type {
+ ContentType::Mask => self.mask_atlas.grow(device, queue, font_system, cache),
+ ContentType::Color => self.color_atlas.grow(device, queue, font_system, cache),
+ };
+
+ if did_grow {
+ self.rebind(device);
+ }
+
+ did_grow
+ }
+
+ pub(crate) fn glyph(&self, glyph: &CacheKey) -> Option<&GlyphDetails> {
+ self.mask_atlas
+ .glyph_cache
+ .peek(glyph)
+ .or_else(|| self.color_atlas.glyph_cache.peek(glyph))
+ }
+
+ pub(crate) fn inner_for_content_mut(&mut self, content_type: ContentType) -> &mut InnerAtlas {
+ match content_type {
+ ContentType::Color => &mut self.color_atlas,
+ ContentType::Mask => &mut self.mask_atlas,
+ }
+ }
+
+ pub(crate) fn get_or_create_pipeline(
+ &self,
+ device: &Device,
+ multisample: MultisampleState,
+ depth_stencil: Option,
+ ) -> Arc {
+ self.cache
+ .get_or_create_pipeline(device, self.format, multisample, depth_stencil)
+ }
+
+ fn rebind(&mut self, device: &wgpu::Device) {
+ self.bind_group = self.cache.create_atlas_bind_group(
+ device,
+ &self.color_atlas.texture_view,
+ &self.mask_atlas.texture_view,
+ );
+ }
+}
diff --git a/vendor/iced_glyphon/src/text_render.rs b/vendor/iced_glyphon/src/text_render.rs
new file mode 100644
index 0000000..163e818
--- /dev/null
+++ b/vendor/iced_glyphon/src/text_render.rs
@@ -0,0 +1,398 @@
+use crate::{
+ ColorMode, FontSystem, GlyphDetails, GlyphToRender, GpuCacheStatus, PrepareError, RenderError,
+ SwashCache, SwashContent, TextArea, TextAtlas, Viewport,
+};
+use std::{num::NonZeroU64, slice, sync::Arc};
+use wgpu::util::StagingBelt;
+use wgpu::{
+ Buffer, BufferDescriptor, BufferUsages, CommandEncoder, DepthStencilState, Device, Extent3d,
+ ImageCopyTexture, ImageDataLayout, MultisampleState, Origin3d, Queue, RenderPass,
+ RenderPipeline, TextureAspect, COPY_BUFFER_ALIGNMENT,
+};
+
+/// A text renderer that uses cached glyphs to render text into an existing render pass.
+pub struct TextRenderer {
+ staging_belt: StagingBelt,
+ vertex_buffer: Buffer,
+ vertex_buffer_size: u64,
+ pipeline: Arc,
+ glyph_vertices: Vec,
+ glyphs_to_render: u32,
+}
+
+impl TextRenderer {
+ /// Creates a new `TextRenderer`.
+ pub fn new(
+ atlas: &mut TextAtlas,
+ device: &Device,
+ multisample: MultisampleState,
+ depth_stencil: Option,
+ ) -> Self {
+ let vertex_buffer_size = next_copy_buffer_size(4096);
+ let vertex_buffer = device.create_buffer(&BufferDescriptor {
+ label: Some("glyphon vertices"),
+ size: vertex_buffer_size,
+ usage: BufferUsages::VERTEX | BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+
+ let pipeline = atlas.get_or_create_pipeline(device, multisample, depth_stencil);
+
+ Self {
+ staging_belt: StagingBelt::new(vertex_buffer_size),
+ vertex_buffer,
+ vertex_buffer_size,
+ pipeline,
+ glyph_vertices: Vec::new(),
+ glyphs_to_render: 0,
+ }
+ }
+
+ /// Prepares all of the provided text areas for rendering.
+ pub fn prepare_with_depth<'a>(
+ &mut self,
+ device: &Device,
+ queue: &Queue,
+ encoder: &mut CommandEncoder,
+ font_system: &mut FontSystem,
+ atlas: &mut TextAtlas,
+ viewport: &Viewport,
+ text_areas: impl IntoIterator- >,
+ cache: &mut SwashCache,
+ mut metadata_to_depth: impl FnMut(usize) -> f32,
+ ) -> Result<(), PrepareError> {
+ self.staging_belt.recall();
+ self.glyph_vertices.clear();
+
+ let resolution = viewport.resolution();
+
+ for text_area in text_areas {
+ for run in text_area.buffer.layout_runs() {
+ for glyph in run.glyphs.iter() {
+ let physical_glyph =
+ glyph.physical((text_area.left, text_area.top), text_area.scale);
+
+ if atlas
+ .mask_atlas
+ .glyph_cache
+ .contains(&physical_glyph.cache_key)
+ {
+ atlas.mask_atlas.promote(physical_glyph.cache_key);
+ } else if atlas
+ .color_atlas
+ .glyph_cache
+ .contains(&physical_glyph.cache_key)
+ {
+ atlas.color_atlas.promote(physical_glyph.cache_key);
+ } else {
+ let Some(image) =
+ cache.get_image_uncached(font_system, physical_glyph.cache_key)
+ else {
+ continue;
+ };
+
+ let content_type = match image.content {
+ SwashContent::Color => ContentType::Color,
+ SwashContent::Mask => ContentType::Mask,
+ SwashContent::SubpixelMask => {
+ // Not implemented yet, but don't panic if this happens.
+ ContentType::Mask
+ }
+ };
+
+ let width = image.placement.width as usize;
+ let height = image.placement.height as usize;
+
+ let should_rasterize = width > 0 && height > 0;
+
+ let (gpu_cache, atlas_id, inner) = if should_rasterize {
+ let mut inner = atlas.inner_for_content_mut(content_type);
+
+ // Find a position in the packer
+ let allocation = loop {
+ match inner.try_allocate(width, height) {
+ Some(a) => break a,
+ None => {
+ if !atlas.grow(
+ device,
+ queue,
+ font_system,
+ cache,
+ content_type,
+ ) {
+ return Err(PrepareError::AtlasFull);
+ }
+
+ inner = atlas.inner_for_content_mut(content_type);
+ }
+ }
+ };
+ let atlas_min = allocation.rectangle.min;
+
+ queue.write_texture(
+ ImageCopyTexture {
+ texture: &inner.texture,
+ mip_level: 0,
+ origin: Origin3d {
+ x: atlas_min.x as u32,
+ y: atlas_min.y as u32,
+ z: 0,
+ },
+ aspect: TextureAspect::All,
+ },
+ &image.data,
+ ImageDataLayout {
+ offset: 0,
+ bytes_per_row: Some(width as u32 * inner.num_channels() as u32),
+ rows_per_image: None,
+ },
+ Extent3d {
+ width: width as u32,
+ height: height as u32,
+ depth_or_array_layers: 1,
+ },
+ );
+
+ (
+ GpuCacheStatus::InAtlas {
+ x: atlas_min.x as u16,
+ y: atlas_min.y as u16,
+ content_type,
+ },
+ Some(allocation.id),
+ inner,
+ )
+ } else {
+ let inner = &mut atlas.color_atlas;
+ (GpuCacheStatus::SkipRasterization, None, inner)
+ };
+
+ inner.put(
+ physical_glyph.cache_key,
+ GlyphDetails {
+ width: width as u16,
+ height: height as u16,
+ gpu_cache,
+ atlas_id,
+ top: image.placement.top as i16,
+ left: image.placement.left as i16,
+ },
+ );
+ }
+
+ let details = atlas.glyph(&physical_glyph.cache_key).unwrap();
+
+ let mut x = physical_glyph.x + details.left as i32;
+ let mut y = (run.line_y * text_area.scale).round() as i32 + physical_glyph.y
+ - details.top as i32;
+
+ let (mut atlas_x, mut atlas_y, content_type) = match details.gpu_cache {
+ GpuCacheStatus::InAtlas { x, y, content_type } => (x, y, content_type),
+ GpuCacheStatus::SkipRasterization => continue,
+ };
+
+ let mut width = details.width as i32;
+ let mut height = details.height as i32;
+
+ let bounds_min_x = text_area.bounds.left.max(0);
+ let bounds_min_y = text_area.bounds.top.max(0);
+ let bounds_max_x = text_area.bounds.right.min(resolution.width as i32);
+ let bounds_max_y = text_area.bounds.bottom.min(resolution.height as i32);
+
+ // Starts beyond right edge or ends beyond left edge
+ let max_x = x + width;
+ if x > bounds_max_x || max_x < bounds_min_x {
+ continue;
+ }
+
+ // Starts beyond bottom edge or ends beyond top edge
+ let max_y = y + height;
+ if y > bounds_max_y || max_y < bounds_min_y {
+ continue;
+ }
+
+ // Clip left ege
+ if x < bounds_min_x {
+ let right_shift = bounds_min_x - x;
+
+ x = bounds_min_x;
+ width = max_x - bounds_min_x;
+ atlas_x += right_shift as u16;
+ }
+
+ // Clip right edge
+ if x + width > bounds_max_x {
+ width = bounds_max_x - x;
+ }
+
+ // Clip top edge
+ if y < bounds_min_y {
+ let bottom_shift = bounds_min_y - y;
+
+ y = bounds_min_y;
+ height = max_y - bounds_min_y;
+ atlas_y += bottom_shift as u16;
+ }
+
+ // Clip bottom edge
+ if y + height > bounds_max_y {
+ height = bounds_max_y - y;
+ }
+
+ let color = match glyph.color_opt {
+ Some(some) => some,
+ None => text_area.default_color,
+ };
+
+ let depth = metadata_to_depth(glyph.metadata);
+
+ self.glyph_vertices.push(GlyphToRender {
+ pos: [x, y],
+ dim: [width as u16, height as u16],
+ uv: [atlas_x, atlas_y],
+ color: color.0,
+ content_type_with_srgb: [
+ content_type as u16,
+ match atlas.color_mode {
+ ColorMode::Accurate => TextColorConversion::ConvertToLinear,
+ ColorMode::Web => TextColorConversion::None,
+ } as u16,
+ ],
+ depth,
+ });
+ }
+ }
+ }
+
+ self.glyphs_to_render = self.glyph_vertices.len() as u32;
+
+ let will_render = !self.glyph_vertices.is_empty();
+ if !will_render {
+ return Ok(());
+ }
+
+ let vertices = self.glyph_vertices.as_slice();
+ let vertices_raw = unsafe {
+ slice::from_raw_parts(
+ vertices as *const _ as *const u8,
+ std::mem::size_of_val(vertices),
+ )
+ };
+
+ if self.vertex_buffer_size >= vertices_raw.len() as u64 {
+ self.staging_belt
+ .write_buffer(
+ encoder,
+ &self.vertex_buffer,
+ 0,
+ NonZeroU64::new(vertices_raw.len() as u64).expect("Non-empty vertices"),
+ device,
+ )
+ .copy_from_slice(vertices_raw);
+ } else {
+ self.vertex_buffer.destroy();
+
+ let (buffer, buffer_size) = create_oversized_buffer(
+ device,
+ Some("glyphon vertices"),
+ vertices_raw,
+ BufferUsages::VERTEX | BufferUsages::COPY_DST,
+ );
+
+ self.vertex_buffer = buffer;
+ self.vertex_buffer_size = buffer_size;
+
+ self.staging_belt.finish();
+ self.staging_belt = StagingBelt::new(buffer_size);
+ }
+
+ self.staging_belt.finish();
+
+ Ok(())
+ }
+
+ pub fn prepare<'a>(
+ &mut self,
+ device: &Device,
+ queue: &Queue,
+ encoder: &mut CommandEncoder,
+ font_system: &mut FontSystem,
+ atlas: &mut TextAtlas,
+ viewport: &Viewport,
+ text_areas: impl IntoIterator
- >,
+ cache: &mut SwashCache,
+ ) -> Result<(), PrepareError> {
+ self.prepare_with_depth(
+ device,
+ queue,
+ encoder,
+ font_system,
+ atlas,
+ viewport,
+ text_areas,
+ cache,
+ zero_depth,
+ )
+ }
+
+ /// Renders all layouts that were previously provided to `prepare`.
+ pub fn render<'pass>(
+ &'pass self,
+ atlas: &'pass TextAtlas,
+ viewport: &'pass Viewport,
+ pass: &mut RenderPass<'pass>,
+ ) -> Result<(), RenderError> {
+ if self.glyphs_to_render == 0 {
+ return Ok(());
+ }
+
+ pass.set_pipeline(&self.pipeline);
+ pass.set_bind_group(0, &atlas.bind_group, &[]);
+ pass.set_bind_group(1, &viewport.bind_group, &[]);
+ pass.set_vertex_buffer(0, self.vertex_buffer.slice(..));
+ pass.draw(0..4, 0..self.glyphs_to_render);
+
+ Ok(())
+ }
+}
+
+#[repr(u16)]
+#[derive(Debug, Clone, Copy, Eq, PartialEq)]
+pub enum ContentType {
+ Color = 0,
+ Mask = 1,
+}
+
+#[repr(u16)]
+#[derive(Debug, Clone, Copy, Eq, PartialEq)]
+enum TextColorConversion {
+ None = 0,
+ ConvertToLinear = 1,
+}
+
+fn next_copy_buffer_size(size: u64) -> u64 {
+ let align_mask = COPY_BUFFER_ALIGNMENT - 1;
+ ((size.next_power_of_two() + align_mask) & !align_mask).max(COPY_BUFFER_ALIGNMENT)
+}
+
+fn create_oversized_buffer(
+ device: &Device,
+ label: Option<&str>,
+ contents: &[u8],
+ usage: BufferUsages,
+) -> (Buffer, u64) {
+ let size = next_copy_buffer_size(contents.len() as u64);
+ let buffer = device.create_buffer(&BufferDescriptor {
+ label,
+ size,
+ usage,
+ mapped_at_creation: true,
+ });
+ buffer.slice(..).get_mapped_range_mut()[..contents.len()].copy_from_slice(contents);
+ buffer.unmap();
+ (buffer, size)
+}
+
+fn zero_depth(_: usize) -> f32 {
+ 0f32
+}
diff --git a/vendor/iced_glyphon/src/viewport.rs b/vendor/iced_glyphon/src/viewport.rs
new file mode 100644
index 0000000..14d3412
--- /dev/null
+++ b/vendor/iced_glyphon/src/viewport.rs
@@ -0,0 +1,57 @@
+use crate::{Cache, Params, Resolution};
+
+use wgpu::{BindGroup, Buffer, BufferDescriptor, BufferUsages, Device, Queue};
+
+use std::mem;
+use std::slice;
+
+#[derive(Debug)]
+pub struct Viewport {
+ params: Params,
+ params_buffer: Buffer,
+ pub(crate) bind_group: BindGroup,
+}
+
+impl Viewport {
+ pub fn new(device: &Device, cache: &Cache) -> Self {
+ let params = Params {
+ screen_resolution: Resolution {
+ width: 0,
+ height: 0,
+ },
+ _pad: [0, 0],
+ };
+
+ let params_buffer = device.create_buffer(&BufferDescriptor {
+ label: Some("glyphon params"),
+ size: mem::size_of::() as u64,
+ usage: BufferUsages::UNIFORM | BufferUsages::COPY_DST,
+ mapped_at_creation: false,
+ });
+
+ let bind_group = cache.create_uniforms_bind_group(device, ¶ms_buffer);
+
+ Self {
+ params,
+ params_buffer,
+ bind_group,
+ }
+ }
+
+ pub fn update(&mut self, queue: &Queue, resolution: Resolution) {
+ if self.params.screen_resolution != resolution {
+ self.params.screen_resolution = resolution;
+
+ queue.write_buffer(&self.params_buffer, 0, unsafe {
+ slice::from_raw_parts(
+ &self.params as *const Params as *const u8,
+ mem::size_of::(),
+ )
+ });
+ }
+ }
+
+ pub fn resolution(&self) -> Resolution {
+ self.params.screen_resolution
+ }
+}