From 6c799b8e994266233014cea66d7769675ec1967c Mon Sep 17 00:00:00 2001 From: Miles Wirht <114884788+philocalyst@users.noreply.github.com> Date: Mon, 13 Jul 2026 21:25:00 -0400 Subject: [PATCH] removed all of the git sources (#91) --- Cargo.lock | 981 +++-- Cargo.toml | 51 +- crates/gpui/Cargo.toml | 4 +- crates/gpui/examples/legacy/hello_world.rs | 2 +- crates/gpui/src/style.rs | 8 +- crates/gpui/src/text_system/line_wrapper.rs | 2 +- crates/gpui_ce_util/Cargo.toml | 16 + crates/gpui_ce_util/LICENSE-APACHE | 222 + crates/gpui_ce_util/src/arc_cow.rs | 141 + crates/gpui_ce_util/src/lib.rs | 393 ++ crates/gpui_collections/Cargo.toml | 20 + crates/gpui_collections/LICENSE-APACHE | 222 + crates/gpui_collections/src/collections.rs | 13 + crates/gpui_collections/src/vecmap.rs | 192 + crates/gpui_collections/src/vecmap_tests.rs | 211 + crates/gpui_derive_refineable/Cargo.toml | 18 + crates/gpui_derive_refineable/LICENSE-APACHE | 222 + .../src/derive_refineable.rs | 548 +++ crates/gpui_linux/Cargo.toml | 5 +- crates/gpui_macos/Cargo.toml | 3 +- crates/gpui_macros/Cargo.toml | 2 +- crates/gpui_macros/src/gpui_macros.rs | 4 +- crates/gpui_media/Cargo.toml | 26 + crates/gpui_media/LICENSE-APACHE | 222 + crates/gpui_media/build.rs | 44 + crates/gpui_media/src/bindings.h | 5 + crates/gpui_media/src/bindings.rs | 10 + crates/gpui_media/src/media.rs | 352 ++ crates/gpui_refineable/Cargo.toml | 15 + crates/gpui_refineable/LICENSE-APACHE | 222 + crates/gpui_refineable/src/refineable.rs | 132 + crates/gpui_scheduler/Cargo.toml | 25 + crates/gpui_scheduler/LICENSE-APACHE | 222 + crates/gpui_scheduler/src/clock.rs | 55 + crates/gpui_scheduler/src/executor.rs | 546 +++ crates/gpui_scheduler/src/scheduler.rs | 209 + crates/gpui_scheduler/src/test_scheduler.rs | 926 +++++ crates/gpui_scheduler/src/tests.rs | 961 +++++ crates/gpui_sum_tree/Cargo.toml | 29 + crates/gpui_sum_tree/LICENSE-APACHE | 222 + crates/gpui_sum_tree/src/cursor.rs | 861 ++++ crates/gpui_sum_tree/src/property_test.rs | 32 + crates/gpui_sum_tree/src/sum_tree.rs | 1898 +++++++++ crates/gpui_sum_tree/src/tree_map.rs | 531 +++ crates/gpui_wgpu/Cargo.toml | 3 +- crates/gpui_zed_util/Cargo.toml | 68 + crates/gpui_zed_util/LICENSE-APACHE | 222 + crates/gpui_zed_util/src/archive.rs | 383 ++ crates/gpui_zed_util/src/command.rs | 140 + crates/gpui_zed_util/src/command/darwin.rs | 915 +++++ crates/gpui_zed_util/src/disambiguate.rs | 202 + crates/gpui_zed_util/src/fs.rs | 111 + crates/gpui_zed_util/src/markdown.rs | 376 ++ crates/gpui_zed_util/src/path_list.rs | 233 ++ crates/gpui_zed_util/src/paths.rs | 3587 +++++++++++++++++ crates/gpui_zed_util/src/process.rs | 92 + crates/gpui_zed_util/src/redact.rs | 49 + crates/gpui_zed_util/src/rel_path.rs | 637 +++ crates/gpui_zed_util/src/schemars.rs | 72 + crates/gpui_zed_util/src/serde.rs | 7 + crates/gpui_zed_util/src/shell.rs | 1051 +++++ crates/gpui_zed_util/src/shell_builder.rs | 327 ++ crates/gpui_zed_util/src/shell_env.rs | 344 ++ crates/gpui_zed_util/src/size.rs | 46 + crates/gpui_zed_util/src/test.rs | 80 + crates/gpui_zed_util/src/test/assertions.rs | 62 + crates/gpui_zed_util/src/test/git.rs | 0 crates/gpui_zed_util/src/test/marked_text.rs | 281 ++ crates/gpui_zed_util/src/time.rs | 33 + crates/gpui_zed_util/src/util.rs | 1074 +++++ flake.nix | 46 +- justfile | 21 + tooling/perf/src/main.rs | 4 +- typos.toml | 2 + 74 files changed, 20842 insertions(+), 451 deletions(-) create mode 100644 crates/gpui_ce_util/Cargo.toml create mode 100644 crates/gpui_ce_util/LICENSE-APACHE create mode 100644 crates/gpui_ce_util/src/arc_cow.rs create mode 100644 crates/gpui_ce_util/src/lib.rs create mode 100644 crates/gpui_collections/Cargo.toml create mode 100644 crates/gpui_collections/LICENSE-APACHE create mode 100644 crates/gpui_collections/src/collections.rs create mode 100644 crates/gpui_collections/src/vecmap.rs create mode 100644 crates/gpui_collections/src/vecmap_tests.rs create mode 100644 crates/gpui_derive_refineable/Cargo.toml create mode 100644 crates/gpui_derive_refineable/LICENSE-APACHE create mode 100644 crates/gpui_derive_refineable/src/derive_refineable.rs create mode 100644 crates/gpui_media/Cargo.toml create mode 100644 crates/gpui_media/LICENSE-APACHE create mode 100644 crates/gpui_media/build.rs create mode 100644 crates/gpui_media/src/bindings.h create mode 100644 crates/gpui_media/src/bindings.rs create mode 100644 crates/gpui_media/src/media.rs create mode 100644 crates/gpui_refineable/Cargo.toml create mode 100644 crates/gpui_refineable/LICENSE-APACHE create mode 100644 crates/gpui_refineable/src/refineable.rs create mode 100644 crates/gpui_scheduler/Cargo.toml create mode 100644 crates/gpui_scheduler/LICENSE-APACHE create mode 100644 crates/gpui_scheduler/src/clock.rs create mode 100644 crates/gpui_scheduler/src/executor.rs create mode 100644 crates/gpui_scheduler/src/scheduler.rs create mode 100644 crates/gpui_scheduler/src/test_scheduler.rs create mode 100644 crates/gpui_scheduler/src/tests.rs create mode 100644 crates/gpui_sum_tree/Cargo.toml create mode 100644 crates/gpui_sum_tree/LICENSE-APACHE create mode 100644 crates/gpui_sum_tree/src/cursor.rs create mode 100644 crates/gpui_sum_tree/src/property_test.rs create mode 100644 crates/gpui_sum_tree/src/sum_tree.rs create mode 100644 crates/gpui_sum_tree/src/tree_map.rs create mode 100644 crates/gpui_zed_util/Cargo.toml create mode 100644 crates/gpui_zed_util/LICENSE-APACHE create mode 100644 crates/gpui_zed_util/src/archive.rs create mode 100644 crates/gpui_zed_util/src/command.rs create mode 100644 crates/gpui_zed_util/src/command/darwin.rs create mode 100644 crates/gpui_zed_util/src/disambiguate.rs create mode 100644 crates/gpui_zed_util/src/fs.rs create mode 100644 crates/gpui_zed_util/src/markdown.rs create mode 100644 crates/gpui_zed_util/src/path_list.rs create mode 100644 crates/gpui_zed_util/src/paths.rs create mode 100644 crates/gpui_zed_util/src/process.rs create mode 100644 crates/gpui_zed_util/src/redact.rs create mode 100644 crates/gpui_zed_util/src/rel_path.rs create mode 100644 crates/gpui_zed_util/src/schemars.rs create mode 100644 crates/gpui_zed_util/src/serde.rs create mode 100644 crates/gpui_zed_util/src/shell.rs create mode 100644 crates/gpui_zed_util/src/shell_builder.rs create mode 100644 crates/gpui_zed_util/src/shell_env.rs create mode 100644 crates/gpui_zed_util/src/size.rs create mode 100644 crates/gpui_zed_util/src/test.rs create mode 100644 crates/gpui_zed_util/src/test/assertions.rs create mode 100644 crates/gpui_zed_util/src/test/git.rs create mode 100644 crates/gpui_zed_util/src/test/marked_text.rs create mode 100644 crates/gpui_zed_util/src/time.rs create mode 100644 crates/gpui_zed_util/src/util.rs diff --git a/Cargo.lock b/Cargo.lock index cd29eabaf3..736c991615 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -114,7 +114,7 @@ checksum = "b169f7a6d4742236a0a00c541b845991d0ac43e546831af1249753ab4c3aa3a0" dependencies = [ "cfg-if", "cipher", - "cpufeatures", + "cpufeatures 0.2.17", "zeroize", ] @@ -710,6 +710,15 @@ dependencies = [ "generic-array", ] +[[package]] +name = "block-buffer" +version = "0.12.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d2f6c7dbe95a6ed67ad9f18e57daf93a2f034c524b99fd2b76d18fdfeb6660aa" +dependencies = [ + "hybrid-array", +] + [[package]] name = "block-padding" version = "0.3.3" @@ -784,18 +793,18 @@ checksum = "72f5acc6cb2ba439de613abc23857ec3d78374d8ed5ac84e9d11336e87da8649" [[package]] name = "bytemuck" -version = "1.25.0" +version = "1.25.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8efb64bd706a16a1bdde310ae86b351e4d21550d98d056f22f8a7f7a2183fec" +checksum = "d6aedf8ae72766347502cf3cb4f41cf5e9cc37d28bee90f1fdaaae15f9cf9424" dependencies = [ "bytemuck_derive", ] [[package]] name = "bytemuck_derive" -version = "1.10.2" +version = "1.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f9abbd1bc6865053c427f7198e6af43bfdedc55ab791faed4fbd361d789575ff" +checksum = "f65693059b6b9c588b9f62fed1cedbf0a8b805631457ea162d68f0de186f3de5" dependencies = [ "proc-macro2", "quote", @@ -816,9 +825,9 @@ checksum = "8f1fe948ff07f4bd06c30984e69f5b4899c516a3ef74f34df92a2df2ab535495" [[package]] name = "bytes" -version = "1.12.0" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8ae3f5d315924270530207e2a68396c3cc547f6dca3fbdca317cfb1a51edb593" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "calloop" @@ -880,9 +889,9 @@ dependencies = [ [[package]] name = "cc" -version = "1.2.66" +version = "1.2.67" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f5d6cac793997bd970000024b2934968efe83b382de4fdcf4fcb46b6ee4ad996" +checksum = "e17dd265a7d0f31ef544e1b20e03add05d3b45b491b633b10d67145d2acc1a38" dependencies = [ "find-msvc-tools", "jobserver", @@ -967,7 +976,7 @@ version = "0.4.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "773f3b9af64447d2ce9850330c473515014aa235e6a783b02db81ff39e4a3dad" dependencies = [ - "crypto-common", + "crypto-common 0.1.7", "inout", "zeroize", ] @@ -1079,15 +1088,6 @@ dependencies = [ "unicode-width", ] -[[package]] -name = "collections" -version = "0.1.0" -source = "git+https://github.com/zed-industries/zed?rev=876ec5a8a074ba83cce2129ed4d76b59c05a37e9#876ec5a8a074ba83cce2129ed4d76b59c05a37e9" -dependencies = [ - "indexmap", - "rustc-hash 2.1.3", -] - [[package]] name = "color_quant" version = "1.1.0" @@ -1146,6 +1146,12 @@ dependencies = [ "wasm-bindgen", ] +[[package]] +name = "const-oid" +version = "0.10.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a6ef517f0926dd24a1582492c791b6a4818a4d94e789a334894aa15b0d12f55c" + [[package]] name = "const-random" version = "0.1.18" @@ -1352,6 +1358,15 @@ dependencies = [ "libc", ] +[[package]] +name = "cpufeatures" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8b2a41393f66f16b0823bb79094d54ac5fbd34ab292ddafb9a0456ac9f87d201" +dependencies = [ + "libc", +] + [[package]] name = "crc32fast" version = "1.5.0" @@ -1399,18 +1414,18 @@ dependencies = [ [[package]] name = "crossbeam-channel" -version = "0.5.15" +version = "0.5.16" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "82b8f8f868b36967f9606790d1903570de9ceaf870a7bf9fbbd3016d636a2cb2" +checksum = "d85363c37faeca707aef026efa9f3b34d077bce547e48f770770625c6013679e" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-deque" -version = "0.8.6" +version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9dd111b7b7f7d55b72c0a6ae361660ee5853c9af73f70c3c2ef6858b950e2e51" +checksum = "5181e0de7b61eb03a81e347d6dd8797bae9da5146707b51077e2d71a54ec0ceb" dependencies = [ "crossbeam-epoch", "crossbeam-utils", @@ -1418,27 +1433,27 @@ dependencies = [ [[package]] name = "crossbeam-epoch" -version = "0.9.18" +version = "0.9.20" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5b82ac4a3c2ca9c3460964f020e1402edd5753411d7737aa39c3714ad1b5420e" +checksum = "2d6914041f254d6e9176c01941b21115dcfb7089e55135a35411081bd106ef3f" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-queue" -version = "0.3.12" +version = "0.3.13" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0f58bbc28f91df819d0aa2a2c00cd19754769c2fad90579b3592b1c9ba7a3115" +checksum = "803d13fb3b09d88be9f4dbc29062c66b19bf7170867ceb746d2a8689bf6c7a26" dependencies = [ "crossbeam-utils", ] [[package]] name = "crossbeam-utils" -version = "0.8.21" +version = "0.8.22" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d0a5c400df2834b80a4c3327b3aad3a4c4cd4de0629063962b03235697506a28" +checksum = "61803da095bee82a81bb1a452ecc25d3b2f1416d1897eb86430c6159ef717c17" [[package]] name = "crunchy" @@ -1457,10 +1472,19 @@ dependencies = [ ] [[package]] -name = "ctor" -version = "1.0.7" +name = "crypto-common" +version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "01334b89b69ff726750c5ce5073fc8bd860e99aa9a8fc5ca11b04730e3aee97a" +checksum = "ce6e4c961d6cd6c9a86db418387425e8bdeaf05b3c8bc1411e6dca4c252f1453" +dependencies = [ + "hybrid-array", +] + +[[package]] +name = "ctor" +version = "1.0.8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "fb22e947478ccf9dc44d8922042c677a63fbb88f2cb468521d1145816e5087cb" dependencies = [ "link-section", "linktime-proc-macro", @@ -1533,14 +1557,10 @@ dependencies = [ ] [[package]] -name = "derive_refineable" -version = "0.1.0" -source = "git+https://github.com/zed-industries/zed?rev=876ec5a8a074ba83cce2129ed4d76b59c05a37e9#876ec5a8a074ba83cce2129ed4d76b59c05a37e9" -dependencies = [ - "proc-macro2", - "quote", - "syn", -] +name = "diff" +version = "0.1.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "56254986775e3233ffa9c4d7d3faaf6d36a2c09d30b20687e9f88bc8bafc16c8" [[package]] name = "digest" @@ -1548,18 +1568,50 @@ version = "0.10.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed9a281f7bc9b7576e61468ba615a66a5c8cfdff42420a70aa82701a3b1e292" dependencies = [ - "block-buffer", - "crypto-common", + "block-buffer 0.10.4", + "crypto-common 0.1.7", "subtle", ] +[[package]] +name = "digest" +version = "0.11.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f1dd6dbb5841937940781866fa1281a1ff7bd3bf827091440879f9994983d5c2" +dependencies = [ + "block-buffer 0.12.1", + "const-oid", + "crypto-common 0.2.2", +] + +[[package]] +name = "dirs" +version = "5.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "44c45a9d03d6676652bcb5e724c7e988de1acad23a711b5217ab9cbecbec2225" +dependencies = [ + "dirs-sys 0.4.1", +] + [[package]] name = "dirs" version = "6.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "c3e8aa94d75141228480295a7d0e7feb620b1a5ad9f12bc40be62411e38cce4e" dependencies = [ - "dirs-sys", + "dirs-sys 0.5.0", +] + +[[package]] +name = "dirs-sys" +version = "0.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "520f05a5cbd335fae5a99ff7a6ab8627577660ee5cfd6a94a6a929b52ff0321c" +dependencies = [ + "libc", + "option-ext", + "redox_users 0.4.6", + "windows-sys 0.48.0", ] [[package]] @@ -1570,7 +1622,7 @@ checksum = "e01a3366d27ee9890022452ee61b2b63a67e6f13f58900b651ff5665f0bb1fab" dependencies = [ "libc", "option-ext", - "redox_users", + "redox_users 0.5.2", "windows-sys 0.61.2", ] @@ -1819,14 +1871,16 @@ dependencies = [ [[package]] name = "exr" -version = "1.74.0" +version = "1.74.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4300e043a56aa2cb633c01af81ca8f699a321879a7854d3896a0ba89056363be" +checksum = "711fe42c9964295e01ee3fba3f9fe0e1d24b98886950d68efe81b1c76e21adf3" dependencies = [ "bit_field", "half", "lebe", "miniz_oxide", + "num-complex", + "pulp", "rayon-core", "smallvec", "zune-inflate", @@ -1922,7 +1976,7 @@ dependencies = [ "futures-core", "futures-sink", "nanorand", - "spin 0.9.8", + "spin 0.9.9", ] [[package]] @@ -2245,6 +2299,18 @@ version = "0.32.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e629b9b98ef3dd8afe6ca2bd0f89306cec16d43d907889945bc5d6687f2f13c7" +[[package]] +name = "git2" +version = "0.21.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ddddbf932745a6be37109b6112d3ee09696106f848449069d3a57bba937ab82e" +dependencies = [ + "bitflags 2.13.0", + "libc", + "libgit2-sys", + "log", +] + [[package]] name = "gl_generator" version = "0.14.0" @@ -2346,7 +2412,6 @@ dependencies = [ "chrono", "cocoa 0.26.0", "cocoa-foundation 0.2.0", - "collections", "core-foundation 0.10.0", "core-foundation-sys", "core-graphics 0.24.0", @@ -2361,10 +2426,15 @@ dependencies = [ "futures", "futures-concurrency", "getrandom 0.3.4", + "gpui_ce_util", + "gpui_collections", "gpui_macros", + "gpui_media", "gpui_platform", + "gpui_refineable", + "gpui_scheduler", "gpui_shared_string", - "gpui_util", + "gpui_sum_tree", "gpui_web", "hdrhistogram", "http", @@ -2374,7 +2444,6 @@ dependencies = [ "log", "lyon", "mach2", - "media", "metal", "num_cpus", "objc", @@ -2388,12 +2457,10 @@ dependencies = [ "postage", "profiling", "proptest", - "rand 0.9.4", + "rand 0.9.5", "raw-window-handle", - "refineable", "regex", "resvg", - "scheduler", "schemars", "seahash", "serde", @@ -2401,17 +2468,15 @@ dependencies = [ "slotmap", "smallvec", "smol", - "spin 0.10.0", + "spin 0.10.1", "stacksafe", "strum", - "sum_tree", "taffy", "thiserror 2.0.18", "ttf-parser", "unicode-segmentation", "url", "usvg", - "util_macros", "uuid", "waker-fn", "wasm-bindgen", @@ -2421,6 +2486,31 @@ dependencies = [ "zed-scap", ] +[[package]] +name = "gpui_ce_util" +version = "0.2.2" +dependencies = [ + "anyhow", + "log", +] + +[[package]] +name = "gpui_collections" +version = "0.2.2" +dependencies = [ + "indexmap", + "rustc-hash 2.1.3", +] + +[[package]] +name = "gpui_derive_refineable" +version = "0.2.2" +dependencies = [ + "proc-macro2", + "quote", + "syn", +] + [[package]] name = "gpui_elements" version = "0.1.0" @@ -2444,11 +2534,12 @@ dependencies = [ "bytemuck", "calloop", "calloop-wayland-source", - "collections", "filedescriptor", "futures", "gpui", + "gpui_collections", "gpui_wgpu", + "gpui_zed_util", "image", "itertools 0.14.0", "libc", @@ -2465,7 +2556,6 @@ dependencies = [ "strum", "swash", "url", - "util", "uuid", "wayland-backend", "wayland-client", @@ -2491,7 +2581,6 @@ dependencies = [ "block", "cbindgen", "cocoa 0.26.0", - "collections", "core-foundation 0.10.0", "core-foundation-sys", "core-graphics 0.24.0", @@ -2504,12 +2593,14 @@ dependencies = [ "foreign-types", "futures", "gpui", + "gpui_collections", + "gpui_media", + "gpui_zed_util", "image", "itertools 0.14.0", "libc", "log", "mach2", - "media", "metal", "objc", "objc2-app-kit 0.3.2", @@ -2519,7 +2610,6 @@ dependencies = [ "semver", "smallvec", "strum", - "util", "uuid", "zed-font-kit", ] @@ -2535,6 +2625,20 @@ dependencies = [ "syn", ] +[[package]] +name = "gpui_media" +version = "0.2.2" +dependencies = [ + "anyhow", + "bindgen", + "core-foundation 0.10.0", + "core-video", + "ctor", + "foreign-types", + "metal", + "objc", +] + [[package]] name = "gpui_platform" version = "0.1.0" @@ -2547,6 +2651,27 @@ dependencies = [ "gpui_windows", ] +[[package]] +name = "gpui_refineable" +version = "0.2.2" +dependencies = [ + "gpui_derive_refineable", +] + +[[package]] +name = "gpui_scheduler" +version = "0.2.2" +dependencies = [ + "async-task", + "backtrace", + "chrono", + "flume", + "futures", + "parking_lot", + "rand 0.9.5", + "web-time", +] + [[package]] name = "gpui_shared_string" version = "0.1.0" @@ -2556,23 +2681,26 @@ dependencies = [ "smol_str", ] +[[package]] +name = "gpui_sum_tree" +version = "0.2.2" +dependencies = [ + "heapless", + "log", + "proptest", + "rand 0.9.5", + "rayon", + "tracing", +] + [[package]] name = "gpui_tokio" version = "0.1.0" dependencies = [ "anyhow", "gpui", + "gpui_zed_util", "tokio", - "util", -] - -[[package]] -name = "gpui_util" -version = "0.1.0" -source = "git+https://github.com/zed-industries/zed?rev=876ec5a8a074ba83cce2129ed4d76b59c05a37e9#876ec5a8a074ba83cce2129ed4d76b59c05a37e9" -dependencies = [ - "anyhow", - "log", ] [[package]] @@ -2604,12 +2732,12 @@ version = "0.1.0" dependencies = [ "anyhow", "bytemuck", - "collections", "cosmic-text", "criterion", "etagere", "gpui", - "gpui_util", + "gpui_ce_util", + "gpui_collections", "itertools 0.14.0", "js-sys", "log", @@ -2634,19 +2762,19 @@ dependencies = [ "accesskit", "accesskit_windows", "anyhow", - "collections", "etagere", "futures", "gpui", + "gpui_collections", "gpui_wgpu", + "gpui_zed_util", "image", "itertools 0.14.0", "log", "parking_lot", - "rand 0.9.4", + "rand 0.9.5", "raw-window-handle", "smallvec", - "util", "uuid", "windows 0.61.3", "windows-core 0.61.2", @@ -2655,6 +2783,47 @@ dependencies = [ "zed-scap", ] +[[package]] +name = "gpui_zed_util" +version = "0.2.2" +dependencies = [ + "anyhow", + "async-fs", + "async_zip", + "command-fds", + "dirs 6.0.0", + "dunce", + "futures", + "futures-lite 1.13.0", + "git2", + "globset", + "gpui_ce_util", + "gpui_collections", + "itertools 0.14.0", + "libc", + "log", + "mach2", + "nix 0.29.0", + "percent-encoding", + "pretty_assertions", + "rand 0.9.5", + "regex", + "rust-embed", + "schemars", + "serde", + "serde_json", + "serde_json_lenient", + "shlex 1.3.0", + "smol", + "take-until", + "tempfile", + "tendril", + "unicase", + "url", + "walkdir", + "which", +] + [[package]] name = "grid" version = "1.0.1" @@ -2796,7 +2965,7 @@ version = "0.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6c49c37c09c17a53d937dfbb742eb3a961d65a994e6bcdcf37e7399d0cc8ab5e" dependencies = [ - "digest", + "digest 0.10.7", ] [[package]] @@ -2818,6 +2987,15 @@ dependencies = [ "itoa", ] +[[package]] +name = "hybrid-array" +version = "0.4.13" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "818356c5132c1fede50f837ca96afbe78ff42413047f4abb886217845e1b6c8c" +dependencies = [ + "typenum", +] + [[package]] name = "iana-time-zone" version = "0.1.65" @@ -3125,9 +3303,9 @@ checksum = "8f42a60cbdf9a97f5d2305f08a87dc4e09308d1276d28c869c684d7777685682" [[package]] name = "jiff" -version = "0.2.31" +version = "0.2.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ccfe6121cbe750cf81efa362d85c0bde7ea298ec43092d3a193baca59cdbd634" +checksum = "961d16382652bfdd8c6f68b223b26a8c93e0d475c672f414411db31c6c5c900e" dependencies = [ "defmt", "jiff-static", @@ -3139,9 +3317,9 @@ dependencies = [ [[package]] name = "jiff-static" -version = "0.2.31" +version = "0.2.32" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e165e897f662d428f3cd3828a919dbe067c2d42bb1031eede74ef9d27ecdedd2" +checksum = "d0879bd39df99c4c5e2c6615ccc026391a423dde10532c573e6086eb94a802cc" dependencies = [ "proc-macro2", "quote", @@ -3268,6 +3446,18 @@ dependencies = [ "cc", ] +[[package]] +name = "libgit2-sys" +version = "0.18.5+1.9.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "005d6ae6eac1912906073e069f7db60b1fa98e052a68227824afe3e3a1c59ca2" +dependencies = [ + "cc", + "libc", + "libz-sys", + "pkg-config", +] + [[package]] name = "libloading" version = "0.8.9" @@ -3293,6 +3483,18 @@ dependencies = [ "libc", ] +[[package]] +name = "libz-sys" +version = "1.1.29" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "85bc9657773828b90eeb625adff10eeac83cc21bbfd8e23a03eaa8a33c9e28d9" +dependencies = [ + "cc", + "libc", + "pkg-config", + "vcpkg", +] + [[package]] name = "linebender_resource_handle" version = "0.1.1" @@ -3301,9 +3503,9 @@ checksum = "d4a5ff6bcca6c4867b1c4fd4ef63e4db7436ef363e0ad7531d1558856bae64f4" [[package]] name = "link-section" -version = "0.18.3" +version = "0.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "24670b639492630905459a6c7d47f063d33c2d4fcd5362f6e5827c5613976c9f" +checksum = "e333fe507b738576d6da5bb3f1a7d7a1c80307ed9ef31624c057d844c19c93e9" [[package]] name = "linktime-proc-macro" @@ -3467,29 +3669,14 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d89e7ee0cfbedfc4da3340218492196241d89eefb6dab27de5df917a6d2e78cf" dependencies = [ "cfg-if", - "digest", -] - -[[package]] -name = "media" -version = "0.1.0" -source = "git+https://github.com/zed-industries/zed?rev=876ec5a8a074ba83cce2129ed4d76b59c05a37e9#876ec5a8a074ba83cce2129ed4d76b59c05a37e9" -dependencies = [ - "anyhow", - "bindgen", - "core-foundation 0.10.0", - "core-video", - "ctor", - "foreign-types", - "metal", - "objc", + "digest 0.10.7", ] [[package]] name = "memchr" -version = "2.8.2" +version = "2.8.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "88904434abc2901f197fe8cc55f0445e7ded921dba5911dad2e2b39b48e663c4" +checksum = "cf8baf1c55e62ffcace7a9f06f4bd9cd3f0c4beb022d3b367256b91b87513d98" [[package]] name = "memmap2" @@ -3524,6 +3711,22 @@ dependencies = [ "paste", ] +[[package]] +name = "mime" +version = "0.3.17" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6877bb514081ee2a7ff5ef9de3281f14a4dd4bceac4c09388074a6b5df8a139a" + +[[package]] +name = "mime_guess" +version = "2.0.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f7c44f8e672c00fe5308fa235f821cb4198414e1c77935c1ab6948d3fd78550e" +dependencies = [ + "mime", + "unicase", +] + [[package]] name = "minimal-lexical" version = "0.2.1" @@ -3552,8 +3755,9 @@ dependencies = [ [[package]] name = "naga" -version = "29.0.3" -source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b2bf919621e7975acb27d881bae2fb993e0d45c8e0446e85e6272971e00dc8df" dependencies = [ "arrayvec", "bit-set 0.9.1", @@ -3666,15 +3870,6 @@ dependencies = [ "winapi", ] -[[package]] -name = "nu-ansi-term" -version = "0.50.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7957b9740744892f114936ab4a57b3f487491bbeafaf8083688b16841a4240e5" -dependencies = [ - "windows-sys 0.61.2", -] - [[package]] name = "num" version = "0.4.3" @@ -3710,7 +3905,7 @@ dependencies = [ "num-iter", "num-traits", "once_cell", - "rand 0.9.4", + "rand 0.9.5", "serde", "smallvec", "zeroize", @@ -3722,6 +3917,7 @@ version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "73f88a1307638156682bada9d7604135552957b7818057dcef22705b4d509495" dependencies = [ + "bytemuck", "num-traits", ] @@ -3747,11 +3943,10 @@ dependencies = [ [[package]] name = "num-iter" -version = "0.1.45" +version = "0.1.46" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1429034a0490724d0075ebb2bc9e875d6503c3cf69e235a8941aa757d83ef5bf" +checksum = "c92800bd69a1eac91786bcfe9da64a897eb72911b8dc3095decbd07429e8048b" dependencies = [ - "autocfg", "num-integer", "num-traits", ] @@ -4028,7 +4223,7 @@ dependencies = [ "blocking", "cbc", "cipher", - "digest", + "digest 0.10.7", "endi", "futures-lite 2.6.1", "futures-util", @@ -4041,7 +4236,7 @@ dependencies = [ "pbkdf2", "serde", "serde_bytes", - "sha2", + "sha2 0.10.9", "subtle", "zbus", "zbus_macros", @@ -4057,9 +4252,9 @@ checksum = "d6790f58c7ff633d8771f42965289203411a5e5c68388703c06e14f24770b41e" [[package]] name = "open" -version = "5.3.6" +version = "5.4.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd8d3b65c44123a56e0133d2cd06ce4361bd3ca99d41198b2f25e3c3db9b8b4a" +checksum = "a0b3d059e795d52b8a72fef45658620edd4d9c359b338564aa14391ffa511ed5" dependencies = [ "is-wsl", "libc", @@ -4156,7 +4351,7 @@ version = "0.12.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f8ed6a7761f76e3b9f92dfb0a60a6a6477c61024b775147ff0973a02653abaf2" dependencies = [ - "digest", + "digest 0.10.7", "hmac", ] @@ -4170,17 +4365,7 @@ checksum = "9b4f627cb1b25917193a259e49bdad08f671f8d9708acfd5fe0a8c1455d87220" name = "perf" version = "0.1.0" dependencies = [ - "collections", - "serde", - "serde_json", -] - -[[package]] -name = "perf" -version = "0.1.0" -source = "git+https://github.com/zed-industries/zed?rev=876ec5a8a074ba83cce2129ed4d76b59c05a37e9#876ec5a8a074ba83cce2129ed4d76b59c05a37e9" -dependencies = [ - "collections", + "gpui_collections", "serde", "serde_json", ] @@ -4413,6 +4598,16 @@ version = "0.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "e8cf8e6a8aa66ce33f63993ffc4ea4271eb5b0530a9002db8455ea6050c77bfa" +[[package]] +name = "pretty_assertions" +version = "1.4.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3ae130e2f271fbc2ac3a40fb1d07180839cdbbe443c7a27e1e3c13c5cac0116d" +dependencies = [ + "diff", + "yansi", +] + [[package]] name = "prettyplease" version = "0.2.37" @@ -4462,15 +4657,16 @@ dependencies = [ [[package]] name = "proptest" -version = "1.10.0" -source = "git+https://github.com/proptest-rs/proptest?rev=3dca198a8fef1b32e3a66f1e1897c955b4dc5b5b#3dca198a8fef1b32e3a66f1e1897c955b4dc5b5b" +version = "1.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4b45fcc2344c680f5025fe57779faef368840d0bd1f42f216291f0dc4ace4744" dependencies = [ "bit-set 0.8.0", "bit-vec 0.8.0", "bitflags 2.13.0", "num-traits", "proptest-macro", - "rand 0.9.4", + "rand 0.9.5", "rand_chacha 0.9.0", "rand_xorshift", "regex-syntax", @@ -4482,7 +4678,8 @@ dependencies = [ [[package]] name = "proptest-macro" version = "0.5.0" -source = "git+https://github.com/proptest-rs/proptest?rev=3dca198a8fef1b32e3a66f1e1897c955b4dc5b5b#3dca198a8fef1b32e3a66f1e1897c955b4dc5b5b" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "efaa288b896cb2b345da7b7f2110ab19e51565b83495b56fcec98a62f8b1f33e" dependencies = [ "convert_case 0.11.0", "proc-macro2", @@ -4501,10 +4698,33 @@ dependencies = [ ] [[package]] -name = "pxfm" -version = "0.1.29" +name = "pulp" +version = "0.22.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e0c5ccf5294c6ccd63a74f1565028353830a9c2f5eb0c682c355c471726a6e3f" +checksum = "046aa45b989642ec2e4717c8e72d677b13edd831a4d3b6cf37d9a3e54912496a" +dependencies = [ + "bytemuck", + "cfg-if", + "libm", + "num-complex", + "paste", + "pulp-wasm-simd-flag", + "raw-cpuid", + "reborrow", + "version_check", +] + +[[package]] +name = "pulp-wasm-simd-flag" +version = "0.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "1d8f70e07b9c3962945a74e59ca1c511bba65b6419468acc217c457d93f3c740" + +[[package]] +name = "pxfm" +version = "0.1.30" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d55d956fa96f5ec02be2e13af0e20391a5aa83d6a074e3ad368959d0fab299ea" [[package]] name = "qoi" @@ -4543,7 +4763,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "cdcc8dd4e2f670d309a5f0e83fe36dfdc05af317008fea29144da1a2ac858e5e" dependencies = [ "memchr", - "serde", ] [[package]] @@ -4569,9 +4788,9 @@ checksum = "f8dcc9c7d52a811697d2151c701e0d08956f92b0e24136cf4cf27b57a6a0d9bf" [[package]] name = "rand" -version = "0.8.6" +version = "0.8.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5ca0ecfa931c29007047d1bc58e623ab12e5590e8c7cc53200d5202b69266d8a" +checksum = "22f6172bdec972074665ed81ed53b71da00bfc44b65a753cfde883ec4c702a1a" dependencies = [ "libc", "rand_chacha 0.3.1", @@ -4580,9 +4799,9 @@ dependencies = [ [[package]] name = "rand" -version = "0.9.4" +version = "0.9.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "44c5af06bb1b7d3216d91932aed5265164bf384dc89cd6ba05cf59a35f5f76ea" +checksum = "b9ef1d0d795eb7d84685bca4f72f3649f064e6641543d3a8c415898726a57b41" dependencies = [ "rand_chacha 0.9.0", "rand_core 0.9.5", @@ -4674,7 +4893,7 @@ dependencies = [ "num-traits", "paste", "profiling", - "rand 0.9.4", + "rand 0.9.5", "rand_chacha 0.9.0", "simd_helpers", "thiserror 2.0.18", @@ -4697,6 +4916,15 @@ dependencies = [ "rgb", ] +[[package]] +name = "raw-cpuid" +version = "11.6.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "498cd0dc59d73224351ee52a95fee0f1a617a2eae0e7d9d720cc622c73a54186" +dependencies = [ + "bitflags 2.13.0", +] + [[package]] name = "raw-window-handle" version = "0.6.2" @@ -4756,6 +4984,12 @@ dependencies = [ "font-types", ] +[[package]] +name = "reborrow" +version = "0.5.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "03251193000f4bd3b042892be858ee50e8b3719f2b08e5833ac4353724632430" + [[package]] name = "redox_syscall" version = "0.5.18" @@ -4765,6 +4999,17 @@ dependencies = [ "bitflags 2.13.0", ] +[[package]] +name = "redox_users" +version = "0.4.6" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ba009ff324d1fc1b900bd1fdb31564febe58a8ccc8a6fdbb93b543d33b13ca43" +dependencies = [ + "getrandom 0.2.17", + "libredox", + "thiserror 1.0.69", +] + [[package]] name = "redox_users" version = "0.5.2" @@ -4796,19 +5041,11 @@ dependencies = [ "syn", ] -[[package]] -name = "refineable" -version = "0.1.0" -source = "git+https://github.com/zed-industries/zed?rev=876ec5a8a074ba83cce2129ed4d76b59c05a37e9#876ec5a8a074ba83cce2129ed4d76b59c05a37e9" -dependencies = [ - "derive_refineable", -] - [[package]] name = "regex" -version = "1.12.4" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1292b7759ae1cb9ec195452d1390a074f0cd8541ab7a5a8c31cd6db45d4a6ba" +checksum = "2a0e75113e14dc5acb068cd0786884f214f1312650a3d36d269f5c4f3cdee8a2" dependencies = [ "aho-corasick", "memchr", @@ -4818,9 +5055,9 @@ dependencies = [ [[package]] name = "regex-automata" -version = "0.4.14" +version = "0.4.15" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6e1dd4122fc1595e8162618945476892eefca7b88c52820e74af6262213cae8f" +checksum = "1f388202e4b80542a0921078cc23b6333bcf1409c1e3f86404cae4766a6131db" dependencies = [ "aho-corasick", "memchr", @@ -4873,9 +5110,9 @@ checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" [[package]] name = "rust-embed" -version = "8.11.0" +version = "8.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "04113cb9355a377d83f06ef1f0a45b8ab8cd7d8b1288160717d66df5c7988d27" +checksum = "e9e7760e252aaba7b09f4be00e36476cf585bdb68a53552ac954cdf504ab4bc9" dependencies = [ "rust-embed-impl", "rust-embed-utils", @@ -4884,10 +5121,11 @@ dependencies = [ [[package]] name = "rust-embed-impl" -version = "8.11.0" +version = "8.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da0902e4c7c8e997159ab384e6d0fc91c221375f6894346ae107f47dd0f3ccaa" +checksum = "3bcfc4d6f53af43755f7a723e4b6b8794fcce052a178dd8c6c1dadc5f5343097" dependencies = [ + "mime_guess", "proc-macro2", "quote", "rust-embed-utils", @@ -4897,20 +5135,20 @@ dependencies = [ [[package]] name = "rust-embed-utils" -version = "8.11.0" +version = "8.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5bcdef0be6fe7f6fa333b1073c949729274b05f123a0ad7efcb8efd878e5c3b1" +checksum = "42ffa149f6aa81b58a5b3011d01a857c4ed12c7a732d2c51947a4c7c692185f0" dependencies = [ "globset", - "sha2", + "sha2 0.11.0", "walkdir", ] [[package]] name = "rustc-demangle" -version = "0.1.27" +version = "0.1.28" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b50b8869d9fc858ce7266cce0194bd74df58b9d0e3f6df3a9fc8eb470d95c09d" +checksum = "b74b56ffa8bb2830709a538c2cbcae9aa062db0d2a42563bfb09bdaae44020eb" [[package]] name = "rustc-hash" @@ -4961,9 +5199,9 @@ dependencies = [ [[package]] name = "rustversion" -version = "1.0.22" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b39cdef0fa800fc44525c84ccb54a029961a8215f9619753635a9c0d2538d46d" +checksum = "cf54715a573b99ac80df0bc206da022bcd442c974952c7b9720069370852e21f" [[package]] name = "rusty-fork" @@ -5010,21 +5248,6 @@ dependencies = [ "winapi-util", ] -[[package]] -name = "scheduler" -version = "0.1.0" -source = "git+https://github.com/zed-industries/zed?rev=876ec5a8a074ba83cce2129ed4d76b59c05a37e9#876ec5a8a074ba83cce2129ed4d76b59c05a37e9" -dependencies = [ - "async-task", - "backtrace", - "chrono", - "flume", - "futures", - "parking_lot", - "rand 0.9.4", - "web-time", -] - [[package]] name = "schemars" version = "1.2.1" @@ -5237,17 +5460,19 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a7507d819769d01a365ab707794a4084392c824f54a7a6a7862f8c3d0892b283" dependencies = [ "cfg-if", - "cpufeatures", - "digest", + "cpufeatures 0.2.17", + "digest 0.10.7", ] [[package]] -name = "sharded-slab" -version = "0.1.7" +name = "sha2" +version = "0.11.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f40ca3c46823713e0d4209592e8d6e826aa57e928f09752619fc696c499637f6" +checksum = "446ba717509524cb3f22f17ecc096f10f4822d76ab5c0b9822c5f9c284e825f4" dependencies = [ - "lazy_static", + "cfg-if", + "cpufeatures 0.3.0", + "digest 0.11.3", ] [[package]] @@ -5372,18 +5597,18 @@ dependencies = [ [[package]] name = "spin" -version = "0.9.8" +version = "0.9.9" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "6980e8d7511241f8acf4aebddbb1ff938df5eebe98691418c4468d0b72a96a67" +checksum = "3763264f6b73151db08c50ff20d7d8a0b8796e021cdea7ceedad07b80155fa0e" dependencies = [ "lock_api", ] [[package]] name = "spin" -version = "0.10.0" +version = "0.10.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d5fe4ccb98d9c292d56fec89a5e07da7fc4cf0dc11e156b41793132775d3e591" +checksum = "023a211cb3138dbc438680b32560ad89f699977624c9f8dbb95a47d5b4c07dd3" dependencies = [ "lock_api", ] @@ -5479,18 +5704,6 @@ version = "2.6.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "13c2bddecc57b384dee18652358fb23172facb8a2c51ccc10d74c157bdea3292" -[[package]] -name = "sum_tree" -version = "0.1.0" -source = "git+https://github.com/zed-industries/zed?rev=876ec5a8a074ba83cce2129ed4d76b59c05a37e9#876ec5a8a074ba83cce2129ed4d76b59c05a37e9" -dependencies = [ - "heapless", - "log", - "rayon", - "tracing", - "ztracing", -] - [[package]] name = "sval" version = "2.20.0" @@ -5744,15 +5957,6 @@ dependencies = [ "syn", ] -[[package]] -name = "thread_local" -version = "1.1.9" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f60246a4944f24f6e018aa17cdeffb7818b76356965d03b07d6a9886e8962185" -dependencies = [ - "cfg-if", -] - [[package]] name = "tiff" version = "0.11.3" @@ -5824,9 +6028,9 @@ dependencies = [ [[package]] name = "tinyvec" -version = "1.11.0" +version = "1.12.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3e61e67053d25a4e82c844e8424039d9745781b3fc4f32b8d55ed50f5f667ef3" +checksum = "bb4ebadaa0af04fab11ae01eb5f9fdb5f9c5b875506e210e71c07873528baa7f" dependencies = [ "tinyvec_macros", ] @@ -5870,7 +6074,7 @@ dependencies = [ "toml_datetime 1.1.1+spec-1.1.0", "toml_parser", "toml_writer", - "winnow 1.0.3", + "winnow 1.0.4", ] [[package]] @@ -5914,7 +6118,7 @@ dependencies = [ "indexmap", "toml_datetime 1.1.1+spec-1.1.0", "toml_parser", - "winnow 1.0.3", + "winnow 1.0.4", ] [[package]] @@ -5923,7 +6127,7 @@ version = "1.1.2+spec-1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a2abe9b86193656635d2411dc43050282ca48aa31c2451210f4202550afb7526" dependencies = [ - "winnow 1.0.3", + "winnow 1.0.4", ] [[package]] @@ -5968,32 +6172,6 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "db97caf9d906fbde555dd62fa95ddba9eecfd14cb388e4f491a66d74cd5fb79a" dependencies = [ "once_cell", - "valuable", -] - -[[package]] -name = "tracing-log" -version = "0.2.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ee855f1f400bd0e5c02d150ae5de3840039a3f54b025156404e34c23c03f47c3" -dependencies = [ - "log", - "once_cell", - "tracing-core", -] - -[[package]] -name = "tracing-subscriber" -version = "0.3.23" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cb7f578e5945fb242538965c2d0b04418d38ec25c79d160cd279bf0731c8d319" -dependencies = [ - "nu-ansi-term", - "sharded-slab", - "smallvec", - "thread_local", - "tracing-core", - "tracing-log", ] [[package]] @@ -6163,60 +6341,11 @@ version = "0.2.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06abde3611657adf66d383f00b093d7faecc7fa57071cce2578660c9f1010821" -[[package]] -name = "util" -version = "0.1.0" -source = "git+https://github.com/zed-industries/zed?rev=876ec5a8a074ba83cce2129ed4d76b59c05a37e9#876ec5a8a074ba83cce2129ed4d76b59c05a37e9" -dependencies = [ - "anyhow", - "async-fs", - "async_zip", - "collections", - "command-fds", - "dirs", - "dunce", - "futures", - "futures-lite 1.13.0", - "globset", - "gpui_util", - "itertools 0.14.0", - "libc", - "log", - "mach2", - "nix 0.29.0", - "percent-encoding", - "regex", - "rust-embed", - "schemars", - "serde", - "serde_json", - "serde_json_lenient", - "shlex 1.3.0", - "smol", - "take-until", - "tempfile", - "tendril", - "unicase", - "url", - "walkdir", - "which", -] - -[[package]] -name = "util_macros" -version = "0.1.0" -source = "git+https://github.com/zed-industries/zed?rev=876ec5a8a074ba83cce2129ed4d76b59c05a37e9#876ec5a8a074ba83cce2129ed4d76b59c05a37e9" -dependencies = [ - "perf 0.1.0 (git+https://github.com/zed-industries/zed?rev=876ec5a8a074ba83cce2129ed4d76b59c05a37e9)", - "quote", - "syn", -] - [[package]] name = "uuid" -version = "1.23.4" +version = "1.23.5" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "bf80a72845275afea99e7f2b434723d3bc7e38470fcd1c7ed39a599c73319a53" +checksum = "ea5fab0d6c3c01ae70085a09cb03d4c7a1d6314e2b3e075392783396d724ca0a" dependencies = [ "getrandom 0.4.3", "js-sys", @@ -6236,17 +6365,11 @@ dependencies = [ "wasm-bindgen", ] -[[package]] -name = "valuable" -version = "0.1.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ba73ea9cf16a25df0c8caa16c51acb937d5712a8429db78a3ee29d5dcacd3a65" - [[package]] name = "value-bag" -version = "1.12.0" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7ba6f5989077681266825251a52748b8c1d8a4ad098cc37e440103d0ea717fc0" +checksum = "5dd4ec1eb1d240636e354a30110a1dfcb37047169a4d9bd6d9d3469df574b5c4" dependencies = [ "value-bag-serde1", "value-bag-sval2", @@ -6254,9 +6377,9 @@ dependencies = [ [[package]] name = "value-bag-serde1" -version = "1.12.0" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "16530907bfe2999a1773ca5900a65101e092c70f642f25cc23ca0c43573262c5" +checksum = "2a8e44fd7ce9cf838a1e2dad56d2d83f2b2435ae1df9cb3cac31e759e455e88d" dependencies = [ "erased-serde", "serde_core", @@ -6265,9 +6388,9 @@ dependencies = [ [[package]] name = "value-bag-sval2" -version = "1.12.0" +version = "1.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d00ae130edd690eaa877e4f40605d534790d1cf1d651e7685bd6a144521b251f" +checksum = "3f9f1705b87b798b06a8d7a51f44ed0626eee413991555e8edfd3562b35a130d" dependencies = [ "sval", "sval_buffer", @@ -6278,6 +6401,12 @@ dependencies = [ "sval_serde", ] +[[package]] +name = "vcpkg" +version = "0.2.15" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "accd4ea62f7bb7a82fe23066fb0957d48ef677f6eeb8215f372f52e48bb32426" + [[package]] name = "version_check" version = "0.9.5" @@ -6537,8 +6666,9 @@ checksum = "a28ac98ddc8b9274cb41bb4d9d4d5c425b6020c50c46f25559911905610b4a88" [[package]] name = "wgpu" -version = "29.0.3" -source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "76e8840e1ba2881d4cbb18d2147627a56af426ff064c0401eb0c8410c6325d07" dependencies = [ "arrayvec", "bitflags 2.13.0", @@ -6566,8 +6696,9 @@ dependencies = [ [[package]] name = "wgpu-core" -version = "29.0.3" -source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2f519832254e56965a9940c4af57dcb75f702b6f6fa4a0b172f685395843a4d7" dependencies = [ "arrayvec", "bit-set 0.9.1", @@ -6598,32 +6729,36 @@ dependencies = [ [[package]] name = "wgpu-core-deps-apple" -version = "29.0.3" -source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "f5e39e26c4c0e07589e67d18546cf79ff45383659fc72fca4dd293358a0347f3" dependencies = [ "wgpu-hal", ] [[package]] name = "wgpu-core-deps-emscripten" -version = "29.0.3" -source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "01e09be551dc939498bdd5f6b2c66e55ab275dad25825267a08605a80fc9f0af" dependencies = [ "wgpu-hal", ] [[package]] name = "wgpu-core-deps-windows-linux-android" -version = "29.0.3" -source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "4e592c1bbef6ad047647ae6e666ebd8cee7a32bb4544d9700ec96cbf73230257" dependencies = [ "wgpu-hal", ] [[package]] name = "wgpu-hal" -version = "29.0.3" -source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "97ace1c17727311c22a46e4e3faf56ea6de81af99dcc839bdfb54857b94d448d" dependencies = [ "android_system_properties", "arrayvec", @@ -6675,8 +6810,9 @@ dependencies = [ [[package]] name = "wgpu-naga-bridge" -version = "29.0.3" -source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "95226013f547544b223281cd16a4fb549aa9dcb562adbda0faae4c73ffbbc161" dependencies = [ "naga", "wgpu-types", @@ -6684,8 +6820,9 @@ dependencies = [ [[package]] name = "wgpu-types" -version = "29.0.3" -source = "git+https://github.com/zed-industries/wgpu.git?rev=357a0c56e0070480ad9daea5d2eaa83150b79e88#357a0c56e0070480ad9daea5d2eaa83150b79e88" +version = "29.0.4" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "84bf84cd9ca8ca45e2b223a3868f1adf9bfc0c66aeac212e76ee7e40fdadf8f5" dependencies = [ "bitflags 2.13.0", "bytemuck", @@ -6745,7 +6882,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "12342cb4d8e3b046f3d80effd474a7a02447231330ef77d71daa6fbc40681143" dependencies = [ "windows-core 0.57.0", - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -6813,7 +6950,7 @@ dependencies = [ "windows-implement 0.57.0", "windows-interface 0.57.0", "windows-result 0.1.2", - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -6957,7 +7094,7 @@ version = "0.1.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5e383302e8ec8515204254685643de10811af0ed97ea37210dc26fb0032647f8" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -6996,13 +7133,22 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-sys" +version = "0.48.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "677d2418bec65e3338edb076e806bc1ec15693c5d0104683f2efe857f61056a9" +dependencies = [ + "windows-targets 0.48.5", +] + [[package]] name = "windows-sys" version = "0.59.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1e38bc4d79ed67fd075bcc251a1c39b32a1776bbe92e5bef1f0bf1f8c531853b" dependencies = [ - "windows-targets", + "windows-targets 0.52.6", ] [[package]] @@ -7014,20 +7160,35 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows-targets" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9a2fa6e2155d7247be68c096456083145c183cbbbc2764150dda45a87197940c" +dependencies = [ + "windows_aarch64_gnullvm 0.48.5", + "windows_aarch64_msvc 0.48.5", + "windows_i686_gnu 0.48.5", + "windows_i686_msvc 0.48.5", + "windows_x86_64_gnu 0.48.5", + "windows_x86_64_gnullvm 0.48.5", + "windows_x86_64_msvc 0.48.5", +] + [[package]] name = "windows-targets" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9b724f72796e036ab90c1021d4780d4d3d648aca59e491e6b98e725b84e99973" dependencies = [ - "windows_aarch64_gnullvm", - "windows_aarch64_msvc", - "windows_i686_gnu", + "windows_aarch64_gnullvm 0.52.6", + "windows_aarch64_msvc 0.52.6", + "windows_i686_gnu 0.52.6", "windows_i686_gnullvm", - "windows_i686_msvc", - "windows_x86_64_gnu", - "windows_x86_64_gnullvm", - "windows_x86_64_msvc", + "windows_i686_msvc 0.52.6", + "windows_x86_64_gnu 0.52.6", + "windows_x86_64_gnullvm 0.52.6", + "windows_x86_64_msvc 0.52.6", ] [[package]] @@ -7048,18 +7209,36 @@ dependencies = [ "windows-link 0.2.1", ] +[[package]] +name = "windows_aarch64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2b38e32f0abccf9987a4e3079dfb67dcd799fb61361e53e2882c3cbaf0d905d8" + [[package]] name = "windows_aarch64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "32a4622180e7a0ec044bb555404c800bc9fd9ec262ec147edd5989ccd0c02cd3" +[[package]] +name = "windows_aarch64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "dc35310971f3b2dbbf3f0690a219f40e2d9afcf64f9ab7cc1be722937c26b4bc" + [[package]] name = "windows_aarch64_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09ec2a7bb152e2252b53fa7803150007879548bc709c039df7627cabbd05d469" +[[package]] +name = "windows_i686_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a75915e7def60c94dcef72200b9a8e58e5091744960da64ec734a6c6e9b3743e" + [[package]] name = "windows_i686_gnu" version = "0.52.6" @@ -7072,24 +7251,48 @@ version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0eee52d38c090b3caa76c563b86c3a4bd71ef1a819287c19d586d7334ae8ed66" +[[package]] +name = "windows_i686_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "8f55c233f70c4b27f66c523580f78f1004e8b5a8b659e05a4eb49d4166cca406" + [[package]] name = "windows_i686_msvc" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "240948bc05c5e7c6dabba28bf89d89ffce3e303022809e73deaefe4f6ec56c66" +[[package]] +name = "windows_x86_64_gnu" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "53d40abd2583d23e4718fddf1ebec84dbff8381c07cae67ff7768bbf19c6718e" + [[package]] name = "windows_x86_64_gnu" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "147a5c80aabfbf0c7d901cb5895d1de30ef2907eb21fbbab29ca94c5b08b1a78" +[[package]] +name = "windows_x86_64_gnullvm" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0b7b52767868a23d5bab768e390dc5f5c55825b6d30b86c844ff2dc7414044cc" + [[package]] name = "windows_x86_64_gnullvm" version = "0.52.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "24d5b23dc417412679681396f2b49f3de8c1473deb516bd34410872eff51ed0d" +[[package]] +name = "windows_x86_64_msvc" +version = "0.48.5" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ed94fce61571a4006852b7389a063ab983c02eb1bb37b47f8272ce92d06d9538" + [[package]] name = "windows_x86_64_msvc" version = "0.52.6" @@ -7107,9 +7310,9 @@ dependencies = [ [[package]] name = "winnow" -version = "1.0.3" +version = "1.0.4" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0592e1c9d151f854e6fd382574c3a0855250e1d9b2f99d9281c6e6391af352f1" +checksum = "23b97319f7b8343df12cc98938e5c3eb436064524c8d2b4e30a1d3a36eecdf81" dependencies = [ "memchr", ] @@ -7212,15 +7415,17 @@ checksum = "bec9e4a500ca8864c5b47b8b482a73d62e4237670e5b5f1d6b9e3cae50f28f2b" [[package]] name = "xim-ctext" version = "0.3.0" -source = "git+https://github.com/zed-industries/xim-rs.git?rev=16f35a2c881b815a2b6cdfd6687988e84f8447d8#16f35a2c881b815a2b6cdfd6687988e84f8447d8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2ac61a7062c40f3c37b6e82eeeef835d5cc7824b632a72784a89b3963c33284c" dependencies = [ "encoding_rs", ] [[package]] name = "xim-parser" -version = "0.2.1" -source = "git+https://github.com/zed-industries/xim-rs.git?rev=16f35a2c881b815a2b6cdfd6687988e84f8447d8#16f35a2c881b815a2b6cdfd6687988e84f8447d8" +version = "0.2.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5dcee45f89572d5a65180af3a84e7ddb24f5ea690a6d3aa9de231281544dd7b7" dependencies = [ "bitflags 2.13.0", ] @@ -7261,6 +7466,12 @@ version = "0.8.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7a5a4b21e1a62b67a2970e6831bc091d7b87e119e7f9791aef9702e3bef04448" +[[package]] +name = "yansi" +version = "1.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "cfe53a6657fd280eaa890a3bc59152892ffa3e30101319d168b781ed6529b049" + [[package]] name = "yazi" version = "0.2.1" @@ -7303,9 +7514,9 @@ dependencies = [ [[package]] name = "zbus" -version = "5.16.0" +version = "5.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "eee682d202a77e4a9f3b2c2bdf48a7b28af5c08c34ddf66f98c93e5e39464285" +checksum = "a28b97f866896a4be7aefd2b5a8e01bb6773d19a775d54ab28b4d094b9a4480e" dependencies = [ "async-broadcast", "async-executor", @@ -7330,7 +7541,7 @@ dependencies = [ "uds_windows", "uuid", "windows-sys 0.61.2", - "winnow 1.0.3", + "winnow 1.0.4", "zbus_macros", "zbus_names", "zvariant", @@ -7362,9 +7573,9 @@ dependencies = [ [[package]] name = "zbus_macros" -version = "5.16.0" +version = "5.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "adf1bd45a81a103745b1757754762a26e8cd01e4532e4d6c8ec431624b80d1d6" +checksum = "5e05ad887425eecf5e8384dc2406a4a9313eb73468712fc1cdea362eb4fe0469" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -7377,23 +7588,23 @@ dependencies = [ [[package]] name = "zbus_names" -version = "4.3.2" +version = "4.3.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7074f3e50b894eac91750142016d30d0a89be8e67dbfd9704fb875825760e52d" +checksum = "1039ca249fee9559680f3a9f05b55e0761fee51af4f6c1e7d8c1f31e549721d2" dependencies = [ "serde", - "winnow 1.0.3", + "winnow 1.0.4", "zvariant", ] [[package]] name = "zbus_xml" -version = "5.1.1" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a8067892e940ed1727dea64690378601603b31d62dfde019a5335fbb7c0e0ed9" +checksum = "59ab0513c0a66a60a8718d5ad712a5094845a20d95b5c1c81e2bd8e904a52b4f" dependencies = [ - "quick-xml 0.39.4", "serde", + "winnow 1.0.4", "zbus_names", "zvariant", ] @@ -7401,14 +7612,15 @@ dependencies = [ [[package]] name = "zed-font-kit" version = "0.14.1-zed" -source = "git+https://github.com/zed-industries/font-kit?rev=94b0f28166665e8fd2f53ff6d268a14955c82269#94b0f28166665e8fd2f53ff6d268a14955c82269" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "a3898e450f36f852edda72e3f985c34426042c4951790b23b107f93394f9bff5" dependencies = [ "bitflags 2.13.0", "byteorder", "core-foundation 0.10.0", "core-graphics 0.24.0", "core-text", - "dirs", + "dirs 5.0.1", "dwrote", "float-ord", "freetype-sys", @@ -7425,14 +7637,15 @@ dependencies = [ [[package]] name = "zed-scap" version = "0.0.8-zed" -source = "git+https://github.com/zed-industries/scap?rev=4afea48c3b002197176fb19cd0f9b180dd36eaac#4afea48c3b002197176fb19cd0f9b180dd36eaac" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "b6b338d705ae33a43ca00287c11129303a7a0aa57b101b72a1c08c863f698ac8" dependencies = [ "anyhow", "cocoa 0.25.0", "core-graphics-helmer-fork", "log", "objc", - "rand 0.8.6", + "rand 0.8.7", "screencapturekit", "screencapturekit-sys", "sysinfo", @@ -7446,7 +7659,8 @@ dependencies = [ [[package]] name = "zed-xim" version = "0.4.0-zed" -source = "git+https://github.com/zed-industries/xim-rs.git?rev=16f35a2c881b815a2b6cdfd6687988e84f8447d8#16f35a2c881b815a2b6cdfd6687988e84f8447d8" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0c0b46ed118eba34d9ba53d94ddc0b665e0e06a2cf874cfa2dd5dec278148642" dependencies = [ "ahash", "hashbrown 0.14.5", @@ -7464,18 +7678,18 @@ checksum = "6df3dc4292935e51816d896edcd52aa30bc297907c26167fec31e2b0c6a32524" [[package]] name = "zerocopy" -version = "0.8.52" +version = "0.8.54" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "ce1022995ff5ff5d841ad7d994facc23098cd40152f2c1d11cd607c6f530653f" +checksum = "b7cbbc0a705a0fd05cc3676525980d2bf5a9bc4adac6d6475209a7887cf59d19" dependencies = [ "zerocopy-derive", ] [[package]] name = "zerocopy-derive" -version = "0.8.52" +version = "0.8.54" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ae7f38b72ec2a254e2b87ef277cf2cd4fb97cbebf944faa6f33354da0867930" +checksum = "e2e817b7b52d0c7358d3246da9d69935ebb18116b2b102b4230dac079b4862f5" dependencies = [ "proc-macro2", "quote", @@ -7556,38 +7770,11 @@ dependencies = [ "syn", ] -[[package]] -name = "zlog" -version = "0.1.0" -source = "git+https://github.com/zed-industries/zed?rev=876ec5a8a074ba83cce2129ed4d76b59c05a37e9#876ec5a8a074ba83cce2129ed4d76b59c05a37e9" -dependencies = [ - "anyhow", - "chrono", - "collections", - "log", -] - [[package]] name = "zmij" -version = "1.0.21" +version = "1.0.23" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b8848ee67ecc8aedbaf3e4122217aff892639231befc6a1b58d29fff4c2cabaa" - -[[package]] -name = "ztracing" -version = "0.1.0" -source = "git+https://github.com/zed-industries/zed?rev=876ec5a8a074ba83cce2129ed4d76b59c05a37e9#876ec5a8a074ba83cce2129ed4d76b59c05a37e9" -dependencies = [ - "tracing", - "tracing-subscriber", - "zlog", - "ztracing_macro", -] - -[[package]] -name = "ztracing_macro" -version = "0.1.0" -source = "git+https://github.com/zed-industries/zed?rev=876ec5a8a074ba83cce2129ed4d76b59c05a37e9#876ec5a8a074ba83cce2129ed4d76b59c05a37e9" +checksum = "29666d0abbfad1e3dc4dcf6144730dd3a3ab225bbbdac83319345b1b44ccfc1b" [[package]] name = "zune-core" @@ -7630,24 +7817,24 @@ dependencies = [ [[package]] name = "zvariant" -version = "5.12.0" +version = "5.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a192a0bde63360d77a7523c833d4b4ce6070a927e2c53246e4c540b1a3e27be0" +checksum = "7cf057bb00bf5c9ad77abb6147b0ca4818236a1858416e9d988e40d6322fefa7" dependencies = [ "endi", "enumflags2", "serde", "serde_bytes", - "winnow 1.0.3", + "winnow 1.0.4", "zvariant_derive", "zvariant_utils", ] [[package]] name = "zvariant_derive" -version = "5.12.0" +version = "5.13.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "90bc6cde9c01c511074be97f7ccb6c19d0da89e3f8662e812e999dcfd4638737" +checksum = "8118ca6bda77bfc0ab51d660db0c955f2505eef854c9a449435bccb616933b31" dependencies = [ "proc-macro-crate", "proc-macro2", @@ -7658,13 +7845,13 @@ dependencies = [ [[package]] name = "zvariant_utils" -version = "3.4.0" +version = "3.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e8535915cfa75547e559d8c68e8139909a4aeee076831e4ef7fc59d8172c4d6" +checksum = "90cb9383f9b45290407a1258b202d3f8f01db719eb60b4e4055c6375af4fc7c7" dependencies = [ "proc-macro2", "quote", "serde", "syn", - "winnow 1.0.3", + "winnow 1.0.4", ] diff --git a/Cargo.toml b/Cargo.toml index d753f97430..0e9ade530a 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -11,6 +11,14 @@ members = [ "./crates/gpui_platform/", "./crates/gpui_shared_string/", "./crates/gpui_elements/", + "./crates/gpui_collections/", + "./crates/gpui_refineable/", + "./crates/gpui_derive_refineable/", + "./crates/gpui_scheduler/", + "./crates/gpui_sum_tree/", + "./crates/gpui_media/", + "./crates/gpui_zed_util/", + "./crates/gpui_ce_util/", "./tooling/perf/", ] default-members = ["./crates/gpui/"] @@ -33,7 +41,7 @@ accesskit_windows = "0.32.1" anyhow = "1.0.86" backtrace = "0.3" bitflags = "2.6.0" -collections = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9", version = "0.1.0" } +collections = { path = "crates/gpui_collections", version = "0.2.2", package = "gpui_collections" } ctor = "1.0.6" derive_more = { version = "2.1.1", features = [ "add", @@ -55,16 +63,13 @@ itertools = "0.14.0" log = { version = "0.4.16", features = ["kv_unstable_serde", "serde"] } parking_lot = "0.12.1" postage = { version = "0.5", features = ["futures-traits"] } -proptest = { git = "https://github.com/proptest-rs/proptest", rev = "3dca198a8fef1b32e3a66f1e1897c955b4dc5b5b", features = [ - "attr-macro", -] } +proptest = { version = "1.10", features = ["attr-macro"] } chrono = { version = "0.4", features = ["serde"] } profiling = "1" rand = "0.9.4" regex = "1.5" -refineable = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9" } -scheduler = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9" } -util_macros = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9" } +refineable = { path = "crates/gpui_refineable", version = "0.2.2", package = "gpui_refineable" } +scheduler = { path = "crates/gpui_scheduler", version = "0.2.2", package = "gpui_scheduler" } schemars = { version = "1.0", features = ["indexmap2"] } serde = { version = "1.0.221", features = ["derive", "rc"] } serde_json = { version = "1.0.144", features = ["preserve_order", "raw_value"] } @@ -73,7 +78,7 @@ smallvec = { version = "1.6", features = ["union", "const_new"] } async-channel = "2.5.0" stacksafe = "1.0" strum = { version = "0.27.2", features = ["derive"] } -sum_tree = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9" } +sum_tree = { path = "crates/gpui_sum_tree", version = "0.2.2", package = "gpui_sum_tree" } thiserror = "2.0.12" hdrhistogram = "7" pollster = "0.4.0" @@ -85,11 +90,11 @@ cocoa-foundation = "=0.2.0" core-foundation = "=0.10.0" core-foundation-sys = "0.8.6" core-video = { version = "0.5.2", features = ["metal"] } -media = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9" } +media = { path = "crates/gpui_media", version = "0.2.2", package = "gpui_media" } objc = "0.2" mach2 = "0.5" metal = "0.33" -scap = { git = "https://github.com/zed-industries/scap", rev = "4afea48c3b002197176fb19cd0f9b180dd36eaac", default-features = false, package = "zed-scap", version = "0.0.8-zed" } +scap = { version = "0.0.8-zed", package = "zed-scap", default-features = false } env_logger = "0.11" unicode-segmentation = "1.10" @@ -108,8 +113,8 @@ ashpd = { version = "0.13", default-features = false, features = [ ] } libc = "0.2" smol = "2.0" -util = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9" } -wgpu = { git = "https://github.com/zed-industries/wgpu.git", rev = "357a0c56e0070480ad9daea5d2eaa83150b79e88" } +util = { path = "crates/gpui_zed_util", version = "0.2.2", package = "gpui_zed_util" } +wgpu = "29.0.3" criterion = { version = "0.5", features = ["html_reports"] } objc2-app-kit = { version = "0.3", default-features = false, features = [ "NSGraphics", @@ -117,20 +122,20 @@ objc2-app-kit = { version = "0.3", default-features = false, features = [ semver = { version = "1.0", features = ["serde"] } windows-core = "0.61" tokio = { version = "1" } -gpui_util = { git = "https://github.com/zed-industries/zed", rev = "876ec5a8a074ba83cce2129ed4d76b59c05a37e9" } +gpui_util = { path = "crates/gpui_ce_util", version = "0.2.2", package = "gpui_ce_util" } -gpui = { path = "./crates/gpui/" } -gpui_platform = { path = "./crates/gpui_platform/" } -gpui_linux = { path = "./crates/gpui_linux/" } -gpui_macos = { path = "./crates/gpui_macos/" } -gpui_windows = { path = "./crates/gpui_windows/" } -gpui_web = { path = "./crates/gpui_web/" } +gpui = { path = "./crates/gpui/", version = "0.2.2" } +gpui_platform = { path = "./crates/gpui_platform/", version = "0.1.0" } +gpui_linux = { path = "./crates/gpui_linux/", version = "0.1.0" } +gpui_macos = { path = "./crates/gpui_macos/", version = "0.1.0" } +gpui_windows = { path = "./crates/gpui_windows/", version = "0.1.0" } +gpui_web = { path = "./crates/gpui_web/", version = "0.1.0" } -gpui_wgpu = { path = "./crates/gpui_wgpu/" } +gpui_wgpu = { path = "./crates/gpui_wgpu/", version = "0.1.0" } -gpui_macros = { path = "./crates/gpui_macros/" } -gpui_shared_string = { path = "./crates/gpui_shared_string/" } -gpui_tokio = { path = "./crates/gpui_tokio/" } +gpui_macros = { path = "./crates/gpui_macros/", version = "0.1.0" } +gpui_shared_string = { path = "./crates/gpui_shared_string/", version = "0.1.0" } +gpui_tokio = { path = "./crates/gpui_tokio/", version = "0.1.0" } [workspace.dependencies.windows] version = "0.61" diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.toml index ef5f5b1c4b..95454317d6 100644 --- a/crates/gpui/Cargo.toml +++ b/crates/gpui/Cargo.toml @@ -77,7 +77,6 @@ resvg = { version = "0.45.0", default-features = false, features = [ ] } usvg = { version = "0.45.0", default-features = false } ttf-parser = "0.25" -util_macros.workspace = true schemars.workspace = true seahash = "4.1" serde.workspace = true @@ -115,8 +114,7 @@ core-foundation-sys.workspace = true core-graphics = "0.24" core-video.workspace = true core-text = "21" -# WARNING: If you change this, you must also publish a new version of zed-font-kit to crates.io -font-kit = { git = "https://github.com/zed-industries/font-kit", rev = "94b0f28166665e8fd2f53ff6d268a14955c82269", package = "zed-font-kit", version = "0.14.1-zed", optional = true } +font-kit = { version = "0.14.1-zed", package = "zed-font-kit", optional = true } foreign-types = "0.5" log.workspace = true media.workspace = true diff --git a/crates/gpui/examples/legacy/hello_world.rs b/crates/gpui/examples/legacy/hello_world.rs index 047441e72b..b217c559dd 100644 --- a/crates/gpui/examples/legacy/hello_world.rs +++ b/crates/gpui/examples/legacy/hello_world.rs @@ -22,7 +22,7 @@ impl Render for HelloWorld { .border_color(rgb(0x0000ff)) .text_xl() .text_color(rgb(0xffffff)) - .child(format!("Hello, {}!", &self.text)) + .child(format!("Hello, {}!", self.text)) .child( div() .flex() diff --git a/crates/gpui/src/style.rs b/crates/gpui/src/style.rs index e0b6632631..b9e8ae16df 100644 --- a/crates/gpui/src/style.rs +++ b/crates/gpui/src/style.rs @@ -1364,9 +1364,7 @@ mod tests { use super::*; - use util_macros::perf; - - #[perf] + #[test] fn test_basic_highlight_style_combination() { let style_a = HighlightStyle::default(); let style_b = HighlightStyle::default(); @@ -1451,7 +1449,7 @@ mod tests { ); } - #[perf] + #[test] fn test_combine_highlights() { assert_eq!( combine_highlights( @@ -1540,7 +1538,7 @@ mod tests { ); } - #[perf] + #[test] fn test_text_style_refinement() { let mut style = Style::default(); style.refine(&StyleRefinement::default().text_size(px(20.0))); diff --git a/crates/gpui/src/text_system/line_wrapper.rs b/crates/gpui/src/text_system/line_wrapper.rs index 3335e7b31d..846c3b3bd4 100644 --- a/crates/gpui/src/text_system/line_wrapper.rs +++ b/crates/gpui/src/text_system/line_wrapper.rs @@ -1046,7 +1046,7 @@ mod tests { ..Default::default() }; - let text = "aa bbb cccc ddddd eeee".into(); + let text = SharedString::from("aa bbb cccc ddddd eeee"); let lines = text_system .shape_text( text, diff --git a/crates/gpui_ce_util/Cargo.toml b/crates/gpui_ce_util/Cargo.toml new file mode 100644 index 0000000000..1414a8864a --- /dev/null +++ b/crates/gpui_ce_util/Cargo.toml @@ -0,0 +1,16 @@ +[package] +name = "gpui_ce_util" +version = "0.2.2" +edition = "2024" +license = "Apache-2.0" +publish = true +description = "Utility structs and functions used by gpui-ce (vendored from Zed's gpui_util)." +repository = "https://github.com/gpui-ce/gpui-ce" + +[lib] +name = "gpui_util" +path = "src/lib.rs" + +[dependencies] +log = { version = "0.4.16", features = ["kv_unstable_serde", "serde"] } +anyhow = "1.0.86" diff --git a/crates/gpui_ce_util/LICENSE-APACHE b/crates/gpui_ce_util/LICENSE-APACHE new file mode 100644 index 0000000000..461a0fe5ba --- /dev/null +++ b/crates/gpui_ce_util/LICENSE-APACHE @@ -0,0 +1,222 @@ +Copyright 2022 - 2025 Zed Industries, Inc. + + + 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. + + + + +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 diff --git a/crates/gpui_ce_util/src/arc_cow.rs b/crates/gpui_ce_util/src/arc_cow.rs new file mode 100644 index 0000000000..41040671bc --- /dev/null +++ b/crates/gpui_ce_util/src/arc_cow.rs @@ -0,0 +1,141 @@ +use std::{ + borrow::Cow, + cmp::Ordering, + fmt::{self, Debug}, + hash::{Hash, Hasher}, + sync::Arc, +}; + +pub enum ArcCow<'a, T: ?Sized> { + Borrowed(&'a T), + Owned(Arc), +} + +impl PartialEq for ArcCow<'_, T> { + fn eq(&self, other: &Self) -> bool { + let a = self.as_ref(); + let b = other.as_ref(); + a == b + } +} + +impl PartialOrd for ArcCow<'_, T> { + fn partial_cmp(&self, other: &Self) -> Option { + self.as_ref().partial_cmp(other.as_ref()) + } +} + +impl Ord for ArcCow<'_, T> { + fn cmp(&self, other: &Self) -> Ordering { + self.as_ref().cmp(other.as_ref()) + } +} + +impl Eq for ArcCow<'_, T> {} + +impl Hash for ArcCow<'_, T> { + fn hash(&self, state: &mut H) { + match self { + Self::Borrowed(borrowed) => Hash::hash(borrowed, state), + Self::Owned(owned) => Hash::hash(&**owned, state), + } + } +} + +impl Clone for ArcCow<'_, T> { + fn clone(&self) -> Self { + match self { + Self::Borrowed(borrowed) => Self::Borrowed(borrowed), + Self::Owned(owned) => Self::Owned(owned.clone()), + } + } +} + +impl<'a, T: ?Sized> From<&'a T> for ArcCow<'a, T> { + fn from(s: &'a T) -> Self { + Self::Borrowed(s) + } +} + +impl From> for ArcCow<'_, T> { + fn from(s: Arc) -> Self { + Self::Owned(s) + } +} + +impl From<&'_ Arc> for ArcCow<'_, T> { + fn from(s: &'_ Arc) -> Self { + Self::Owned(s.clone()) + } +} + +impl From for ArcCow<'_, str> { + fn from(value: String) -> Self { + Self::Owned(value.into()) + } +} + +impl From<&String> for ArcCow<'_, str> { + fn from(value: &String) -> Self { + Self::Owned(value.clone().into()) + } +} + +impl<'a> From> for ArcCow<'a, str> { + fn from(value: Cow<'a, str>) -> Self { + match value { + Cow::Borrowed(borrowed) => Self::Borrowed(borrowed), + Cow::Owned(owned) => Self::Owned(owned.into()), + } + } +} + +impl From> for ArcCow<'_, [T]> { + fn from(vec: Vec) -> Self { + ArcCow::Owned(Arc::from(vec)) + } +} + +impl<'a> From<&'a str> for ArcCow<'a, [u8]> { + fn from(s: &'a str) -> Self { + ArcCow::Borrowed(s.as_bytes()) + } +} + +impl std::borrow::Borrow for ArcCow<'_, T> { + fn borrow(&self) -> &T { + match self { + ArcCow::Borrowed(borrowed) => borrowed, + ArcCow::Owned(owned) => owned.as_ref(), + } + } +} + +impl std::ops::Deref for ArcCow<'_, T> { + type Target = T; + + fn deref(&self) -> &Self::Target { + match self { + ArcCow::Borrowed(s) => s, + ArcCow::Owned(s) => s.as_ref(), + } + } +} + +impl AsRef for ArcCow<'_, T> { + fn as_ref(&self) -> &T { + match self { + ArcCow::Borrowed(borrowed) => borrowed, + ArcCow::Owned(owned) => owned.as_ref(), + } + } +} + +impl Debug for ArcCow<'_, T> { + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + match self { + ArcCow::Borrowed(borrowed) => Debug::fmt(borrowed, f), + ArcCow::Owned(owned) => Debug::fmt(&**owned, f), + } + } +} diff --git a/crates/gpui_ce_util/src/lib.rs b/crates/gpui_ce_util/src/lib.rs new file mode 100644 index 0000000000..eac1e2559a --- /dev/null +++ b/crates/gpui_ce_util/src/lib.rs @@ -0,0 +1,393 @@ +// FluentBuilder +// pub use gpui_util::{FutureExt, Timeout, arc_cow::ArcCow}; + +use std::{ + env, + ops::AddAssign, + panic::Location, + pin::Pin, + sync::OnceLock, + task::{Context, Poll}, + time::Instant, +}; + +pub mod arc_cow; + +pub fn post_inc + AddAssign + Copy>(value: &mut T) -> T { + let prev = *value; + *value += T::from(1); + prev +} + +pub fn measure(label: &str, f: impl FnOnce() -> R) -> R { + static ZED_MEASUREMENTS: OnceLock = OnceLock::new(); + let zed_measurements = ZED_MEASUREMENTS.get_or_init(|| { + env::var("ZED_MEASUREMENTS") + .map(|measurements| measurements == "1" || measurements == "true") + .unwrap_or(false) + }); + + if *zed_measurements { + let start = Instant::now(); + let result = f(); + let elapsed = start.elapsed(); + eprintln!("{}: {:?}", label, elapsed); + result + } else { + f() + } +} + +#[macro_export] +macro_rules! debug_panic { + ( $($fmt_arg:tt)* ) => { + if cfg!(debug_assertions) { + panic!( $($fmt_arg)* ); + } else { + let backtrace = std::backtrace::Backtrace::capture(); + log::error!("{}\n{:?}", format_args!($($fmt_arg)*), backtrace); + } + }; +} + +#[track_caller] +pub fn some_or_debug_panic(option: Option) -> Option { + #[cfg(debug_assertions)] + if option.is_none() { + panic!("Unexpected None"); + } + option +} + +/// Expands to an immediately-invoked function expression. Good for using the ? operator +/// in functions which do not return an Option or Result. +/// +/// Accepts a normal block, an async block, or an async move block. +#[macro_export] +macro_rules! maybe { + ($block:block) => { + (|| $block)() + }; + (async $block:block) => { + (async || $block)() + }; + (async move $block:block) => { + (async move || $block)() + }; +} +pub trait ResultExt { + type Ok; + + fn log_err(self) -> Option; + /// Like [`ResultExt::log_err`], but uses `{:?}` formatting so `anyhow::Error` values emit their + /// full backtrace. Reach for this only when a backtrace is genuinely wanted — most call sites + /// should stick with `log_err` / `warn_on_err`, whose output is a single chained error message. + fn log_err_with_backtrace(self) -> Option + where + E: std::fmt::Debug; + /// Assert that this result should never be an error in development or tests. + fn debug_assert_ok(self, reason: &str) -> Self; + fn warn_on_err(self) -> Option; + fn log_with_level(self, level: log::Level) -> Option; + fn anyhow(self) -> anyhow::Result + where + E: Into; +} + +impl ResultExt for Result +where + E: std::fmt::Display, +{ + type Ok = T; + + #[track_caller] + fn log_err(self) -> Option { + self.log_with_level(log::Level::Error) + } + + #[track_caller] + fn log_err_with_backtrace(self) -> Option + where + E: std::fmt::Debug, + { + match self { + Ok(value) => Some(value), + Err(error) => { + log_error_with_caller( + *Location::caller(), + DebugAsDisplay(&error), + log::Level::Error, + ); + None + } + } + } + + #[track_caller] + fn debug_assert_ok(self, reason: &str) -> Self { + if let Err(error) = &self { + debug_panic!("{reason} - {error:#}"); + } + self + } + + #[track_caller] + fn warn_on_err(self) -> Option { + self.log_with_level(log::Level::Warn) + } + + #[track_caller] + fn log_with_level(self, level: log::Level) -> Option { + match self { + Ok(value) => Some(value), + Err(error) => { + log_error_with_caller(*Location::caller(), error, level); + None + } + } + } + + fn anyhow(self) -> anyhow::Result + where + E: Into, + { + self.map_err(Into::into) + } +} + +fn log_error_with_caller(caller: core::panic::Location<'_>, error: E, level: log::Level) +where + E: std::fmt::Display, +{ + #[cfg(not(windows))] + let file = caller.file(); + #[cfg(windows)] + let file = caller.file().replace('\\', "/"); + // In this codebase all crates reside in a `crates` directory, + // so discard the prefix up to that segment to find the crate name + let file = file.split_once("crates/"); + let target = file.as_ref().and_then(|(_, s)| s.split_once("/src/")); + + let module_path = target.map(|(krate, module)| { + if module.starts_with(krate) { + module.trim_end_matches(".rs").replace('/', "::") + } else { + krate.to_owned() + "::" + &module.trim_end_matches(".rs").replace('/', "::") + } + }); + let file = file.map(|(_, file)| format!("crates/{file}")); + log::logger().log( + &log::Record::builder() + .target(module_path.as_deref().unwrap_or("")) + .module_path(file.as_deref()) + .args(format_args!("{:#}", error)) + .file(Some(caller.file())) + .line(Some(caller.line())) + .level(level) + .build(), + ); +} + +pub fn log_err(error: &E) { + log_error_with_caller(*Location::caller(), error, log::Level::Error); +} + +// Forces `{:?}` formatting through a `Display`-bounded logging helper so `anyhow::Error` emits a +// backtrace instead of the single-line chained message produced by its `Display`/`{:#}` forms. +struct DebugAsDisplay<'a, E>(&'a E); + +impl std::fmt::Display for DebugAsDisplay<'_, E> { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{:?}", self.0) + } +} + +pub trait TryFutureExt { + fn log_err(self) -> LogErrorFuture + where + Self: Sized; + + fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture + where + Self: Sized; + + fn warn_on_err(self) -> LogErrorFuture + where + Self: Sized; + fn unwrap(self) -> UnwrapFuture + where + Self: Sized; +} + +/// `{:?}`-formatting companion to [`TryFutureExt`]; emits a backtrace for `anyhow::Error`. Prefer +/// [`TryFutureExt`] unless a backtrace is genuinely wanted. +pub trait TryFutureExtBacktrace { + fn log_err_with_backtrace(self) -> LogErrorWithBacktraceFuture + where + Self: Sized; + + fn log_tracked_err_with_backtrace( + self, + location: core::panic::Location<'static>, + ) -> LogErrorWithBacktraceFuture + where + Self: Sized; +} + +impl TryFutureExt for F +where + F: Future>, + E: std::fmt::Display, +{ + #[track_caller] + fn log_err(self) -> LogErrorFuture + where + Self: Sized, + { + let location = Location::caller(); + LogErrorFuture(self, log::Level::Error, *location) + } + + fn log_tracked_err(self, location: core::panic::Location<'static>) -> LogErrorFuture + where + Self: Sized, + { + LogErrorFuture(self, log::Level::Error, location) + } + + #[track_caller] + fn warn_on_err(self) -> LogErrorFuture + where + Self: Sized, + { + let location = Location::caller(); + LogErrorFuture(self, log::Level::Warn, *location) + } + + fn unwrap(self) -> UnwrapFuture + where + Self: Sized, + { + UnwrapFuture(self) + } +} + +impl TryFutureExtBacktrace for F +where + F: Future>, + E: std::fmt::Debug, +{ + #[track_caller] + fn log_err_with_backtrace(self) -> LogErrorWithBacktraceFuture + where + Self: Sized, + { + let location = Location::caller(); + LogErrorWithBacktraceFuture(self, log::Level::Error, *location) + } + + fn log_tracked_err_with_backtrace( + self, + location: core::panic::Location<'static>, + ) -> LogErrorWithBacktraceFuture + where + Self: Sized, + { + LogErrorWithBacktraceFuture(self, log::Level::Error, location) + } +} + +#[must_use] +pub struct LogErrorFuture(F, log::Level, core::panic::Location<'static>); + +impl Future for LogErrorFuture +where + F: Future>, + E: std::fmt::Display, +{ + type Output = Option; + + fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + let level = self.1; + let location = self.2; + let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) }; + match inner.poll(cx) { + Poll::Ready(output) => Poll::Ready(match output { + Ok(output) => Some(output), + Err(error) => { + log_error_with_caller(location, error, level); + None + } + }), + Poll::Pending => Poll::Pending, + } + } +} + +#[must_use] +pub struct LogErrorWithBacktraceFuture(F, log::Level, core::panic::Location<'static>); + +impl Future for LogErrorWithBacktraceFuture +where + F: Future>, + E: std::fmt::Debug, +{ + type Output = Option; + + fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + let level = self.1; + let location = self.2; + let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) }; + match inner.poll(cx) { + Poll::Ready(output) => Poll::Ready(match output { + Ok(output) => Some(output), + Err(error) => { + log_error_with_caller(location, DebugAsDisplay(&error), level); + None + } + }), + Poll::Pending => Poll::Pending, + } + } +} + +pub struct UnwrapFuture(F); + +impl Future for UnwrapFuture +where + F: Future>, + E: std::fmt::Debug, +{ + type Output = T; + + fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + let inner = unsafe { Pin::new_unchecked(&mut self.get_unchecked_mut().0) }; + match inner.poll(cx) { + Poll::Ready(result) => Poll::Ready(result.unwrap()), + Poll::Pending => Poll::Pending, + } + } +} + +pub struct Deferred(Option); + +impl Deferred { + /// Drop without running the deferred function. + pub fn abort(mut self) { + self.0.take(); + } +} + +impl Drop for Deferred { + fn drop(&mut self) { + if let Some(f) = self.0.take() { + f() + } + } +} + +/// Run the given function when the returned value is dropped (unless it's cancelled). +#[must_use] +pub fn defer(f: F) -> Deferred { + Deferred(Some(f)) +} diff --git a/crates/gpui_collections/Cargo.toml b/crates/gpui_collections/Cargo.toml new file mode 100644 index 0000000000..65ec688098 --- /dev/null +++ b/crates/gpui_collections/Cargo.toml @@ -0,0 +1,20 @@ +[package] +name = "gpui_collections" +version = "0.2.2" +edition = "2024" +license = "Apache-2.0" +publish = true +description = "Blessed hash collections used by gpui-ce (vendored from Zed)." +repository = "https://github.com/gpui-ce/gpui-ce" + +[lib] +name = "collections" +path = "src/collections.rs" +doctest = false + +[features] +test-support = [] + +[dependencies] +indexmap = { version = "2", features = ["serde"] } +rustc-hash = "2" diff --git a/crates/gpui_collections/LICENSE-APACHE b/crates/gpui_collections/LICENSE-APACHE new file mode 100644 index 0000000000..461a0fe5ba --- /dev/null +++ b/crates/gpui_collections/LICENSE-APACHE @@ -0,0 +1,222 @@ +Copyright 2022 - 2025 Zed Industries, Inc. + + + 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. + + + + +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 diff --git a/crates/gpui_collections/src/collections.rs b/crates/gpui_collections/src/collections.rs new file mode 100644 index 0000000000..8e6c334d2b --- /dev/null +++ b/crates/gpui_collections/src/collections.rs @@ -0,0 +1,13 @@ +pub type HashMap = FxHashMap; +pub type HashSet = FxHashSet; +pub type IndexMap = indexmap::IndexMap; +pub type IndexSet = indexmap::IndexSet; + +pub use indexmap::Equivalent; +pub use rustc_hash::FxHasher; +pub use rustc_hash::{FxHashMap, FxHashSet}; +pub use std::collections::*; + +pub mod vecmap; +#[cfg(test)] +mod vecmap_tests; diff --git a/crates/gpui_collections/src/vecmap.rs b/crates/gpui_collections/src/vecmap.rs new file mode 100644 index 0000000000..bec6596b92 --- /dev/null +++ b/crates/gpui_collections/src/vecmap.rs @@ -0,0 +1,192 @@ +/// A collection that provides a map interface but is backed by vectors. +/// +/// This is suitable for small key-value stores where the item count is not +/// large enough to overcome the overhead of a more complex algorithm. +/// +/// If this meets your use cases, then [`VecMap`] should be a drop-in +/// replacement for [`std::collections::HashMap`] or [`crate::HashMap`]. Note +/// that we are adding APIs on an as-needed basis. If the API you need is not +/// present yet, please add it! +/// +/// Because it uses vectors as a backing store, the map also iterates over items +/// in insertion order, like [`crate::IndexMap`]. +/// +/// This struct uses a struct-of-arrays (SoA) representation which tends to be +/// more cache efficient and promotes autovectorization when using simple key or +/// value types. +#[derive(Default)] +pub struct VecMap { + keys: Vec, + values: Vec, +} + +impl VecMap { + pub fn new() -> Self { + Self { + keys: Vec::new(), + values: Vec::new(), + } + } + + pub fn iter(&self) -> Iter<'_, K, V> { + Iter { + iter: self.keys.iter().zip(self.values.iter()), + } + } +} + +impl VecMap { + pub fn entry(&mut self, key: K) -> Entry<'_, K, V> { + match self.keys.iter().position(|k| k == &key) { + Some(index) => Entry::Occupied(OccupiedEntry { + key: &self.keys[index], + value: &mut self.values[index], + }), + None => Entry::Vacant(VacantEntry { map: self, key }), + } + } + + /// Like [`Self::entry`] but takes its key by reference instead of by value. + /// + /// This can be helpful if you have a key where cloning is expensive, as we + /// can avoid cloning the key until a value is inserted under that entry. + pub fn entry_ref<'a, 'k>(&'a mut self, key: &'k K) -> EntryRef<'k, 'a, K, V> { + match self.keys.iter().position(|k| k == key) { + Some(index) => EntryRef::Occupied(OccupiedEntry { + key: &self.keys[index], + value: &mut self.values[index], + }), + None => EntryRef::Vacant(VacantEntryRef { map: self, key }), + } + } +} + +pub struct Iter<'a, K, V> { + iter: std::iter::Zip, std::slice::Iter<'a, V>>, +} + +impl<'a, K, V> Iterator for Iter<'a, K, V> { + type Item = (&'a K, &'a V); + + fn next(&mut self) -> Option { + self.iter.next() + } +} + +pub enum Entry<'a, K, V> { + Occupied(OccupiedEntry<'a, K, V>), + Vacant(VacantEntry<'a, K, V>), +} + +impl<'a, K, V> Entry<'a, K, V> { + pub fn key(&self) -> &K { + match self { + Entry::Occupied(entry) => entry.key, + Entry::Vacant(entry) => &entry.key, + } + } + + pub fn or_insert_with_key(self, default: F) -> &'a mut V + where + F: FnOnce(&K) -> V, + { + match self { + Entry::Occupied(entry) => entry.value, + Entry::Vacant(entry) => { + entry.map.values.push(default(&entry.key)); + entry.map.keys.push(entry.key); + match entry.map.values.last_mut() { + Some(value) => value, + None => unreachable!("vec empty after pushing to it"), + } + } + } + } + + pub fn or_insert_with(self, default: F) -> &'a mut V + where + F: FnOnce() -> V, + { + self.or_insert_with_key(|_| default()) + } + + pub fn or_insert(self, value: V) -> &'a mut V { + self.or_insert_with_key(|_| value) + } + + pub fn or_insert_default(self) -> &'a mut V + where + V: Default, + { + self.or_insert_with_key(|_| Default::default()) + } +} + +pub struct OccupiedEntry<'a, K, V> { + key: &'a K, + value: &'a mut V, +} + +pub struct VacantEntry<'a, K, V> { + map: &'a mut VecMap, + key: K, +} + +pub enum EntryRef<'key, 'map, K, V> { + Occupied(OccupiedEntry<'map, K, V>), + Vacant(VacantEntryRef<'key, 'map, K, V>), +} + +impl<'key, 'map, K, V> EntryRef<'key, 'map, K, V> { + pub fn key(&self) -> &K { + match self { + EntryRef::Occupied(entry) => entry.key, + EntryRef::Vacant(entry) => entry.key, + } + } +} + +impl<'key, 'map, K, V> EntryRef<'key, 'map, K, V> +where + K: Clone, +{ + pub fn or_insert_with_key(self, default: F) -> &'map mut V + where + F: FnOnce(&K) -> V, + { + match self { + EntryRef::Occupied(entry) => entry.value, + EntryRef::Vacant(entry) => { + entry.map.values.push(default(entry.key)); + entry.map.keys.push(entry.key.clone()); + match entry.map.values.last_mut() { + Some(value) => value, + None => unreachable!("vec empty after pushing to it"), + } + } + } + } + + pub fn or_insert_with(self, default: F) -> &'map mut V + where + F: FnOnce() -> V, + { + self.or_insert_with_key(|_| default()) + } + + pub fn or_insert(self, value: V) -> &'map mut V { + self.or_insert_with_key(|_| value) + } + + pub fn or_insert_default(self) -> &'map mut V + where + V: Default, + { + self.or_insert_with_key(|_| Default::default()) + } +} + +pub struct VacantEntryRef<'key, 'map, K, V> { + map: &'map mut VecMap, + key: &'key K, +} diff --git a/crates/gpui_collections/src/vecmap_tests.rs b/crates/gpui_collections/src/vecmap_tests.rs new file mode 100644 index 0000000000..1f698f8331 --- /dev/null +++ b/crates/gpui_collections/src/vecmap_tests.rs @@ -0,0 +1,211 @@ +//! Tests for the VecMap collection. +//! +//! This is in a sibling module so that the tests are guaranteed to only cover +//! states that can be created by the public API. + +use crate::vecmap::*; + +#[test] +fn test_entry_vacant_or_insert() { + let mut map: VecMap<&str, i32> = VecMap::new(); + let value = map.entry("a").or_insert(1); + assert_eq!(*value, 1); + assert_eq!(map.iter().collect::>(), vec![(&"a", &1)]); +} + +#[test] +fn test_entry_occupied_or_insert_keeps_existing() { + let mut map: VecMap<&str, i32> = VecMap::new(); + map.entry("a").or_insert(1); + let value = map.entry("a").or_insert(99); + assert_eq!(*value, 1); + assert_eq!(map.iter().collect::>(), vec![(&"a", &1)]); +} + +#[test] +fn test_entry_or_insert_with() { + let mut map: VecMap<&str, i32> = VecMap::new(); + map.entry("a").or_insert_with(|| 42); + assert_eq!(map.iter().collect::>(), vec![(&"a", &42)]); +} + +#[test] +fn test_entry_or_insert_with_not_called_when_occupied() { + let mut map: VecMap<&str, i32> = VecMap::new(); + map.entry("a").or_insert(1); + map.entry("a") + .or_insert_with(|| panic!("should not be called")); + assert_eq!(map.iter().collect::>(), vec![(&"a", &1)]); +} + +#[test] +fn test_entry_or_insert_with_key() { + let mut map: VecMap<&str, String> = VecMap::new(); + map.entry("hello").or_insert_with_key(|k| k.to_uppercase()); + assert_eq!( + map.iter().collect::>(), + vec![(&"hello", &"HELLO".to_string())] + ); +} + +#[test] +fn test_entry_or_insert_default() { + let mut map: VecMap<&str, i32> = VecMap::new(); + map.entry("a").or_insert_default(); + assert_eq!(map.iter().collect::>(), vec![(&"a", &0)]); +} + +#[test] +fn test_entry_key() { + let mut map: VecMap<&str, i32> = VecMap::new(); + assert_eq!(*map.entry("a").key(), "a"); + map.entry("a").or_insert(1); + assert_eq!(*map.entry("a").key(), "a"); +} + +#[test] +fn test_entry_mut_ref_can_be_updated() { + let mut map: VecMap<&str, i32> = VecMap::new(); + let value = map.entry("a").or_insert(0); + *value = 5; + assert_eq!(map.iter().collect::>(), vec![(&"a", &5)]); +} + +#[test] +fn test_insertion_order_preserved() { + let mut map: VecMap<&str, i32> = VecMap::new(); + map.entry("b").or_insert(2); + map.entry("a").or_insert(1); + map.entry("c").or_insert(3); + assert_eq!( + map.iter().collect::>(), + vec![(&"b", &2), (&"a", &1), (&"c", &3)] + ); +} + +#[test] +fn test_multiple_entries_independent() { + let mut map: VecMap = VecMap::new(); + map.entry(1).or_insert(10); + map.entry(2).or_insert(20); + map.entry(3).or_insert(30); + assert_eq!(map.iter().count(), 3); + // Re-inserting does not duplicate keys + map.entry(1).or_insert(99); + assert_eq!(map.iter().count(), 3); +} + +// entry_ref tests + +use std::cell::Cell; +use std::rc::Rc; + +#[derive(PartialEq, Eq)] +struct CountedKey { + value: String, + clone_count: Rc>, +} + +impl Clone for CountedKey { + fn clone(&self) -> Self { + self.clone_count.set(self.clone_count.get() + 1); + CountedKey { + value: self.value.clone(), + clone_count: self.clone_count.clone(), + } + } +} + +#[test] +fn test_entry_ref_vacant_or_insert() { + let mut map: VecMap = VecMap::new(); + let key = "a".to_string(); + let value = map.entry_ref(&key).or_insert(1); + assert_eq!(*value, 1); + assert_eq!(map.iter().count(), 1); +} + +#[test] +fn test_entry_ref_occupied_or_insert_keeps_existing() { + let mut map: VecMap = VecMap::new(); + map.entry_ref(&"a".to_string()).or_insert(1); + let value = map.entry_ref(&"a".to_string()).or_insert(99); + assert_eq!(*value, 1); + assert_eq!(map.iter().count(), 1); +} + +#[test] +fn test_entry_ref_key_not_cloned_when_occupied() { + let clone_count = Rc::new(Cell::new(0)); + let key = CountedKey { + value: "a".to_string(), + clone_count: clone_count.clone(), + }; + + let mut map: VecMap = VecMap::new(); + map.entry_ref(&key).or_insert(1); + let clones_after_insert = clone_count.get(); + + // Looking up an existing key must not clone it. + map.entry_ref(&key).or_insert(99); + assert_eq!(clone_count.get(), clones_after_insert); +} + +#[test] +fn test_entry_ref_key_cloned_exactly_once_on_vacant_insert() { + let clone_count = Rc::new(Cell::new(0)); + let key = CountedKey { + value: "a".to_string(), + clone_count: clone_count.clone(), + }; + + let mut map: VecMap = VecMap::new(); + map.entry_ref(&key).or_insert(1); + assert_eq!(clone_count.get(), 1); +} + +#[test] +fn test_entry_ref_or_insert_with_key() { + let mut map: VecMap = VecMap::new(); + let key = "hello".to_string(); + map.entry_ref(&key).or_insert_with_key(|k| k.to_uppercase()); + assert_eq!( + map.iter().collect::>(), + vec![(&"hello".to_string(), &"HELLO".to_string())] + ); +} + +#[test] +fn test_entry_ref_or_insert_with_not_called_when_occupied() { + let mut map: VecMap = VecMap::new(); + let key = "a".to_string(); + map.entry_ref(&key).or_insert(1); + map.entry_ref(&key) + .or_insert_with(|| panic!("should not be called")); + assert_eq!(map.iter().collect::>(), vec![(&key, &1)]); +} + +#[test] +fn test_entry_ref_or_insert_default() { + let mut map: VecMap = VecMap::new(); + map.entry_ref(&"a".to_string()).or_insert_default(); + assert_eq!(map.iter().collect::>(), vec![(&"a".to_string(), &0)]); +} + +#[test] +fn test_entry_ref_key() { + let mut map: VecMap = VecMap::new(); + let key = "a".to_string(); + assert_eq!(*map.entry_ref(&key).key(), key); + map.entry_ref(&key).or_insert(1); + assert_eq!(*map.entry_ref(&key).key(), key); +} + +#[test] +fn test_entry_ref_mut_ref_can_be_updated() { + let mut map: VecMap = VecMap::new(); + let key = "a".to_string(); + let value = map.entry_ref(&key).or_insert(0); + *value = 5; + assert_eq!(map.iter().collect::>(), vec![(&key, &5)]); +} diff --git a/crates/gpui_derive_refineable/Cargo.toml b/crates/gpui_derive_refineable/Cargo.toml new file mode 100644 index 0000000000..60ba12e8b4 --- /dev/null +++ b/crates/gpui_derive_refineable/Cargo.toml @@ -0,0 +1,18 @@ +[package] +name = "gpui_derive_refineable" +version = "0.2.2" +edition = "2024" +license = "Apache-2.0" +publish = true +description = "Derive macro for gpui-ce's Refineable (vendored from Zed)." + +[lib] +name = "derive_refineable" +path = "src/derive_refineable.rs" +proc-macro = true +doctest = false + +[dependencies] +proc-macro2 = "1.0.101" +quote = "1.0.41" +syn = { version = "2.0.117", features = ["full", "extra-traits", "visit-mut"] } diff --git a/crates/gpui_derive_refineable/LICENSE-APACHE b/crates/gpui_derive_refineable/LICENSE-APACHE new file mode 100644 index 0000000000..461a0fe5ba --- /dev/null +++ b/crates/gpui_derive_refineable/LICENSE-APACHE @@ -0,0 +1,222 @@ +Copyright 2022 - 2025 Zed Industries, Inc. + + + 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. + + + + +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 diff --git a/crates/gpui_derive_refineable/src/derive_refineable.rs b/crates/gpui_derive_refineable/src/derive_refineable.rs new file mode 100644 index 0000000000..c7c8a91ad9 --- /dev/null +++ b/crates/gpui_derive_refineable/src/derive_refineable.rs @@ -0,0 +1,548 @@ +use proc_macro::TokenStream; +use proc_macro2::TokenStream as TokenStream2; +use quote::{format_ident, quote}; +use syn::{ + DeriveInput, Field, FieldsNamed, PredicateType, TraitBound, Type, TypeParamBound, WhereClause, + WherePredicate, parse_macro_input, parse_quote, +}; + +#[proc_macro_derive(Refineable, attributes(refineable))] +pub fn derive_refineable(input: TokenStream) -> TokenStream { + let DeriveInput { + ident, + data, + generics, + attrs, + .. + } = parse_macro_input!(input); + + let refineable_attr = attrs.iter().find(|attr| attr.path().is_ident("refineable")); + + let mut impl_debug_on_refinement = false; + let mut derives_serialize = false; + let mut refinement_traits_to_derive = vec![]; + + if let Some(refineable_attr) = refineable_attr { + let _ = refineable_attr.parse_nested_meta(|meta| { + if meta.path.is_ident("Debug") { + impl_debug_on_refinement = true; + } else { + if meta.path.is_ident("Serialize") { + derives_serialize = true; + } + refinement_traits_to_derive.push(meta.path); + } + Ok(()) + }); + } + + let refinement_ident = format_ident!("{}Refinement", ident); + let (impl_generics, ty_generics, where_clause) = generics.split_for_impl(); + + let fields = match data { + syn::Data::Struct(syn::DataStruct { + fields: syn::Fields::Named(FieldsNamed { named, .. }), + .. + }) => named.into_iter().collect::>(), + _ => panic!("This derive macro only supports structs with named fields"), + }; + + let field_names: Vec<_> = fields.iter().map(|f| f.ident.as_ref().unwrap()).collect(); + let field_visibilities: Vec<_> = fields.iter().map(|f| &f.vis).collect(); + let wrapped_types: Vec<_> = fields.iter().map(|f| get_wrapper_type(f, &f.ty)).collect(); + + let field_attributes: Vec = fields + .iter() + .map(|f| { + if derives_serialize { + if is_refineable_field(f) { + quote! { #[serde(default, skip_serializing_if = "::refineable::IsEmpty::is_empty")] } + } else { + quote! { #[serde(skip_serializing_if = "::std::option::Option::is_none")] } + } + } else { + quote! {} + } + }) + .collect(); + + // Create trait bound that each wrapped type must implement Clone + let type_param_bounds: Vec<_> = wrapped_types + .iter() + .map(|ty| { + WherePredicate::Type(PredicateType { + lifetimes: None, + bounded_ty: ty.clone(), + colon_token: Default::default(), + bounds: { + let mut punctuated = syn::punctuated::Punctuated::new(); + punctuated.push_value(TypeParamBound::Trait(TraitBound { + paren_token: None, + modifier: syn::TraitBoundModifier::None, + lifetimes: None, + path: parse_quote!(Clone), + })); + + punctuated + }, + }) + }) + .collect(); + + // Append to where_clause or create a new one if it doesn't exist + let where_clause = match where_clause.cloned() { + Some(mut where_clause) => { + where_clause.predicates.extend(type_param_bounds); + where_clause.clone() + } + None => WhereClause { + where_token: Default::default(), + predicates: type_param_bounds.into_iter().collect(), + }, + }; + + let refineable_refine_assignments: Vec = fields + .iter() + .map(|field| { + let name = &field.ident; + let is_refineable = is_refineable_field(field); + let is_optional = is_optional_field(field); + + if is_refineable { + quote! { + self.#name.refine(&refinement.#name); + } + } else if is_optional { + quote! { + if let Some(value) = &refinement.#name { + self.#name = Some(value.clone()); + } + } + } else { + quote! { + if let Some(value) = &refinement.#name { + self.#name = value.clone(); + } + } + } + }) + .collect(); + + let refineable_refined_assignments: Vec = fields + .iter() + .map(|field| { + let name = &field.ident; + let is_refineable = is_refineable_field(field); + let is_optional = is_optional_field(field); + + if is_refineable { + quote! { + self.#name = self.#name.refined(refinement.#name); + } + } else if is_optional { + quote! { + if let Some(value) = refinement.#name { + self.#name = Some(value); + } + } + } else { + quote! { + if let Some(value) = refinement.#name { + self.#name = value; + } + } + } + }) + .collect(); + + let refinement_refine_assignments: Vec = fields + .iter() + .map(|field| { + let name = &field.ident; + let is_refineable = is_refineable_field(field); + + if is_refineable { + quote! { + self.#name.refine(&refinement.#name); + } + } else { + quote! { + if let Some(value) = &refinement.#name { + self.#name = Some(value.clone()); + } + } + } + }) + .collect(); + + let refinement_refined_assignments: Vec = fields + .iter() + .map(|field| { + let name = &field.ident; + let is_refineable = is_refineable_field(field); + + if is_refineable { + quote! { + self.#name = self.#name.refined(refinement.#name); + } + } else { + quote! { + if let Some(value) = refinement.#name { + self.#name = Some(value); + } + } + } + }) + .collect(); + + let from_refinement_assignments: Vec = fields + .iter() + .map(|field| { + let name = &field.ident; + let is_refineable = is_refineable_field(field); + let is_optional = is_optional_field(field); + + if is_refineable { + quote! { + #name: value.#name.into(), + } + } else if is_optional { + quote! { + #name: value.#name.map(|v| v.into()), + } + } else { + quote! { + #name: value.#name.map(|v| v.into()).unwrap_or_default(), + } + } + }) + .collect(); + + let debug_impl = if impl_debug_on_refinement { + let refinement_field_debugs: Vec = fields + .iter() + .map(|field| { + let name = &field.ident; + quote! { + if self.#name.is_some() { + debug_struct.field(stringify!(#name), &self.#name); + } else { + all_some = false; + } + } + }) + .collect(); + + quote! { + impl #impl_generics std::fmt::Debug for #refinement_ident #ty_generics + #where_clause + { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + let mut debug_struct = f.debug_struct(stringify!(#refinement_ident)); + let mut all_some = true; + #( #refinement_field_debugs )* + if all_some { + debug_struct.finish() + } else { + debug_struct.finish_non_exhaustive() + } + } + } + } + } else { + quote! {} + }; + + let refinement_is_empty_conditions: Vec = fields + .iter() + .enumerate() + .map(|(i, field)| { + let name = &field.ident; + + let condition = if is_refineable_field(field) { + quote! { self.#name.is_empty() } + } else { + quote! { self.#name.is_none() } + }; + + if i < fields.len() - 1 { + quote! { #condition && } + } else { + condition + } + }) + .collect(); + + let refineable_is_superset_conditions: Vec = fields + .iter() + .map(|field| { + let name = &field.ident; + let is_refineable = is_refineable_field(field); + let is_optional = is_optional_field(field); + + if is_refineable { + quote! { + if !self.#name.is_superset_of(&refinement.#name) { + return false; + } + } + } else if is_optional { + quote! { + if refinement.#name.is_some() && &self.#name != &refinement.#name { + return false; + } + } + } else { + quote! { + if let Some(refinement_value) = &refinement.#name { + if &self.#name != refinement_value { + return false; + } + } + } + } + }) + .collect(); + + let refinement_is_superset_conditions: Vec = fields + .iter() + .map(|field| { + let name = &field.ident; + let is_refineable = is_refineable_field(field); + + if is_refineable { + quote! { + if !self.#name.is_superset_of(&refinement.#name) { + return false; + } + } + } else { + quote! { + if refinement.#name.is_some() && &self.#name != &refinement.#name { + return false; + } + } + } + }) + .collect(); + + let refineable_subtract_assignments: Vec = fields + .iter() + .map(|field| { + let name = &field.ident; + let is_refineable = is_refineable_field(field); + let is_optional = is_optional_field(field); + + if is_refineable { + quote! { + #name: self.#name.subtract(&refinement.#name), + } + } else if is_optional { + quote! { + #name: if &self.#name == &refinement.#name { + None + } else { + self.#name.clone() + }, + } + } else { + quote! { + #name: if let Some(refinement_value) = &refinement.#name { + if &self.#name == refinement_value { + None + } else { + Some(self.#name.clone()) + } + } else { + Some(self.#name.clone()) + }, + } + } + }) + .collect(); + + let refinement_subtract_assignments: Vec = fields + .iter() + .map(|field| { + let name = &field.ident; + let is_refineable = is_refineable_field(field); + + if is_refineable { + quote! { + #name: self.#name.subtract(&refinement.#name), + } + } else { + quote! { + #name: if &self.#name == &refinement.#name { + None + } else { + self.#name.clone() + }, + } + } + }) + .collect(); + + let mut derive_stream = quote! {}; + for trait_to_derive in refinement_traits_to_derive { + derive_stream.extend(quote! { #[derive(#trait_to_derive)] }) + } + + let r#gen = quote! { + /// A refinable version of [`#ident`], see that documentation for details. + #[derive(Clone)] + #derive_stream + pub struct #refinement_ident #impl_generics { + #( + #[allow(missing_docs)] + #field_attributes + #field_visibilities #field_names: #wrapped_types + ),* + } + + impl #impl_generics Refineable for #ident #ty_generics + #where_clause + { + type Refinement = #refinement_ident #ty_generics; + + fn refine(&mut self, refinement: &Self::Refinement) { + #( #refineable_refine_assignments )* + } + + fn refined(mut self, refinement: Self::Refinement) -> Self { + #( #refineable_refined_assignments )* + self + } + + fn is_superset_of(&self, refinement: &Self::Refinement) -> bool + { + #( #refineable_is_superset_conditions )* + true + } + + fn subtract(&self, refinement: &Self::Refinement) -> Self::Refinement + { + #refinement_ident { + #( #refineable_subtract_assignments )* + } + } + } + + impl #impl_generics Refineable for #refinement_ident #ty_generics + #where_clause + { + type Refinement = #refinement_ident #ty_generics; + + fn refine(&mut self, refinement: &Self::Refinement) { + #( #refinement_refine_assignments )* + } + + fn refined(mut self, refinement: Self::Refinement) -> Self { + #( #refinement_refined_assignments )* + self + } + + fn is_superset_of(&self, refinement: &Self::Refinement) -> bool + { + #( #refinement_is_superset_conditions )* + true + } + + fn subtract(&self, refinement: &Self::Refinement) -> Self::Refinement + { + #refinement_ident { + #( #refinement_subtract_assignments )* + } + } + } + + impl #impl_generics ::refineable::IsEmpty for #refinement_ident #ty_generics + #where_clause + { + fn is_empty(&self) -> bool { + #( #refinement_is_empty_conditions )* + } + } + + impl #impl_generics From<#refinement_ident #ty_generics> for #ident #ty_generics + #where_clause + { + fn from(value: #refinement_ident #ty_generics) -> Self { + Self { + #( #from_refinement_assignments )* + } + } + } + + impl #impl_generics ::core::default::Default for #refinement_ident #ty_generics + #where_clause + { + fn default() -> Self { + #refinement_ident { + #( #field_names: Default::default() ),* + } + } + } + + impl #impl_generics #refinement_ident #ty_generics + #where_clause + { + /// Returns `true` if all fields are `Some` + pub fn is_some(&self) -> bool { + #( + if self.#field_names.is_some() { + return true; + } + )* + false + } + } + + #debug_impl + }; + r#gen.into() +} + +fn is_refineable_field(f: &Field) -> bool { + f.attrs + .iter() + .any(|attr| attr.path().is_ident("refineable")) +} + +fn is_optional_field(f: &Field) -> bool { + if let Type::Path(typepath) = &f.ty + && typepath.qself.is_none() + { + let segments = &typepath.path.segments; + if segments.len() == 1 && segments.iter().any(|s| s.ident == "Option") { + return true; + } + } + false +} + +fn get_wrapper_type(field: &Field, ty: &Type) -> syn::Type { + if is_refineable_field(field) { + let struct_name = if let Type::Path(tp) = ty { + tp.path.segments.last().unwrap().ident.clone() + } else { + panic!("Expected struct type for a refineable field"); + }; + + let refinement_struct_name = if struct_name.to_string().ends_with("Refinement") { + format_ident!("{}", struct_name) + } else { + format_ident!("{}Refinement", struct_name) + }; + let generics = if let Type::Path(tp) = ty { + &tp.path.segments.last().unwrap().arguments + } else { + &syn::PathArguments::None + }; + parse_quote!(#refinement_struct_name #generics) + } else if is_optional_field(field) { + ty.clone() + } else { + parse_quote!(Option<#ty>) + } +} diff --git a/crates/gpui_linux/Cargo.toml b/crates/gpui_linux/Cargo.toml index f9db98371d..543eb25f5a 100644 --- a/crates/gpui_linux/Cargo.toml +++ b/crates/gpui_linux/Cargo.toml @@ -125,9 +125,8 @@ x11rb = { version = "0.13.1", features = [ "sync", "dri3", ], optional = true } -# WARNING: If you change this, you must also publish a new version of zed-xim to crates.io -xim = { git = "https://github.com/zed-industries/xim-rs.git", rev = "16f35a2c881b815a2b6cdfd6687988e84f8447d8", features = [ +xim = { version = "0.4.0-zed", package = "zed-xim", features = [ "x11rb-xcb", "x11rb-client", -], package = "zed-xim", version = "0.4.0-zed", optional = true } +], optional = true } x11-clipboard = { version = "0.9.3", optional = true } diff --git a/crates/gpui_macos/Cargo.toml b/crates/gpui_macos/Cargo.toml index 2c9446401b..48a03a291c 100644 --- a/crates/gpui_macos/Cargo.toml +++ b/crates/gpui_macos/Cargo.toml @@ -38,8 +38,7 @@ ctor.workspace = true derive_more.workspace = true dispatch2 = "0.3.1" etagere = "0.2" -# WARNING: If you change this, you must also publish a new version of zed-font-kit to crates.io -font-kit = { git = "https://github.com/zed-industries/font-kit", rev = "94b0f28166665e8fd2f53ff6d268a14955c82269", package = "zed-font-kit", version = "0.14.1-zed", optional = true } +font-kit = { version = "0.14.1-zed", package = "zed-font-kit", optional = true } foreign-types = "0.5" futures.workspace = true image.workspace = true diff --git a/crates/gpui_macros/Cargo.toml b/crates/gpui_macros/Cargo.toml index 30996af0b4..d27219942c 100644 --- a/crates/gpui_macros/Cargo.toml +++ b/crates/gpui_macros/Cargo.toml @@ -2,7 +2,7 @@ name = "gpui_macros" version = "0.1.0" edition.workspace = true -publish = false +publish = true license = "Apache-2.0" description = "Macros used by gpui" diff --git a/crates/gpui_macros/src/gpui_macros.rs b/crates/gpui_macros/src/gpui_macros.rs index e30c85e6ed..e2e174a1b2 100644 --- a/crates/gpui_macros/src/gpui_macros.rs +++ b/crates/gpui_macros/src/gpui_macros.rs @@ -193,7 +193,7 @@ pub fn test(args: TokenStream, function: TokenStream) -> TokenStream { /// /// A property test, much like a standard GPUI randomized test, allows testing /// claims of the form "for any possible X, Y should hold". For example: -/// ``` +/// ```ignore /// #[gpui::property_test] /// fn test_arithmetic(x: i32, y: i32) { /// assert!(x == y || x < y || x > y); @@ -236,7 +236,7 @@ pub fn test(args: TokenStream, function: TokenStream) -> TokenStream { /// `Arbitrary`. Parameters to a `#[gpui::property_test]`, by default, use a /// type's `Arbitrary` implementation. If you'd like to provide a custom /// strategy, you can use `#[strategy = ...]` on the argument: -/// ``` +/// ```ignore /// #[gpui::property_test] /// fn int_test(#[strategy = 1..10] x: i32, #[strategy = "[a-zA-Z0-9]{20}"] s: String) { /// assert!(s.len() > (x as usize)); diff --git a/crates/gpui_media/Cargo.toml b/crates/gpui_media/Cargo.toml new file mode 100644 index 0000000000..a0ce0160b6 --- /dev/null +++ b/crates/gpui_media/Cargo.toml @@ -0,0 +1,26 @@ +[package] +name = "gpui_media" +version = "0.2.2" +edition = "2024" +license = "Apache-2.0" +publish = true +description = "macOS CoreMedia/CoreVideo bindings for gpui-ce (vendored from Zed)." + +[lib] +name = "media" +path = "src/media.rs" +doctest = false + +[dependencies] +anyhow = "1.0.86" + +[target.'cfg(target_os = "macos")'.dependencies] +core-foundation = "=0.10.0" +ctor = "1.0.6" +foreign-types = "0.5" +metal = "0.33" +core-video = { version = "0.5.2", features = ["metal"] } +objc = "0.2" + +[build-dependencies] +bindgen = "0.71" diff --git a/crates/gpui_media/LICENSE-APACHE b/crates/gpui_media/LICENSE-APACHE new file mode 100644 index 0000000000..461a0fe5ba --- /dev/null +++ b/crates/gpui_media/LICENSE-APACHE @@ -0,0 +1,222 @@ +Copyright 2022 - 2025 Zed Industries, Inc. + + + 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. + + + + +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 diff --git a/crates/gpui_media/build.rs b/crates/gpui_media/build.rs new file mode 100644 index 0000000000..090002e9e9 --- /dev/null +++ b/crates/gpui_media/build.rs @@ -0,0 +1,44 @@ +#![allow(clippy::disallowed_methods, reason = "build scripts are exempt")] +#[cfg(target_os = "macos")] +fn main() { + use std::{env, path::PathBuf, process::Command}; + + let sdk_path = String::from_utf8( + Command::new("xcrun") + .args(["--sdk", "macosx", "--show-sdk-path"]) + .output() + .unwrap() + .stdout, + ) + .unwrap(); + let sdk_path = sdk_path.trim_end(); + + println!("cargo:rerun-if-changed=src/bindings.h"); + let bindings = bindgen::Builder::default() + .header("src/bindings.h") + .clang_arg(format!("-isysroot{}", sdk_path)) + .clang_arg("-xobjective-c") + .allowlist_type("CMItemIndex") + .allowlist_type("CMSampleTimingInfo") + .allowlist_type("CMVideoCodecType") + .allowlist_type("VTEncodeInfoFlags") + .allowlist_function("CMTimeMake") + .allowlist_var("kCVPixelFormatType_.*") + .allowlist_var("kCVReturn.*") + .allowlist_var("VTEncodeInfoFlags_.*") + .allowlist_var("kCMVideoCodecType_.*") + .allowlist_var("kCMTime.*") + .allowlist_var("kCMSampleAttachmentKey_.*") + .parse_callbacks(Box::new(bindgen::CargoCallbacks::new())) + .layout_tests(false) + .generate() + .expect("unable to generate bindings"); + + let out_path = PathBuf::from(env::var("OUT_DIR").unwrap()); + bindings + .write_to_file(out_path.join("bindings.rs")) + .expect("couldn't write dispatch bindings"); +} + +#[cfg(not(target_os = "macos"))] +fn main() {} diff --git a/crates/gpui_media/src/bindings.h b/crates/gpui_media/src/bindings.h new file mode 100644 index 0000000000..4df283d0c1 --- /dev/null +++ b/crates/gpui_media/src/bindings.h @@ -0,0 +1,5 @@ +#import +#import +#import +#import +#import diff --git a/crates/gpui_media/src/bindings.rs b/crates/gpui_media/src/bindings.rs new file mode 100644 index 0000000000..a1c78c17c4 --- /dev/null +++ b/crates/gpui_media/src/bindings.rs @@ -0,0 +1,10 @@ +#![allow(non_upper_case_globals)] +#![allow(non_camel_case_types)] +#![allow(non_snake_case)] +#![allow(unused)] + +#[cfg(target_os = "macos")] +use objc::*; + +#[cfg(target_os = "macos")] +include!(concat!(env!("OUT_DIR"), "/bindings.rs")); diff --git a/crates/gpui_media/src/media.rs b/crates/gpui_media/src/media.rs new file mode 100644 index 0000000000..c42bad62e7 --- /dev/null +++ b/crates/gpui_media/src/media.rs @@ -0,0 +1,352 @@ +#![allow(non_snake_case)] +#![allow(non_camel_case_types)] + +mod bindings; + +#[cfg(target_os = "macos")] +pub mod core_media { + #![allow(non_snake_case)] + + pub use crate::bindings::{ + CMItemIndex, CMSampleTimingInfo, CMTime, CMTimeMake, CMVideoCodecType, + kCMSampleAttachmentKey_NotSync, kCMTimeInvalid, kCMVideoCodecType_H264, + }; + use anyhow::Result; + use core_foundation::{ + array::{CFArray, CFArrayRef}, + base::{CFTypeID, OSStatus, TCFType}, + declare_TCFType, + dictionary::CFDictionary, + impl_CFTypeDescription, impl_TCFType, + string::CFString, + }; + use core_video::image_buffer::{CVImageBuffer, CVImageBufferRef}; + use std::{ffi::c_void, ptr}; + + #[repr(C)] + pub struct __CMSampleBuffer(c_void); + // The ref type must be a pointer to the underlying struct. + pub type CMSampleBufferRef = *const __CMSampleBuffer; + + declare_TCFType!(CMSampleBuffer, CMSampleBufferRef); + impl_TCFType!(CMSampleBuffer, CMSampleBufferRef, CMSampleBufferGetTypeID); + impl_CFTypeDescription!(CMSampleBuffer); + + impl CMSampleBuffer { + pub fn attachments(&self) -> Vec> { + unsafe { + let attachments = + CMSampleBufferGetSampleAttachmentsArray(self.as_concrete_TypeRef(), true); + CFArray::::wrap_under_get_rule(attachments) + .into_iter() + .map(|attachments| { + CFDictionary::wrap_under_get_rule(attachments.as_concrete_TypeRef()) + }) + .collect() + } + } + + pub fn image_buffer(&self) -> Option { + unsafe { + let ptr = CMSampleBufferGetImageBuffer(self.as_concrete_TypeRef()); + if ptr.is_null() { + None + } else { + Some(CVImageBuffer::wrap_under_get_rule(ptr)) + } + } + } + + pub fn sample_timing_info(&self, index: usize) -> Result { + unsafe { + let mut timing_info = CMSampleTimingInfo { + duration: kCMTimeInvalid, + presentationTimeStamp: kCMTimeInvalid, + decodeTimeStamp: kCMTimeInvalid, + }; + let result = CMSampleBufferGetSampleTimingInfo( + self.as_concrete_TypeRef(), + index as CMItemIndex, + &mut timing_info, + ); + anyhow::ensure!( + result == 0, + "error getting sample timing info, code {result}" + ); + Ok(timing_info) + } + } + + pub fn format_description(&self) -> CMFormatDescription { + unsafe { + CMFormatDescription::wrap_under_get_rule(CMSampleBufferGetFormatDescription( + self.as_concrete_TypeRef(), + )) + } + } + + pub fn data(&self) -> CMBlockBuffer { + unsafe { + CMBlockBuffer::wrap_under_get_rule(CMSampleBufferGetDataBuffer( + self.as_concrete_TypeRef(), + )) + } + } + } + + #[link(name = "CoreMedia", kind = "framework")] + unsafe extern "C" { + fn CMSampleBufferGetTypeID() -> CFTypeID; + fn CMSampleBufferGetSampleAttachmentsArray( + buffer: CMSampleBufferRef, + create_if_necessary: bool, + ) -> CFArrayRef; + fn CMSampleBufferGetImageBuffer(buffer: CMSampleBufferRef) -> CVImageBufferRef; + fn CMSampleBufferGetSampleTimingInfo( + buffer: CMSampleBufferRef, + index: CMItemIndex, + timing_info_out: *mut CMSampleTimingInfo, + ) -> OSStatus; + fn CMSampleBufferGetFormatDescription(buffer: CMSampleBufferRef) -> CMFormatDescriptionRef; + fn CMSampleBufferGetDataBuffer(sample_buffer: CMSampleBufferRef) -> CMBlockBufferRef; + } + + #[repr(C)] + pub struct __CMFormatDescription(c_void); + pub type CMFormatDescriptionRef = *const __CMFormatDescription; + + declare_TCFType!(CMFormatDescription, CMFormatDescriptionRef); + impl_TCFType!( + CMFormatDescription, + CMFormatDescriptionRef, + CMFormatDescriptionGetTypeID + ); + impl_CFTypeDescription!(CMFormatDescription); + + impl CMFormatDescription { + pub fn h264_parameter_set_count(&self) -> usize { + unsafe { + let mut count = 0; + let result = CMVideoFormatDescriptionGetH264ParameterSetAtIndex( + self.as_concrete_TypeRef(), + 0, + ptr::null_mut(), + ptr::null_mut(), + &mut count, + ptr::null_mut(), + ); + assert_eq!(result, 0); + count + } + } + + pub fn h264_parameter_set_at_index(&self, index: usize) -> Result<&[u8]> { + unsafe { + let mut bytes = ptr::null(); + let mut len = 0; + let result = CMVideoFormatDescriptionGetH264ParameterSetAtIndex( + self.as_concrete_TypeRef(), + index, + &mut bytes, + &mut len, + ptr::null_mut(), + ptr::null_mut(), + ); + anyhow::ensure!(result == 0, "error getting parameter set, code: {result}"); + Ok(std::slice::from_raw_parts(bytes, len)) + } + } + } + + #[link(name = "CoreMedia", kind = "framework")] + unsafe extern "C" { + fn CMFormatDescriptionGetTypeID() -> CFTypeID; + fn CMVideoFormatDescriptionGetH264ParameterSetAtIndex( + video_desc: CMFormatDescriptionRef, + parameter_set_index: usize, + parameter_set_pointer_out: *mut *const u8, + parameter_set_size_out: *mut usize, + parameter_set_count_out: *mut usize, + NALUnitHeaderLengthOut: *mut isize, + ) -> OSStatus; + } + + #[repr(C)] + pub struct __CMBlockBuffer(c_void); + pub type CMBlockBufferRef = *const __CMBlockBuffer; + + declare_TCFType!(CMBlockBuffer, CMBlockBufferRef); + impl_TCFType!(CMBlockBuffer, CMBlockBufferRef, CMBlockBufferGetTypeID); + impl_CFTypeDescription!(CMBlockBuffer); + + impl CMBlockBuffer { + pub fn bytes(&self) -> &[u8] { + unsafe { + let mut bytes = ptr::null(); + let mut len = 0; + let result = CMBlockBufferGetDataPointer( + self.as_concrete_TypeRef(), + 0, + &mut 0, + &mut len, + &mut bytes, + ); + assert!(result == 0, "could not get block buffer data"); + std::slice::from_raw_parts(bytes, len) + } + } + } + + #[link(name = "CoreMedia", kind = "framework")] + unsafe extern "C" { + fn CMBlockBufferGetTypeID() -> CFTypeID; + fn CMBlockBufferGetDataPointer( + buffer: CMBlockBufferRef, + offset: usize, + length_at_offset_out: *mut usize, + total_length_out: *mut usize, + data_pointer_out: *mut *const u8, + ) -> OSStatus; + } +} + +#[cfg(target_os = "macos")] +pub mod core_video { + #![allow(non_snake_case)] + + #[cfg(target_os = "macos")] + use core_foundation::{ + base::{CFTypeID, TCFType}, + declare_TCFType, impl_CFTypeDescription, impl_TCFType, + }; + #[cfg(target_os = "macos")] + use std::ffi::c_void; + + use crate::bindings::{CVReturn, kCVReturnSuccess}; + pub use crate::bindings::{ + kCVPixelFormatType_32BGRA, kCVPixelFormatType_420YpCbCr8BiPlanarFullRange, + kCVPixelFormatType_420YpCbCr8BiPlanarVideoRange, kCVPixelFormatType_420YpCbCr8Planar, + }; + use anyhow::Result; + use core_foundation::{ + base::kCFAllocatorDefault, dictionary::CFDictionaryRef, mach_port::CFAllocatorRef, + }; + use foreign_types::ForeignTypeRef; + + use metal::{MTLDevice, MTLPixelFormat}; + use std::ptr; + + #[repr(C)] + pub struct __CVMetalTextureCache(c_void); + pub type CVMetalTextureCacheRef = *const __CVMetalTextureCache; + + declare_TCFType!(CVMetalTextureCache, CVMetalTextureCacheRef); + impl_TCFType!( + CVMetalTextureCache, + CVMetalTextureCacheRef, + CVMetalTextureCacheGetTypeID + ); + impl_CFTypeDescription!(CVMetalTextureCache); + + impl CVMetalTextureCache { + /// # Safety + /// + /// metal_device must be valid according to CVMetalTextureCacheCreate + pub unsafe fn new(metal_device: *mut MTLDevice) -> Result { + let mut this = ptr::null(); + let result = unsafe { + CVMetalTextureCacheCreate( + kCFAllocatorDefault, + ptr::null(), + metal_device, + ptr::null(), + &mut this, + ) + }; + anyhow::ensure!( + result == kCVReturnSuccess, + "could not create texture cache, code: {result}" + ); + unsafe { Ok(CVMetalTextureCache::wrap_under_create_rule(this)) } + } + + /// # Safety + /// + /// The arguments to this function must be valid according to CVMetalTextureCacheCreateTextureFromImage + pub unsafe fn create_texture_from_image( + &self, + source: ::core_video::image_buffer::CVImageBufferRef, + texture_attributes: CFDictionaryRef, + pixel_format: MTLPixelFormat, + width: usize, + height: usize, + plane_index: usize, + ) -> Result { + let mut this = ptr::null(); + let result = unsafe { + CVMetalTextureCacheCreateTextureFromImage( + kCFAllocatorDefault, + self.as_concrete_TypeRef(), + source, + texture_attributes, + pixel_format, + width, + height, + plane_index, + &mut this, + ) + }; + anyhow::ensure!( + result == kCVReturnSuccess, + "could not create texture, code: {result}" + ); + unsafe { Ok(CVMetalTexture::wrap_under_create_rule(this)) } + } + } + + #[link(name = "CoreVideo", kind = "framework")] + unsafe extern "C" { + fn CVMetalTextureCacheGetTypeID() -> CFTypeID; + fn CVMetalTextureCacheCreate( + allocator: CFAllocatorRef, + cache_attributes: CFDictionaryRef, + metal_device: *const MTLDevice, + texture_attributes: CFDictionaryRef, + cache_out: *mut CVMetalTextureCacheRef, + ) -> CVReturn; + fn CVMetalTextureCacheCreateTextureFromImage( + allocator: CFAllocatorRef, + texture_cache: CVMetalTextureCacheRef, + source_image: ::core_video::image_buffer::CVImageBufferRef, + texture_attributes: CFDictionaryRef, + pixel_format: MTLPixelFormat, + width: usize, + height: usize, + plane_index: usize, + texture_out: *mut CVMetalTextureRef, + ) -> CVReturn; + } + + #[repr(C)] + pub struct __CVMetalTexture(c_void); + pub type CVMetalTextureRef = *const __CVMetalTexture; + + declare_TCFType!(CVMetalTexture, CVMetalTextureRef); + impl_TCFType!(CVMetalTexture, CVMetalTextureRef, CVMetalTextureGetTypeID); + impl_CFTypeDescription!(CVMetalTexture); + + impl CVMetalTexture { + pub fn as_texture_ref(&self) -> &metal::TextureRef { + unsafe { + let texture = CVMetalTextureGetTexture(self.as_concrete_TypeRef()); + metal::TextureRef::from_ptr(texture as *mut _) + } + } + } + + #[link(name = "CoreVideo", kind = "framework")] + unsafe extern "C" { + fn CVMetalTextureGetTypeID() -> CFTypeID; + fn CVMetalTextureGetTexture(texture: CVMetalTextureRef) -> *mut c_void; + } +} diff --git a/crates/gpui_refineable/Cargo.toml b/crates/gpui_refineable/Cargo.toml new file mode 100644 index 0000000000..ab3e54a77d --- /dev/null +++ b/crates/gpui_refineable/Cargo.toml @@ -0,0 +1,15 @@ +[package] +name = "gpui_refineable" +version = "0.2.2" +edition = "2024" +license = "Apache-2.0" +publish = true +description = "Refineable trait + cascade for gpui-ce (vendored from Zed)." + +[lib] +name = "refineable" +path = "src/refineable.rs" +doctest = false + +[dependencies] +derive_refineable = { package = "gpui_derive_refineable", version = "0.2.2", path = "../gpui_derive_refineable" } diff --git a/crates/gpui_refineable/LICENSE-APACHE b/crates/gpui_refineable/LICENSE-APACHE new file mode 100644 index 0000000000..461a0fe5ba --- /dev/null +++ b/crates/gpui_refineable/LICENSE-APACHE @@ -0,0 +1,222 @@ +Copyright 2022 - 2025 Zed Industries, Inc. + + + 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. + + + + +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 diff --git a/crates/gpui_refineable/src/refineable.rs b/crates/gpui_refineable/src/refineable.rs new file mode 100644 index 0000000000..b2305d4b5a --- /dev/null +++ b/crates/gpui_refineable/src/refineable.rs @@ -0,0 +1,132 @@ +pub use derive_refineable::Refineable; + +/// A trait for types that can be refined with partial updates. +/// +/// The `Refineable` trait enables hierarchical configuration patterns where a base configuration +/// can be selectively overridden by refinements. This is particularly useful for styling and +/// settings, and theme hierarchies. +/// +/// # Derive Macro +/// +/// The `#[derive(Refineable)]` macro automatically generates a companion refinement type and +/// implements this trait. For a struct `Style`, it creates `StyleRefinement` where each field is +/// wrapped appropriately: +/// +/// - **Refineable fields** (marked with `#[refineable]`): Become the corresponding refinement type +/// (e.g., `Bar` becomes `BarRefinement`, or `BarRefinement` remains `BarRefinement`) +/// - **Optional fields** (`Option`): Remain as `Option` +/// - **Regular fields**: Become `Option` +/// +/// ## Attributes +/// +/// The derive macro supports these attributes on the struct: +/// - `#[refineable(Debug)]`: Implements `Debug` for the refinement type +/// - `#[refineable(Serialize)]`: Derives `Serialize` which skips serializing `None` +/// - `#[refineable(OtherTrait)]`: Derives additional traits on the refinement type +/// +/// Fields can be marked with: +/// - `#[refineable]`: Field is itself refineable (uses nested refinement type) +pub trait Refineable: Clone { + type Refinement: Refineable + IsEmpty + Default; + + /// Applies the given refinement to this instance, modifying it in place. + /// + /// Only non-empty values in the refinement are applied. + /// + /// * For refineable fields, this recursively calls `refine`. + /// * For other fields, the value is replaced if present in the refinement. + fn refine(&mut self, refinement: &Self::Refinement); + + /// Returns a new instance with the refinement applied, equivalent to cloning `self` and calling + /// `refine` on it. + fn refined(self, refinement: Self::Refinement) -> Self; + + /// Creates an instance from a cascade by merging all refinements atop the default value. + fn from_cascade(cascade: &Cascade) -> Self + where + Self: Default + Sized, + { + Self::default().refined(cascade.merged()) + } + + /// Returns `true` if this instance would contain all values from the refinement. + /// + /// For refineable fields, this recursively checks `is_superset_of`. For other fields, this + /// checks if the refinement's `Some` values match this instance's values. + fn is_superset_of(&self, refinement: &Self::Refinement) -> bool; + + /// Returns a refinement that represents the difference between this instance and the given + /// refinement. + /// + /// For refineable fields, this recursively calls `subtract`. For other fields, the field is + /// `None` if the field's value is equal to the refinement. + fn subtract(&self, refinement: &Self::Refinement) -> Self::Refinement; +} + +pub trait IsEmpty { + /// Returns `true` if applying this refinement would have no effect. + fn is_empty(&self) -> bool; +} + +/// A cascade of refinements that can be merged in priority order. +/// +/// A cascade maintains a sequence of optional refinements where later entries +/// take precedence over earlier ones. The first slot (index 0) is always the +/// base refinement and is guaranteed to be present. +/// +/// This is useful for implementing configuration hierarchies like CSS cascading, +/// where styles from different sources (user agent, user, author) are combined +/// with specific precedence rules. +pub struct Cascade(Vec>); + +impl Default for Cascade { + fn default() -> Self { + Self(vec![Some(Default::default())]) + } +} + +/// A handle to a specific slot in a cascade. +/// +/// Slots are used to identify specific positions in the cascade where +/// refinements can be set or updated. +#[derive(Copy, Clone)] +pub struct CascadeSlot(usize); + +impl Cascade { + /// Reserves a new slot in the cascade and returns a handle to it. + /// + /// The new slot is initially empty (`None`) and can be populated later + /// using `set()`. + pub fn reserve(&mut self) -> CascadeSlot { + self.0.push(None); + CascadeSlot(self.0.len() - 1) + } + + /// Returns a mutable reference to the base refinement (slot 0). + /// + /// The base refinement is always present and serves as the foundation + /// for the cascade. + pub fn base(&mut self) -> &mut S::Refinement { + self.0[0].as_mut().unwrap() + } + + /// Sets the refinement for a specific slot in the cascade. + /// + /// Setting a slot to `None` effectively removes it from consideration + /// during merging. + pub fn set(&mut self, slot: CascadeSlot, refinement: Option) { + self.0[slot.0] = refinement + } + + /// Merges all refinements in the cascade into a single refinement. + /// + /// Refinements are applied in order, with later slots taking precedence. + /// Empty slots (`None`) are skipped during merging. + pub fn merged(&self) -> S::Refinement { + let mut merged = self.0[0].clone().unwrap(); + for refinement in self.0.iter().skip(1).flatten() { + merged.refine(refinement); + } + merged + } +} diff --git a/crates/gpui_scheduler/Cargo.toml b/crates/gpui_scheduler/Cargo.toml new file mode 100644 index 0000000000..b5f3e230c2 --- /dev/null +++ b/crates/gpui_scheduler/Cargo.toml @@ -0,0 +1,25 @@ +[package] +name = "gpui_scheduler" +version = "0.2.2" +edition = "2024" +license = "Apache-2.0" +publish = true +description = "Async task scheduler/executor for gpui-ce (vendored from Zed)." + +[lib] +name = "scheduler" +path = "src/scheduler.rs" +doctest = false + +[features] +test-support = [] + +[dependencies] +async-task = "4.7" +backtrace = "0.3.76" +chrono = { version = "0.4.42", features = ["serde"] } +flume = "0.11" +futures = "0.3.32" +parking_lot = "0.12.5" +rand = "0.9.4" +web-time = "1.1.0" diff --git a/crates/gpui_scheduler/LICENSE-APACHE b/crates/gpui_scheduler/LICENSE-APACHE new file mode 100644 index 0000000000..461a0fe5ba --- /dev/null +++ b/crates/gpui_scheduler/LICENSE-APACHE @@ -0,0 +1,222 @@ +Copyright 2022 - 2025 Zed Industries, Inc. + + + 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. + + + + +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 diff --git a/crates/gpui_scheduler/src/clock.rs b/crates/gpui_scheduler/src/clock.rs new file mode 100644 index 0000000000..c015fec153 --- /dev/null +++ b/crates/gpui_scheduler/src/clock.rs @@ -0,0 +1,55 @@ +use chrono::{DateTime, Utc}; +use parking_lot::Mutex; +use std::time::Duration; + +pub use web_time::Instant; + +pub trait Clock { + fn utc_now(&self) -> DateTime; + fn now(&self) -> Instant; +} + +pub struct TestClock(Mutex); + +struct TestClockState { + now: Instant, + utc_now: DateTime, +} + +impl TestClock { + pub fn new() -> Self { + const START_TIME: &str = "2025-07-01T23:59:58-00:00"; + let utc_now = DateTime::parse_from_rfc3339(START_TIME).unwrap().to_utc(); + Self(Mutex::new(TestClockState { + now: Instant::now(), + utc_now, + })) + } + + pub fn set_utc_now(&self, now: DateTime) { + let mut state = self.0.lock(); + state.utc_now = now; + } + + pub fn advance(&self, duration: Duration) { + let mut state = self.0.lock(); + state.now += duration; + state.utc_now += duration; + } +} + +impl Default for TestClock { + fn default() -> Self { + Self::new() + } +} + +impl Clock for TestClock { + fn utc_now(&self) -> DateTime { + self.0.lock().utc_now + } + + fn now(&self) -> Instant { + self.0.lock().now + } +} diff --git a/crates/gpui_scheduler/src/executor.rs b/crates/gpui_scheduler/src/executor.rs new file mode 100644 index 0000000000..93645c4a85 --- /dev/null +++ b/crates/gpui_scheduler/src/executor.rs @@ -0,0 +1,546 @@ +use crate::{Instant, Priority, RunnableMeta, Scheduler, SessionId, Timer}; +use async_task::Runnable; +use std::{ + any::Any, + future::Future, + marker::PhantomData, + mem::ManuallyDrop, + panic::Location, + pin::Pin, + rc::Rc, + sync::Arc, + task::{Context, Poll}, + thread::{self, ThreadId}, + time::Duration, +}; + +/// Type-erased closure shape expected by [`Scheduler::spawn_dedicated`]: +/// runs on a [`LocalExecutor`], returns a boxed future whose output is itself +/// boxed as `Box`. +pub type DedicatedFn = Box< + dyn FnOnce(LocalExecutor) -> Pin> + 'static>> + + Send + + 'static, +>; + +/// A `!Send` executor pinned to a single session. Tasks spawned on it run in +/// order on whichever thread drains the dispatch destination supplied at +/// construction time — typically the main thread for the default session, or +/// a dedicated OS thread for sessions created by `spawn_dedicated_thread`. +#[derive(Clone)] +pub struct LocalExecutor { + session_id: SessionId, + scheduler: Arc, + // Spawned tasks' schedule callbacks each hold an `Arc` clone of this + // closure, so the destination it captures stays alive as long as work + // could still land on it. + dispatch: Arc) + Send + Sync>, + not_send: PhantomData>, +} + +impl LocalExecutor { + /// Constructs a local executor that runs spawned tasks by sending their + /// runnables through `dispatch`. The `scheduler` is retained for access to + /// clocks, timers, and other scheduler-level services. + /// + /// For the common case of routing runnables through + /// `Scheduler::schedule_local`, callers pass a closure that does exactly + /// that. `spawn_dedicated_thread` instead passes a closure that sends to + /// the dedicated thread's channel. + pub fn new( + session_id: SessionId, + scheduler: Arc, + dispatch: impl Fn(Runnable) + Send + Sync + 'static, + ) -> Self { + Self { + session_id, + scheduler, + dispatch: Arc::new(dispatch), + not_send: PhantomData, + } + } + + pub fn session_id(&self) -> SessionId { + self.session_id + } + + pub fn scheduler(&self) -> &Arc { + &self.scheduler + } + + #[track_caller] + pub fn spawn(&self, future: F) -> Task + where + F: Future + 'static, + F::Output: 'static, + { + let dispatch = self.dispatch.clone(); + let location = Location::caller(); + let (runnable, task) = spawn_local_with_source_location( + future, + move |runnable| dispatch(runnable), + RunnableMeta { location }, + ); + runnable.schedule(); + Task(TaskState::Spawned(task)) + } + + pub fn block_on(&self, future: Fut) -> Fut::Output { + use std::cell::Cell; + + let output = Cell::new(None); + let future = async { + output.set(Some(future.await)); + }; + let mut future = std::pin::pin!(future); + + self.scheduler + .block(Some(self.session_id), future.as_mut(), None); + + output.take().expect("block_on future did not complete") + } + + /// Block until the future completes or timeout occurs. + /// Returns Ok(output) if completed, Err(future) if timed out. + pub fn block_with_timeout( + &self, + timeout: Duration, + future: Fut, + ) -> Result + use> { + use std::cell::Cell; + + let output = Cell::new(None); + let mut future = Box::pin(future); + + { + let future_ref = &mut future; + let wrapper = async { + output.set(Some(future_ref.await)); + }; + let mut wrapper = std::pin::pin!(wrapper); + + self.scheduler + .block(Some(self.session_id), wrapper.as_mut(), Some(timeout)); + } + + match output.take() { + Some(value) => Ok(value), + None => Err(future), + } + } + + #[track_caller] + pub fn timer(&self, duration: Duration) -> Timer { + self.scheduler.timer(duration) + } + + pub fn now(&self) -> Instant { + self.scheduler.clock().now() + } + + /// Spawn a closure on a fresh session pinned to its own [`LocalExecutor`]. + /// The closure runs on a new OS thread under `PlatformScheduler`, or on + /// the test scheduler's loop under `TestScheduler`. + /// + /// The returned `Task` represents the dedicated work: dropping it cancels + /// the dedicated closure, `.await`ing it yields the closure's return + /// value, `.detach()`ing it lets the dedicated work run independently of + /// the caller. + #[track_caller] + pub fn spawn_dedicated(&self, f: F) -> Task + where + F: FnOnce(LocalExecutor) -> Fut + Send + 'static, + Fut: Future + 'static, + Fut::Output: Send + Sync + 'static, + { + self.scheduler + .clone() + .spawn_dedicated(box_dedicated(f)) + .downcast::() + } +} + +/// Boxes the user-supplied dedicated closure into the type-erased shape +/// expected by [`Scheduler::spawn_dedicated`]. The user's `Fut::Output` is +/// boxed as `Box` on the dedicated side and downcast +/// back to `Fut::Output` by [`Task::downcast`] in the wrapper. +fn box_dedicated(f: F) -> DedicatedFn +where + F: FnOnce(LocalExecutor) -> Fut + Send + 'static, + Fut: Future + 'static, + Fut::Output: Send + Sync + 'static, +{ + Box::new(move |executor| { + Box::pin(async move { Box::new(f(executor).await) as Box }) + }) +} + +#[derive(Clone)] +pub struct BackgroundExecutor { + scheduler: Arc, +} + +impl BackgroundExecutor { + pub fn new(scheduler: Arc) -> Self { + Self { scheduler } + } + + #[track_caller] + pub fn spawn(&self, future: F) -> Task + where + F: Future + Send + 'static, + F::Output: Send + 'static, + { + self.spawn_with_priority(Priority::default(), future) + } + + #[track_caller] + pub fn spawn_with_priority(&self, priority: Priority, future: F) -> Task + where + F: Future + Send + 'static, + F::Output: Send + 'static, + { + let scheduler = Arc::downgrade(&self.scheduler); + let location = Location::caller(); + let (runnable, task) = async_task::Builder::new() + .metadata(RunnableMeta { location }) + .spawn( + move |_| future, + move |runnable| { + if let Some(scheduler) = scheduler.upgrade() { + scheduler.schedule_background_with_priority(runnable, priority); + } + }, + ); + runnable.schedule(); + Task(TaskState::Spawned(task)) + } + + /// Spawns a future on a dedicated realtime thread for audio processing. + #[track_caller] + pub fn spawn_realtime(&self, future: F) -> Task + where + F: Future + Send + 'static, + F::Output: Send + 'static, + { + let location = Location::caller(); + let (tx, rx) = flume::bounded::>(1); + + self.scheduler.spawn_realtime(Box::new(move || { + while let Ok(runnable) = rx.recv() { + runnable.run(); + } + })); + + let (runnable, task) = async_task::Builder::new() + .metadata(RunnableMeta { location }) + .spawn( + move |_| future, + move |runnable| { + let _ = tx.send(runnable); + }, + ); + runnable.schedule(); + Task(TaskState::Spawned(task)) + } + + #[track_caller] + pub fn timer(&self, duration: Duration) -> Timer { + self.scheduler.timer(duration) + } + + pub fn now(&self) -> Instant { + self.scheduler.clock().now() + } + + pub fn scheduler(&self) -> &Arc { + &self.scheduler + } + + /// Spawn a closure on a fresh session pinned to its own [`LocalExecutor`]. + /// The closure runs on a new OS thread under `PlatformScheduler`, or on + /// the test scheduler's loop under `TestScheduler`. + /// + /// The returned `Task` represents the dedicated work: dropping it cancels + /// the dedicated closure, `.await`ing it yields the closure's return + /// value, `.detach()`ing it lets the dedicated work run independently of + /// the caller. + #[track_caller] + pub fn spawn_dedicated(&self, f: F) -> Task + where + F: FnOnce(LocalExecutor) -> Fut + Send + 'static, + Fut: Future + 'static, + Fut::Output: Send + Sync + 'static, + { + self.scheduler + .clone() + .spawn_dedicated(box_dedicated(f)) + .downcast::() + } +} + +/// Task is a primitive that allows work to happen in the background. +/// +/// It implements [`Future`] so you can `.await` on it. +/// +/// If you drop a task it will be cancelled immediately. Calling [`Task::detach`] allows +/// the task to continue running, but with no way to return a value. +#[must_use] +pub struct Task(TaskState); + +enum TaskState { + /// A task that is ready to return a value + Ready(Option), + + /// A task that is currently running. + Spawned(async_task::Task), + + /// A typed view of a [`Task>`] obtained via + /// [`Task::downcast`]. The inner task drives the actual work; the + /// downcast layer just unwraps the `Box` on poll. + Downcast { + inner: Box>>, + marker: PhantomData T>, + }, +} + +impl Task { + /// Creates a new task that will resolve with the value + pub fn ready(val: T) -> Self { + Task(TaskState::Ready(Some(val))) + } + + /// Creates a Task from an async_task::Task + pub fn from_async_task(task: async_task::Task) -> Self { + Task(TaskState::Spawned(task)) + } + + pub fn is_ready(&self) -> bool { + match &self.0 { + TaskState::Ready(_) => true, + TaskState::Spawned(task) => task.is_finished(), + TaskState::Downcast { inner, .. } => inner.is_ready(), + } + } + + /// Detaching a task runs it to completion in the background + pub fn detach(self) { + match self { + Task(TaskState::Ready(_)) => {} + Task(TaskState::Spawned(task)) => task.detach(), + Task(TaskState::Downcast { inner, .. }) => inner.detach(), + } + } + + /// Converts this task into a fallible task that returns `Option`. + pub fn fallible(self) -> FallibleTask { + FallibleTask(match self.0 { + TaskState::Ready(val) => FallibleTaskState::Ready(val), + TaskState::Spawned(task) => FallibleTaskState::Spawned(task.fallible()), + TaskState::Downcast { inner, .. } => FallibleTaskState::Downcast { + inner: Box::new(inner.fallible()), + marker: PhantomData, + }, + }) + } +} + +impl Task> { + /// Reinterprets the boxed output as a concrete `T` via downcast on + /// completion. Used by [`LocalExecutor::spawn_dedicated`] and + /// [`BackgroundExecutor::spawn_dedicated`] to recover the user closure's + /// `Fut::Output` from the dyn-safe [`Scheduler::spawn_dedicated`]. + /// + /// Panics on poll if the inner output is not in fact a `T` -- a logic + /// error in whatever produced the inner task, since the downcast type is + /// chosen by the caller of `downcast`. + pub fn downcast(self) -> Task { + Task(TaskState::Downcast { + inner: Box::new(self), + marker: PhantomData, + }) + } +} + +impl std::fmt::Debug for Task { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.0 { + TaskState::Ready(_) => f.debug_tuple("Task::Ready").finish(), + TaskState::Spawned(task) => f.debug_tuple("Task::Spawned").field(task).finish(), + TaskState::Downcast { inner, .. } => { + f.debug_tuple("Task::Downcast").field(inner).finish() + } + } + } +} + +/// A task that returns `Option` instead of panicking when cancelled. +#[must_use] +pub struct FallibleTask(FallibleTaskState); + +enum FallibleTaskState { + /// A task that is ready to return a value + Ready(Option), + + /// A task that is currently running (wraps async_task::FallibleTask). + Spawned(async_task::FallibleTask), + + /// Mirror of [`TaskState::Downcast`] for fallible tasks. + Downcast { + inner: Box>>, + marker: PhantomData T>, + }, +} + +impl FallibleTask { + /// Creates a new fallible task that will resolve with the value. + pub fn ready(val: T) -> Self { + FallibleTask(FallibleTaskState::Ready(Some(val))) + } + + /// Detaching a task runs it to completion in the background. + pub fn detach(self) { + match self.0 { + FallibleTaskState::Ready(_) => {} + FallibleTaskState::Spawned(task) => task.detach(), + FallibleTaskState::Downcast { inner, .. } => inner.detach(), + } + } +} + +impl Future for FallibleTask { + type Output = Option; + + fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + match unsafe { self.get_unchecked_mut() } { + FallibleTask(FallibleTaskState::Ready(val)) => Poll::Ready(val.take()), + FallibleTask(FallibleTaskState::Spawned(task)) => Pin::new(task).poll(cx), + FallibleTask(FallibleTaskState::Downcast { inner, .. }) => { + match Pin::new(inner.as_mut()).poll(cx) { + Poll::Ready(Some(boxed_any)) => Poll::Ready(Some( + *boxed_any + .downcast::() + .expect("FallibleTask::poll: downcast type mismatch"), + )), + Poll::Ready(None) => Poll::Ready(None), + Poll::Pending => Poll::Pending, + } + } + } + } +} + +impl std::fmt::Debug for FallibleTask { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + match &self.0 { + FallibleTaskState::Ready(_) => f.debug_tuple("FallibleTask::Ready").finish(), + FallibleTaskState::Spawned(task) => { + f.debug_tuple("FallibleTask::Spawned").field(task).finish() + } + FallibleTaskState::Downcast { inner, .. } => f + .debug_tuple("FallibleTask::Downcast") + .field(inner) + .finish(), + } + } +} + +impl Future for Task { + type Output = T; + + fn poll(self: Pin<&mut Self>, cx: &mut Context) -> Poll { + match unsafe { self.get_unchecked_mut() } { + Task(TaskState::Ready(val)) => Poll::Ready(val.take().unwrap()), + Task(TaskState::Spawned(task)) => Pin::new(task).poll(cx), + Task(TaskState::Downcast { inner, .. }) => match Pin::new(inner.as_mut()).poll(cx) { + Poll::Ready(boxed_any) => Poll::Ready( + *boxed_any + .downcast::() + .expect("Task::poll: downcast type mismatch"), + ), + Poll::Pending => Poll::Pending, + }, + } + } +} + +/// Variant of `async_task::spawn_local` that includes the source location of the spawn in panics. +#[track_caller] +fn spawn_local_with_source_location( + future: Fut, + schedule: S, + metadata: RunnableMeta, +) -> ( + async_task::Runnable, + async_task::Task, +) +where + Fut: Future + 'static, + Fut::Output: 'static, + S: async_task::Schedule + Send + Sync + 'static, +{ + #[inline] + fn thread_id() -> ThreadId { + std::thread_local! { + static ID: ThreadId = thread::current().id(); + } + ID.try_with(|id| *id) + .unwrap_or_else(|_| thread::current().id()) + } + + struct Checked { + id: ThreadId, + inner: ManuallyDrop, + location: &'static Location<'static>, + } + + impl Drop for Checked { + fn drop(&mut self) { + assert_eq!( + self.id, + thread_id(), + "local task dropped by a thread that didn't spawn it. Task spawned at {}", + self.location + ); + // SAFETY: `inner` is wrapped in `ManuallyDrop`, so this is the only + // place it is dropped. The thread check above ensures local futures + // are dropped on the thread that created them. + unsafe { ManuallyDrop::drop(&mut self.inner) }; + } + } + + impl Future for Checked { + type Output = F::Output; + + fn poll(self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + // SAFETY: We don't move any fields out of `self`; this mutable + // reference is only used to check metadata and to project the pin to + // `inner` below. + let this = unsafe { self.get_unchecked_mut() }; + assert!( + this.id == thread_id(), + "local task polled by a thread that didn't spawn it. Task spawned at {}", + this.location + ); + // SAFETY: `inner` is structurally pinned by `Checked`; after + // `Checked` is pinned, `inner` is never moved. The thread check + // above ensures the local future is only polled by its spawning + // thread. + unsafe { Pin::new_unchecked(&mut *this.inner).poll(cx) } + } + } + + let location = metadata.location; + + let future = move |_| Checked { + id: thread_id(), + inner: ManuallyDrop::new(future), + location, + }; + + let builder = async_task::Builder::new().metadata(metadata); + // SAFETY: `Checked` enforces the invariants required by `spawn_unchecked`: + // the non-`Send` future is only polled and dropped on the thread that + // spawned it. + unsafe { builder.spawn_unchecked(future, schedule) } +} diff --git a/crates/gpui_scheduler/src/scheduler.rs b/crates/gpui_scheduler/src/scheduler.rs new file mode 100644 index 0000000000..402d49ea18 --- /dev/null +++ b/crates/gpui_scheduler/src/scheduler.rs @@ -0,0 +1,209 @@ +mod clock; +mod executor; +mod test_scheduler; +#[cfg(test)] +mod tests; + +pub use clock::*; +pub use executor::*; +pub use test_scheduler::*; + +use async_task::Runnable; +use futures::channel::oneshot; +use std::{ + any::Any, + future::Future, + panic::Location, + pin::Pin, + sync::Arc, + task::{Context, Poll}, + thread, + time::Duration, +}; + +/// Task priority for background tasks. +/// +/// Higher priority tasks are more likely to be scheduled before lower priority tasks, +/// but this is not a strict guarantee - the scheduler may interleave tasks of different +/// priorities to prevent starvation. +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)] +#[repr(u8)] +pub enum Priority { + /// Realtime priority + /// + /// Spawning a task with this priority will spin it off on a separate thread dedicated just to that task. Only use for audio. + RealtimeAudio, + /// High priority - use for tasks critical to user experience/responsiveness. + High, + /// Medium priority - suitable for most use cases. + #[default] + Medium, + /// Low priority - use for background work that can be deprioritized. + Low, +} + +impl Priority { + /// Returns the relative probability weight for this priority level. + /// Used by schedulers to determine task selection probability. + pub const fn weight(self) -> u32 { + match self { + Priority::High => 60, + Priority::Medium => 30, + Priority::Low => 10, + // realtime priorities are not considered for probability scheduling + Priority::RealtimeAudio => 0, + } + } +} + +/// Metadata attached to runnables for debugging and profiling. +#[derive(Clone)] +pub struct RunnableMeta { + /// The source location where the task was spawned. + pub location: &'static Location<'static>, +} + +impl std::fmt::Debug for RunnableMeta { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_struct("RunnableMeta") + .field("location", &self.location) + .finish() + } +} + +pub trait Scheduler: Send + Sync { + /// Block until the given future completes or timeout occurs. + /// + /// Returns `true` if the future completed, `false` if it timed out. + /// The future is passed as a pinned mutable reference so the caller + /// retains ownership and can continue polling or return it on timeout. + fn block( + &self, + session_id: Option, + future: Pin<&mut dyn Future>, + timeout: Option, + ) -> bool; + + /// Schedule a runnable on the local (session-pinned) queue for `session_id`. + /// Runnables scheduled here run in order on whichever thread drains the + /// session — the main thread for ordinary sessions, or a dedicated OS + /// thread for sessions created via `spawn_dedicated_thread`. + fn schedule_local(&self, session_id: SessionId, runnable: Runnable); + + /// Schedule a background task with the given priority. + fn schedule_background_with_priority( + &self, + runnable: Runnable, + priority: Priority, + ); + + /// Spawn a closure on a dedicated realtime thread for audio processing. + fn spawn_realtime(&self, f: Box); + + /// Schedule a background task with default (medium) priority. + fn schedule_background(&self, runnable: Runnable) { + self.schedule_background_with_priority(runnable, Priority::default()); + } + + #[track_caller] + fn timer(&self, timeout: Duration) -> Timer; + fn clock(&self) -> Arc; + + /// Spawn a closure on a fresh session pinned to its own [`LocalExecutor`]. + /// + /// `PlatformScheduler` runs the closure on a new OS thread (see + /// [`spawn_dedicated_thread`]). `TestScheduler` runs it on the test + /// scheduler's loop alongside everything else so determinism under + /// `TestScheduler::many` is preserved. + /// + /// This is the dyn-safe entry point: the closure's output is type-erased + /// as `Box` so the trait stays object-safe. + /// Callers typically reach for the type-safe wrappers on + /// [`LocalExecutor::spawn_dedicated`] and + /// [`BackgroundExecutor::spawn_dedicated`], which compose this method + /// with [`Task::downcast`] to recover the closure's concrete return type. + fn spawn_dedicated(self: Arc, f: DedicatedFn) -> Task>; + + fn as_test(&self) -> Option<&TestScheduler> { + None + } +} + +/// Spawn work on a fresh OS thread that's exclusive to the returned task and +/// anything spawned on the executor it provides. Blocking syscalls inside that +/// work don't disturb any other executor in the process. +/// +/// `f` is called on the dedicated thread with a [`LocalExecutor`] pinned +/// to it. The future `f` returns may freely be `!Send`. The returned `Task` is +/// that future's task: dropping it cancels the root, but detached children +/// keep running until they finish. The thread shuts down once the executor and +/// every task on it are gone. +/// +/// The caller is responsible for supplying a `session_id` that's distinct from +/// every other live session on `scheduler`. Concrete schedulers typically wrap +/// this in an inherent method that allocates the id from their own counter. +pub fn spawn_dedicated_thread( + session_id: SessionId, + scheduler: Arc, + f: F, +) -> Task +where + F: FnOnce(LocalExecutor) -> Fut + Send + 'static, + Fut: Future + 'static, + Fut::Output: Send + 'static, +{ + let (runnable_sender, runnable_receiver) = flume::unbounded::>(); + let (task_sender, task_receiver) = flume::bounded::>(1); + + thread::Builder::new() + .name(format!("spawn_dedicated session {:?}", session_id)) + .spawn(move || { + let dispatch = move |runnable: Runnable| { + let _ = runnable_sender.send(runnable); + }; + let executor = LocalExecutor::new(session_id, scheduler, dispatch); + let root_task = executor.spawn(f(executor.clone())); + let _ = task_sender.send(root_task); + // After this drop, every strong reference to the runnable sender + // lives inside a spawned task or a user-held executor clone. The + // recv loop exits once all of those are gone. + drop(executor); + + while let Ok(runnable) = runnable_receiver.recv() { + runnable.run(); + } + }) + .expect("failed to spawn dedicated thread"); + + task_receiver + .recv() + .expect("dedicated thread failed to produce root task") +} + +#[derive(Copy, Clone, Debug, Eq, PartialEq, Ord, PartialOrd, Hash)] +pub struct SessionId(u16); + +impl SessionId { + pub fn new(id: u16) -> Self { + SessionId(id) + } +} + +pub struct Timer(oneshot::Receiver<()>); + +impl Timer { + pub fn new(rx: oneshot::Receiver<()>) -> Self { + Timer(rx) + } +} + +impl Future for Timer { + type Output = (); + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll<()> { + match Pin::new(&mut self.0).poll(cx) { + Poll::Ready(_) => Poll::Ready(()), + Poll::Pending => Poll::Pending, + } + } +} diff --git a/crates/gpui_scheduler/src/test_scheduler.rs b/crates/gpui_scheduler/src/test_scheduler.rs new file mode 100644 index 0000000000..4dc06a06e4 --- /dev/null +++ b/crates/gpui_scheduler/src/test_scheduler.rs @@ -0,0 +1,926 @@ +use crate::{ + BackgroundExecutor, Clock, Instant, LocalExecutor, Priority, RunnableMeta, Scheduler, + SessionId, Task, TestClock, Timer, +}; +use async_task::Runnable; +use backtrace::{Backtrace, BacktraceFrame}; +use futures::channel::oneshot; +use parking_lot::{Mutex, MutexGuard}; +use rand::{ + distr::{StandardUniform, uniform::SampleRange, uniform::SampleUniform}, + prelude::*, +}; +use std::any::Any; +use std::{ + any::type_name_of_val, + collections::{BTreeMap, HashSet, VecDeque}, + env, + fmt::Write, + future::Future, + mem, + ops::RangeInclusive, + panic::{self, AssertUnwindSafe}, + pin::Pin, + sync::{ + Arc, + atomic::{AtomicBool, Ordering::SeqCst}, + }, + task::{Context, Poll, RawWaker, RawWakerVTable, Waker}, + thread::{self, Thread}, + time::Duration, +}; + +const PENDING_TRACES_VAR_NAME: &str = "PENDING_TRACES"; + +pub struct TestScheduler { + clock: Arc, + rng: Arc>, + state: Arc>, + thread: Thread, +} + +impl TestScheduler { + /// Run a test once with default configuration (seed 0) + pub fn once(f: impl AsyncFnOnce(Arc) -> R) -> R { + Self::with_seed(0, f) + } + + /// Run a test multiple times with sequential seeds (0, 1, 2, ...) + pub fn many( + default_iterations: usize, + mut f: impl AsyncFnMut(Arc) -> R, + ) -> Vec { + let num_iterations = std::env::var("ITERATIONS") + .map(|iterations| iterations.parse().unwrap()) + .unwrap_or(default_iterations); + + let seed = std::env::var("SEED") + .map(|seed| seed.parse().unwrap()) + .unwrap_or(0); + + let interactive = !std::env::var("SCHEDULER_NONINTERACTIVE").is_ok(); + + (seed..seed + num_iterations as u64) + .map(|seed| { + let mut unwind_safe_f = AssertUnwindSafe(&mut f); + if interactive { + eprintln!("Running seed: {seed}"); + } + match panic::catch_unwind(move || Self::with_seed(seed, &mut *unwind_safe_f)) { + Ok(result) => result, + Err(error) => { + eprintln!("\x1b[31mFailing Seed: {seed}\x1b[0m"); + panic::resume_unwind(error); + } + } + }) + .collect() + } + + fn with_seed(seed: u64, f: impl AsyncFnOnce(Arc) -> R) -> R { + let scheduler = Arc::new(TestScheduler::new(TestSchedulerConfig::with_seed(seed))); + let future = f(scheduler.clone()); + let result = scheduler.foreground().block_on(future); + scheduler.run(); // Ensure spawned tasks finish up before returning in tests + result + } + + pub fn new(config: TestSchedulerConfig) -> Self { + Self { + rng: Arc::new(Mutex::new(StdRng::seed_from_u64(config.seed))), + state: Arc::new(Mutex::new(SchedulerState { + runnables: VecDeque::new(), + timers: Vec::new(), + blocked_sessions: Vec::new(), + randomize_order: config.randomize_order, + allow_parking: config.allow_parking, + timeout_ticks: config.timeout_ticks, + next_session_id: SessionId(0), + capture_pending_traces: config.capture_pending_traces, + pending_traces: BTreeMap::new(), + next_trace_id: TraceId(0), + is_main_thread: true, + non_determinism_error: None, + finished: false, + parking_allowed_once: false, + unparked: false, + })), + clock: Arc::new(TestClock::new()), + thread: thread::current(), + } + } + + pub fn end_test(&self) { + let mut state = self.state.lock(); + if let Some((message, backtrace)) = &state.non_determinism_error { + if cfg!(miri) { + // miri cannot debug print backtraces with `miri-disable-isolation` enabled + panic!("{}", message) + } else { + panic!("{}\n{:?}", message, backtrace) + } + } + state.finished = true; + } + + pub fn clock(&self) -> Arc { + self.clock.clone() + } + + pub fn rng(&self) -> SharedRng { + SharedRng(self.rng.clone()) + } + + pub fn set_timeout_ticks(&self, timeout_ticks: RangeInclusive) { + self.state.lock().timeout_ticks = timeout_ticks; + } + + pub fn allow_parking(&self) { + let mut state = self.state.lock(); + state.allow_parking = true; + state.parking_allowed_once = true; + } + + pub fn forbid_parking(&self) { + self.state.lock().allow_parking = false; + } + + pub fn parking_allowed(&self) -> bool { + self.state.lock().allow_parking + } + + pub fn is_main_thread(&self) -> bool { + self.state.lock().is_main_thread + } + + pub fn allocate_session_id(&self) -> SessionId { + let mut state = self.state.lock(); + state.next_session_id.0 += 1; + state.next_session_id + } + + /// Create a local executor for this scheduler. + pub fn foreground(self: &Arc) -> LocalExecutor { + let session_id = self.allocate_session_id(); + let scheduler = Arc::downgrade(self); + LocalExecutor::new(session_id, self.clone(), move |runnable| { + if let Some(scheduler) = scheduler.upgrade() { + scheduler.schedule_local(session_id, runnable); + } + }) + } + + /// Create a background executor for this scheduler + pub fn background(self: &Arc) -> BackgroundExecutor { + BackgroundExecutor::new(self.clone()) + } + + pub fn yield_random(&self) -> Yield { + let rng = &mut *self.rng.lock(); + if rng.random_bool(0.1) { + Yield(rng.random_range(10..20)) + } else { + Yield(rng.random_range(0..2)) + } + } + + pub fn run(&self) { + while self.step() { + // Continue until no work remains + } + } + + pub fn run_with_clock_advancement(&self) { + while self.step() || self.advance_clock_to_next_timer() { + // Continue until no work remains + } + } + + /// Execute one tick of the scheduler, processing expired timers and running + /// at most one task. Returns true if any work was done. + /// + /// This is the public interface for GPUI's TestDispatcher to drive task execution. + pub fn tick(&self) -> bool { + self.step_filtered(false) + } + + /// Execute one tick, but only run background tasks (no foreground/session tasks). + /// Returns true if any work was done. + pub fn tick_background_only(&self) -> bool { + self.step_filtered(true) + } + + /// Check if there are any pending tasks or timers that could run. + pub fn has_pending_tasks(&self) -> bool { + let state = self.state.lock(); + !state.runnables.is_empty() || !state.timers.is_empty() + } + + /// Returns counts of (foreground_tasks, background_tasks) currently queued. + /// Foreground tasks are those with a session_id, background tasks have none. + pub fn pending_task_counts(&self) -> (usize, usize) { + let state = self.state.lock(); + let foreground = state + .runnables + .iter() + .filter(|r| r.session_id.is_some()) + .count(); + let background = state + .runnables + .iter() + .filter(|r| r.session_id.is_none()) + .count(); + (foreground, background) + } + + fn step(&self) -> bool { + self.step_filtered(false) + } + + fn step_filtered(&self, background_only: bool) -> bool { + let (elapsed_count, runnables_before) = { + let mut state = self.state.lock(); + let end_ix = state + .timers + .partition_point(|timer| timer.expiration <= self.clock.now()); + let elapsed: Vec<_> = state.timers.drain(..end_ix).collect(); + let count = elapsed.len(); + let runnables = state.runnables.len(); + drop(state); + // Dropping elapsed timers here wakes the waiting futures + drop(elapsed); + (count, runnables) + }; + + if elapsed_count > 0 { + let runnables_after = self.state.lock().runnables.len(); + if std::env::var("DEBUG_SCHEDULER").is_ok() { + eprintln!( + "[scheduler] Expired {} timers at {:?}, runnables: {} -> {}", + elapsed_count, + self.clock.now(), + runnables_before, + runnables_after + ); + } + return true; + } + + let runnable = { + let state = &mut *self.state.lock(); + + // Find candidate tasks: + // - For foreground tasks (with session_id), only the first task from each session + // is a candidate (to preserve intra-session ordering) + // - For background tasks (no session_id), all are candidates + // - Tasks from blocked sessions are excluded + // - If background_only is true, skip foreground tasks entirely + let mut seen_sessions = HashSet::new(); + let candidate_indices: Vec = state + .runnables + .iter() + .enumerate() + .filter(|(_, runnable)| { + if let Some(session_id) = runnable.session_id { + // Skip foreground tasks if background_only mode + if background_only { + return false; + } + // Exclude tasks from blocked sessions + if state.blocked_sessions.contains(&session_id) { + return false; + } + // Only include first task from each session (insert returns true if new) + seen_sessions.insert(session_id) + } else { + // Background tasks are always candidates + true + } + }) + .map(|(ix, _)| ix) + .collect(); + + if candidate_indices.is_empty() { + None + } else if state.randomize_order { + // Use priority-weighted random selection + let weights: Vec = candidate_indices + .iter() + .map(|&ix| state.runnables[ix].priority.weight()) + .collect(); + let total_weight: u32 = weights.iter().sum(); + + if total_weight == 0 { + // Fallback to uniform random if all weights are zero + let choice = self.rng.lock().random_range(0..candidate_indices.len()); + state.runnables.remove(candidate_indices[choice]) + } else { + let mut target = self.rng.lock().random_range(0..total_weight); + let mut selected_idx = 0; + for (i, &weight) in weights.iter().enumerate() { + if target < weight { + selected_idx = i; + break; + } + target -= weight; + } + state.runnables.remove(candidate_indices[selected_idx]) + } + } else { + // Non-randomized: just take the first candidate task + state.runnables.remove(candidate_indices[0]) + } + }; + + if let Some(runnable) = runnable { + let is_foreground = runnable.session_id.is_some(); + let was_main_thread = self.state.lock().is_main_thread; + self.state.lock().is_main_thread = is_foreground; + runnable.run(); + self.state.lock().is_main_thread = was_main_thread; + return true; + } + + false + } + + /// Drops all runnable tasks from the scheduler. + /// + /// This is used by the leak detector to ensure that all tasks have been dropped as tasks may keep entities alive otherwise. + /// Why do we even have tasks left when tests finish you may ask. The reason for that is simple, the scheduler itself is the executor and it retains the scheduled runnables. + /// A lot of tasks, including every foreground task contain an executor handle that keeps the test scheduler alive, causing a reference cycle, thus the need for this function right now. + pub fn drain_tasks(&self) { + // dropping runnables may reschedule tasks + // due to drop impls with executors in them + // so drop until we reach a fixpoint + loop { + let mut state = self.state.lock(); + if state.runnables.is_empty() && state.timers.is_empty() { + break; + } + let runnables = std::mem::take(&mut state.runnables); + let timers = std::mem::take(&mut state.timers); + drop(state); + drop(timers); + drop(runnables); + } + } + + pub fn advance_clock_to_next_timer(&self) -> bool { + if let Some(timer) = self.state.lock().timers.first() { + self.clock.advance(timer.expiration - self.clock.now()); + true + } else { + false + } + } + + pub fn advance_clock(&self, duration: Duration) { + let debug = std::env::var("DEBUG_SCHEDULER").is_ok(); + let start = self.clock.now(); + let next_now = start + duration; + if debug { + let timer_count = self.state.lock().timers.len(); + eprintln!( + "[scheduler] advance_clock({:?}) from {:?}, {} pending timers", + duration, start, timer_count + ); + } + loop { + self.run(); + if let Some(timer) = self.state.lock().timers.first() + && timer.expiration <= next_now + { + let advance_to = timer.expiration; + if debug { + eprintln!( + "[scheduler] Advancing clock {:?} -> {:?} for timer", + self.clock.now(), + advance_to + ); + } + self.clock.advance(advance_to - self.clock.now()); + } else { + break; + } + } + self.clock.advance(next_now - self.clock.now()); + if debug { + eprintln!( + "[scheduler] advance_clock done, now at {:?}", + self.clock.now() + ); + } + } + + fn park(&self, deadline: Option) -> bool { + if self.state.lock().allow_parking { + let start = Instant::now(); + // Enforce a hard timeout to prevent tests from hanging indefinitely + let hard_deadline = start + Duration::from_secs(15); + + // Use the earlier of the provided deadline or the hard timeout deadline + let effective_deadline = deadline + .map(|d| d.min(hard_deadline)) + .unwrap_or(hard_deadline); + + // Park in small intervals to allow checking both deadlines + const PARK_INTERVAL: Duration = Duration::from_millis(100); + loop { + let now = Instant::now(); + if now >= effective_deadline { + // Check if we hit the hard timeout + if now >= hard_deadline { + panic!( + "Test timed out after 15 seconds while parking. \ + This may indicate a deadlock or missing waker.", + ); + } + // Hit the provided deadline + return false; + } + + let remaining = effective_deadline.saturating_duration_since(now); + let park_duration = remaining.min(PARK_INTERVAL); + let before_park = Instant::now(); + thread::park_timeout(park_duration); + let elapsed = before_park.elapsed(); + + // Advance the test clock by the real elapsed time while parking + self.clock.advance(elapsed); + + // Check if any timers have expired after advancing the clock. + // If so, return so the caller can process them. + if self + .state + .lock() + .timers + .first() + .is_some_and(|t| t.expiration <= self.clock.now()) + { + return true; + } + + // Check if we were woken up by a different thread. + // We use a flag because timing-based detection is unreliable: + // OS scheduling delays can cause elapsed >= park_duration even when + // we were woken early by unpark(). + if std::mem::take(&mut self.state.lock().unparked) { + return true; + } + } + } else if deadline.is_some() { + false + } else if cfg!(miri) { + // miri cannot debug print backtraces with `miri-disable-isolation` enabled + panic!("Parking forbidden."); + } else if self.state.lock().capture_pending_traces { + let mut pending_traces = String::new(); + for (_, trace) in mem::take(&mut self.state.lock().pending_traces) { + writeln!(pending_traces, "{:?}", exclude_wakers_from_trace(trace)).unwrap(); + } + panic!("Parking forbidden. Pending traces:\n{}", pending_traces); + } else { + panic!( + "Parking forbidden. Re-run with {PENDING_TRACES_VAR_NAME}=1 to show pending traces" + ); + } + } +} + +fn assert_correct_thread(expected: &Thread, state: &Arc>) { + let current_thread = thread::current(); + let mut state = state.lock(); + if state.parking_allowed_once { + return; + } + if current_thread.id() == expected.id() { + return; + } + + let message = format!( + "Detected activity on thread {:?} {:?}, but test scheduler is running on {:?} {:?}. Your test is not deterministic.", + current_thread.name(), + current_thread.id(), + expected.name(), + expected.id(), + ); + let backtrace = Backtrace::new(); + if state.finished { + panic!("{}", message); + } else { + state.non_determinism_error = Some((message, backtrace)) + } +} + +impl Scheduler for TestScheduler { + /// Block until the given future completes, with an optional timeout. If the + /// future is unable to make progress at any moment before the timeout and + /// no other tasks or timers remain, we panic unless parking is allowed. If + /// parking is allowed, we block up to the timeout or indefinitely if none + /// is provided. This is to allow testing a mix of deterministic and + /// non-deterministic async behavior, such as when interacting with I/O in + /// an otherwise deterministic test. + fn block( + &self, + session_id: Option, + mut future: Pin<&mut dyn Future>, + timeout: Option, + ) -> bool { + if let Some(session_id) = session_id { + self.state.lock().blocked_sessions.push(session_id); + } + + let deadline = timeout.map(|timeout| Instant::now() + timeout); + let awoken = Arc::new(AtomicBool::new(false)); + let waker = Box::new(TracingWaker { + id: None, + awoken: awoken.clone(), + thread: self.thread.clone(), + state: self.state.clone(), + }); + let waker = unsafe { Waker::new(Box::into_raw(waker) as *const (), &WAKER_VTABLE) }; + let max_ticks = if timeout.is_some() { + self.rng + .lock() + .random_range(self.state.lock().timeout_ticks.clone()) + } else { + usize::MAX + }; + let mut cx = Context::from_waker(&waker); + + let mut completed = false; + for _ in 0..max_ticks { + match future.as_mut().poll(&mut cx) { + Poll::Ready(()) => { + completed = true; + break; + } + Poll::Pending => {} + } + + let mut stepped = None; + while self.rng.lock().random() { + let stepped = stepped.get_or_insert(false); + if self.step() { + *stepped = true; + } else { + break; + } + } + + let stepped = stepped.unwrap_or(true); + let awoken = awoken.swap(false, SeqCst); + if !stepped && !awoken { + let parking_allowed = self.state.lock().allow_parking; + // In deterministic mode (parking forbidden), instantly jump to the next timer. + // In non-deterministic mode (parking allowed), let real time pass instead. + let advanced_to_timer = !parking_allowed && self.advance_clock_to_next_timer(); + if !advanced_to_timer && !self.park(deadline) { + break; + } + } + } + + if session_id.is_some() { + self.state.lock().blocked_sessions.pop(); + } + + completed + } + + fn schedule_local(&self, session_id: SessionId, runnable: Runnable) { + assert_correct_thread(&self.thread, &self.state); + let mut state = self.state.lock(); + let ix = if state.randomize_order { + let start_ix = state + .runnables + .iter() + .rposition(|task| task.session_id == Some(session_id)) + .map_or(0, |ix| ix + 1); + self.rng + .lock() + .random_range(start_ix..=state.runnables.len()) + } else { + state.runnables.len() + }; + state.runnables.insert( + ix, + ScheduledRunnable { + session_id: Some(session_id), + priority: Priority::default(), + runnable, + }, + ); + state.unparked = true; + drop(state); + self.thread.unpark(); + } + + fn schedule_background_with_priority( + &self, + runnable: Runnable, + priority: Priority, + ) { + assert_correct_thread(&self.thread, &self.state); + let mut state = self.state.lock(); + let ix = if state.randomize_order { + self.rng.lock().random_range(0..=state.runnables.len()) + } else { + state.runnables.len() + }; + state.runnables.insert( + ix, + ScheduledRunnable { + session_id: None, + priority, + runnable, + }, + ); + state.unparked = true; + drop(state); + self.thread.unpark(); + } + + fn spawn_realtime(&self, f: Box) { + std::thread::spawn(move || { + f(); + }); + } + + #[track_caller] + fn timer(&self, duration: Duration) -> Timer { + let (tx, rx) = oneshot::channel(); + let state = &mut *self.state.lock(); + state.timers.push(ScheduledTimer { + expiration: self.clock.now() + duration, + _notify: tx, + }); + state.timers.sort_by_key(|timer| timer.expiration); + Timer(rx) + } + + fn clock(&self) -> Arc { + self.clock.clone() + } + + /// In the test world, dedicated work is just a fresh local session driven + /// by the test scheduler's run loop alongside everything else. No real + /// thread is spawned, so determinism under `TestScheduler::many` is + /// preserved. + fn spawn_dedicated( + self: Arc, + f: Box< + dyn FnOnce( + LocalExecutor, + ) + -> Pin> + 'static>> + + Send + + 'static, + >, + ) -> Task> { + let session_id = self.allocate_session_id(); + let scheduler = Arc::downgrade(&self); + let executor = LocalExecutor::new(session_id, self, move |runnable| { + if let Some(scheduler) = scheduler.upgrade() { + scheduler.schedule_local(session_id, runnable); + } + }); + executor.spawn(f(executor.clone())) + } + + fn as_test(&self) -> Option<&TestScheduler> { + Some(self) + } +} + +#[derive(Clone, Debug)] +pub struct TestSchedulerConfig { + pub seed: u64, + pub randomize_order: bool, + pub allow_parking: bool, + pub capture_pending_traces: bool, + pub timeout_ticks: RangeInclusive, +} + +impl TestSchedulerConfig { + pub fn with_seed(seed: u64) -> Self { + Self { + seed, + ..Default::default() + } + } +} + +impl Default for TestSchedulerConfig { + fn default() -> Self { + Self { + seed: 0, + randomize_order: true, + allow_parking: false, + capture_pending_traces: env::var(PENDING_TRACES_VAR_NAME) + .is_ok_and(|var| var == "1" || var == "true"), + timeout_ticks: 1..=1000, + } + } +} + +struct ScheduledRunnable { + session_id: Option, + priority: Priority, + runnable: Runnable, +} + +impl ScheduledRunnable { + fn run(self) { + self.runnable.run(); + } +} + +struct ScheduledTimer { + expiration: Instant, + _notify: oneshot::Sender<()>, +} + +struct SchedulerState { + runnables: VecDeque, + timers: Vec, + blocked_sessions: Vec, + randomize_order: bool, + allow_parking: bool, + timeout_ticks: RangeInclusive, + next_session_id: SessionId, + capture_pending_traces: bool, + next_trace_id: TraceId, + pending_traces: BTreeMap, + is_main_thread: bool, + non_determinism_error: Option<(String, Backtrace)>, + parking_allowed_once: bool, + finished: bool, + unparked: bool, +} + +const WAKER_VTABLE: RawWakerVTable = RawWakerVTable::new( + TracingWaker::clone_raw, + TracingWaker::wake_raw, + TracingWaker::wake_by_ref_raw, + TracingWaker::drop_raw, +); + +#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord)] +struct TraceId(usize); + +struct TracingWaker { + id: Option, + awoken: Arc, + thread: Thread, + state: Arc>, +} + +impl Clone for TracingWaker { + fn clone(&self) -> Self { + let mut state = self.state.lock(); + let id = if state.capture_pending_traces { + let id = state.next_trace_id; + state.next_trace_id.0 += 1; + state.pending_traces.insert(id, Backtrace::new_unresolved()); + Some(id) + } else { + None + }; + Self { + id, + awoken: self.awoken.clone(), + thread: self.thread.clone(), + state: self.state.clone(), + } + } +} + +impl Drop for TracingWaker { + fn drop(&mut self) { + assert_correct_thread(&self.thread, &self.state); + + if let Some(id) = self.id { + self.state.lock().pending_traces.remove(&id); + } + } +} + +impl TracingWaker { + fn wake(self) { + self.wake_by_ref(); + } + + fn wake_by_ref(&self) { + assert_correct_thread(&self.thread, &self.state); + + let mut state = self.state.lock(); + if let Some(id) = self.id { + state.pending_traces.remove(&id); + } + state.unparked = true; + drop(state); + self.awoken.store(true, SeqCst); + self.thread.unpark(); + } + + fn clone_raw(waker: *const ()) -> RawWaker { + let waker = waker as *const TracingWaker; + let waker = unsafe { &*waker }; + RawWaker::new( + Box::into_raw(Box::new(waker.clone())) as *const (), + &WAKER_VTABLE, + ) + } + + fn wake_raw(waker: *const ()) { + let waker = unsafe { Box::from_raw(waker as *mut TracingWaker) }; + waker.wake(); + } + + fn wake_by_ref_raw(waker: *const ()) { + let waker = waker as *const TracingWaker; + let waker = unsafe { &*waker }; + waker.wake_by_ref(); + } + + fn drop_raw(waker: *const ()) { + let waker = unsafe { Box::from_raw(waker as *mut TracingWaker) }; + drop(waker); + } +} + +pub struct Yield(usize); + +/// A wrapper around `Arc>` that provides convenient methods +/// for random number generation without requiring explicit locking. +#[derive(Clone)] +pub struct SharedRng(Arc>); + +impl SharedRng { + /// Lock the inner RNG for direct access. Use this when you need multiple + /// random operations without re-locking between each one. + pub fn lock(&self) -> MutexGuard<'_, StdRng> { + self.0.lock() + } + + /// Generate a random value in the given range. + pub fn random_range(&self, range: R) -> T + where + T: SampleUniform, + R: SampleRange, + { + self.0.lock().random_range(range) + } + + /// Generate a random boolean with the given probability of being true. + pub fn random_bool(&self, p: f64) -> bool { + self.0.lock().random_bool(p) + } + + /// Generate a random value of the given type. + pub fn random(&self) -> T + where + StandardUniform: Distribution, + { + self.0.lock().random() + } + + /// Generate a random ratio - true with probability `numerator/denominator`. + pub fn random_ratio(&self, numerator: u32, denominator: u32) -> bool { + self.0.lock().random_ratio(numerator, denominator) + } +} + +impl Future for Yield { + type Output = (); + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context) -> Poll { + if self.0 == 0 { + Poll::Ready(()) + } else { + self.0 -= 1; + cx.waker().wake_by_ref(); + Poll::Pending + } + } +} + +fn exclude_wakers_from_trace(mut trace: Backtrace) -> Backtrace { + trace.resolve(); + let mut frames: Vec = trace.into(); + let waker_clone_frame_ix = frames.iter().position(|frame| { + frame.symbols().iter().any(|symbol| { + symbol + .name() + .is_some_and(|name| format!("{name:#?}") == type_name_of_val(&Waker::clone)) + }) + }); + + if let Some(waker_clone_frame_ix) = waker_clone_frame_ix { + frames.drain(..waker_clone_frame_ix + 1); + } + + Backtrace::from(frames) +} diff --git a/crates/gpui_scheduler/src/tests.rs b/crates/gpui_scheduler/src/tests.rs new file mode 100644 index 0000000000..bff1bff963 --- /dev/null +++ b/crates/gpui_scheduler/src/tests.rs @@ -0,0 +1,961 @@ +use super::*; +use futures::{ + FutureExt, + channel::{mpsc, oneshot}, + executor::block_on, + future, + sink::SinkExt, + stream::{FuturesUnordered, StreamExt}, +}; +use std::{ + cell::RefCell, + collections::{BTreeSet, HashSet}, + pin::Pin, + rc::Rc, + sync::Arc, + task::{Context, Poll, Waker}, +}; + +#[test] +fn test_foreground_executor_spawn() { + let result = TestScheduler::once(async |scheduler| { + let task = scheduler.foreground().spawn(async move { 42 }); + task.await + }); + assert_eq!(result, 42); +} + +#[test] +fn test_background_executor_spawn() { + TestScheduler::once(async |scheduler| { + let task = scheduler.background().spawn(async move { 42 }); + let result = task.await; + assert_eq!(result, 42); + }); +} + +#[test] +fn test_scheduler_drops_with_stalled_detached_foreground_task() { + let scheduler = Arc::new(TestScheduler::new(TestSchedulerConfig::default())); + let weak_scheduler = Arc::downgrade(&scheduler); + let (sender, receiver) = oneshot::channel::<()>(); + + scheduler + .foreground() + .spawn(async move { + receiver.await.ok(); + }) + .detach(); + scheduler.run(); + + drop(scheduler); + assert!(weak_scheduler.upgrade().is_none()); + drop(sender); +} + +#[test] +fn test_scheduler_drops_with_stalled_detached_background_task() { + let scheduler = Arc::new(TestScheduler::new(TestSchedulerConfig::default())); + let weak_scheduler = Arc::downgrade(&scheduler); + let (sender, receiver) = oneshot::channel::<()>(); + + scheduler + .background() + .spawn(async move { + receiver.await.ok(); + }) + .detach(); + scheduler.run(); + + drop(scheduler); + assert!(weak_scheduler.upgrade().is_none()); + drop(sender); +} + +#[test] +fn test_foreground_ordering() { + let mut traces = HashSet::new(); + + TestScheduler::many(if cfg!(miri) { 5 } else { 100 }, async |scheduler| { + #[derive(Hash, PartialEq, Eq)] + struct TraceEntry { + session: usize, + task: usize, + } + + let trace = Rc::new(RefCell::new(Vec::new())); + + let foreground_1 = scheduler.foreground(); + for task in 0..10 { + foreground_1 + .spawn({ + let trace = trace.clone(); + async move { + trace.borrow_mut().push(TraceEntry { session: 0, task }); + } + }) + .detach(); + } + + let foreground_2 = scheduler.foreground(); + for task in 0..10 { + foreground_2 + .spawn({ + let trace = trace.clone(); + async move { + trace.borrow_mut().push(TraceEntry { session: 1, task }); + } + }) + .detach(); + } + + scheduler.run(); + + assert_eq!( + trace + .borrow() + .iter() + .filter(|entry| entry.session == 0) + .map(|entry| entry.task) + .collect::>(), + (0..10).collect::>() + ); + assert_eq!( + trace + .borrow() + .iter() + .filter(|entry| entry.session == 1) + .map(|entry| entry.task) + .collect::>(), + (0..10).collect::>() + ); + + traces.insert(trace.take()); + }); + + assert!(traces.len() > 1, "Expected at least two traces"); +} + +#[test] +fn test_timer_ordering() { + TestScheduler::many(1, async |scheduler| { + let background = scheduler.background(); + let futures = FuturesUnordered::new(); + futures.push( + async { + background.timer(Duration::from_millis(100)).await; + 2 + } + .boxed(), + ); + futures.push( + async { + background.timer(Duration::from_millis(50)).await; + 1 + } + .boxed(), + ); + futures.push( + async { + background.timer(Duration::from_millis(150)).await; + 3 + } + .boxed(), + ); + assert_eq!(futures.collect::>().await, vec![1, 2, 3]); + }); +} + +#[test] +fn test_foreground_task_can_hold_mut_borrow_across_await() { + TestScheduler::once(async |scheduler| { + let foreground = scheduler.foreground(); + let (sender, mut receiver) = mpsc::unbounded::<()>(); + + foreground + .spawn(async move { + receiver.next().await; + }) + .detach(); + + scheduler.run(); + sender.unbounded_send(()).unwrap(); + scheduler.run(); + }); +} + +#[test] +fn test_send_from_bg_to_fg() { + TestScheduler::once(async |scheduler| { + let foreground = scheduler.foreground(); + let background = scheduler.background(); + + let (sender, receiver) = oneshot::channel::(); + + background + .spawn(async move { + sender.send(42).unwrap(); + }) + .detach(); + + let task = foreground.spawn(async move { receiver.await.unwrap() }); + let result = task.await; + assert_eq!(result, 42); + }); +} + +#[test] +fn test_randomize_order() { + // Test deterministic mode: different seeds should produce same execution order + let mut deterministic_results = HashSet::new(); + for seed in 0..10 { + let config = TestSchedulerConfig { + seed, + randomize_order: false, + ..Default::default() + }; + let order = block_on(capture_execution_order(config)); + assert_eq!(order.len(), 6); + deterministic_results.insert(order); + } + + // All deterministic runs should produce the same result + assert_eq!( + deterministic_results.len(), + 1, + "Deterministic mode should always produce same execution order" + ); + + // Test randomized mode: different seeds can produce different execution orders + let mut randomized_results = HashSet::new(); + for seed in 0..20 { + let config = TestSchedulerConfig::with_seed(seed); + let order = block_on(capture_execution_order(config)); + assert_eq!(order.len(), 6); + randomized_results.insert(order); + } + + // Randomized mode should produce multiple different execution orders + assert!( + randomized_results.len() > 1, + "Randomized mode should produce multiple different orders" + ); +} + +async fn capture_execution_order(config: TestSchedulerConfig) -> Vec { + let scheduler = Arc::new(TestScheduler::new(config)); + let foreground = scheduler.foreground(); + let background = scheduler.background(); + + let (sender, receiver) = mpsc::unbounded::(); + + // Spawn foreground tasks + for i in 0..3 { + let mut sender = sender.clone(); + foreground + .spawn(async move { + sender.send(format!("fg-{}", i)).await.ok(); + }) + .detach(); + } + + // Spawn background tasks + for i in 0..3 { + let mut sender = sender.clone(); + background + .spawn(async move { + sender.send(format!("bg-{}", i)).await.ok(); + }) + .detach(); + } + + drop(sender); // Close sender to signal no more messages + scheduler.run(); + + receiver.collect().await +} + +#[test] +fn test_block() { + let scheduler = Arc::new(TestScheduler::new(TestSchedulerConfig::default())); + let (tx, rx) = oneshot::channel(); + + // Spawn background task to send value + scheduler + .background() + .spawn(async move { + tx.send(42).unwrap(); + }) + .detach(); + + // Block on receiving the value + let result = scheduler.foreground().block_on(async { rx.await.unwrap() }); + assert_eq!(result, 42); +} + +#[test] +#[should_panic(expected = "Parking forbidden.")] +fn test_parking_panics() { + let config = TestSchedulerConfig { + capture_pending_traces: true, + ..Default::default() + }; + let scheduler = Arc::new(TestScheduler::new(config)); + scheduler.foreground().block_on(async { + let (_tx, rx) = oneshot::channel::<()>(); + rx.await.unwrap(); // This will never complete + }); +} + +#[test] +fn test_block_with_parking() { + let config = TestSchedulerConfig { + allow_parking: true, + ..Default::default() + }; + let scheduler = Arc::new(TestScheduler::new(config)); + let (tx, rx) = oneshot::channel(); + + // Spawn background task to send value + scheduler + .background() + .spawn(async move { + tx.send(42).unwrap(); + }) + .detach(); + + // Block on receiving the value (will park if needed) + let result = scheduler.foreground().block_on(async { rx.await.unwrap() }); + assert_eq!(result, 42); +} + +#[test] +fn test_helper_methods() { + // Test the once method + let result = TestScheduler::once(async |scheduler: Arc| { + let background = scheduler.background(); + background.spawn(async { 42 }).await + }); + assert_eq!(result, 42); + + // Test the many method + let results = TestScheduler::many(3, async |scheduler: Arc| { + let background = scheduler.background(); + background.spawn(async { 10 }).await + }); + assert_eq!(results, vec![10, 10, 10]); +} + +#[test] +fn test_many_with_arbitrary_seed() { + for seed in [0u64, 1, 5, 42] { + let mut seeds_seen = Vec::new(); + let iterations = 3usize; + + for current_seed in seed..seed + iterations as u64 { + let scheduler = Arc::new(TestScheduler::new(TestSchedulerConfig::with_seed( + current_seed, + ))); + let captured_seed = current_seed; + scheduler + .foreground() + .block_on(async { seeds_seen.push(captured_seed) }); + scheduler.run(); + } + + assert_eq!( + seeds_seen, + (seed..seed + iterations as u64).collect::>(), + "Expected {iterations} iterations starting at seed {seed}" + ); + } +} + +#[test] +fn test_block_with_timeout() { + // Test case: future completes within timeout + TestScheduler::once(async |scheduler| { + let foreground = scheduler.foreground(); + let future = future::ready(42); + let output = foreground.block_with_timeout(Duration::from_millis(100), future); + assert_eq!(output.ok(), Some(42)); + }); + + // Test case: future times out + TestScheduler::once(async |scheduler| { + // Make timeout behavior deterministic by forcing the timeout tick budget to be exactly 0. + // This prevents `block_with_timeout` from making progress via extra scheduler stepping and + // accidentally completing work that we expect to time out. + scheduler.set_timeout_ticks(0..=0); + + let foreground = scheduler.foreground(); + let future = future::pending::<()>(); + let output = foreground.block_with_timeout(Duration::from_millis(50), future); + assert!(output.is_err(), "future should not have finished"); + }); + + // Test case: future makes progress via timer but still times out + let mut results = BTreeSet::new(); + TestScheduler::many(if cfg!(miri) { 5 } else { 100 }, async |scheduler| { + // Keep the existing probabilistic behavior here (do not force 0 ticks), since this subtest + // is explicitly checking that some seeds/timeouts can complete while others can time out. + let task = scheduler.background().spawn(async move { + Yield { polls: 10 }.await; + 42 + }); + let output = scheduler + .foreground() + .block_with_timeout(Duration::from_millis(50), task); + results.insert(output.ok()); + }); + assert_eq!( + results.into_iter().collect::>(), + if cfg!(miri) { + vec![Some(42)] + } else { + vec![None, Some(42)] + } + ); + + // Regression test: + // A timed-out future must not be cancelled. The returned future should still be + // pollable to completion later. We also want to ensure time only advances when we + // explicitly advance it (not by yielding). + TestScheduler::once(async |scheduler| { + // Force immediate timeout: the timeout tick budget is 0 so we will not step or + // advance timers inside `block_with_timeout`. + scheduler.set_timeout_ticks(0..=0); + + let background = scheduler.background(); + + // This task should only complete once time is explicitly advanced. + let task = background.spawn({ + let scheduler = scheduler.clone(); + async move { + scheduler.timer(Duration::from_millis(100)).await; + 123 + } + }); + + // This should time out before we advance time enough for the timer to fire. + let timed_out = scheduler + .foreground() + .block_with_timeout(Duration::from_millis(50), task); + assert!( + timed_out.is_err(), + "expected timeout before advancing the clock enough for the timer" + ); + + // Now explicitly advance time and ensure the returned future can complete. + let mut task = timed_out.err().unwrap(); + scheduler.advance_clock(Duration::from_millis(100)); + scheduler.run(); + + let output = scheduler.foreground().block_on(&mut task); + assert_eq!(output, 123); + }); +} + +// When calling block, we shouldn't make progress on foreground-spawned futures with the same session id. +#[test] +fn test_block_does_not_progress_same_session_foreground() { + let mut task2_made_progress_once = false; + TestScheduler::many(if cfg!(miri) { 5 } else { 1000 }, async |scheduler| { + let foreground1 = scheduler.foreground(); + let foreground2 = scheduler.foreground(); + + let task1 = foreground1.spawn(async move {}); + let task2 = foreground2.spawn(async move {}); + + foreground1.block_on(async { + scheduler.yield_random().await; + assert!(!task1.is_ready()); + task2_made_progress_once |= task2.is_ready(); + }); + + task1.await; + task2.await; + }); + + assert!( + task2_made_progress_once, + "Expected task from different foreground executor to make progress (at least once)" + ); +} + +struct Yield { + polls: usize, +} + +impl Future for Yield { + type Output = (); + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + self.polls -= 1; + if self.polls == 0 { + Poll::Ready(()) + } else { + cx.waker().wake_by_ref(); + Poll::Pending + } + } +} + +#[test] +fn test_nondeterministic_wake_detection() { + let config = TestSchedulerConfig { + allow_parking: false, + ..Default::default() + }; + let scheduler = Arc::new(TestScheduler::new(config)); + + // A future that captures its waker and sends it to an external thread + struct SendWakerToThread { + waker_tx: Option>, + } + + impl Future for SendWakerToThread { + type Output = (); + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + if let Some(tx) = self.waker_tx.take() { + tx.send(cx.waker().clone()).ok(); + } + Poll::Ready(()) + } + } + + let (waker_tx, waker_rx) = std::sync::mpsc::channel::(); + + // Get a waker by running a future that sends it + scheduler.foreground().block_on(SendWakerToThread { + waker_tx: Some(waker_tx), + }); + + // Spawn a real OS thread that will call wake() on the waker + let handle = std::thread::spawn(move || { + if let Ok(waker) = waker_rx.recv() { + // This should trigger the non-determinism detection + waker.wake(); + } + }); + + // Wait for the spawned thread to complete + handle.join().ok(); + + // The non-determinism error should be detected when end_test is called + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + scheduler.end_test(); + })); + assert!(result.is_err(), "Expected end_test to panic"); + let panic_payload = result.unwrap_err(); + let panic_message = panic_payload + .downcast_ref::() + .map(|s| s.as_str()) + .or_else(|| panic_payload.downcast_ref::<&str>().copied()) + .unwrap_or(""); + assert!( + panic_message.contains("Your test is not deterministic"), + "Expected panic message to contain non-determinism error, got: {}", + panic_message + ); +} + +#[test] +fn test_nondeterministic_wake_allowed_with_parking() { + let config = TestSchedulerConfig { + allow_parking: true, + ..Default::default() + }; + let scheduler = Arc::new(TestScheduler::new(config)); + + // A future that captures its waker and sends it to an external thread + struct WakeFromExternalThread { + waker_sent: bool, + waker_tx: Option>, + } + + impl Future for WakeFromExternalThread { + type Output = (); + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + if !self.waker_sent { + self.waker_sent = true; + if let Some(tx) = self.waker_tx.take() { + tx.send(cx.waker().clone()).ok(); + } + Poll::Pending + } else { + Poll::Ready(()) + } + } + } + + let (waker_tx, waker_rx) = std::sync::mpsc::channel::(); + + // Spawn a real OS thread that will call wake() on the waker + std::thread::spawn(move || { + if let Ok(waker) = waker_rx.recv() { + // With allow_parking, this should NOT panic + waker.wake(); + } + }); + + // This should complete without panicking + scheduler.foreground().block_on(WakeFromExternalThread { + waker_sent: false, + waker_tx: Some(waker_tx), + }); +} + +#[test] +fn test_nondeterministic_waker_drop_detection() { + let config = TestSchedulerConfig { + allow_parking: false, + ..Default::default() + }; + let scheduler = Arc::new(TestScheduler::new(config)); + + // A future that captures its waker and sends it to an external thread + struct SendWakerToThread { + waker_tx: Option>, + } + + impl Future for SendWakerToThread { + type Output = (); + + fn poll(mut self: Pin<&mut Self>, cx: &mut Context<'_>) -> Poll { + if let Some(tx) = self.waker_tx.take() { + tx.send(cx.waker().clone()).ok(); + } + Poll::Ready(()) + } + } + + let (waker_tx, waker_rx) = std::sync::mpsc::channel::(); + + // Get a waker by running a future that sends it + scheduler.foreground().block_on(SendWakerToThread { + waker_tx: Some(waker_tx), + }); + + // Spawn a real OS thread that will drop the waker without calling wake + let handle = std::thread::spawn(move || { + if let Ok(waker) = waker_rx.recv() { + // This should trigger the non-determinism detection on drop + drop(waker); + } + }); + + // Wait for the spawned thread to complete + handle.join().ok(); + + // The non-determinism error should be detected when end_test is called + let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| { + scheduler.end_test(); + })); + assert!(result.is_err(), "Expected end_test to panic"); + let panic_payload = result.unwrap_err(); + let panic_message = panic_payload + .downcast_ref::() + .map(|s| s.as_str()) + .or_else(|| panic_payload.downcast_ref::<&str>().copied()) + .unwrap_or(""); + assert!( + panic_message.contains("Your test is not deterministic"), + "Expected panic message to contain non-determinism error, got: {}", + panic_message + ); +} + +#[test] +fn test_background_priority_scheduling() { + use parking_lot::Mutex; + + // Run many iterations to get statistical significance + let mut high_before_low_count = 0; + let iterations = if cfg!(miri) { 5 } else { 100 }; + + for seed in 0..iterations { + let config = TestSchedulerConfig::with_seed(seed); + let scheduler = Arc::new(TestScheduler::new(config)); + let background = scheduler.background(); + + let execution_order = Arc::new(Mutex::new(Vec::new())); + + // Spawn low priority tasks first + for i in 0..3 { + let order = execution_order.clone(); + background + .spawn_with_priority(Priority::Low, async move { + order.lock().push(format!("low-{}", i)); + }) + .detach(); + } + + // Spawn high priority tasks second + for i in 0..3 { + let order = execution_order.clone(); + background + .spawn_with_priority(Priority::High, async move { + order.lock().push(format!("high-{}", i)); + }) + .detach(); + } + + scheduler.run(); + + // Count how many high priority tasks ran in the first half + let order = execution_order.lock(); + let high_in_first_half = order + .iter() + .take(3) + .filter(|s| s.starts_with("high")) + .count(); + + if high_in_first_half >= 2 { + high_before_low_count += 1; + } + } + + // High priority tasks should tend to run before low priority tasks + // With weights of 60 vs 10, high priority should dominate early execution + assert!( + high_before_low_count > iterations / 2, + "Expected high priority tasks to run before low priority tasks more often. \ + Got {} out of {} iterations", + high_before_low_count, + iterations + ); +} + +#[test] +fn test_spawn_dedicated_basic_round_trip() { + let result = TestScheduler::once(async |scheduler| { + scheduler + .background() + .spawn_dedicated(|_executor| async { 42 }) + .await + }); + assert_eq!(result, 42); +} + +#[test] +fn test_spawn_dedicated_not_send_future() { + let result = TestScheduler::once(async |scheduler| { + scheduler + .background() + .spawn_dedicated(|_executor| async move { + // `Rc>` is `!Send`. If `spawn_dedicated` required + // the returned future to be `Send`, this wouldn't compile. + let state = Rc::new(RefCell::new(0_i32)); + for _ in 0..5 { + *state.borrow_mut() += 1; + } + *state.borrow() + }) + .await + }); + assert_eq!(result, 5); +} + +#[test] +fn test_spawn_dedicated_send_closure_captures() { + use parking_lot::Mutex; + + let observed = TestScheduler::once(async |scheduler| { + let shared = Arc::new(Mutex::new(0_i32)); + let shared_for_closure = shared.clone(); + let returned = scheduler + .background() + .spawn_dedicated(move |_executor| { + // `shared_for_closure` crossed the `Send` boundary of the + // closure; we then mutate it from inside the !Send future. + let local = shared_for_closure; + async move { + *local.lock() = 7; + } + }) + .await; + let _: () = returned; + *shared.lock() + }); + assert_eq!(observed, 7); +} + +#[test] +fn test_spawn_dedicated_inner_spawn_local() { + let result = TestScheduler::once(async |scheduler| { + scheduler + .background() + .spawn_dedicated(|executor| async move { + // The provided executor can spawn additional `!Send` work + // onto the same dedicated session. + let inner = Rc::new(RefCell::new(0_i32)); + let inner_for_child = inner.clone(); + let child = executor.spawn(async move { + *inner_for_child.borrow_mut() = 99; + *inner_for_child.borrow() + }); + child.await + }) + .await + }); + assert_eq!(result, 99); +} + +#[test] +fn test_spawn_dedicated_determinism_under_many() { + use parking_lot::Mutex; + + let outcomes = TestScheduler::many(if cfg!(miri) { 4 } else { 20 }, async |scheduler| { + let trace = Arc::new(Mutex::new(Vec::::new())); + + let background = scheduler.background(); + let mut tasks = Vec::new(); + for id in 0..4_u32 { + let trace = trace.clone(); + let task = background.spawn_dedicated(move |executor| async move { + for step in 0..3 { + trace.lock().push(id * 100 + step); + executor.spawn(async {}).await; + } + id + }); + tasks.push(task); + } + + let mut outputs = Vec::new(); + for task in tasks { + outputs.push(task.await); + } + + (trace.lock().clone(), outputs) + }); + + // Re-running with the same seed should produce the same trace. Run a + // second pass with identical seeds and compare to the first. + let outcomes_replay = TestScheduler::many(if cfg!(miri) { 4 } else { 20 }, async |scheduler| { + let trace = Arc::new(Mutex::new(Vec::::new())); + + let background = scheduler.background(); + let mut tasks = Vec::new(); + for id in 0..4_u32 { + let trace = trace.clone(); + let task = background.spawn_dedicated(move |executor| async move { + for step in 0..3 { + trace.lock().push(id * 100 + step); + executor.spawn(async {}).await; + } + id + }); + tasks.push(task); + } + + let mut outputs = Vec::new(); + for task in tasks { + outputs.push(task.await); + } + + (trace.lock().clone(), outputs) + }); + + assert_eq!( + outcomes, outcomes_replay, + "per-seed outcomes should be reproducible" + ); + + // Sanity: at least one seed produced a non-monotonic trace, + // demonstrating that dedicated tasks really do interleave under the + // scheduler's randomization. + let any_interleaved = outcomes.iter().any(|(trace, _)| { + trace + .windows(2) + .any(|window| window[0] / 100 != window[1] / 100) + }); + assert!( + any_interleaved, + "expected at least one seed to interleave dedicated tasks" + ); +} + +#[test] +fn test_spawn_dedicated_dropping_task_cancels_future() { + use parking_lot::Mutex; + + let counter_after = TestScheduler::once(async |scheduler| { + let counter = Arc::new(Mutex::new(0_u32)); + let (resume_tx, resume_rx) = oneshot::channel::<()>(); + + let task = { + let counter = counter.clone(); + scheduler + .background() + .spawn_dedicated(move |_executor| async move { + *counter.lock() = 1; + // Park here until the test resumes us. If the task is + // dropped before this resolves, the second assignment + // below must never happen. + let _ = resume_rx.await; + *counter.lock() = 2; + }) + }; + + // Let the dedicated future make its first observable step. + scheduler.run(); + assert_eq!(*counter.lock(), 1); + + // Cancel by dropping the root task, then unblock the parked oneshot. + // The future must not advance past the await: counter stays at 1. + drop(task); + let _ = resume_tx.send(()); + scheduler.run(); + + *counter.lock() + }); + + assert_eq!( + counter_after, 1, + "dropping the dedicated task must cancel the root future before its second write" + ); +} + +#[test] +fn test_spawn_dedicated_detached_child_runs_after_root_completes() { + use parking_lot::Mutex; + + let child_ran = TestScheduler::once(async |scheduler| { + let child_ran = Arc::new(Mutex::new(false)); + + let task = { + let child_ran = child_ran.clone(); + scheduler + .background() + .spawn_dedicated(move |executor| async move { + executor + .spawn(async move { + *child_ran.lock() = true; + }) + .detach(); + // Root returns immediately, before the child has had a + // chance to run. + }) + }; + + task.await; + + // Drain the dedicated session. The detached child must run. + scheduler.run(); + + *child_ran.lock() + }); + + assert!( + child_ran, + "detached child must complete after the root, not be cancelled with it" + ); +} + +// The production smoke test for `spawn_dedicated` lives in the `gpui` crate +// alongside `PlatformScheduler`, which is the real production implementation +// of the `Scheduler` trait. See `crates/gpui/src/platform_scheduler.rs`. diff --git a/crates/gpui_sum_tree/Cargo.toml b/crates/gpui_sum_tree/Cargo.toml new file mode 100644 index 0000000000..1bbcc3a1f4 --- /dev/null +++ b/crates/gpui_sum_tree/Cargo.toml @@ -0,0 +1,29 @@ +[package] +name = "gpui_sum_tree" +version = "0.2.2" +edition = "2024" +license = "Apache-2.0" +description = "Copy-on-write B+ tree with monoidal summaries for gpui-ce (vendored from Zed)." +publish = true + +[lib] +name = "sum_tree" +path = "src/sum_tree.rs" +doctest = false + +[dependencies] +heapless = "0.9.2" +rayon = "1.11.0" +log = "0.4.29" +tracing = { version = "0.1.43", features = ["attributes"] } +proptest = { version = "1.0", features = ["attr-macro"], optional = true } + +[dev-dependencies] +rand = "0.9" +proptest = { version = "1.0", features = ["attr-macro"] } + +[features] +test-support = ["proptest"] + +[package.metadata.cargo-machete] +ignored = ["tracing"] diff --git a/crates/gpui_sum_tree/LICENSE-APACHE b/crates/gpui_sum_tree/LICENSE-APACHE new file mode 100644 index 0000000000..461a0fe5ba --- /dev/null +++ b/crates/gpui_sum_tree/LICENSE-APACHE @@ -0,0 +1,222 @@ +Copyright 2022 - 2025 Zed Industries, Inc. + + + 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. + + + + +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 diff --git a/crates/gpui_sum_tree/src/cursor.rs b/crates/gpui_sum_tree/src/cursor.rs new file mode 100644 index 0000000000..536e035747 --- /dev/null +++ b/crates/gpui_sum_tree/src/cursor.rs @@ -0,0 +1,861 @@ +use super::*; +use heapless::Vec as ArrayVec; +use std::{cmp::Ordering, mem, sync::Arc}; +use tracing::instrument; + +#[derive(Clone)] +struct StackEntry<'a, T: Item, D> { + tree: &'a SumTree, + index: u32, + position: D, +} + +impl<'a, T: Item, D> StackEntry<'a, T, D> { + #[inline] + fn index(&self) -> usize { + self.index as usize + } +} + +impl fmt::Debug for StackEntry<'_, T, D> { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("StackEntry") + .field("index", &self.index) + .field("position", &self.position) + .finish() + } +} + +#[derive(Clone)] +pub struct Cursor<'a, 'b, T: Item, D> { + tree: &'a SumTree, + stack: ArrayVec, 16, u8>, + pub position: D, + did_seek: bool, + at_end: bool, + cx: ::Context<'b>, +} + +impl fmt::Debug for Cursor<'_, '_, T, D> +where + T::Summary: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_struct("Cursor") + .field("tree", &self.tree) + .field("stack", &self.stack) + .field("position", &self.position) + .field("did_seek", &self.did_seek) + .field("at_end", &self.at_end) + .finish() + } +} + +pub struct Iter<'a, T: Item> { + tree: &'a SumTree, + stack: ArrayVec, 16, u8>, +} + +impl<'a, 'b, T, D> Cursor<'a, 'b, T, D> +where + T: Item, + D: Dimension<'a, T::Summary>, +{ + pub fn new(tree: &'a SumTree, cx: ::Context<'b>) -> Self { + Self { + tree, + stack: ArrayVec::new(), + position: D::zero(cx), + did_seek: false, + at_end: tree.is_empty(), + cx, + } + } + + pub fn reset(&mut self) { + self.did_seek = false; + self.at_end = self.tree.is_empty(); + self.stack.truncate(0); + self.position = D::zero(self.cx); + } + + pub fn start(&self) -> &D { + &self.position + } + + #[track_caller] + pub fn end(&self) -> D { + if let Some(item_summary) = self.item_summary() { + let mut end = self.start().clone(); + end.add_summary(item_summary, self.cx); + end + } else { + self.start().clone() + } + } + + /// Item is None, when the list is empty, or this cursor is at the end of the list. + #[track_caller] + pub fn item(&self) -> Option<&'a T> { + self.assert_did_seek(); + if let Some(entry) = self.stack.last() { + match *entry.tree.0 { + Node::Leaf { ref items, .. } => { + if entry.index() == items.len() { + None + } else { + Some(&items[entry.index()]) + } + } + _ => unreachable!(), + } + } else { + None + } + } + + #[track_caller] + pub fn item_summary(&self) -> Option<&'a T::Summary> { + self.assert_did_seek(); + if let Some(entry) = self.stack.last() { + match *entry.tree.0 { + Node::Leaf { + ref item_summaries, .. + } => { + if entry.index() == item_summaries.len() { + None + } else { + Some(&item_summaries[entry.index()]) + } + } + _ => unreachable!(), + } + } else { + None + } + } + + #[track_caller] + pub fn next_item(&self) -> Option<&'a T> { + self.assert_did_seek(); + if let Some(entry) = self.stack.last() { + if entry.index() == entry.tree.0.items().len() - 1 { + if let Some(next_leaf) = self.next_leaf() { + Some(next_leaf.0.items().first().unwrap()) + } else { + None + } + } else { + match *entry.tree.0 { + Node::Leaf { ref items, .. } => Some(&items[entry.index() + 1]), + _ => unreachable!(), + } + } + } else if self.at_end { + None + } else { + self.tree.first() + } + } + + #[track_caller] + fn next_leaf(&self) -> Option<&'a SumTree> { + for entry in self.stack.iter().rev().skip(1) { + if entry.index() < entry.tree.0.child_trees().len() - 1 { + match *entry.tree.0 { + Node::Internal { + ref child_trees, .. + } => return Some(child_trees[entry.index() + 1].leftmost_leaf()), + Node::Leaf { .. } => unreachable!(), + }; + } + } + None + } + + #[track_caller] + pub fn prev_item(&self) -> Option<&'a T> { + self.assert_did_seek(); + if let Some(entry) = self.stack.last() { + if entry.index() == 0 { + if let Some(prev_leaf) = self.prev_leaf() { + Some(prev_leaf.0.items().last().unwrap()) + } else { + None + } + } else { + match *entry.tree.0 { + Node::Leaf { ref items, .. } => Some(&items[entry.index() - 1]), + _ => unreachable!(), + } + } + } else if self.at_end { + self.tree.last() + } else { + None + } + } + + #[track_caller] + fn prev_leaf(&self) -> Option<&'a SumTree> { + for entry in self.stack.iter().rev().skip(1) { + if entry.index() != 0 { + match *entry.tree.0 { + Node::Internal { + ref child_trees, .. + } => return Some(child_trees[entry.index() - 1].rightmost_leaf()), + Node::Leaf { .. } => unreachable!(), + }; + } + } + None + } + + #[track_caller] + #[instrument(skip_all)] + pub fn prev(&mut self) { + self.search_backward(|_| true) + } + + #[track_caller] + pub fn search_backward(&mut self, mut filter_node: F) + where + F: FnMut(&T::Summary) -> bool, + { + if !self.did_seek { + self.did_seek = true; + self.at_end = true; + } + + if self.at_end { + self.position = D::zero(self.cx); + self.at_end = self.tree.is_empty(); + if !self.tree.is_empty() { + self.stack + .push(StackEntry { + tree: self.tree, + index: self.tree.0.child_summaries().len() as u32, + position: D::from_summary(self.tree.summary(), self.cx), + }) + .unwrap_oob(); + } + } + + let mut descending = false; + while !self.stack.is_empty() { + if let Some(StackEntry { position, .. }) = self.stack.iter().rev().nth(1) { + self.position = position.clone(); + } else { + self.position = D::zero(self.cx); + } + + let entry = self.stack.last_mut().unwrap(); + if !descending { + if entry.index() == 0 { + self.stack.pop(); + continue; + } else { + entry.index -= 1; + } + } + + for summary in &entry.tree.0.child_summaries()[..entry.index()] { + self.position.add_summary(summary, self.cx); + } + entry.position = self.position.clone(); + + descending = filter_node(&entry.tree.0.child_summaries()[entry.index()]); + match entry.tree.0.as_ref() { + Node::Internal { child_trees, .. } => { + if descending { + let tree = &child_trees[entry.index()]; + self.stack + .push(StackEntry { + position: D::zero(self.cx), + tree, + index: tree.0.child_summaries().len() as u32 - 1, + }) + .unwrap_oob(); + } + } + Node::Leaf { .. } => { + if descending { + break; + } + } + } + } + } + + #[track_caller] + pub fn next(&mut self) { + self.search_forward(|_| true) + } + + #[track_caller] + pub fn search_forward(&mut self, mut filter_node: F) + where + F: FnMut(&T::Summary) -> bool, + { + let mut descend = false; + + if self.stack.is_empty() { + if !self.at_end { + self.stack + .push(StackEntry { + tree: self.tree, + index: 0, + position: D::zero(self.cx), + }) + .unwrap_oob(); + descend = true; + } + self.did_seek = true; + } + + while !self.stack.is_empty() { + let new_subtree = { + let entry = self.stack.last_mut().unwrap(); + match entry.tree.0.as_ref() { + Node::Internal { + child_trees, + child_summaries, + .. + } => { + if !descend { + entry.index += 1; + entry.position = self.position.clone(); + } + + while entry.index() < child_summaries.len() { + let next_summary = &child_summaries[entry.index()]; + if filter_node(next_summary) { + break; + } else { + entry.index += 1; + entry.position.add_summary(next_summary, self.cx); + self.position.add_summary(next_summary, self.cx); + } + } + + child_trees.get(entry.index()) + } + Node::Leaf { item_summaries, .. } => { + if !descend { + let item_summary = &item_summaries[entry.index()]; + entry.index += 1; + entry.position.add_summary(item_summary, self.cx); + self.position.add_summary(item_summary, self.cx); + } + + loop { + if let Some(next_item_summary) = item_summaries.get(entry.index()) { + if filter_node(next_item_summary) { + return; + } else { + entry.index += 1; + entry.position.add_summary(next_item_summary, self.cx); + self.position.add_summary(next_item_summary, self.cx); + } + } else { + break None; + } + } + } + } + }; + + if let Some(subtree) = new_subtree { + descend = true; + self.stack + .push(StackEntry { + tree: subtree, + index: 0, + position: self.position.clone(), + }) + .unwrap_oob(); + } else { + descend = false; + self.stack.pop(); + } + } + + self.at_end = self.stack.is_empty(); + debug_assert!(self.stack.is_empty() || self.stack.last().unwrap().tree.0.is_leaf()); + } + + #[track_caller] + fn assert_did_seek(&self) { + assert!( + self.did_seek, + "Must call `seek`, `next` or `prev` before calling this method" + ); + } + + pub fn did_seek(&self) -> bool { + self.did_seek + } +} + +impl<'a, 'b, T, D> Cursor<'a, 'b, T, D> +where + T: Item, + D: Dimension<'a, T::Summary>, +{ + /// Returns whether we found the item you were seeking for. + #[track_caller] + #[instrument(skip_all)] + pub fn seek(&mut self, pos: &Target, bias: Bias) -> bool + where + Target: SeekTarget<'a, T::Summary, D>, + { + self.reset(); + self.seek_internal(pos, bias, &mut ()) + } + + /// Returns whether we found the item you were seeking for. + /// + /// # Panics + /// + /// If we did not seek before, use seek instead in that case. + #[track_caller] + #[instrument(skip_all)] + pub fn seek_forward(&mut self, pos: &Target, bias: Bias) -> bool + where + Target: SeekTarget<'a, T::Summary, D>, + { + self.seek_internal(pos, bias, &mut ()) + } + + /// Advances the cursor and returns traversed items as a tree. + #[track_caller] + pub fn slice(&mut self, end: &Target, bias: Bias) -> SumTree + where + Target: SeekTarget<'a, T::Summary, D>, + { + let mut slice = SliceSeekAggregate { + tree: SumTree::new(self.cx), + leaf_items: ArrayVec::new(), + leaf_item_summaries: ArrayVec::new(), + leaf_summary: ::zero(self.cx), + }; + self.seek_internal(end, bias, &mut slice); + slice.tree + } + + #[track_caller] + pub fn suffix(&mut self) -> SumTree { + self.slice(&End::new(), Bias::Right) + } + + #[track_caller] + pub fn summary(&mut self, end: &Target, bias: Bias) -> Output + where + Target: SeekTarget<'a, T::Summary, D>, + Output: Dimension<'a, T::Summary>, + { + let mut summary = SummarySeekAggregate(Output::zero(self.cx)); + self.seek_internal(end, bias, &mut summary); + summary.0 + } + + /// Returns whether we found the item you were seeking for. + #[track_caller] + #[instrument(skip_all)] + fn seek_internal( + &mut self, + target: &dyn SeekTarget<'a, T::Summary, D>, + bias: Bias, + aggregate: &mut dyn SeekAggregate<'a, T>, + ) -> bool { + assert!( + target.cmp(&self.position, self.cx).is_ge(), + "cannot seek backward", + ); + + if !self.did_seek { + self.did_seek = true; + self.stack + .push(StackEntry { + tree: self.tree, + index: 0, + position: D::zero(self.cx), + }) + .unwrap_oob(); + } + + let mut ascending = false; + 'outer: while let Some(entry) = self.stack.last_mut() { + match *entry.tree.0 { + Node::Internal { + ref child_summaries, + ref child_trees, + .. + } => { + if ascending { + entry.index += 1; + entry.position = self.position.clone(); + } + + for (child_tree, child_summary) in child_trees[entry.index()..] + .iter() + .zip(&child_summaries[entry.index()..]) + { + let mut child_end = self.position.clone(); + child_end.add_summary(child_summary, self.cx); + + let comparison = target.cmp(&child_end, self.cx); + if comparison == Ordering::Greater + || (comparison == Ordering::Equal && bias == Bias::Right) + { + self.position = child_end; + aggregate.push_tree(child_tree, child_summary, self.cx); + entry.index += 1; + entry.position = self.position.clone(); + } else { + self.stack + .push(StackEntry { + tree: child_tree, + index: 0, + position: self.position.clone(), + }) + .unwrap_oob(); + ascending = false; + continue 'outer; + } + } + } + Node::Leaf { + ref items, + ref item_summaries, + .. + } => { + aggregate.begin_leaf(); + + for (item, item_summary) in items[entry.index()..] + .iter() + .zip(&item_summaries[entry.index()..]) + { + let mut child_end = self.position.clone(); + child_end.add_summary(item_summary, self.cx); + + let comparison = target.cmp(&child_end, self.cx); + if comparison == Ordering::Greater + || (comparison == Ordering::Equal && bias == Bias::Right) + { + self.position = child_end; + aggregate.push_item(item, item_summary, self.cx); + entry.index += 1; + } else { + aggregate.end_leaf(self.cx); + break 'outer; + } + } + + aggregate.end_leaf(self.cx); + } + } + + self.stack.pop(); + ascending = true; + } + + self.at_end = self.stack.is_empty(); + debug_assert!(self.stack.is_empty() || self.stack.last().unwrap().tree.0.is_leaf()); + + let mut end = self.position.clone(); + if bias == Bias::Left + && let Some(summary) = self.item_summary() + { + end.add_summary(summary, self.cx); + } + + target.cmp(&end, self.cx) == Ordering::Equal + } +} + +impl<'a, T: Item> Iter<'a, T> { + pub(crate) fn new(tree: &'a SumTree) -> Self { + Self { + tree, + stack: Default::default(), + } + } +} + +impl<'a, T: Item> Iterator for Iter<'a, T> { + type Item = &'a T; + + fn next(&mut self) -> Option { + let mut descend = false; + + if self.stack.is_empty() { + self.stack + .push(StackEntry { + tree: self.tree, + index: 0, + position: (), + }) + .unwrap_oob(); + descend = true; + } + + while let Some(entry) = self.stack.last_mut() { + let new_subtree = { + match entry.tree.0.as_ref() { + Node::Internal { child_trees, .. } => { + if !descend { + entry.index += 1; + } + child_trees.get(entry.index()) + } + Node::Leaf { items, .. } => { + if !descend { + entry.index += 1; + } + + if let Some(next_item) = items.get(entry.index()) { + return Some(next_item); + } else { + None + } + } + } + }; + + if let Some(subtree) = new_subtree { + descend = true; + self.stack + .push(StackEntry { + tree: subtree, + index: 0, + position: (), + }) + .unwrap_oob(); + } else { + descend = false; + self.stack.pop(); + } + } + + None + } + + fn last(mut self) -> Option { + self.stack.clear(); + self.tree.rightmost_leaf().last() + } + + fn size_hint(&self) -> (usize, Option) { + let lower_bound = match self.stack.last() { + Some(top) => top.tree.0.child_summaries().len() - top.index as usize, + None => self.tree.0.child_summaries().len(), + }; + + (lower_bound, None) + } +} + +impl<'a, 'b, T: Item, D> Iterator for Cursor<'a, 'b, T, D> +where + D: Dimension<'a, T::Summary>, +{ + type Item = &'a T; + + fn next(&mut self) -> Option { + if !self.did_seek { + self.next(); + } + + if let Some(item) = self.item() { + self.next(); + Some(item) + } else { + None + } + } +} + +pub struct FilterCursor<'a, 'b, F, T: Item, D> { + cursor: Cursor<'a, 'b, T, D>, + filter_node: F, +} + +impl<'a, 'b, F, T: Item, D> FilterCursor<'a, 'b, F, T, D> +where + F: FnMut(&T::Summary) -> bool, + T: Item, + D: Dimension<'a, T::Summary>, +{ + pub fn new( + tree: &'a SumTree, + cx: ::Context<'b>, + filter_node: F, + ) -> Self { + let cursor = tree.cursor::(cx); + Self { + cursor, + filter_node, + } + } + + pub fn start(&self) -> &D { + self.cursor.start() + } + + pub fn end(&self) -> D { + self.cursor.end() + } + + pub fn item(&self) -> Option<&'a T> { + self.cursor.item() + } + + pub fn item_summary(&self) -> Option<&'a T::Summary> { + self.cursor.item_summary() + } + + pub fn next(&mut self) { + self.cursor.search_forward(&mut self.filter_node); + } + + pub fn prev(&mut self) { + self.cursor.search_backward(&mut self.filter_node); + } +} + +impl<'a, 'b, F, T: Item, U> Iterator for FilterCursor<'a, 'b, F, T, U> +where + F: FnMut(&T::Summary) -> bool, + U: Dimension<'a, T::Summary>, +{ + type Item = &'a T; + + fn next(&mut self) -> Option { + if !self.cursor.did_seek { + self.next(); + } + + if let Some(item) = self.item() { + self.cursor.search_forward(&mut self.filter_node); + Some(item) + } else { + None + } + } +} + +trait SeekAggregate<'a, T: Item> { + fn begin_leaf(&mut self); + fn end_leaf(&mut self, cx: ::Context<'_>); + fn push_item( + &mut self, + item: &'a T, + summary: &'a T::Summary, + cx: ::Context<'_>, + ); + fn push_tree( + &mut self, + tree: &'a SumTree, + summary: &'a T::Summary, + cx: ::Context<'_>, + ); +} + +struct SliceSeekAggregate { + tree: SumTree, + leaf_items: ArrayVec, + leaf_item_summaries: ArrayVec, + leaf_summary: T::Summary, +} + +struct SummarySeekAggregate(D); + +impl SeekAggregate<'_, T> for () { + fn begin_leaf(&mut self) {} + fn end_leaf(&mut self, _: ::Context<'_>) {} + fn push_item(&mut self, _: &T, _: &T::Summary, _: ::Context<'_>) {} + fn push_tree( + &mut self, + _: &SumTree, + _: &T::Summary, + _: ::Context<'_>, + ) { + } +} + +impl SeekAggregate<'_, T> for SliceSeekAggregate { + fn begin_leaf(&mut self) {} + fn end_leaf(&mut self, cx: ::Context<'_>) { + self.tree.append( + SumTree(Arc::new(Node::Leaf { + summary: mem::replace(&mut self.leaf_summary, ::zero(cx)), + items: mem::take(&mut self.leaf_items), + item_summaries: mem::take(&mut self.leaf_item_summaries), + })), + cx, + ); + } + fn push_item( + &mut self, + item: &T, + summary: &T::Summary, + cx: ::Context<'_>, + ) { + self.leaf_items.push(item.clone()).unwrap_oob(); + self.leaf_item_summaries.push(summary.clone()).unwrap_oob(); + Summary::add_summary(&mut self.leaf_summary, summary, cx); + } + fn push_tree( + &mut self, + tree: &SumTree, + _: &T::Summary, + cx: ::Context<'_>, + ) { + self.tree.append(tree.clone(), cx); + } +} + +impl<'a, T: Item, D> SeekAggregate<'a, T> for SummarySeekAggregate +where + D: Dimension<'a, T::Summary>, +{ + fn begin_leaf(&mut self) {} + fn end_leaf(&mut self, _: ::Context<'_>) {} + fn push_item( + &mut self, + _: &T, + summary: &'a T::Summary, + cx: ::Context<'_>, + ) { + self.0.add_summary(summary, cx); + } + fn push_tree( + &mut self, + _: &SumTree, + summary: &'a T::Summary, + cx: ::Context<'_>, + ) { + self.0.add_summary(summary, cx); + } +} + +struct End(PhantomData); + +impl End { + fn new() -> Self { + Self(PhantomData) + } +} + +impl<'a, S: Summary, D: Dimension<'a, S>> SeekTarget<'a, S, D> for End { + fn cmp(&self, _: &D, _: S::Context<'_>) -> Ordering { + Ordering::Greater + } +} + +impl fmt::Debug for End { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + f.debug_tuple("End").finish() + } +} diff --git a/crates/gpui_sum_tree/src/property_test.rs b/crates/gpui_sum_tree/src/property_test.rs new file mode 100644 index 0000000000..d6c6bd76f9 --- /dev/null +++ b/crates/gpui_sum_tree/src/property_test.rs @@ -0,0 +1,32 @@ +use core::fmt::Debug; + +use proptest::{prelude::*, sample::SizeRange}; + +use crate::{Item, SumTree, Summary}; + +impl Arbitrary for SumTree +where + T: Debug + Arbitrary + Item + 'static, + T::Summary: Debug + Summary = ()>, +{ + type Parameters = (); + type Strategy = BoxedStrategy; + + fn arbitrary_with((): Self::Parameters) -> Self::Strategy { + any::>() + .prop_map(|vec| SumTree::from_iter(vec, ())) + .boxed() + } +} + +/// A strategy for producing a [`SumTree`] with a given size. +/// +/// Equivalent to [`proptest::collection::vec`]. +pub fn sum_tree(values: S, size: impl Into) -> impl Strategy> +where + T: Debug + Arbitrary + Item + 'static, + T::Summary: Debug + Summary = ()>, + S: Strategy, +{ + proptest::collection::vec(values, size).prop_map(|vec| SumTree::from_iter(vec, ())) +} diff --git a/crates/gpui_sum_tree/src/sum_tree.rs b/crates/gpui_sum_tree/src/sum_tree.rs new file mode 100644 index 0000000000..8b20e605c0 --- /dev/null +++ b/crates/gpui_sum_tree/src/sum_tree.rs @@ -0,0 +1,1898 @@ +mod cursor; +#[cfg(any(test, feature = "test-support"))] +pub mod property_test; +mod tree_map; + +pub use cursor::{Cursor, FilterCursor, Iter}; +use heapless::Vec as ArrayVec; +use rayon::iter::{IndexedParallelIterator, IntoParallelIterator, ParallelIterator as _}; +use std::marker::PhantomData; +use std::mem; +use std::{cmp::Ordering, fmt, iter::FromIterator, sync::Arc}; +use tracing::instrument; +pub use tree_map::{MapSeekTarget, TreeMap, TreeSet}; + +#[cfg(test)] +pub const TREE_BASE: usize = 2; +#[cfg(not(test))] +pub const TREE_BASE: usize = 6; + +// Helper for when we cannot use ArrayVec::::push().unwrap() as T doesn't impl Debug +trait CapacityResultExt { + fn unwrap_oob(self); +} + +impl CapacityResultExt for Result<(), T> { + fn unwrap_oob(self) { + self.unwrap_or_else(|_| panic!("item should fit into fixed size ArrayVec")) + } +} + +/// An item that can be stored in a [`SumTree`] +/// +/// Must be summarized by a type that implements [`Summary`] +pub trait Item: Clone { + type Summary: Summary; + + fn summary(&self, cx: ::Context<'_>) -> Self::Summary; +} + +/// An [`Item`] whose summary has a specific key that can be used to identify it +pub trait KeyedItem: Item { + type Key: for<'a> Dimension<'a, Self::Summary> + Ord; + + fn key(&self) -> Self::Key; +} + +/// A type that describes the Sum of all [`Item`]s in a subtree of the [`SumTree`] +/// +/// Each Summary type can have multiple [`Dimension`]s that it measures, +/// which can be used to navigate the tree +pub trait Summary: Clone { + type Context<'a>: Copy; + fn zero<'a>(cx: Self::Context<'a>) -> Self; + fn add_summary<'a>(&mut self, summary: &Self, cx: Self::Context<'a>); +} + +pub trait ContextLessSummary: Clone { + fn zero() -> Self; + fn add_summary(&mut self, summary: &Self); +} + +impl Summary for T { + type Context<'a> = (); + + fn zero<'a>((): ()) -> Self { + T::zero() + } + + fn add_summary<'a>(&mut self, summary: &Self, (): ()) { + T::add_summary(self, summary) + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub struct NoSummary; + +/// Catch-all implementation for when you need something that implements [`Summary`] without a specific type. +/// We implement it on a `NoSummary` instead of re-using `()`, as that avoids blanket impl collisions with `impl Dimension for T` +/// (as we also need unit type to be a fill-in dimension) +impl ContextLessSummary for NoSummary { + fn zero() -> Self { + NoSummary + } + + fn add_summary(&mut self, _: &Self) {} +} + +/// Each [`Summary`] type can have more than one [`Dimension`] type that it measures. +/// +/// You can use dimensions to seek to a specific location in the [`SumTree`] +/// +/// # Example: +/// Zed's rope has a `TextSummary` type that summarizes lines, characters, and bytes. +/// Each of these are different dimensions we may want to seek to +pub trait Dimension<'a, S: Summary>: Clone { + fn zero(cx: S::Context<'_>) -> Self; + + fn add_summary(&mut self, summary: &'a S, cx: S::Context<'_>); + #[must_use] + fn with_added_summary(mut self, summary: &'a S, cx: S::Context<'_>) -> Self { + self.add_summary(summary, cx); + self + } + + fn from_summary(summary: &'a S, cx: S::Context<'_>) -> Self { + let mut dimension = Self::zero(cx); + dimension.add_summary(summary, cx); + dimension + } +} + +impl<'a, T: Summary> Dimension<'a, T> for T { + fn zero(cx: T::Context<'_>) -> Self { + Summary::zero(cx) + } + + fn add_summary(&mut self, summary: &'a T, cx: T::Context<'_>) { + Summary::add_summary(self, summary, cx); + } +} + +pub trait SeekTarget<'a, S: Summary, D: Dimension<'a, S>> { + fn cmp(&self, cursor_location: &D, cx: S::Context<'_>) -> Ordering; +} + +impl<'a, S: Summary, D: Dimension<'a, S> + Ord> SeekTarget<'a, S, D> for D { + fn cmp(&self, cursor_location: &Self, _: S::Context<'_>) -> Ordering { + Ord::cmp(self, cursor_location) + } +} + +impl<'a, T: Summary> Dimension<'a, T> for () { + fn zero(_: T::Context<'_>) -> Self {} + + fn add_summary(&mut self, _: &'a T, _: T::Context<'_>) {} +} + +#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)] +pub struct Dimensions(pub D1, pub D2, pub D3); + +impl<'a, T: Summary, D1: Dimension<'a, T>, D2: Dimension<'a, T>, D3: Dimension<'a, T>> + Dimension<'a, T> for Dimensions +{ + fn zero(cx: T::Context<'_>) -> Self { + Dimensions(D1::zero(cx), D2::zero(cx), D3::zero(cx)) + } + + fn add_summary(&mut self, summary: &'a T, cx: T::Context<'_>) { + self.0.add_summary(summary, cx); + self.1.add_summary(summary, cx); + self.2.add_summary(summary, cx); + } +} + +impl<'a, S, D1, D2, D3> SeekTarget<'a, S, Dimensions> for D1 +where + S: Summary, + D1: SeekTarget<'a, S, D1> + Dimension<'a, S>, + D2: Dimension<'a, S>, + D3: Dimension<'a, S>, +{ + fn cmp(&self, cursor_location: &Dimensions, cx: S::Context<'_>) -> Ordering { + self.cmp(&cursor_location.0, cx) + } +} + +/// Bias is used to settle ambiguities when determining positions in an ordered sequence. +/// +/// The primary use case is for text, where Bias influences +/// which character an offset or anchor is associated with. +/// +/// # Examples +/// Given the buffer `AˇBCD`: +/// - The offset of the cursor is 1 +/// - [Bias::Left] would attach the cursor to the character `A` +/// - [Bias::Right] would attach the cursor to the character `B` +/// +/// Given the buffer `A«BCˇ»D`: +/// - The offset of the cursor is 3, and the selection is from 1 to 3 +/// - The left anchor of the selection has [Bias::Right], attaching it to the character `B` +/// - The right anchor of the selection has [Bias::Left], attaching it to the character `C` +/// +/// Given the buffer `{ˇ<...>`, where `<...>` is a folded region: +/// - The display offset of the cursor is 1, but the offset in the buffer is determined by the bias +/// - [Bias::Left] would attach the cursor to the character `{`, with a buffer offset of 1 +/// - [Bias::Right] would attach the cursor to the first character of the folded region, +/// and the buffer offset would be the offset of the first character of the folded region +#[derive(Copy, Clone, Eq, PartialEq, PartialOrd, Ord, Debug, Hash, Default)] +pub enum Bias { + /// Attach to the character on the left + #[default] + Left, + /// Attach to the character on the right + Right, +} + +impl Bias { + pub fn invert(self) -> Self { + match self { + Self::Left => Self::Right, + Self::Right => Self::Left, + } + } +} + +/// A B+ tree in which each leaf node contains `Item`s of type `T` and a `Summary`s for each `Item`. +/// Each internal node contains a `Summary` of the items in its subtree. +/// +/// The maximum number of items per node is `TREE_BASE * 2`. +/// +/// Any [`Dimension`] supported by the [`Summary`] type can be used to seek to a specific location in the tree. +#[derive(Clone)] +pub struct SumTree(Arc>); + +impl fmt::Debug for SumTree +where + T: fmt::Debug + Item, + T::Summary: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result { + f.debug_tuple("SumTree").field(&self.0).finish() + } +} + +impl SumTree { + pub fn new(cx: ::Context<'_>) -> Self { + SumTree(Arc::new(Node::Leaf { + summary: ::zero(cx), + items: ArrayVec::new(), + item_summaries: ArrayVec::new(), + })) + } + + /// Useful in cases where the item type has a non-trivial context type, but the zero value of the summary type doesn't depend on that context. + pub fn from_summary(summary: T::Summary) -> Self { + SumTree(Arc::new(Node::Leaf { + summary, + items: ArrayVec::new(), + item_summaries: ArrayVec::new(), + })) + } + + pub fn from_item(item: T, cx: ::Context<'_>) -> Self { + let mut tree = Self::new(cx); + tree.push(item, cx); + tree + } + + pub fn from_iter>( + iter: I, + cx: ::Context<'_>, + ) -> Self { + let mut nodes = Vec::new(); + + let mut iter = iter.into_iter().fuse().peekable(); + while iter.peek().is_some() { + let items: ArrayVec = + iter.by_ref().take(2 * TREE_BASE).collect(); + let item_summaries: ArrayVec = + items.iter().map(|item| item.summary(cx)).collect(); + + let mut summary = item_summaries[0].clone(); + for item_summary in &item_summaries[1..] { + ::add_summary(&mut summary, item_summary, cx); + } + + nodes.push(SumTree(Arc::new(Node::Leaf { + summary, + items, + item_summaries, + }))); + } + + let mut parent_nodes = Vec::new(); + let mut height = 0; + while nodes.len() > 1 { + height += 1; + let mut current_parent_node = None; + for child_node in nodes.drain(..) { + let parent_node = current_parent_node.get_or_insert_with(|| { + SumTree(Arc::new(Node::Internal { + summary: ::zero(cx), + height, + child_summaries: ArrayVec::new(), + child_trees: ArrayVec::new(), + })) + }); + let Node::Internal { + summary, + child_summaries, + child_trees, + .. + } = Arc::get_mut(&mut parent_node.0).unwrap() + else { + unreachable!() + }; + let child_summary = child_node.summary(); + ::add_summary(summary, child_summary, cx); + child_summaries.push(child_summary.clone()).unwrap_oob(); + child_trees.push(child_node.clone()).unwrap_oob(); + + if child_trees.len() == 2 * TREE_BASE { + parent_nodes.extend(current_parent_node.take()); + } + } + parent_nodes.extend(current_parent_node.take()); + mem::swap(&mut nodes, &mut parent_nodes); + } + + if nodes.is_empty() { + Self::new(cx) + } else { + debug_assert_eq!(nodes.len(), 1); + nodes.pop().unwrap() + } + } + + pub fn from_par_iter(iter: I, cx: ::Context<'_>) -> Self + where + I: IntoParallelIterator, + Iter: IndexedParallelIterator, + T: Send + Sync, + T::Summary: Send + Sync, + for<'a> ::Context<'a>: Sync, + { + let mut nodes = iter + .into_par_iter() + .chunks(2 * TREE_BASE) + .map(|items| { + let items: ArrayVec = items.into_iter().collect(); + let item_summaries: ArrayVec = + items.iter().map(|item| item.summary(cx)).collect(); + let mut summary = item_summaries[0].clone(); + for item_summary in &item_summaries[1..] { + ::add_summary(&mut summary, item_summary, cx); + } + SumTree(Arc::new(Node::Leaf { + summary, + items, + item_summaries, + })) + }) + .collect::>(); + + let mut height = 0; + while nodes.len() > 1 { + height += 1; + nodes = nodes + .into_par_iter() + .chunks(2 * TREE_BASE) + .map(|child_nodes| { + let child_trees: ArrayVec, { 2 * TREE_BASE }, u8> = + child_nodes.into_iter().collect(); + let child_summaries: ArrayVec = child_trees + .iter() + .map(|child_tree| child_tree.summary().clone()) + .collect(); + let mut summary = child_summaries[0].clone(); + for child_summary in &child_summaries[1..] { + ::add_summary(&mut summary, child_summary, cx); + } + SumTree(Arc::new(Node::Internal { + height, + summary, + child_summaries, + child_trees, + })) + }) + .collect::>(); + } + + if nodes.is_empty() { + Self::new(cx) + } else { + debug_assert_eq!(nodes.len(), 1); + nodes.pop().unwrap() + } + } + + #[allow(unused)] + pub fn items<'a>(&'a self, cx: ::Context<'a>) -> Vec { + let mut items = Vec::new(); + let mut cursor = self.cursor::<()>(cx); + cursor.next(); + while let Some(item) = cursor.item() { + items.push(item.clone()); + cursor.next(); + } + items + } + + pub fn iter(&self) -> Iter<'_, T> { + Iter::new(self) + } + + /// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()`. + /// + /// Only returns the item that exactly has the target match. + #[instrument(skip_all)] + pub fn find_exact<'a, 'slf, D, Target>( + &'slf self, + cx: ::Context<'a>, + target: &Target, + bias: Bias, + ) -> (D, D, Option<&'slf T>) + where + D: Dimension<'slf, T::Summary>, + Target: SeekTarget<'slf, T::Summary, D>, + { + let tree_end = D::zero(cx).with_added_summary(self.summary(), cx); + let comparison = target.cmp(&tree_end, cx); + if comparison == Ordering::Greater || (comparison == Ordering::Equal && bias == Bias::Right) + { + return (tree_end.clone(), tree_end, None); + } + + let mut pos = D::zero(cx); + return match Self::find_iterate::<_, _, true>(cx, target, bias, &mut pos, self) { + Some((item, end)) => (pos, end, Some(item)), + None => (pos.clone(), pos, None), + }; + } + + /// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()` + #[instrument(skip_all)] + pub fn find<'a, 'slf, D, Target>( + &'slf self, + cx: ::Context<'a>, + target: &Target, + bias: Bias, + ) -> (D, D, Option<&'slf T>) + where + D: Dimension<'slf, T::Summary>, + Target: SeekTarget<'slf, T::Summary, D>, + { + let tree_end = D::zero(cx).with_added_summary(self.summary(), cx); + let comparison = target.cmp(&tree_end, cx); + if comparison == Ordering::Greater || (comparison == Ordering::Equal && bias == Bias::Right) + { + return (tree_end.clone(), tree_end, None); + } + + let mut pos = D::zero(cx); + return match Self::find_iterate::<_, _, false>(cx, target, bias, &mut pos, self) { + Some((item, end)) => (pos, end, Some(item)), + None => (pos.clone(), pos, None), + }; + } + + fn find_iterate<'tree, 'a, D, Target, const EXACT: bool>( + cx: ::Context<'a>, + target: &Target, + bias: Bias, + position: &mut D, + mut this: &'tree SumTree, + ) -> Option<(&'tree T, D)> + where + D: Dimension<'tree, T::Summary>, + Target: SeekTarget<'tree, T::Summary, D>, + { + 'iterate: loop { + match &*this.0 { + Node::Internal { + child_summaries, + child_trees, + .. + } => { + for (child_tree, child_summary) in child_trees.iter().zip(child_summaries) { + let child_end = position.clone().with_added_summary(child_summary, cx); + + let comparison = target.cmp(&child_end, cx); + let target_in_child = comparison == Ordering::Less + || (comparison == Ordering::Equal && bias == Bias::Left); + if target_in_child { + this = child_tree; + continue 'iterate; + } + *position = child_end; + } + } + Node::Leaf { + items, + item_summaries, + .. + } => { + for (item, item_summary) in items.iter().zip(item_summaries) { + let mut child_end = position.clone(); + child_end.add_summary(item_summary, cx); + + let comparison = target.cmp(&child_end, cx); + let entry_found = if EXACT { + comparison == Ordering::Equal + } else { + comparison == Ordering::Less + || (comparison == Ordering::Equal && bias == Bias::Left) + }; + if entry_found { + return Some((item, child_end)); + } + + *position = child_end; + } + } + } + return None; + } + } + + /// A more efficient version of `Cursor::new()` + `Cursor::seek()` + `Cursor::item()` + #[instrument(skip_all)] + pub fn find_with_prev<'a, 'slf, D, Target>( + &'slf self, + cx: ::Context<'a>, + target: &Target, + bias: Bias, + ) -> (D, D, Option<(Option<&'slf T>, &'slf T)>) + where + D: Dimension<'slf, T::Summary>, + Target: SeekTarget<'slf, T::Summary, D>, + { + let tree_end = D::zero(cx).with_added_summary(self.summary(), cx); + let comparison = target.cmp(&tree_end, cx); + if comparison == Ordering::Greater || (comparison == Ordering::Equal && bias == Bias::Right) + { + return (tree_end.clone(), tree_end, None); + } + + let mut pos = D::zero(cx); + return match Self::find_with_prev_iterate::<_, _, false>(cx, target, bias, &mut pos, self) { + Some((prev, item, end)) => (pos, end, Some((prev, item))), + None => (pos.clone(), pos, None), + }; + } + + fn find_with_prev_iterate<'tree, 'a, D, Target, const EXACT: bool>( + cx: ::Context<'a>, + target: &Target, + bias: Bias, + position: &mut D, + mut this: &'tree SumTree, + ) -> Option<(Option<&'tree T>, &'tree T, D)> + where + D: Dimension<'tree, T::Summary>, + Target: SeekTarget<'tree, T::Summary, D>, + { + let mut prev = None; + 'iterate: loop { + match &*this.0 { + Node::Internal { + child_summaries, + child_trees, + .. + } => { + for (child_tree, child_summary) in child_trees.iter().zip(child_summaries) { + let child_end = position.clone().with_added_summary(child_summary, cx); + + let comparison = target.cmp(&child_end, cx); + let target_in_child = comparison == Ordering::Less + || (comparison == Ordering::Equal && bias == Bias::Left); + if target_in_child { + this = child_tree; + continue 'iterate; + } + prev = child_tree.last(); + *position = child_end; + } + } + Node::Leaf { + items, + item_summaries, + .. + } => { + for (item, item_summary) in items.iter().zip(item_summaries) { + let mut child_end = position.clone(); + child_end.add_summary(item_summary, cx); + + let comparison = target.cmp(&child_end, cx); + let entry_found = if EXACT { + comparison == Ordering::Equal + } else { + comparison == Ordering::Less + || (comparison == Ordering::Equal && bias == Bias::Left) + }; + if entry_found { + return Some((prev, item, child_end)); + } + + prev = Some(item); + *position = child_end; + } + } + } + return None; + } + } + + pub fn cursor<'a, 'b, D>( + &'a self, + cx: ::Context<'b>, + ) -> Cursor<'a, 'b, T, D> + where + D: Dimension<'a, T::Summary>, + { + Cursor::new(self, cx) + } + + /// Note: If the summary type requires a non `()` context, then the filter cursor + /// that is returned cannot be used with Rust's iterators. + pub fn filter<'a, 'b, F, U>( + &'a self, + cx: ::Context<'b>, + filter_node: F, + ) -> FilterCursor<'a, 'b, F, T, U> + where + F: FnMut(&T::Summary) -> bool, + U: Dimension<'a, T::Summary>, + { + FilterCursor::new(self, cx, filter_node) + } + + #[allow(dead_code)] + pub fn first(&self) -> Option<&T> { + self.leftmost_leaf().0.items().first() + } + + pub fn last(&self) -> Option<&T> { + self.rightmost_leaf().0.items().last() + } + + pub fn last_summary(&self) -> Option<&T::Summary> { + self.rightmost_leaf().0.child_summaries().last() + } + + pub fn update_last( + &mut self, + f: impl FnOnce(&mut T), + cx: ::Context<'_>, + ) { + self.update_last_recursive(f, cx); + } + + fn update_last_recursive( + &mut self, + f: impl FnOnce(&mut T), + cx: ::Context<'_>, + ) -> Option { + match Arc::make_mut(&mut self.0) { + Node::Internal { + summary, + child_summaries, + child_trees, + .. + } => { + let last_summary = child_summaries.last_mut().unwrap(); + let last_child = child_trees.last_mut().unwrap(); + *last_summary = last_child.update_last_recursive(f, cx).unwrap(); + *summary = sum(child_summaries.iter(), cx); + Some(summary.clone()) + } + Node::Leaf { + summary, + items, + item_summaries, + } => { + if let Some((item, item_summary)) = items.last_mut().zip(item_summaries.last_mut()) + { + (f)(item); + *item_summary = item.summary(cx); + *summary = sum(item_summaries.iter(), cx); + Some(summary.clone()) + } else { + None + } + } + } + } + + pub fn update_first( + &mut self, + f: impl FnOnce(&mut T), + cx: ::Context<'_>, + ) { + self.update_first_recursive(f, cx); + } + + fn update_first_recursive( + &mut self, + f: impl FnOnce(&mut T), + cx: ::Context<'_>, + ) -> Option { + match Arc::make_mut(&mut self.0) { + Node::Internal { + summary, + child_summaries, + child_trees, + .. + } => { + let first_summary = child_summaries.first_mut().unwrap(); + let first_child = child_trees.first_mut().unwrap(); + *first_summary = first_child.update_first_recursive(f, cx).unwrap(); + *summary = sum(child_summaries.iter(), cx); + Some(summary.clone()) + } + Node::Leaf { + summary, + items, + item_summaries, + } => { + if let Some((item, item_summary)) = + items.first_mut().zip(item_summaries.first_mut()) + { + (f)(item); + *item_summary = item.summary(cx); + *summary = sum(item_summaries.iter(), cx); + Some(summary.clone()) + } else { + None + } + } + } + } + + pub fn extent<'a, D: Dimension<'a, T::Summary>>( + &'a self, + cx: ::Context<'_>, + ) -> D { + let mut extent = D::zero(cx); + match self.0.as_ref() { + Node::Internal { summary, .. } | Node::Leaf { summary, .. } => { + extent.add_summary(summary, cx); + } + } + extent + } + + pub fn summary(&self) -> &T::Summary { + match self.0.as_ref() { + Node::Internal { summary, .. } => summary, + Node::Leaf { summary, .. } => summary, + } + } + + pub fn is_empty(&self) -> bool { + match self.0.as_ref() { + Node::Internal { .. } => false, + Node::Leaf { items, .. } => items.is_empty(), + } + } + + pub fn extend(&mut self, iter: I, cx: ::Context<'_>) + where + I: IntoIterator, + { + self.append(Self::from_iter(iter, cx), cx); + } + + pub fn par_extend(&mut self, iter: I, cx: ::Context<'_>) + where + I: IntoParallelIterator, + Iter: IndexedParallelIterator, + T: Send + Sync, + T::Summary: Send + Sync, + for<'a> ::Context<'a>: Sync, + { + self.append(Self::from_par_iter(iter, cx), cx); + } + + pub fn push(&mut self, item: T, cx: ::Context<'_>) { + let summary = item.summary(cx); + self.append( + SumTree(Arc::new(Node::Leaf { + summary: summary.clone(), + items: ArrayVec::from_iter(Some(item)), + item_summaries: ArrayVec::from_iter(Some(summary)), + })), + cx, + ); + } + + pub fn append(&mut self, mut other: Self, cx: ::Context<'_>) { + if self.is_empty() { + *self = other; + } else if !other.0.is_leaf() || !other.0.items().is_empty() { + if self.0.height() < other.0.height() { + if let Some(tree) = Self::append_large(self.clone(), &mut other, cx) { + *self = Self::from_child_trees(tree, other, cx); + } else { + *self = other; + } + } else if let Some(split_tree) = self.push_tree_recursive(other, cx) { + *self = Self::from_child_trees(self.clone(), split_tree, cx); + } + } + } + + fn push_tree_recursive( + &mut self, + other: SumTree, + cx: ::Context<'_>, + ) -> Option> { + match Arc::make_mut(&mut self.0) { + Node::Internal { + height, + summary, + child_summaries, + child_trees, + .. + } => { + let other_node = other.0.clone(); + ::add_summary(summary, other_node.summary(), cx); + + let height_delta = *height - other_node.height(); + let mut summaries_to_append = ArrayVec::::new(); + let mut trees_to_append = ArrayVec::, { 2 * TREE_BASE }, u8>::new(); + if height_delta == 0 { + summaries_to_append.extend(other_node.child_summaries().iter().cloned()); + trees_to_append.extend(other_node.child_trees().iter().cloned()); + } else if height_delta == 1 && !other_node.is_underflowing() { + summaries_to_append + .push(other_node.summary().clone()) + .unwrap_oob(); + trees_to_append.push(other).unwrap_oob(); + } else { + let tree_to_append = child_trees + .last_mut() + .unwrap() + .push_tree_recursive(other, cx); + *child_summaries.last_mut().unwrap() = + child_trees.last().unwrap().0.summary().clone(); + + if let Some(split_tree) = tree_to_append { + summaries_to_append + .push(split_tree.0.summary().clone()) + .unwrap_oob(); + trees_to_append.push(split_tree).unwrap_oob(); + } + } + + let child_count = child_trees.len() + trees_to_append.len(); + if child_count > 2 * TREE_BASE { + let left_summaries: ArrayVec<_, { 2 * TREE_BASE }, u8>; + let right_summaries: ArrayVec<_, { 2 * TREE_BASE }, u8>; + let left_trees; + let right_trees; + + let midpoint = (child_count + child_count % 2) / 2; + { + let mut all_summaries = child_summaries + .iter() + .chain(summaries_to_append.iter()) + .cloned(); + left_summaries = all_summaries.by_ref().take(midpoint).collect(); + right_summaries = all_summaries.collect(); + let mut all_trees = + child_trees.iter().chain(trees_to_append.iter()).cloned(); + left_trees = all_trees.by_ref().take(midpoint).collect(); + right_trees = all_trees.collect(); + } + *summary = sum(left_summaries.iter(), cx); + *child_summaries = left_summaries; + *child_trees = left_trees; + + Some(SumTree(Arc::new(Node::Internal { + height: *height, + summary: sum(right_summaries.iter(), cx), + child_summaries: right_summaries, + child_trees: right_trees, + }))) + } else { + child_summaries.extend(summaries_to_append); + child_trees.extend(trees_to_append); + None + } + } + Node::Leaf { + summary, + items, + item_summaries, + } => { + let other_node = other.0; + + let child_count = items.len() + other_node.items().len(); + if child_count > 2 * TREE_BASE { + let left_items; + let right_items; + let left_summaries; + let right_summaries: ArrayVec; + + let midpoint = (child_count + child_count % 2) / 2; + { + let mut all_items = items.iter().chain(other_node.items().iter()).cloned(); + left_items = all_items.by_ref().take(midpoint).collect(); + right_items = all_items.collect(); + + let mut all_summaries = item_summaries + .iter() + .chain(other_node.child_summaries()) + .cloned(); + left_summaries = all_summaries.by_ref().take(midpoint).collect(); + right_summaries = all_summaries.collect(); + } + *items = left_items; + *item_summaries = left_summaries; + *summary = sum(item_summaries.iter(), cx); + Some(SumTree(Arc::new(Node::Leaf { + items: right_items, + summary: sum(right_summaries.iter(), cx), + item_summaries: right_summaries, + }))) + } else { + ::add_summary(summary, other_node.summary(), cx); + items.extend(other_node.items().iter().cloned()); + item_summaries.extend(other_node.child_summaries().iter().cloned()); + None + } + } + } + } + + // appends the `large` tree to a `small` tree, assumes small.height() <= large.height() + fn append_large( + small: Self, + large: &mut Self, + cx: ::Context<'_>, + ) -> Option { + if small.0.height() == large.0.height() { + if !small.0.is_underflowing() { + Some(small) + } else { + Self::merge_into_right(small, large, cx) + } + } else { + debug_assert!(small.0.height() < large.0.height()); + let Node::Internal { + height, + summary, + child_summaries, + child_trees, + } = Arc::make_mut(&mut large.0) + else { + unreachable!(); + }; + let mut full_summary = small.summary().clone(); + Summary::add_summary(&mut full_summary, summary, cx); + *summary = full_summary; + + let first = child_trees.first_mut().unwrap(); + let res = Self::append_large(small, first, cx); + *child_summaries.first_mut().unwrap() = first.summary().clone(); + if let Some(tree) = res { + if child_trees.len() < 2 * TREE_BASE { + child_summaries + .insert(0, tree.summary().clone()) + .unwrap_oob(); + child_trees.insert(0, tree).unwrap_oob(); + None + } else { + let new_child_summaries = { + let mut res = ArrayVec::from_iter([tree.summary().clone()]); + res.extend(child_summaries.drain(..TREE_BASE)); + res + }; + let tree = SumTree(Arc::new(Node::Internal { + height: *height, + summary: sum(new_child_summaries.iter(), cx), + child_summaries: new_child_summaries, + child_trees: { + let mut res = ArrayVec::from_iter([tree]); + res.extend(child_trees.drain(..TREE_BASE)); + res + }, + })); + + *summary = sum(child_summaries.iter(), cx); + Some(tree) + } + } else { + None + } + } + } + + // Merge two nodes into `large`. + // + // `large` will contain the contents of `small` followed by its own data. + // If the combined data exceed the node capacity, returns a new node that + // holds the first half of the merged items and `large` is left with the + // second half + // + // The nodes must be on the same height + // It only makes sense to call this when `small` is underflowing + fn merge_into_right( + small: Self, + large: &mut Self, + cx: <::Summary as Summary>::Context<'_>, + ) -> Option> { + debug_assert_eq!(small.0.height(), large.0.height()); + match (small.0.as_ref(), Arc::make_mut(&mut large.0)) { + ( + Node::Internal { + summary: small_summary, + child_summaries: small_child_summaries, + child_trees: small_child_trees, + .. + }, + Node::Internal { + summary, + child_summaries, + child_trees, + height, + }, + ) => { + let total_child_count = child_trees.len() + small_child_trees.len(); + if total_child_count <= 2 * TREE_BASE { + let mut all_trees = small_child_trees.clone(); + all_trees.extend(child_trees.drain(..)); + *child_trees = all_trees; + + let mut all_summaries = small_child_summaries.clone(); + all_summaries.extend(child_summaries.drain(..)); + *child_summaries = all_summaries; + + let mut full_summary = small_summary.clone(); + Summary::add_summary(&mut full_summary, summary, cx); + *summary = full_summary; + None + } else { + let midpoint = total_child_count.div_ceil(2); + let mut all_trees = small_child_trees.iter().chain(child_trees.iter()).cloned(); + let left_trees = all_trees.by_ref().take(midpoint).collect(); + *child_trees = all_trees.collect(); + + let mut all_summaries = small_child_summaries + .iter() + .chain(child_summaries.iter()) + .cloned(); + let left_summaries: ArrayVec<_, { 2 * TREE_BASE }, u8> = + all_summaries.by_ref().take(midpoint).collect(); + *child_summaries = all_summaries.collect(); + + *summary = sum(child_summaries.iter(), cx); + Some(SumTree(Arc::new(Node::Internal { + height: *height, + summary: sum(left_summaries.iter(), cx), + child_summaries: left_summaries, + child_trees: left_trees, + }))) + } + } + ( + Node::Leaf { + summary: small_summary, + items: small_items, + item_summaries: small_item_summaries, + }, + Node::Leaf { + summary, + items, + item_summaries, + }, + ) => { + let total_child_count = small_items.len() + items.len(); + if total_child_count <= 2 * TREE_BASE { + let mut all_items = small_items.clone(); + all_items.extend(items.drain(..)); + *items = all_items; + + let mut all_summaries = small_item_summaries.clone(); + all_summaries.extend(item_summaries.drain(..)); + *item_summaries = all_summaries; + + let mut full_summary = small_summary.clone(); + Summary::add_summary(&mut full_summary, summary, cx); + *summary = full_summary; + None + } else { + let midpoint = total_child_count.div_ceil(2); + let mut all_items = small_items.iter().chain(items.iter()).cloned(); + let left_items = all_items.by_ref().take(midpoint).collect(); + *items = all_items.collect(); + + let mut all_summaries = small_item_summaries + .iter() + .chain(item_summaries.iter()) + .cloned(); + let left_summaries: ArrayVec<_, { 2 * TREE_BASE }, u8> = + all_summaries.by_ref().take(midpoint).collect(); + *item_summaries = all_summaries.collect(); + + *summary = sum(item_summaries.iter(), cx); + Some(SumTree(Arc::new(Node::Leaf { + items: left_items, + summary: sum(left_summaries.iter(), cx), + item_summaries: left_summaries, + }))) + } + } + _ => unreachable!(), + } + } + + fn from_child_trees( + left: SumTree, + right: SumTree, + cx: ::Context<'_>, + ) -> Self { + let height = left.0.height() + 1; + let mut child_summaries = ArrayVec::new(); + child_summaries.push(left.0.summary().clone()).unwrap_oob(); + child_summaries.push(right.0.summary().clone()).unwrap_oob(); + let mut child_trees = ArrayVec::new(); + child_trees.push(left).unwrap_oob(); + child_trees.push(right).unwrap_oob(); + SumTree(Arc::new(Node::Internal { + height, + summary: sum(child_summaries.iter(), cx), + child_summaries, + child_trees, + })) + } + + fn leftmost_leaf(&self) -> &Self { + match *self.0 { + Node::Leaf { .. } => self, + Node::Internal { + ref child_trees, .. + } => child_trees.first().unwrap().leftmost_leaf(), + } + } + + fn rightmost_leaf(&self) -> &Self { + match *self.0 { + Node::Leaf { .. } => self, + Node::Internal { + ref child_trees, .. + } => child_trees.last().unwrap().rightmost_leaf(), + } + } +} + +impl PartialEq for SumTree { + fn eq(&self, other: &Self) -> bool { + self.iter().eq(other.iter()) + } +} + +impl Eq for SumTree {} + +impl SumTree { + pub fn insert_or_replace<'a, 'b>( + &'a mut self, + item: T, + cx: ::Context<'b>, + ) -> Option { + let mut replaced = None; + { + let mut cursor = self.cursor::(cx); + let mut new_tree = cursor.slice(&item.key(), Bias::Left); + if let Some(cursor_item) = cursor.item() + && cursor_item.key() == item.key() + { + replaced = Some(cursor_item.clone()); + cursor.next(); + } + new_tree.push(item, cx); + new_tree.append(cursor.suffix(), cx); + drop(cursor); + *self = new_tree + }; + replaced + } + + pub fn remove(&mut self, key: &T::Key, cx: ::Context<'_>) -> Option { + let mut removed = None; + *self = { + let mut cursor = self.cursor::(cx); + let mut new_tree = cursor.slice(key, Bias::Left); + if let Some(item) = cursor.item() + && item.key() == *key + { + removed = Some(item.clone()); + cursor.next(); + } + new_tree.append(cursor.suffix(), cx); + new_tree + }; + removed + } + + pub fn edit( + &mut self, + mut edits: Vec>, + cx: ::Context<'_>, + ) -> Vec { + if edits.is_empty() { + return Vec::new(); + } + + let mut removed = Vec::new(); + edits.sort_unstable_by_key(|item| item.key()); + + *self = { + let mut cursor = self.cursor::(cx); + let mut new_tree = SumTree::new(cx); + let mut buffered_items = Vec::new(); + + cursor.seek(&T::Key::zero(cx), Bias::Left); + for edit in edits { + let new_key = edit.key(); + let mut old_item = cursor.item(); + + if old_item + .as_ref() + .is_some_and(|old_item| old_item.key() < new_key) + { + new_tree.extend(buffered_items.drain(..), cx); + let slice = cursor.slice(&new_key, Bias::Left); + new_tree.append(slice, cx); + old_item = cursor.item(); + } + + if let Some(old_item) = old_item + && old_item.key() == new_key + { + removed.push(old_item.clone()); + cursor.next(); + } + + match edit { + Edit::Insert(item) => { + buffered_items.push(item); + } + Edit::Remove(_) => {} + } + } + + new_tree.extend(buffered_items, cx); + new_tree.append(cursor.suffix(), cx); + new_tree + }; + + removed + } + + pub fn get<'a>( + &'a self, + key: &T::Key, + cx: ::Context<'a>, + ) -> Option<&'a T> { + if let (_, _, Some(item)) = self.find_exact::(cx, key, Bias::Left) { + Some(item) + } else { + None + } + } +} + +impl Default for SumTree +where + T: Item, + S: for<'a> Summary = ()>, +{ + fn default() -> Self { + Self::new(()) + } +} + +#[derive(Clone)] +pub enum Node { + Internal { + height: u8, + summary: T::Summary, + child_summaries: ArrayVec, + child_trees: ArrayVec, { 2 * TREE_BASE }, u8>, + }, + Leaf { + summary: T::Summary, + items: ArrayVec, + item_summaries: ArrayVec, + }, +} + +impl fmt::Debug for Node +where + T: Item + fmt::Debug, + T::Summary: fmt::Debug, +{ + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + Node::Internal { + height, + summary, + child_summaries, + child_trees, + } => f + .debug_struct("Internal") + .field("height", height) + .field("summary", summary) + .field("child_summaries", child_summaries) + .field("child_trees", child_trees) + .finish(), + Node::Leaf { + summary, + items, + item_summaries, + } => f + .debug_struct("Leaf") + .field("summary", summary) + .field("items", items) + .field("item_summaries", item_summaries) + .finish(), + } + } +} + +impl Node { + fn is_leaf(&self) -> bool { + matches!(self, Node::Leaf { .. }) + } + + fn height(&self) -> u8 { + match self { + Node::Internal { height, .. } => *height, + Node::Leaf { .. } => 0, + } + } + + fn summary(&self) -> &T::Summary { + match self { + Node::Internal { summary, .. } => summary, + Node::Leaf { summary, .. } => summary, + } + } + + fn child_summaries(&self) -> &[T::Summary] { + match self { + Node::Internal { + child_summaries, .. + } => child_summaries.as_slice(), + Node::Leaf { item_summaries, .. } => item_summaries.as_slice(), + } + } + + fn child_trees(&self) -> &ArrayVec, { 2 * TREE_BASE }, u8> { + match self { + Node::Internal { child_trees, .. } => child_trees, + Node::Leaf { .. } => panic!("Leaf nodes have no child trees"), + } + } + + fn items(&self) -> &ArrayVec { + match self { + Node::Leaf { items, .. } => items, + Node::Internal { .. } => panic!("Internal nodes have no items"), + } + } + + fn is_underflowing(&self) -> bool { + match self { + Node::Internal { child_trees, .. } => child_trees.len() < TREE_BASE, + Node::Leaf { items, .. } => items.len() < TREE_BASE, + } + } +} + +#[derive(Debug)] +pub enum Edit { + Insert(T), + Remove(T::Key), +} + +impl Edit { + fn key(&self) -> T::Key { + match self { + Edit::Insert(item) => item.key(), + Edit::Remove(key) => key.clone(), + } + } +} + +fn sum<'a, T, I>(iter: I, cx: T::Context<'_>) -> T +where + T: 'a + Summary, + I: Iterator, +{ + let mut sum = T::zero(cx); + for value in iter { + sum.add_summary(value, cx); + } + sum +} + +#[cfg(test)] +mod tests { + use super::*; + use rand::{distr::StandardUniform, prelude::*}; + use std::cmp; + + #[test] + fn test_extend_and_push_tree() { + let mut tree1 = SumTree::default(); + tree1.extend(0..20, ()); + + let mut tree2 = SumTree::default(); + tree2.extend(50..100, ()); + + tree1.append(tree2, ()); + assert_eq!(tree1.items(()), (0..20).chain(50..100).collect::>()); + } + + #[test] + fn test_random() { + let mut starting_seed = 0; + if let Ok(value) = std::env::var("SEED") { + starting_seed = value.parse().expect("invalid SEED variable"); + } + let mut num_iterations = 100; + if let Ok(value) = std::env::var("ITERATIONS") { + num_iterations = value.parse().expect("invalid ITERATIONS variable"); + } + let num_operations = std::env::var("OPERATIONS") + .map_or(5, |o| o.parse().expect("invalid OPERATIONS variable")); + + for seed in starting_seed..(starting_seed + num_iterations) { + eprintln!("seed = {}", seed); + let mut rng = StdRng::seed_from_u64(seed); + + let rng = &mut rng; + let mut tree = SumTree::::default(); + let count = rng.random_range(0..10); + if rng.random() { + tree.extend(rng.sample_iter(StandardUniform).take(count), ()); + } else { + let items = rng + .sample_iter(StandardUniform) + .take(count) + .collect::>(); + tree.par_extend(items, ()); + } + + for _ in 0..num_operations { + let splice_end = rng.random_range(0..tree.extent::(()).0 + 1); + let splice_start = rng.random_range(0..splice_end + 1); + let count = rng.random_range(0..10); + let tree_end = tree.extent::(()); + let new_items = rng + .sample_iter(StandardUniform) + .take(count) + .collect::>(); + + let mut reference_items = tree.items(()); + reference_items.splice(splice_start..splice_end, new_items.clone()); + + tree = { + let mut cursor = tree.cursor::(()); + let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right); + if rng.random() { + new_tree.extend(new_items, ()); + } else { + new_tree.par_extend(new_items, ()); + } + cursor.seek(&Count(splice_end), Bias::Right); + new_tree.append(cursor.slice(&tree_end, Bias::Right), ()); + new_tree + }; + + assert_eq!(tree.items(()), reference_items); + assert_eq!( + tree.iter().collect::>(), + tree.cursor::<()>(()).collect::>() + ); + + log::info!("tree items: {:?}", tree.items(())); + + let mut filter_cursor = + tree.filter::<_, Count>((), |summary| summary.contains_even); + let expected_filtered_items = tree + .items(()) + .into_iter() + .enumerate() + .filter(|(_, item)| (item & 1) == 0) + .collect::>(); + + let mut item_ix = if rng.random() { + filter_cursor.next(); + 0 + } else { + filter_cursor.prev(); + expected_filtered_items.len().saturating_sub(1) + }; + while item_ix < expected_filtered_items.len() { + log::info!("filter_cursor, item_ix: {}", item_ix); + let actual_item = filter_cursor.item().unwrap(); + let (reference_index, reference_item) = expected_filtered_items[item_ix]; + assert_eq!(actual_item, &reference_item); + assert_eq!(filter_cursor.start().0, reference_index); + log::info!("next"); + filter_cursor.next(); + item_ix += 1; + + while item_ix > 0 && rng.random_bool(0.2) { + log::info!("prev"); + filter_cursor.prev(); + item_ix -= 1; + + if item_ix == 0 && rng.random_bool(0.2) { + filter_cursor.prev(); + assert_eq!(filter_cursor.item(), None); + assert_eq!(filter_cursor.start().0, 0); + filter_cursor.next(); + } + } + } + assert_eq!(filter_cursor.item(), None); + + let mut before_start = false; + let mut cursor = tree.cursor::(()); + let start_pos = rng.random_range(0..=reference_items.len()); + cursor.seek(&Count(start_pos), Bias::Right); + let mut pos = rng.random_range(start_pos..=reference_items.len()); + cursor.seek_forward(&Count(pos), Bias::Right); + + for i in 0..10 { + assert_eq!(cursor.start().0, pos); + + if pos > 0 { + assert_eq!(cursor.prev_item().unwrap(), &reference_items[pos - 1]); + } else { + assert_eq!(cursor.prev_item(), None); + } + + if pos < reference_items.len() && !before_start { + assert_eq!(cursor.item().unwrap(), &reference_items[pos]); + } else { + assert_eq!(cursor.item(), None); + } + + if before_start { + assert_eq!(cursor.next_item(), reference_items.first()); + } else if pos + 1 < reference_items.len() { + assert_eq!(cursor.next_item().unwrap(), &reference_items[pos + 1]); + } else { + assert_eq!(cursor.next_item(), None); + } + + if i < 5 { + cursor.next(); + if pos < reference_items.len() { + pos += 1; + before_start = false; + } + } else { + cursor.prev(); + if pos == 0 { + before_start = true; + } + pos = pos.saturating_sub(1); + } + } + } + + for _ in 0..10 { + let end = rng.random_range(0..tree.extent::(()).0 + 1); + let start = rng.random_range(0..end + 1); + let start_bias = if rng.random() { + Bias::Left + } else { + Bias::Right + }; + let end_bias = if rng.random() { + Bias::Left + } else { + Bias::Right + }; + + let mut cursor = tree.cursor::(()); + cursor.seek(&Count(start), start_bias); + let slice = cursor.slice(&Count(end), end_bias); + + cursor.seek(&Count(start), start_bias); + let summary = cursor.summary::<_, Sum>(&Count(end), end_bias); + + assert_eq!(summary.0, slice.summary().sum); + } + } + } + + #[test] + fn test_cursor() { + // Empty tree + let tree = SumTree::::default(); + let mut cursor = tree.cursor::(()); + assert_eq!( + cursor.slice(&Count(0), Bias::Right).items(()), + Vec::::new() + ); + assert_eq!(cursor.item(), None); + assert_eq!(cursor.prev_item(), None); + assert_eq!(cursor.next_item(), None); + assert_eq!(cursor.start().sum, 0); + cursor.prev(); + assert_eq!(cursor.item(), None); + assert_eq!(cursor.prev_item(), None); + assert_eq!(cursor.next_item(), None); + assert_eq!(cursor.start().sum, 0); + cursor.next(); + assert_eq!(cursor.item(), None); + assert_eq!(cursor.prev_item(), None); + assert_eq!(cursor.next_item(), None); + assert_eq!(cursor.start().sum, 0); + + // Single-element tree + let mut tree = SumTree::::default(); + tree.extend(vec![1], ()); + let mut cursor = tree.cursor::(()); + assert_eq!( + cursor.slice(&Count(0), Bias::Right).items(()), + Vec::::new() + ); + assert_eq!(cursor.item(), Some(&1)); + assert_eq!(cursor.prev_item(), None); + assert_eq!(cursor.next_item(), None); + assert_eq!(cursor.start().sum, 0); + + cursor.next(); + assert_eq!(cursor.item(), None); + assert_eq!(cursor.prev_item(), Some(&1)); + assert_eq!(cursor.next_item(), None); + assert_eq!(cursor.start().sum, 1); + + cursor.prev(); + assert_eq!(cursor.item(), Some(&1)); + assert_eq!(cursor.prev_item(), None); + assert_eq!(cursor.next_item(), None); + assert_eq!(cursor.start().sum, 0); + + let mut cursor = tree.cursor::(()); + assert_eq!(cursor.slice(&Count(1), Bias::Right).items(()), [1]); + assert_eq!(cursor.item(), None); + assert_eq!(cursor.prev_item(), Some(&1)); + assert_eq!(cursor.next_item(), None); + assert_eq!(cursor.start().sum, 1); + + cursor.seek(&Count(0), Bias::Right); + assert_eq!( + cursor + .slice(&tree.extent::(()), Bias::Right) + .items(()), + [1] + ); + assert_eq!(cursor.item(), None); + assert_eq!(cursor.prev_item(), Some(&1)); + assert_eq!(cursor.next_item(), None); + assert_eq!(cursor.start().sum, 1); + + // Multiple-element tree + let mut tree = SumTree::default(); + tree.extend(vec![1, 2, 3, 4, 5, 6], ()); + let mut cursor = tree.cursor::(()); + + assert_eq!(cursor.slice(&Count(2), Bias::Right).items(()), [1, 2]); + assert_eq!(cursor.item(), Some(&3)); + assert_eq!(cursor.prev_item(), Some(&2)); + assert_eq!(cursor.next_item(), Some(&4)); + assert_eq!(cursor.start().sum, 3); + + cursor.next(); + assert_eq!(cursor.item(), Some(&4)); + assert_eq!(cursor.prev_item(), Some(&3)); + assert_eq!(cursor.next_item(), Some(&5)); + assert_eq!(cursor.start().sum, 6); + + cursor.next(); + assert_eq!(cursor.item(), Some(&5)); + assert_eq!(cursor.prev_item(), Some(&4)); + assert_eq!(cursor.next_item(), Some(&6)); + assert_eq!(cursor.start().sum, 10); + + cursor.next(); + assert_eq!(cursor.item(), Some(&6)); + assert_eq!(cursor.prev_item(), Some(&5)); + assert_eq!(cursor.next_item(), None); + assert_eq!(cursor.start().sum, 15); + + cursor.next(); + cursor.next(); + assert_eq!(cursor.item(), None); + assert_eq!(cursor.prev_item(), Some(&6)); + assert_eq!(cursor.next_item(), None); + assert_eq!(cursor.start().sum, 21); + + cursor.prev(); + assert_eq!(cursor.item(), Some(&6)); + assert_eq!(cursor.prev_item(), Some(&5)); + assert_eq!(cursor.next_item(), None); + assert_eq!(cursor.start().sum, 15); + + cursor.prev(); + assert_eq!(cursor.item(), Some(&5)); + assert_eq!(cursor.prev_item(), Some(&4)); + assert_eq!(cursor.next_item(), Some(&6)); + assert_eq!(cursor.start().sum, 10); + + cursor.prev(); + assert_eq!(cursor.item(), Some(&4)); + assert_eq!(cursor.prev_item(), Some(&3)); + assert_eq!(cursor.next_item(), Some(&5)); + assert_eq!(cursor.start().sum, 6); + + cursor.prev(); + assert_eq!(cursor.item(), Some(&3)); + assert_eq!(cursor.prev_item(), Some(&2)); + assert_eq!(cursor.next_item(), Some(&4)); + assert_eq!(cursor.start().sum, 3); + + cursor.prev(); + assert_eq!(cursor.item(), Some(&2)); + assert_eq!(cursor.prev_item(), Some(&1)); + assert_eq!(cursor.next_item(), Some(&3)); + assert_eq!(cursor.start().sum, 1); + + cursor.prev(); + assert_eq!(cursor.item(), Some(&1)); + assert_eq!(cursor.prev_item(), None); + assert_eq!(cursor.next_item(), Some(&2)); + assert_eq!(cursor.start().sum, 0); + + cursor.prev(); + assert_eq!(cursor.item(), None); + assert_eq!(cursor.prev_item(), None); + assert_eq!(cursor.next_item(), Some(&1)); + assert_eq!(cursor.start().sum, 0); + + cursor.next(); + assert_eq!(cursor.item(), Some(&1)); + assert_eq!(cursor.prev_item(), None); + assert_eq!(cursor.next_item(), Some(&2)); + assert_eq!(cursor.start().sum, 0); + + let mut cursor = tree.cursor::(()); + assert_eq!( + cursor + .slice(&tree.extent::(()), Bias::Right) + .items(()), + tree.items(()) + ); + assert_eq!(cursor.item(), None); + assert_eq!(cursor.prev_item(), Some(&6)); + assert_eq!(cursor.next_item(), None); + assert_eq!(cursor.start().sum, 21); + + cursor.seek(&Count(3), Bias::Right); + assert_eq!( + cursor + .slice(&tree.extent::(()), Bias::Right) + .items(()), + [4, 5, 6] + ); + assert_eq!(cursor.item(), None); + assert_eq!(cursor.prev_item(), Some(&6)); + assert_eq!(cursor.next_item(), None); + assert_eq!(cursor.start().sum, 21); + + // Seeking can bias left or right + cursor.seek(&Count(1), Bias::Left); + assert_eq!(cursor.item(), Some(&1)); + cursor.seek(&Count(1), Bias::Right); + assert_eq!(cursor.item(), Some(&2)); + + // Slicing without resetting starts from where the cursor is parked at. + cursor.seek(&Count(1), Bias::Right); + assert_eq!(cursor.slice(&Count(3), Bias::Right).items(()), vec![2, 3]); + assert_eq!(cursor.slice(&Count(6), Bias::Left).items(()), vec![4, 5]); + assert_eq!(cursor.slice(&Count(6), Bias::Right).items(()), vec![6]); + } + + #[test] + fn test_edit() { + let mut tree = SumTree::::default(); + + let removed = tree.edit(vec![Edit::Insert(1), Edit::Insert(2), Edit::Insert(0)], ()); + assert_eq!(tree.items(()), vec![0, 1, 2]); + assert_eq!(removed, Vec::::new()); + assert_eq!(tree.get(&0, ()), Some(&0)); + assert_eq!(tree.get(&1, ()), Some(&1)); + assert_eq!(tree.get(&2, ()), Some(&2)); + assert_eq!(tree.get(&4, ()), None); + + let removed = tree.edit(vec![Edit::Insert(2), Edit::Insert(4), Edit::Remove(0)], ()); + assert_eq!(tree.items(()), vec![1, 2, 4]); + assert_eq!(removed, vec![0, 2]); + assert_eq!(tree.get(&0, ()), None); + assert_eq!(tree.get(&1, ()), Some(&1)); + assert_eq!(tree.get(&2, ()), Some(&2)); + assert_eq!(tree.get(&4, ()), Some(&4)); + } + + #[test] + fn test_from_iter() { + assert_eq!( + SumTree::from_iter(0..100, ()).items(()), + (0..100).collect::>() + ); + + // Ensure `from_iter` works correctly when the given iterator restarts + // after calling `next` if `None` was already returned. + let mut ix = 0; + let iterator = std::iter::from_fn(|| { + ix = (ix + 1) % 2; + if ix == 1 { Some(1) } else { None } + }); + assert_eq!(SumTree::from_iter(iterator, ()).items(()), vec![1]); + } + + #[derive(Clone, Default, Debug)] + pub struct IntegersSummary { + count: usize, + sum: usize, + contains_even: bool, + max: u8, + } + + #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)] + struct Count(usize); + + #[derive(Ord, PartialOrd, Default, Eq, PartialEq, Clone, Debug)] + struct Sum(usize); + + impl Item for u8 { + type Summary = IntegersSummary; + + fn summary(&self, _cx: ()) -> Self::Summary { + IntegersSummary { + count: 1, + sum: *self as usize, + contains_even: (*self & 1) == 0, + max: *self, + } + } + } + + impl KeyedItem for u8 { + type Key = u8; + + fn key(&self) -> Self::Key { + *self + } + } + + impl ContextLessSummary for IntegersSummary { + fn zero() -> Self { + Default::default() + } + + fn add_summary(&mut self, other: &Self) { + self.count += other.count; + self.sum += other.sum; + self.contains_even |= other.contains_even; + self.max = cmp::max(self.max, other.max); + } + } + + impl Dimension<'_, IntegersSummary> for u8 { + fn zero(_cx: ()) -> Self { + Default::default() + } + + fn add_summary(&mut self, summary: &IntegersSummary, _: ()) { + *self = summary.max; + } + } + + impl Dimension<'_, IntegersSummary> for Count { + fn zero(_cx: ()) -> Self { + Default::default() + } + + fn add_summary(&mut self, summary: &IntegersSummary, _: ()) { + self.0 += summary.count; + } + } + + impl SeekTarget<'_, IntegersSummary, IntegersSummary> for Count { + fn cmp(&self, cursor_location: &IntegersSummary, _: ()) -> Ordering { + self.0.cmp(&cursor_location.count) + } + } + + impl Dimension<'_, IntegersSummary> for Sum { + fn zero(_cx: ()) -> Self { + Default::default() + } + + fn add_summary(&mut self, summary: &IntegersSummary, _: ()) { + self.0 += summary.sum; + } + } +} diff --git a/crates/gpui_sum_tree/src/tree_map.rs b/crates/gpui_sum_tree/src/tree_map.rs new file mode 100644 index 0000000000..004ec91851 --- /dev/null +++ b/crates/gpui_sum_tree/src/tree_map.rs @@ -0,0 +1,531 @@ +use std::{cmp::Ordering, fmt::Debug}; + +use crate::{Bias, ContextLessSummary, Dimension, Edit, Item, KeyedItem, SeekTarget, SumTree}; + +/// A cheaply-cloneable ordered map based on a [SumTree](crate::SumTree). +#[derive(Clone, PartialEq, Eq)] +pub struct TreeMap(SumTree>) +where + K: Clone + Ord, + V: Clone; + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct MapEntry { + key: K, + value: V, +} + +#[derive(Clone, Debug, PartialEq, Eq, PartialOrd, Ord)] +pub struct MapKey(Option); + +impl Default for MapKey { + fn default() -> Self { + Self(None) + } +} + +#[derive(Clone, Debug)] +pub struct MapKeyRef<'a, K>(Option<&'a K>); + +impl Default for MapKeyRef<'_, K> { + fn default() -> Self { + Self(None) + } +} + +#[derive(Clone, Debug, PartialEq, Eq)] +pub struct TreeSet(TreeMap) +where + K: Clone + Ord; + +impl TreeMap { + pub fn from_ordered_entries(entries: impl IntoIterator) -> Self { + let tree = SumTree::from_iter( + entries + .into_iter() + .map(|(key, value)| MapEntry { key, value }), + (), + ); + Self(tree) + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn contains_key(&self, key: &K) -> bool { + self.get(key).is_some() + } + + pub fn get(&self, key: &K) -> Option<&V> { + let (.., item) = self + .0 + .find::, _>((), &MapKeyRef(Some(key)), Bias::Left); + if let Some(item) = item { + if Some(key) == item.key().0.as_ref() { + Some(&item.value) + } else { + None + } + } else { + None + } + } + + pub fn insert(&mut self, key: K, value: V) { + self.0.insert_or_replace(MapEntry { key, value }, ()); + } + + pub fn insert_or_replace(&mut self, key: K, value: V) -> Option { + self.0 + .insert_or_replace(MapEntry { key, value }, ()) + .map(|it| it.value) + } + + pub fn extend(&mut self, iter: impl IntoIterator) { + let edits: Vec<_> = iter + .into_iter() + .map(|(key, value)| Edit::Insert(MapEntry { key, value })) + .collect(); + self.0.edit(edits, ()); + } + + pub fn clear(&mut self) { + self.0 = SumTree::default(); + } + + pub fn remove(&mut self, key: &K) -> Option { + let mut removed = None; + let mut cursor = self.0.cursor::>(()); + let key = MapKeyRef(Some(key)); + let mut new_tree = cursor.slice(&key, Bias::Left); + if key.cmp(&cursor.end(), ()) == Ordering::Equal { + removed = Some(cursor.item().unwrap().value.clone()); + cursor.next(); + } + new_tree.append(cursor.suffix(), ()); + drop(cursor); + self.0 = new_tree; + removed + } + + pub fn remove_range(&mut self, start: &impl MapSeekTarget, end: &impl MapSeekTarget) { + let start = MapSeekTargetAdaptor(start); + let end = MapSeekTargetAdaptor(end); + let mut cursor = self.0.cursor::>(()); + let mut new_tree = cursor.slice(&start, Bias::Left); + cursor.seek(&end, Bias::Left); + new_tree.append(cursor.suffix(), ()); + drop(cursor); + self.0 = new_tree; + } + + /// Returns the key-value pair with the greatest key less than or equal to the given key. + pub fn closest(&self, key: &K) -> Option<(&K, &V)> { + let mut cursor = self.0.cursor::>(()); + let key = MapKeyRef(Some(key)); + cursor.seek(&key, Bias::Right); + cursor.prev(); + cursor.item().map(|item| (&item.key, &item.value)) + } + + pub fn iter_from<'a>(&'a self, from: &K) -> impl Iterator + 'a { + let mut cursor = self.0.cursor::>(()); + let from_key = MapKeyRef(Some(from)); + cursor.seek(&from_key, Bias::Left); + + cursor.map(|map_entry| (&map_entry.key, &map_entry.value)) + } + + pub fn update(&mut self, key: &K, f: F) -> Option + where + F: FnOnce(&mut V) -> T, + { + let mut cursor = self.0.cursor::>(()); + let key = MapKeyRef(Some(key)); + let mut new_tree = cursor.slice(&key, Bias::Left); + let mut result = None; + if key.cmp(&cursor.end(), ()) == Ordering::Equal { + let mut updated = cursor.item().unwrap().clone(); + result = Some(f(&mut updated.value)); + new_tree.push(updated, ()); + cursor.next(); + } + new_tree.append(cursor.suffix(), ()); + drop(cursor); + self.0 = new_tree; + result + } + + pub fn retain bool>(&mut self, mut predicate: F) { + let mut new_map = SumTree::>::default(); + + let mut cursor = self.0.cursor::>(()); + cursor.next(); + while let Some(item) = cursor.item() { + if predicate(&item.key, &item.value) { + new_map.push(item.clone(), ()); + } + cursor.next(); + } + drop(cursor); + + self.0 = new_map; + } + + pub fn iter(&self) -> impl Iterator + '_ { + self.0.iter().map(|entry| (&entry.key, &entry.value)) + } + + pub fn values(&self) -> impl Iterator + '_ { + self.0.iter().map(|entry| &entry.value) + } + + pub fn first(&self) -> Option<(&K, &V)> { + self.0.first().map(|entry| (&entry.key, &entry.value)) + } + + pub fn last(&self) -> Option<(&K, &V)> { + self.0.last().map(|entry| (&entry.key, &entry.value)) + } + + pub fn insert_tree(&mut self, other: TreeMap) { + let edits = other + .iter() + .map(|(key, value)| { + Edit::Insert(MapEntry { + key: key.to_owned(), + value: value.to_owned(), + }) + }) + .collect(); + + self.0.edit(edits, ()); + } +} + +impl Debug for TreeMap +where + K: Clone + Debug + Ord, + V: Clone + Debug, +{ + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.debug_map().entries(self.iter()).finish() + } +} + +#[derive(Debug)] +struct MapSeekTargetAdaptor<'a, T>(&'a T); + +impl<'a, K: Clone + Ord, T: MapSeekTarget> SeekTarget<'a, MapKey, MapKeyRef<'a, K>> + for MapSeekTargetAdaptor<'_, T> +{ + fn cmp(&self, cursor_location: &MapKeyRef, _: ()) -> Ordering { + if let Some(key) = &cursor_location.0 { + MapSeekTarget::cmp_cursor(self.0, key) + } else { + Ordering::Greater + } + } +} + +pub trait MapSeekTarget { + fn cmp_cursor(&self, cursor_location: &K) -> Ordering; +} + +impl MapSeekTarget for K { + fn cmp_cursor(&self, cursor_location: &K) -> Ordering { + self.cmp(cursor_location) + } +} + +impl Default for TreeMap +where + K: Clone + Ord, + V: Clone, +{ + fn default() -> Self { + Self(Default::default()) + } +} + +impl Item for MapEntry +where + K: Clone + Ord, + V: Clone, +{ + type Summary = MapKey; + + fn summary(&self, _cx: ()) -> Self::Summary { + self.key() + } +} + +impl KeyedItem for MapEntry +where + K: Clone + Ord, + V: Clone, +{ + type Key = MapKey; + + fn key(&self) -> Self::Key { + MapKey(Some(self.key.clone())) + } +} + +impl ContextLessSummary for MapKey +where + K: Clone, +{ + fn zero() -> Self { + Default::default() + } + + fn add_summary(&mut self, summary: &Self) { + *self = summary.clone() + } +} + +impl<'a, K> Dimension<'a, MapKey> for MapKeyRef<'a, K> +where + K: Clone + Ord, +{ + fn zero(_cx: ()) -> Self { + Default::default() + } + + fn add_summary(&mut self, summary: &'a MapKey, _: ()) { + self.0 = summary.0.as_ref(); + } +} + +impl<'a, K> SeekTarget<'a, MapKey, MapKeyRef<'a, K>> for MapKeyRef<'_, K> +where + K: Clone + Ord, +{ + fn cmp(&self, cursor_location: &MapKeyRef, _: ()) -> Ordering { + Ord::cmp(&self.0, &cursor_location.0) + } +} + +impl Default for TreeSet +where + K: Clone + Ord, +{ + fn default() -> Self { + Self(Default::default()) + } +} + +impl TreeSet +where + K: Clone + Ord, +{ + pub fn from_ordered_entries(entries: impl IntoIterator) -> Self { + Self(TreeMap::from_ordered_entries( + entries.into_iter().map(|key| (key, ())), + )) + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn insert(&mut self, key: K) { + self.0.insert(key, ()); + } + + pub fn remove(&mut self, key: &K) -> bool { + self.0.remove(key).is_some() + } + + pub fn extend(&mut self, iter: impl IntoIterator) { + self.0.extend(iter.into_iter().map(|key| (key, ()))); + } + + pub fn contains(&self, key: &K) -> bool { + self.0.get(key).is_some() + } + + pub fn iter(&self) -> impl Iterator + '_ { + self.0.iter().map(|(k, _)| k) + } + + pub fn iter_from<'a>(&'a self, key: &K) -> impl Iterator + 'a { + self.0.iter_from(key).map(move |(k, _)| k) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_basic() { + let mut map = TreeMap::default(); + assert_eq!(map.iter().collect::>(), vec![]); + + map.insert(3, "c"); + assert_eq!(map.get(&3), Some(&"c")); + assert_eq!(map.iter().collect::>(), vec![(&3, &"c")]); + + map.insert(1, "a"); + assert_eq!(map.get(&1), Some(&"a")); + assert_eq!(map.iter().collect::>(), vec![(&1, &"a"), (&3, &"c")]); + + map.insert(2, "b"); + assert_eq!(map.get(&2), Some(&"b")); + assert_eq!(map.get(&1), Some(&"a")); + assert_eq!(map.get(&3), Some(&"c")); + assert_eq!( + map.iter().collect::>(), + vec![(&1, &"a"), (&2, &"b"), (&3, &"c")] + ); + + assert_eq!(map.closest(&0), None); + assert_eq!(map.closest(&1), Some((&1, &"a"))); + assert_eq!(map.closest(&10), Some((&3, &"c"))); + + map.remove(&2); + assert_eq!(map.get(&2), None); + assert_eq!(map.iter().collect::>(), vec![(&1, &"a"), (&3, &"c")]); + + assert_eq!(map.closest(&2), Some((&1, &"a"))); + + map.remove(&3); + assert_eq!(map.get(&3), None); + assert_eq!(map.iter().collect::>(), vec![(&1, &"a")]); + + map.remove(&1); + assert_eq!(map.get(&1), None); + assert_eq!(map.iter().collect::>(), vec![]); + + map.insert(4, "d"); + map.insert(5, "e"); + map.insert(6, "f"); + map.retain(|key, _| *key % 2 == 0); + assert_eq!(map.iter().collect::>(), vec![(&4, &"d"), (&6, &"f")]); + } + + #[test] + fn test_iter_from() { + let mut map = TreeMap::default(); + + map.insert("a", 1); + map.insert("b", 2); + map.insert("baa", 3); + map.insert("baaab", 4); + map.insert("c", 5); + + let result = map + .iter_from(&"ba") + .take_while(|(key, _)| key.starts_with("ba")) + .collect::>(); + + assert_eq!(result.len(), 2); + assert!(result.iter().any(|(k, _)| k == &&"baa")); + assert!(result.iter().any(|(k, _)| k == &&"baaab")); + + let result = map + .iter_from(&"c") + .take_while(|(key, _)| key.starts_with("c")) + .collect::>(); + + assert_eq!(result.len(), 1); + assert!(result.iter().any(|(k, _)| k == &&"c")); + } + + #[test] + fn test_insert_tree() { + let mut map = TreeMap::default(); + map.insert("a", 1); + map.insert("b", 2); + map.insert("c", 3); + + let mut other = TreeMap::default(); + other.insert("a", 2); + other.insert("b", 2); + other.insert("d", 4); + + map.insert_tree(other); + + assert_eq!(map.iter().count(), 4); + assert_eq!(map.get(&"a"), Some(&2)); + assert_eq!(map.get(&"b"), Some(&2)); + assert_eq!(map.get(&"c"), Some(&3)); + assert_eq!(map.get(&"d"), Some(&4)); + } + + #[test] + fn test_extend() { + let mut map = TreeMap::default(); + map.insert("a", 1); + map.insert("b", 2); + map.insert("c", 3); + map.extend([("a", 2), ("b", 2), ("d", 4)]); + assert_eq!(map.iter().count(), 4); + assert_eq!(map.get(&"a"), Some(&2)); + assert_eq!(map.get(&"b"), Some(&2)); + assert_eq!(map.get(&"c"), Some(&3)); + assert_eq!(map.get(&"d"), Some(&4)); + } + + #[test] + fn test_remove_between_and_path_successor() { + use std::path::{Path, PathBuf}; + + #[derive(Debug)] + pub struct PathDescendants<'a>(&'a Path); + + impl MapSeekTarget for PathDescendants<'_> { + fn cmp_cursor(&self, key: &PathBuf) -> Ordering { + if key.starts_with(self.0) { + Ordering::Greater + } else { + self.0.cmp(key) + } + } + } + + let mut map = TreeMap::default(); + + map.insert(PathBuf::from("a"), 1); + map.insert(PathBuf::from("a/a"), 1); + map.insert(PathBuf::from("b"), 2); + map.insert(PathBuf::from("b/a/a"), 3); + map.insert(PathBuf::from("b/a/a/a/b"), 4); + map.insert(PathBuf::from("c"), 5); + map.insert(PathBuf::from("c/a"), 6); + + map.remove_range( + &PathBuf::from("b/a"), + &PathDescendants(&PathBuf::from("b/a")), + ); + + assert_eq!(map.get(&PathBuf::from("a")), Some(&1)); + assert_eq!(map.get(&PathBuf::from("a/a")), Some(&1)); + assert_eq!(map.get(&PathBuf::from("b")), Some(&2)); + assert_eq!(map.get(&PathBuf::from("b/a/a")), None); + assert_eq!(map.get(&PathBuf::from("b/a/a/a/b")), None); + assert_eq!(map.get(&PathBuf::from("c")), Some(&5)); + assert_eq!(map.get(&PathBuf::from("c/a")), Some(&6)); + + map.remove_range(&PathBuf::from("c"), &PathDescendants(&PathBuf::from("c"))); + + assert_eq!(map.get(&PathBuf::from("a")), Some(&1)); + assert_eq!(map.get(&PathBuf::from("a/a")), Some(&1)); + assert_eq!(map.get(&PathBuf::from("b")), Some(&2)); + assert_eq!(map.get(&PathBuf::from("c")), None); + assert_eq!(map.get(&PathBuf::from("c/a")), None); + + map.remove_range(&PathBuf::from("a"), &PathDescendants(&PathBuf::from("a"))); + + assert_eq!(map.get(&PathBuf::from("a")), None); + assert_eq!(map.get(&PathBuf::from("a/a")), None); + assert_eq!(map.get(&PathBuf::from("b")), Some(&2)); + + map.remove_range(&PathBuf::from("b"), &PathDescendants(&PathBuf::from("b"))); + + assert_eq!(map.get(&PathBuf::from("b")), None); + } +} diff --git a/crates/gpui_wgpu/Cargo.toml b/crates/gpui_wgpu/Cargo.toml index 61a5746df3..ea6adde5ef 100644 --- a/crates/gpui_wgpu/Cargo.toml +++ b/crates/gpui_wgpu/Cargo.toml @@ -34,8 +34,7 @@ gpui_util.workspace = true wgpu.workspace = true # Optional: only needed on platforms with multiple font sources (e.g. Linux) -# WARNING: If you change this, you must also publish a new version of zed-font-kit to crates.io -font-kit = { git = "https://github.com/zed-industries/font-kit", rev = "94b0f28166665e8fd2f53ff6d268a14955c82269", package = "zed-font-kit", version = "0.14.1-zed", optional = true } +font-kit = { version = "0.14.1-zed", package = "zed-font-kit", optional = true } [target.'cfg(not(target_family = "wasm"))'.dependencies] pollster.workspace = true diff --git a/crates/gpui_zed_util/Cargo.toml b/crates/gpui_zed_util/Cargo.toml new file mode 100644 index 0000000000..7e52740764 --- /dev/null +++ b/crates/gpui_zed_util/Cargo.toml @@ -0,0 +1,68 @@ +[package] +name = "gpui_zed_util" +version = "0.2.2" +edition = "2024" +license = "Apache-2.0" +publish = true +description = "OS/utility helpers used by gpui-ce platform backends (vendored from Zed's util)." +repository = "https://github.com/gpui-ce/gpui-ce" + +[lib] +name = "util" +path = "src/util.rs" +doctest = true + +[dependencies] +anyhow = "1.0.86" +async_zip = { version = "0.0.18", features = ["deflate", "deflate64"] } +collections = { package = "gpui_collections", version = "0.2.2", path = "../gpui_collections" } +dunce = "1.0" +futures-lite = "1.13" +futures = "0.3.32" +globset = "0.4" +itertools = "0.14.0" +log = { version = "0.4.16", features = ["kv_unstable_serde", "serde"] } +regex = "1.5" +rust-embed = { version = "8.11", features = ["include-exclude"] } +schemars = { version = "1.0", features = ["indexmap2"] } +serde = { version = "1.0.221", features = ["derive", "rc"] } +serde_json = { version = "1.0.144", features = ["preserve_order", "raw_value"] } +serde_json_lenient = { version = "0.2", features = [ + "preserve_order", + "raw_value", +] } +shlex = "1.3.0" +take-until = "0.2.0" +tempfile = "3.20.0" +unicase = "2.6" +url = "2.2" +percent-encoding = "2.3.2" +gpui_util = { package = "gpui_ce_util", version = "0.2.2", path = "../gpui_ce_util" } + +[target.'cfg(not(target_family = "wasm"))'.dependencies] +smol = "2.0" +which = "6.0.0" +async-fs = "2.1" +walkdir = "2.5" +dirs = "6.0" + +[target.'cfg(unix)'.dependencies] +command-fds = "0.3.1" +libc = "0.2" +nix = { version = "0.29", features = ["user"] } + +[target.'cfg(target_os = "macos")'.dependencies] +mach2 = "0.5" + +[target.'cfg(windows)'.dependencies] +tendril = "0.4.3" + +[dev-dependencies] +pretty_assertions = { version = "1.3.0", features = ["unstable"] } +git2 = { version = "0.21", default-features = false, features = [ + "vendored-libgit2", +] } +rand = "0.9" + +[features] +test-support = [] diff --git a/crates/gpui_zed_util/LICENSE-APACHE b/crates/gpui_zed_util/LICENSE-APACHE new file mode 100644 index 0000000000..461a0fe5ba --- /dev/null +++ b/crates/gpui_zed_util/LICENSE-APACHE @@ -0,0 +1,222 @@ +Copyright 2022 - 2025 Zed Industries, Inc. + + + 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. + + + + +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 diff --git a/crates/gpui_zed_util/src/archive.rs b/crates/gpui_zed_util/src/archive.rs new file mode 100644 index 0000000000..7fe43a25c3 --- /dev/null +++ b/crates/gpui_zed_util/src/archive.rs @@ -0,0 +1,383 @@ +use std::path::Path; + +use anyhow::{Context as _, Result}; +use async_zip::base::read; +#[cfg(not(windows))] +use futures::AsyncSeek; +use futures::{AsyncRead, io::BufReader}; + +#[cfg(any(unix, windows))] +fn archive_path_is_normal(filename: &str) -> bool { + Path::new(filename).components().all(|c| { + matches!( + c, + std::path::Component::Normal(_) | std::path::Component::CurDir + ) + }) +} + +#[cfg(windows)] +pub async fn extract_zip(destination: &Path, reader: R) -> Result<()> { + let mut reader = read::stream::ZipFileReader::new(BufReader::new(reader)); + + let destination = &destination + .canonicalize() + .unwrap_or_else(|_| destination.to_path_buf()); + + while let Some(mut item) = reader.next_with_entry().await? { + let entry_reader = item.reader_mut(); + let entry = entry_reader.entry(); + let filename = entry + .filename() + .as_str() + .context("reading zip entry file name")?; + + if !archive_path_is_normal(filename) { + reader = item.skip().await.context("reading next zip entry")?; + continue; + } + + let path = destination.join(filename); + + if entry + .dir() + .with_context(|| format!("reading zip entry metadata for path {path:?}"))? + { + std::fs::create_dir_all(&path) + .with_context(|| format!("creating directory {path:?}"))?; + } else { + let parent_dir = path + .parent() + .with_context(|| format!("no parent directory for {path:?}"))?; + std::fs::create_dir_all(parent_dir) + .with_context(|| format!("creating parent directory {parent_dir:?}"))?; + let mut file = smol::fs::File::create(&path) + .await + .with_context(|| format!("creating file {path:?}"))?; + futures::io::copy(entry_reader, &mut file) + .await + .with_context(|| format!("extracting into file {path:?}"))?; + } + + reader = item.skip().await.context("reading next zip entry")?; + } + + Ok(()) +} + +#[cfg(unix)] +pub async fn extract_zip(destination: &Path, reader: R) -> Result<()> { + // Unix needs file permissions copied when extracting. + // This is only possible to do when a reader impls `AsyncSeek` and `seek::ZipFileReader` is used. + // `stream::ZipFileReader` also has the `unix_permissions` method, but it will always return `Some(0)`. + // + // A typical `reader` comes from a streaming network response, so cannot be sought right away, + // and reading the entire archive into the memory seems wasteful. + // + // So, save the stream into a temporary file first and then get it read with a seeking reader. + let mut file = async_fs::File::from(tempfile::tempfile().context("creating a temporary file")?); + futures::io::copy(&mut BufReader::new(reader), &mut file) + .await + .context("saving archive contents into the temporary file")?; + extract_seekable_zip(destination, file).await +} + +#[cfg(unix)] +pub async fn extract_seekable_zip( + destination: &Path, + reader: R, +) -> Result<()> { + let mut reader = read::seek::ZipFileReader::new(BufReader::new(reader)) + .await + .context("reading the zip archive")?; + let destination = &destination + .canonicalize() + .unwrap_or_else(|_| destination.to_path_buf()); + for (i, entry) in reader.file().entries().to_vec().into_iter().enumerate() { + let filename = entry + .filename() + .as_str() + .context("reading zip entry file name")?; + + if !archive_path_is_normal(filename) { + continue; + } + + let path = destination.join(filename); + + if entry + .dir() + .with_context(|| format!("reading zip entry metadata for path {path:?}"))? + { + std::fs::create_dir_all(&path) + .with_context(|| format!("creating directory {path:?}"))?; + } else { + let parent_dir = path + .parent() + .with_context(|| format!("no parent directory for {path:?}"))?; + std::fs::create_dir_all(parent_dir) + .with_context(|| format!("creating parent directory {parent_dir:?}"))?; + let mut file = smol::fs::File::create(&path) + .await + .with_context(|| format!("creating file {path:?}"))?; + let mut entry_reader = reader + .reader_with_entry(i) + .await + .with_context(|| format!("reading entry for path {path:?}"))?; + futures::io::copy(&mut entry_reader, &mut file) + .await + .with_context(|| format!("extracting into file {path:?}"))?; + + if let Some(perms) = entry.unix_permissions() + && perms != 0o000 + { + use std::os::unix::fs::PermissionsExt; + let permissions = std::fs::Permissions::from_mode(u32::from(perms)); + file.set_permissions(permissions) + .await + .with_context(|| format!("setting permissions for file {path:?}"))?; + } + } + } + + Ok(()) +} + +#[cfg(test)] +mod tests { + use async_zip::ZipEntryBuilder; + use async_zip::base::write::ZipFileWriter; + use futures::{AsyncSeek, AsyncWriteExt}; + use smol::io::Cursor; + use tempfile::TempDir; + + use super::*; + + #[allow(unused_variables)] + async fn compress_zip(src_dir: &Path, dst: &Path, keep_file_permissions: bool) -> Result<()> { + let mut out = smol::fs::File::create(dst).await?; + let mut writer = ZipFileWriter::new(&mut out); + + for entry in walkdir::WalkDir::new(src_dir) { + let entry = entry?; + let path = entry.path(); + + if path.is_dir() { + continue; + } + + let relative_path = path.strip_prefix(src_dir)?; + let data = smol::fs::read(&path).await?; + + let filename = relative_path.display().to_string(); + + #[cfg(unix)] + { + let mut builder = + ZipEntryBuilder::new(filename.into(), async_zip::Compression::Deflate); + use std::os::unix::fs::PermissionsExt; + let metadata = std::fs::metadata(path)?; + let perms = keep_file_permissions.then(|| metadata.permissions().mode() as u16); + builder = builder.unix_permissions(perms.unwrap_or_default()); + writer.write_entry_whole(builder, &data).await?; + } + #[cfg(not(unix))] + { + let builder = + ZipEntryBuilder::new(filename.into(), async_zip::Compression::Deflate); + writer.write_entry_whole(builder, &data).await?; + } + } + + writer.close().await?; + out.flush().await?; + out.sync_all().await?; + + Ok(()) + } + + #[track_caller] + fn assert_file_content(path: &Path, content: &str) { + assert!(path.exists(), "file not found: {:?}", path); + let actual = std::fs::read_to_string(path).unwrap(); + assert_eq!(actual, content); + } + + #[track_caller] + fn make_test_data() -> TempDir { + let dir = tempfile::tempdir().unwrap(); + let dst = dir.path(); + + std::fs::write(dst.join("test"), "Hello world.").unwrap(); + std::fs::create_dir_all(dst.join("foo/bar")).unwrap(); + std::fs::write(dst.join("foo/bar.txt"), "Foo bar.").unwrap(); + std::fs::write(dst.join("foo/dar.md"), "Bar dar.").unwrap(); + std::fs::write(dst.join("foo/bar/dar你好.txt"), "你好世界").unwrap(); + + dir + } + + async fn read_archive(path: &Path) -> impl AsyncRead + AsyncSeek + Unpin { + let data = smol::fs::read(&path).await.unwrap(); + Cursor::new(data) + } + + #[test] + fn test_extract_zip() { + let test_dir = make_test_data(); + let zip_file = test_dir.path().join("test.zip"); + + smol::block_on(async { + compress_zip(test_dir.path(), &zip_file, true) + .await + .unwrap(); + let reader = read_archive(&zip_file).await; + + let dir = tempfile::tempdir().unwrap(); + let dst = dir.path(); + extract_zip(dst, reader).await.unwrap(); + + assert_file_content(&dst.join("test"), "Hello world."); + assert_file_content(&dst.join("foo/bar.txt"), "Foo bar."); + assert_file_content(&dst.join("foo/dar.md"), "Bar dar."); + assert_file_content(&dst.join("foo/bar/dar你好.txt"), "你好世界"); + }); + } + + #[cfg(unix)] + #[test] + fn test_extract_zip_preserves_executable_permissions() { + use std::os::unix::fs::PermissionsExt; + + smol::block_on(async { + let test_dir = tempfile::tempdir().unwrap(); + let executable_path = test_dir.path().join("my_script"); + + // Create an executable file + std::fs::write(&executable_path, "#!/bin/bash\necho 'Hello'").unwrap(); + let mut perms = std::fs::metadata(&executable_path).unwrap().permissions(); + perms.set_mode(0o755); // rwxr-xr-x + std::fs::set_permissions(&executable_path, perms).unwrap(); + + // Create zip + let zip_file = test_dir.path().join("test.zip"); + compress_zip(test_dir.path(), &zip_file, true) + .await + .unwrap(); + + // Extract to new location + let extract_dir = tempfile::tempdir().unwrap(); + let reader = read_archive(&zip_file).await; + extract_zip(extract_dir.path(), reader).await.unwrap(); + + // Check permissions are preserved + let extracted_path = extract_dir.path().join("my_script"); + assert!(extracted_path.exists()); + let extracted_perms = std::fs::metadata(&extracted_path).unwrap().permissions(); + assert_eq!(extracted_perms.mode() & 0o777, 0o755); + }); + } + + #[cfg(unix)] + #[test] + fn test_extract_zip_sets_default_permissions() { + use std::os::unix::fs::PermissionsExt; + + smol::block_on(async { + let test_dir = tempfile::tempdir().unwrap(); + let file_path = test_dir.path().join("my_script"); + + std::fs::write(&file_path, "#!/bin/bash\necho 'Hello'").unwrap(); + // The permissions will be shaped by the umask in the test environment + let original_perms = std::fs::metadata(&file_path).unwrap().permissions(); + + // Create zip + let zip_file = test_dir.path().join("test.zip"); + compress_zip(test_dir.path(), &zip_file, false) + .await + .unwrap(); + + // Extract to new location + let extract_dir = tempfile::tempdir().unwrap(); + let reader = read_archive(&zip_file).await; + extract_zip(extract_dir.path(), reader).await.unwrap(); + + // Permissions were not stored, so will be whatever the umask generates + // by default for new files. This should match what we saw when we previously wrote + // the file. + let extracted_path = extract_dir.path().join("my_script"); + assert!(extracted_path.exists()); + let extracted_perms = std::fs::metadata(&extracted_path).unwrap().permissions(); + assert_eq!( + extracted_perms.mode(), + original_perms.mode(), + "Expected matching Unix file mode for unzipped file without keep_file_permissions" + ); + assert_eq!( + extracted_perms, original_perms, + "Expected default set of permissions for unzipped file without keep_file_permissions" + ); + }); + } + + #[test] + fn test_archive_path_is_normal_rejects_traversal() { + assert!(!archive_path_is_normal("../parent.txt")); + assert!(!archive_path_is_normal("foo/../../grandparent.txt")); + assert!(!archive_path_is_normal("/tmp/absolute.txt")); + + assert!(archive_path_is_normal("foo/bar.txt")); + assert!(archive_path_is_normal("foo/bar/baz.txt")); + assert!(archive_path_is_normal("./foo/bar.txt")); + assert!(archive_path_is_normal("normal.txt")); + } + + async fn build_zip_with_entries(entries: &[(&str, &[u8])]) -> Cursor> { + let mut buf = Cursor::new(Vec::new()); + let mut writer = ZipFileWriter::new(&mut buf); + for (name, data) in entries { + let builder = ZipEntryBuilder::new((*name).into(), async_zip::Compression::Stored); + writer.write_entry_whole(builder, data).await.unwrap(); + } + writer.close().await.unwrap(); + buf.set_position(0); + buf + } + + #[test] + fn test_extract_zip_skips_path_traversal_entries() { + smol::block_on(async { + let base_dir = tempfile::tempdir().unwrap(); + let extract_dir = base_dir.path().join("subdir"); + std::fs::create_dir_all(&extract_dir).unwrap(); + + let absolute_target = base_dir.path().join("absolute.txt"); + let reader = build_zip_with_entries(&[ + ("normal.txt", b"normal file"), + ("subdir/nested.txt", b"nested file"), + ("../parent.txt", b"parent file"), + ("foo/../../grandparent.txt", b"grandparent file"), + (absolute_target.to_str().unwrap(), b"absolute file"), + ]) + .await; + + extract_zip(&extract_dir, reader).await.unwrap(); + + assert_file_content(&extract_dir.join("normal.txt"), "normal file"); + assert_file_content(&extract_dir.join("subdir/nested.txt"), "nested file"); + + assert!( + !base_dir.path().join("parent.txt").exists(), + "parent traversal entry should have been skipped" + ); + assert!( + !base_dir.path().join("grandparent.txt").exists(), + "nested traversal entry should have been skipped" + ); + assert!( + !absolute_target.exists(), + "absolute path entry should have been skipped" + ); + }); + } +} diff --git a/crates/gpui_zed_util/src/command.rs b/crates/gpui_zed_util/src/command.rs new file mode 100644 index 0000000000..a131d3c15b --- /dev/null +++ b/crates/gpui_zed_util/src/command.rs @@ -0,0 +1,140 @@ +use std::ffi::OsStr; +#[cfg(not(target_os = "macos"))] +use std::path::Path; + +#[cfg(target_os = "macos")] +mod darwin; + +#[cfg(target_os = "macos")] +pub use darwin::{Child, Command, Stdio}; + +#[cfg(target_os = "windows")] +const CREATE_NO_WINDOW: u32 = 0x0800_0000_u32; + +pub fn new_command(program: impl AsRef) -> Command { + Command::new(program) +} + +#[cfg(target_os = "windows")] +pub fn new_std_command(program: impl AsRef) -> std::process::Command { + use std::os::windows::process::CommandExt; + + let mut command = std::process::Command::new(program); + command.creation_flags(CREATE_NO_WINDOW); + command +} + +#[cfg(not(target_os = "windows"))] +pub fn new_std_command(program: impl AsRef) -> std::process::Command { + std::process::Command::new(program) +} + +#[cfg(not(target_os = "macos"))] +pub type Child = smol::process::Child; + +#[cfg(not(target_os = "macos"))] +pub use std::process::Stdio; + +#[cfg(not(target_os = "macos"))] +#[derive(Debug)] +pub struct Command(smol::process::Command); + +#[cfg(not(target_os = "macos"))] +impl Command { + #[inline] + pub fn new(program: impl AsRef) -> Self { + #[cfg(target_os = "windows")] + { + use smol::process::windows::CommandExt; + let mut cmd = smol::process::Command::new(program); + cmd.creation_flags(CREATE_NO_WINDOW); + Self(cmd) + } + #[cfg(not(target_os = "windows"))] + Self(smol::process::Command::new(program)) + } + + pub fn arg(&mut self, arg: impl AsRef) -> &mut Self { + self.0.arg(arg); + self + } + + pub fn args(&mut self, args: I) -> &mut Self + where + I: IntoIterator, + S: AsRef, + { + self.0.args(args); + self + } + + pub fn get_args(&self) -> impl Iterator { + self.0.get_args() + } + + pub fn env(&mut self, key: impl AsRef, val: impl AsRef) -> &mut Self { + self.0.env(key, val); + self + } + + pub fn envs(&mut self, vars: I) -> &mut Self + where + I: IntoIterator, + K: AsRef, + V: AsRef, + { + self.0.envs(vars); + self + } + + pub fn env_remove(&mut self, key: impl AsRef) -> &mut Self { + self.0.env_remove(key); + self + } + + pub fn env_clear(&mut self) -> &mut Self { + self.0.env_clear(); + self + } + + pub fn current_dir(&mut self, dir: impl AsRef) -> &mut Self { + self.0.current_dir(dir); + self + } + + pub fn stdin(&mut self, cfg: impl Into) -> &mut Self { + self.0.stdin(cfg.into()); + self + } + + pub fn stdout(&mut self, cfg: impl Into) -> &mut Self { + self.0.stdout(cfg.into()); + self + } + + pub fn stderr(&mut self, cfg: impl Into) -> &mut Self { + self.0.stderr(cfg.into()); + self + } + + pub fn kill_on_drop(&mut self, kill_on_drop: bool) -> &mut Self { + self.0.kill_on_drop(kill_on_drop); + self + } + + pub fn spawn(&mut self) -> std::io::Result { + self.0.spawn() + } + + pub async fn output(&mut self) -> std::io::Result { + self.0.output().await + } + + pub async fn status(&mut self) -> std::io::Result { + self.0.status().await + } + + pub fn get_program(&self) -> &OsStr { + self.0.get_program() + } +} diff --git a/crates/gpui_zed_util/src/command/darwin.rs b/crates/gpui_zed_util/src/command/darwin.rs new file mode 100644 index 0000000000..1c31433a9c --- /dev/null +++ b/crates/gpui_zed_util/src/command/darwin.rs @@ -0,0 +1,915 @@ +use mach2::exception_types::{ + EXC_MASK_ALL, EXCEPTION_DEFAULT, exception_behavior_t, exception_mask_t, +}; +use mach2::port::{MACH_PORT_NULL, mach_port_t}; +use mach2::thread_status::{THREAD_STATE_NONE, thread_state_flavor_t}; +use smol::Unblock; +use std::collections::BTreeMap; +use std::ffi::{CString, OsStr, OsString}; +use std::io; +use std::os::unix::ffi::OsStrExt; +use std::os::unix::io::FromRawFd; +use std::os::unix::process::ExitStatusExt; +use std::path::{Path, PathBuf}; +use std::process::{ExitStatus, Output}; +use std::ptr; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Default)] +pub enum Stdio { + /// A new pipe should be arranged to connect the parent and child processes. + #[default] + Piped, + /// The child inherits from the corresponding parent descriptor. + Inherit, + /// This stream will be ignored (redirected to `/dev/null`). + Null, +} + +impl Stdio { + pub fn piped() -> Self { + Self::Piped + } + + pub fn inherit() -> Self { + Self::Inherit + } + + pub fn null() -> Self { + Self::Null + } +} + +unsafe extern "C" { + fn posix_spawnattr_setexceptionports_np( + attr: *mut libc::posix_spawnattr_t, + mask: exception_mask_t, + new_port: mach_port_t, + behavior: exception_behavior_t, + new_flavor: thread_state_flavor_t, + ) -> libc::c_int; + + fn posix_spawn_file_actions_addchdir_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + path: *const libc::c_char, + ) -> libc::c_int; + + fn posix_spawn_file_actions_addinherit_np( + file_actions: *mut libc::posix_spawn_file_actions_t, + filedes: libc::c_int, + ) -> libc::c_int; + + static environ: *const *mut libc::c_char; +} + +#[derive(Debug)] +pub struct Command { + program: OsString, + args: Vec, + envs: BTreeMap>, + env_clear: bool, + current_dir: Option, + stdin_cfg: Option, + stdout_cfg: Option, + stderr_cfg: Option, + kill_on_drop: bool, +} + +impl Command { + pub fn new(program: impl AsRef) -> Self { + Self { + program: program.as_ref().to_owned(), + args: Vec::new(), + envs: BTreeMap::new(), + env_clear: false, + current_dir: None, + stdin_cfg: None, + stdout_cfg: None, + stderr_cfg: None, + kill_on_drop: false, + } + } + + pub fn arg(&mut self, arg: impl AsRef) -> &mut Self { + self.args.push(arg.as_ref().to_owned()); + self + } + + pub fn args(&mut self, args: I) -> &mut Self + where + I: IntoIterator, + S: AsRef, + { + self.args + .extend(args.into_iter().map(|a| a.as_ref().to_owned())); + self + } + + pub fn get_args(&self) -> impl Iterator { + self.args.iter().map(|s| s.as_os_str()) + } + + pub fn env(&mut self, key: impl AsRef, val: impl AsRef) -> &mut Self { + self.envs + .insert(key.as_ref().to_owned(), Some(val.as_ref().to_owned())); + self + } + + pub fn envs(&mut self, vars: I) -> &mut Self + where + I: IntoIterator, + K: AsRef, + V: AsRef, + { + for (key, val) in vars { + self.envs + .insert(key.as_ref().to_owned(), Some(val.as_ref().to_owned())); + } + self + } + + pub fn env_remove(&mut self, key: impl AsRef) -> &mut Self { + let key = key.as_ref().to_owned(); + if self.env_clear { + self.envs.remove(&key); + } else { + self.envs.insert(key, None); + } + self + } + + pub fn env_clear(&mut self) -> &mut Self { + self.env_clear = true; + self.envs.clear(); + self + } + + pub fn current_dir(&mut self, dir: impl AsRef) -> &mut Self { + self.current_dir = Some(dir.as_ref().to_owned()); + self + } + + pub fn stdin(&mut self, cfg: Stdio) -> &mut Self { + self.stdin_cfg = Some(cfg); + self + } + + pub fn stdout(&mut self, cfg: Stdio) -> &mut Self { + self.stdout_cfg = Some(cfg); + self + } + + pub fn stderr(&mut self, cfg: Stdio) -> &mut Self { + self.stderr_cfg = Some(cfg); + self + } + + pub fn kill_on_drop(&mut self, kill_on_drop: bool) -> &mut Self { + self.kill_on_drop = kill_on_drop; + self + } + + pub fn spawn(&mut self) -> io::Result { + let current_dir = self + .current_dir + .as_deref() + .unwrap_or_else(|| Path::new(".")); + + // Optimization: if no environment modifications were requested, pass None + // to spawn_posix so it uses the `environ` global directly, avoiding a + // full copy of the environment. This matches std::process::Command behavior. + let envs = if self.env_clear || !self.envs.is_empty() { + let mut result = BTreeMap::::new(); + if !self.env_clear { + for (key, val) in std::env::vars_os() { + result.insert(key, val); + } + } + for (key, maybe_val) in &self.envs { + if let Some(val) = maybe_val { + result.insert(key.clone(), val.clone()); + } else { + result.remove(key); + } + } + Some(result.into_iter().collect::>()) + } else { + None + }; + + spawn_posix_spawn(SpawnOptions { + program: &self.program, + args: &self.args, + current_dir, + envs: envs.as_deref(), + stdin_cfg: self.stdin_cfg.unwrap_or_default(), + stdout_cfg: self.stdout_cfg.unwrap_or_default(), + stderr_cfg: self.stderr_cfg.unwrap_or_default(), + kill_on_drop: self.kill_on_drop, + }) + } + + pub async fn output(&mut self) -> io::Result { + self.stdin_cfg.get_or_insert(Stdio::null()); + self.stdout_cfg.get_or_insert(Stdio::piped()); + self.stderr_cfg.get_or_insert(Stdio::piped()); + + let child = self.spawn()?; + child.output().await + } + + pub async fn status(&mut self) -> io::Result { + let mut child = self.spawn()?; + child.status().await + } + + pub fn get_program(&self) -> &OsStr { + self.program.as_os_str() + } +} + +#[derive(Debug)] +pub struct Child { + pid: libc::pid_t, + pub stdin: Option>, + pub stdout: Option>, + pub stderr: Option>, + kill_on_drop: bool, + status: Option, +} + +impl Drop for Child { + fn drop(&mut self) { + if self.kill_on_drop && self.status.is_none() { + let _ = self.kill(); + } + } +} + +impl Child { + pub fn id(&self) -> u32 { + self.pid as u32 + } + + pub fn kill(&mut self) -> io::Result<()> { + let result = unsafe { libc::kill(self.pid, libc::SIGKILL) }; + if result == -1 { + Err(io::Error::last_os_error()) + } else { + Ok(()) + } + } + + pub fn try_status(&mut self) -> io::Result> { + if let Some(status) = self.status { + return Ok(Some(status)); + } + + let mut status: libc::c_int = 0; + let result = unsafe { libc::waitpid(self.pid, &mut status, libc::WNOHANG) }; + + if result == -1 { + Err(io::Error::last_os_error()) + } else if result == 0 { + Ok(None) + } else { + let exit_status = ExitStatus::from_raw(status); + self.status = Some(exit_status); + Ok(Some(exit_status)) + } + } + + pub fn status( + &mut self, + ) -> impl std::future::Future> + Send + 'static { + self.stdin.take(); + + let pid = self.pid; + let cached_status = self.status; + + async move { + if let Some(status) = cached_status { + return Ok(status); + } + + smol::unblock(move || { + let mut status: libc::c_int = 0; + let result = unsafe { libc::waitpid(pid, &mut status, 0) }; + if result == -1 { + Err(io::Error::last_os_error()) + } else { + Ok(ExitStatus::from_raw(status)) + } + }) + .await + } + } + + pub async fn output(mut self) -> io::Result { + use futures_lite::AsyncReadExt; + + let status = self.status(); + + let stdout = self.stdout.take(); + let stdout_future = async move { + let mut data = Vec::new(); + if let Some(mut stdout) = stdout { + stdout.read_to_end(&mut data).await?; + } + io::Result::Ok(data) + }; + + let stderr = self.stderr.take(); + let stderr_future = async move { + let mut data = Vec::new(); + if let Some(mut stderr) = stderr { + stderr.read_to_end(&mut data).await?; + } + io::Result::Ok(data) + }; + + let (stdout_data, stderr_data) = + futures_lite::future::try_zip(stdout_future, stderr_future).await?; + let status = status.await?; + + Ok(Output { + status, + stdout: stdout_data, + stderr: stderr_data, + }) + } +} + +struct SpawnOptions<'a> { + program: &'a OsStr, + args: &'a [OsString], + current_dir: &'a Path, + envs: Option<&'a [(OsString, OsString)]>, + stdin_cfg: Stdio, + stdout_cfg: Stdio, + stderr_cfg: Stdio, + kill_on_drop: bool, +} + +fn spawn_posix_spawn(options: SpawnOptions<'_>) -> io::Result { + let SpawnOptions { + program, + args, + current_dir, + envs, + stdin_cfg, + stdout_cfg, + stderr_cfg, + kill_on_drop, + } = options; + let program_cstr = CString::new(program.as_bytes()).map_err(|_| invalid_input_error())?; + + let current_dir_cstr = + CString::new(current_dir.as_os_str().as_bytes()).map_err(|_| invalid_input_error())?; + + let mut argv_cstrs = vec![program_cstr.clone()]; + for arg in args { + let cstr = CString::new(arg.as_bytes()).map_err(|_| invalid_input_error())?; + argv_cstrs.push(cstr); + } + let mut argv_ptrs: Vec<*mut libc::c_char> = argv_cstrs + .iter() + .map(|s| s.as_ptr() as *mut libc::c_char) + .collect(); + argv_ptrs.push(ptr::null_mut()); + + let envp: Vec = if let Some(envs) = envs { + envs.iter() + .map(|(key, value)| { + let mut env_str = key.as_bytes().to_vec(); + env_str.push(b'='); + env_str.extend_from_slice(value.as_bytes()); + CString::new(env_str) + }) + .collect::, _>>() + .map_err(|_| invalid_input_error())? + } else { + Vec::new() + }; + let mut envp_ptrs: Vec<*mut libc::c_char> = envp + .iter() + .map(|s| s.as_ptr() as *mut libc::c_char) + .collect(); + envp_ptrs.push(ptr::null_mut()); + + let (stdin_read, stdin_write) = match stdin_cfg { + Stdio::Piped => { + let (r, w) = create_pipe()?; + (Some(r), Some(w)) + } + Stdio::Null => { + let fd = open_dev_null(libc::O_RDONLY)?; + (Some(fd), None) + } + Stdio::Inherit => (None, None), + }; + + let (stdout_read, stdout_write) = match stdout_cfg { + Stdio::Piped => { + let (r, w) = create_pipe()?; + (Some(r), Some(w)) + } + Stdio::Null => { + let fd = open_dev_null(libc::O_WRONLY)?; + (None, Some(fd)) + } + Stdio::Inherit => (None, None), + }; + + let (stderr_read, stderr_write) = match stderr_cfg { + Stdio::Piped => { + let (r, w) = create_pipe()?; + (Some(r), Some(w)) + } + Stdio::Null => { + let fd = open_dev_null(libc::O_WRONLY)?; + (None, Some(fd)) + } + Stdio::Inherit => (None, None), + }; + + let mut attr: libc::posix_spawnattr_t = ptr::null_mut(); + let mut file_actions: libc::posix_spawn_file_actions_t = ptr::null_mut(); + + unsafe { + cvt_nz(libc::posix_spawnattr_init(&mut attr))?; + cvt_nz(libc::posix_spawn_file_actions_init(&mut file_actions))?; + + cvt_nz(libc::posix_spawnattr_setflags( + &mut attr, + libc::POSIX_SPAWN_CLOEXEC_DEFAULT as libc::c_short, + ))?; + + cvt_nz(posix_spawnattr_setexceptionports_np( + &mut attr, + EXC_MASK_ALL, + MACH_PORT_NULL, + EXCEPTION_DEFAULT as exception_behavior_t, + THREAD_STATE_NONE, + ))?; + + cvt_nz(posix_spawn_file_actions_addchdir_np( + &mut file_actions, + current_dir_cstr.as_ptr(), + ))?; + + if let Some(fd) = stdin_read { + cvt_nz(libc::posix_spawn_file_actions_adddup2( + &mut file_actions, + fd, + libc::STDIN_FILENO, + ))?; + cvt_nz(posix_spawn_file_actions_addinherit_np( + &mut file_actions, + libc::STDIN_FILENO, + ))?; + } + + if let Some(fd) = stdout_write { + cvt_nz(libc::posix_spawn_file_actions_adddup2( + &mut file_actions, + fd, + libc::STDOUT_FILENO, + ))?; + cvt_nz(posix_spawn_file_actions_addinherit_np( + &mut file_actions, + libc::STDOUT_FILENO, + ))?; + } + + if let Some(fd) = stderr_write { + cvt_nz(libc::posix_spawn_file_actions_adddup2( + &mut file_actions, + fd, + libc::STDERR_FILENO, + ))?; + cvt_nz(posix_spawn_file_actions_addinherit_np( + &mut file_actions, + libc::STDERR_FILENO, + ))?; + } + + let mut pid: libc::pid_t = 0; + + let spawn_result = libc::posix_spawnp( + &mut pid, + program_cstr.as_ptr(), + &file_actions, + &attr, + argv_ptrs.as_ptr(), + if envs.is_some() { + envp_ptrs.as_ptr() + } else { + environ + }, + ); + + libc::posix_spawnattr_destroy(&mut attr); + libc::posix_spawn_file_actions_destroy(&mut file_actions); + + if let Some(fd) = stdin_read { + libc::close(fd); + } + if let Some(fd) = stdout_write { + libc::close(fd); + } + if let Some(fd) = stderr_write { + libc::close(fd); + } + + cvt_nz(spawn_result)?; + + Ok(Child { + pid, + stdin: stdin_write.map(|fd| Unblock::new(std::fs::File::from_raw_fd(fd))), + stdout: stdout_read.map(|fd| Unblock::new(std::fs::File::from_raw_fd(fd))), + stderr: stderr_read.map(|fd| Unblock::new(std::fs::File::from_raw_fd(fd))), + kill_on_drop, + status: None, + }) + } +} + +fn create_pipe() -> io::Result<(libc::c_int, libc::c_int)> { + let mut fds: [libc::c_int; 2] = [0; 2]; + unsafe { + let result = libc::pipe(fds.as_mut_ptr()); + if result == -1 { + let error = io::Error::last_os_error(); + return Err(error); + } + + // Set close-on-exec on both ends of the pipe. + // + // Without this, unrelated spawns elsewhere in the process (e.g. + // `smol::process` or `async_process`, which on Apple platforms use + // `posix_spawn` *without* `POSIX_SPAWN_CLOEXEC_DEFAULT`) would inherit + // these file descriptors and keep the pipes open even after we drop our + // side. + for &fd in &fds { + let result = libc::ioctl(fd, libc::FIOCLEX); + if result == -1 { + let error = io::Error::last_os_error(); + libc::close(fds[0]); + libc::close(fds[1]); + return Err(error); + } + } + + Ok((fds[0], fds[1])) + } +} + +fn open_dev_null(flags: libc::c_int) -> io::Result { + // Set close-on-exec for this pipe, for the same reason as in `create_pipe`. + let fd = unsafe { + libc::open( + c"/dev/null".as_ptr() as *const libc::c_char, + flags | libc::O_CLOEXEC, + ) + }; + if fd == -1 { + return Err(io::Error::last_os_error()); + } + Ok(fd) +} + +/// Zero means `Ok()`, all other values are treated as raw OS errors. Does not look at `errno`. +/// Mirrored after Rust's std `cvt_nz` function. +fn cvt_nz(error: libc::c_int) -> io::Result<()> { + if error == 0 { + Ok(()) + } else { + Err(io::Error::from_raw_os_error(error)) + } +} + +fn invalid_input_error() -> io::Error { + io::Error::new( + io::ErrorKind::InvalidInput, + "invalid argument: path or argument contains null byte", + ) +} + +#[cfg(test)] +mod tests { + use super::*; + use futures_lite::AsyncWriteExt; + + // Verifies that pipes returned by `create_pipe` aren't visible to unrelated + // child processes spawned via `std::process::Command`. On macOS, `std` + // uses `posix_spawn` without `POSIX_SPAWN_CLOEXEC_DEFAULT`, so any + // non-CLOEXEC fd in the parent leaks into the child. Without + // `FD_CLOEXEC` on our pipe fds, an unrelated spawn (a terminal, the crash + // handler, etc.) running concurrently with a piped git child would hold + // git's stdin write end open and deadlock the git child on `read()`. + #[test] + fn test_create_pipe_not_inherited_by_unrelated_spawn() { + let (read_fd, write_fd) = create_pipe().expect("create_pipe failed"); + + // Probe with the exact fds returned by `create_pipe` (no dup), since + // duping with `F_DUPFD` would lose CLOEXEC and `F_DUPFD_CLOEXEC` would + // unconditionally set it, either of which would defeat the test. + #[allow(clippy::disallowed_methods)] + let output = std::process::Command::new("/bin/sh") + .arg("-c") + .arg(format!( + "for fd in {read_fd} {write_fd}; do \ + if [ -e /dev/fd/$fd ]; then \ + echo $fd WAS INHERITED; \ + else \ + echo $fd WAS NOT INHERITED; \ + fi; \ + done; \ + echo DONE" + )) + .output() + .expect("failed to spawn sh"); + + let stdout = String::from_utf8_lossy(&output.stdout).into_owned(); + + unsafe { + libc::close(read_fd); + libc::close(write_fd); + } + + assert_eq!( + stdout, + format!("{read_fd} WAS NOT INHERITED\n{write_fd} WAS NOT INHERITED\nDONE\n") + ); + } + + #[test] + fn test_spawn_echo() { + smol::block_on(async { + let output = Command::new("/bin/echo") + .args(["-n", "hello world"]) + .output() + .await + .expect("failed to run command"); + + assert!(output.status.success()); + assert_eq!(output.stdout, b"hello world"); + }); + } + + #[test] + fn test_spawn_cat_stdin() { + smol::block_on(async { + let mut child = Command::new("/bin/cat") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .expect("failed to spawn"); + + if let Some(ref mut stdin) = child.stdin { + stdin + .write_all(b"hello from stdin") + .await + .expect("failed to write"); + stdin.close().await.expect("failed to close"); + } + drop(child.stdin.take()); + + let output = child.output().await.expect("failed to get output"); + assert!(output.status.success()); + assert_eq!(output.stdout, b"hello from stdin"); + }); + } + + #[test] + fn test_spawn_stderr() { + smol::block_on(async { + let output = Command::new("/bin/sh") + .args(["-c", "echo error >&2"]) + .output() + .await + .expect("failed to run command"); + + assert!(output.status.success()); + assert_eq!(output.stderr, b"error\n"); + }); + } + + #[test] + fn test_spawn_exit_code() { + smol::block_on(async { + let output = Command::new("/bin/sh") + .args(["-c", "exit 42"]) + .output() + .await + .expect("failed to run command"); + + assert!(!output.status.success()); + assert_eq!(output.status.code(), Some(42)); + }); + } + + #[test] + fn test_spawn_current_dir() { + smol::block_on(async { + let output = Command::new("/bin/pwd") + .current_dir("/tmp") + .output() + .await + .expect("failed to run command"); + + assert!(output.status.success()); + let pwd = String::from_utf8_lossy(&output.stdout); + assert!(pwd.trim() == "/tmp" || pwd.trim() == "/private/tmp"); + }); + } + + #[test] + fn test_spawn_env() { + smol::block_on(async { + let output = Command::new("/bin/sh") + .args(["-c", "echo $MY_TEST_VAR"]) + .env("MY_TEST_VAR", "test_value") + .output() + .await + .expect("failed to run command"); + + assert!(output.status.success()); + assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "test_value"); + }); + } + + #[test] + fn test_spawn_status() { + smol::block_on(async { + let status = Command::new("/usr/bin/true") + .status() + .await + .expect("failed to run command"); + + assert!(status.success()); + + let status = Command::new("/usr/bin/false") + .status() + .await + .expect("failed to run command"); + + assert!(!status.success()); + }); + } + + #[test] + fn test_env_remove_removes_set_env() { + smol::block_on(async { + let output = Command::new("/bin/sh") + .args(["-c", "echo ${MY_VAR:-unset}"]) + .env("MY_VAR", "set_value") + .env_remove("MY_VAR") + .output() + .await + .expect("failed to run command"); + + assert!(output.status.success()); + assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "unset"); + }); + } + + #[test] + fn test_env_remove_removes_inherited_env() { + smol::block_on(async { + // SAFETY: This test is single-threaded and we clean up the var at the end + unsafe { std::env::set_var("TEST_INHERITED_VAR", "inherited_value") }; + + let output = Command::new("/bin/sh") + .args(["-c", "echo ${TEST_INHERITED_VAR:-unset}"]) + .env_remove("TEST_INHERITED_VAR") + .output() + .await + .expect("failed to run command"); + + assert!(output.status.success()); + assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "unset"); + + // SAFETY: Cleaning up test env var + unsafe { std::env::remove_var("TEST_INHERITED_VAR") }; + }); + } + + #[test] + fn test_env_after_env_remove() { + smol::block_on(async { + let output = Command::new("/bin/sh") + .args(["-c", "echo ${MY_VAR:-unset}"]) + .env_remove("MY_VAR") + .env("MY_VAR", "new_value") + .output() + .await + .expect("failed to run command"); + + assert!(output.status.success()); + assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "new_value"); + }); + } + + #[test] + fn test_env_remove_after_env_clear() { + smol::block_on(async { + let output = Command::new("/bin/sh") + .args(["-c", "echo ${MY_VAR:-unset}"]) + .env_clear() + .env("MY_VAR", "set_value") + .env_remove("MY_VAR") + .output() + .await + .expect("failed to run command"); + + assert!(output.status.success()); + assert_eq!(String::from_utf8_lossy(&output.stdout).trim(), "unset"); + }); + } + + #[test] + fn test_stdio_null_stdin() { + smol::block_on(async { + let child = Command::new("/bin/cat") + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .spawn() + .expect("failed to spawn"); + + let output = child.output().await.expect("failed to get output"); + assert!(output.status.success()); + assert!( + output.stdout.is_empty(), + "stdin from /dev/null should produce no output from cat" + ); + }); + } + + #[test] + fn test_stdio_null_stdout() { + smol::block_on(async { + let mut child = Command::new("/bin/echo") + .args(["hello"]) + .stdout(Stdio::null()) + .spawn() + .expect("failed to spawn"); + + assert!( + child.stdout.is_none(), + "stdout should be None when Stdio::null() is used" + ); + + let status = child.status().await.expect("failed to get status"); + assert!(status.success()); + }); + } + + #[test] + fn test_stdio_null_stderr() { + smol::block_on(async { + let mut child = Command::new("/bin/sh") + .args(["-c", "echo error >&2"]) + .stderr(Stdio::null()) + .spawn() + .expect("failed to spawn"); + + assert!( + child.stderr.is_none(), + "stderr should be None when Stdio::null() is used" + ); + + let status = child.status().await.expect("failed to get status"); + assert!(status.success()); + }); + } + + #[test] + fn test_stdio_piped_stdin() { + smol::block_on(async { + let mut child = Command::new("/bin/cat") + .stdin(Stdio::piped()) + .stdout(Stdio::piped()) + .spawn() + .expect("failed to spawn"); + + assert!( + child.stdin.is_some(), + "stdin should be Some when Stdio::piped() is used" + ); + + if let Some(ref mut stdin) = child.stdin { + stdin + .write_all(b"piped input") + .await + .expect("failed to write"); + stdin.close().await.expect("failed to close"); + } + drop(child.stdin.take()); + + let output = child.output().await.expect("failed to get output"); + assert!(output.status.success()); + assert_eq!(output.stdout, b"piped input"); + }); + } +} diff --git a/crates/gpui_zed_util/src/disambiguate.rs b/crates/gpui_zed_util/src/disambiguate.rs new file mode 100644 index 0000000000..8a64af4496 --- /dev/null +++ b/crates/gpui_zed_util/src/disambiguate.rs @@ -0,0 +1,202 @@ +use std::collections::HashMap; +use std::hash::Hash; + +/// Computes the minimum detail level needed for each item so that no two items +/// share the same description. Items whose descriptions are unique at level 0 +/// stay at 0; items that collide get their detail level incremented until either +/// the collision is resolved or increasing the level no longer changes the +/// description (preventing infinite loops for truly identical items). +/// +/// The `get_description` closure must return a sequence that eventually reaches +/// a "fixed point" where increasing `detail` no longer changes the output. If +/// an item reaches its fixed point, it is assumed it will no longer change and +/// will no longer be checked for collisions. +pub fn compute_disambiguation_details( + items: &[T], + get_description: impl Fn(&T, usize) -> D, +) -> Vec +where + D: Eq + Hash + Clone, +{ + let mut details = vec![0usize; items.len()]; + let mut descriptions: HashMap> = HashMap::default(); + let mut current_descriptions: Vec = + items.iter().map(|item| get_description(item, 0)).collect(); + + loop { + let mut any_collisions = false; + + for (index, (item, &detail)) in items.iter().zip(&details).enumerate() { + if detail > 0 { + let new_description = get_description(item, detail); + if new_description == current_descriptions[index] { + continue; + } + current_descriptions[index] = new_description; + } + descriptions + .entry(current_descriptions[index].clone()) + .or_default() + .push(index); + } + + for (_, indices) in descriptions.drain() { + if indices.len() > 1 { + any_collisions = true; + for index in indices { + details[index] += 1; + } + } + } + + if !any_collisions { + break; + } + } + + details +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_no_conflicts() { + let items = vec!["alpha", "beta", "gamma"]; + let details = compute_disambiguation_details(&items, |item, _detail| item.to_string()); + assert_eq!(details, vec![0, 0, 0]); + } + + #[test] + fn test_simple_two_way_conflict() { + // Two items with the same base name but different parents. + let items = vec![("src/foo.rs", "foo.rs"), ("lib/foo.rs", "foo.rs")]; + let details = compute_disambiguation_details(&items, |item, detail| match detail { + 0 => item.1.to_string(), + _ => item.0.to_string(), + }); + assert_eq!(details, vec![1, 1]); + } + + #[test] + fn test_three_way_conflict() { + let items = vec![ + ("foo.rs", "a/foo.rs"), + ("foo.rs", "b/foo.rs"), + ("foo.rs", "c/foo.rs"), + ]; + let details = compute_disambiguation_details(&items, |item, detail| match detail { + 0 => item.0.to_string(), + _ => item.1.to_string(), + }); + assert_eq!(details, vec![1, 1, 1]); + } + + #[test] + fn test_deeper_conflict() { + // At detail 0, all three show "file.rs". + // At detail 1, items 0 and 1 both show "src/file.rs", item 2 shows "lib/file.rs". + // At detail 2, item 0 shows "a/src/file.rs", item 1 shows "b/src/file.rs". + let items = vec![ + vec!["file.rs", "src/file.rs", "a/src/file.rs"], + vec!["file.rs", "src/file.rs", "b/src/file.rs"], + vec!["file.rs", "lib/file.rs", "x/lib/file.rs"], + ]; + let details = compute_disambiguation_details(&items, |item, detail| { + let clamped = detail.min(item.len() - 1); + item[clamped].to_string() + }); + assert_eq!(details, vec![2, 2, 1]); + } + + #[test] + fn test_mixed_conflicting_and_unique() { + let items = vec![ + ("src/foo.rs", "foo.rs"), + ("lib/foo.rs", "foo.rs"), + ("src/bar.rs", "bar.rs"), + ]; + let details = compute_disambiguation_details(&items, |item, detail| match detail { + 0 => item.1.to_string(), + _ => item.0.to_string(), + }); + assert_eq!(details, vec![1, 1, 0]); + } + + #[test] + fn test_identical_items_terminates() { + // All items return the same description at every detail level. + // The algorithm must terminate rather than looping forever. + let items = vec!["same", "same", "same"]; + let details = compute_disambiguation_details(&items, |item, _detail| item.to_string()); + // After bumping to 1, the description doesn't change from level 0, + // so the items are skipped and the loop terminates. + assert_eq!(details, vec![1, 1, 1]); + } + + #[test] + fn test_single_item() { + let items = vec!["only"]; + let details = compute_disambiguation_details(&items, |item, _detail| item.to_string()); + assert_eq!(details, vec![0]); + } + + #[test] + fn test_empty_input() { + let items: Vec<&str> = vec![]; + let details = compute_disambiguation_details(&items, |item, _detail| item.to_string()); + let expected: Vec = vec![]; + assert_eq!(details, expected); + } + + #[test] + fn test_duplicate_paths_from_multiple_groups() { + use std::path::Path; + + // Simulates the sidebar scenario: a path like /Users/rtfeldman/code/zed + // appears in two project groups (e.g. "zed" alone and "zed, roc"). + // After deduplication, only unique paths should be disambiguated. + // + // Paths: + // /Users/rtfeldman/code/worktrees/zed/focal-arrow/zed (group 1) + // /Users/rtfeldman/code/zed (group 2) + // /Users/rtfeldman/code/zed (group 3, same path as group 2) + // /Users/rtfeldman/code/roc (group 3) + // + // A naive flat_map collects duplicates. The duplicate /code/zed entries + // collide with each other and drive the detail to the full path. + // The fix is to deduplicate before disambiguating. + + fn path_suffix(path: &Path, detail: usize) -> String { + let mut components: Vec<_> = path + .components() + .rev() + .filter_map(|c| match c { + std::path::Component::Normal(s) => Some(s.to_string_lossy()), + _ => None, + }) + .take(detail + 1) + .collect(); + components.reverse(); + components.join("/") + } + + let all_paths: Vec<&Path> = vec![ + Path::new("/Users/rtfeldman/code/worktrees/zed/focal-arrow/zed"), + Path::new("/Users/rtfeldman/code/zed"), + Path::new("/Users/rtfeldman/code/roc"), + ]; + + let details = + compute_disambiguation_details(&all_paths, |path, detail| path_suffix(path, detail)); + + // focal-arrow/zed and code/zed both end in "zed", so they need detail 1. + // "roc" is unique at detail 0. + assert_eq!(details, vec![1, 1, 0]); + + assert_eq!(path_suffix(all_paths[0], details[0]), "focal-arrow/zed"); + assert_eq!(path_suffix(all_paths[1], details[1]), "code/zed"); + assert_eq!(path_suffix(all_paths[2], details[2]), "roc"); + } +} diff --git a/crates/gpui_zed_util/src/fs.rs b/crates/gpui_zed_util/src/fs.rs new file mode 100644 index 0000000000..60aab4a2e7 --- /dev/null +++ b/crates/gpui_zed_util/src/fs.rs @@ -0,0 +1,111 @@ +use crate::ResultExt; +use anyhow::{Result, bail}; +use async_fs as fs; +use futures_lite::StreamExt; +use std::path::{Path, PathBuf}; + +/// Removes all files and directories matching the given predicate +pub async fn remove_matching(dir: &Path, predicate: F) +where + F: Fn(&Path) -> bool, +{ + if let Some(mut entries) = fs::read_dir(dir).await.log_err() { + while let Some(entry) = entries.next().await { + if let Some(entry) = entry.log_err() { + let entry_path = entry.path(); + if predicate(entry_path.as_path()) + && let Ok(metadata) = fs::metadata(&entry_path).await + { + if metadata.is_file() { + fs::remove_file(&entry_path).await.log_err(); + } else { + fs::remove_dir_all(&entry_path).await.log_err(); + } + } + } + } + } +} + +pub async fn collect_matching(dir: &Path, predicate: F) -> Vec +where + F: Fn(&Path) -> bool, +{ + let mut matching = vec![]; + + if let Some(mut entries) = fs::read_dir(dir).await.log_err() { + while let Some(entry) = entries.next().await { + if let Some(entry) = entry.log_err() + && predicate(entry.path().as_path()) + { + matching.push(entry.path()); + } + } + } + + matching +} + +pub async fn find_file_name_in_dir(dir: &Path, predicate: F) -> Option +where + F: Fn(&str) -> bool, +{ + if let Some(mut entries) = fs::read_dir(dir).await.log_err() { + while let Some(entry) = entries.next().await { + if let Some(entry) = entry.log_err() { + let entry_path = entry.path(); + + if let Some(file_name) = entry_path + .file_name() + .map(|file_name| file_name.to_string_lossy()) + && predicate(&file_name) + { + return Some(entry_path); + } + } + } + } + + None +} + +pub async fn move_folder_files_to_folder>( + source_path: P, + target_path: P, +) -> Result<()> { + if !target_path.as_ref().is_dir() { + bail!("Folder not found or is not a directory"); + } + + let mut entries = fs::read_dir(source_path.as_ref()).await?; + while let Some(entry) = entries.next().await { + let entry = entry?; + let old_path = entry.path(); + let new_path = target_path.as_ref().join(entry.file_name()); + + fs::rename(&old_path, &new_path).await?; + } + + fs::remove_dir(source_path).await?; + + Ok(()) +} + +#[cfg(unix)] +/// Set the permissions for the given path so that the file becomes executable. +/// This is a noop for non-unix platforms. +pub async fn make_file_executable(path: &Path) -> std::io::Result<()> { + fs::set_permissions( + path, + ::from_mode(0o755), + ) + .await +} + +#[cfg(not(unix))] +#[allow(clippy::unused_async)] +/// Set the permissions for the given path so that the file becomes executable. +/// This is a noop for non-unix platforms. +pub async fn make_file_executable(_path: &Path) -> std::io::Result<()> { + Ok(()) +} diff --git a/crates/gpui_zed_util/src/markdown.rs b/crates/gpui_zed_util/src/markdown.rs new file mode 100644 index 0000000000..e42ce13b59 --- /dev/null +++ b/crates/gpui_zed_util/src/markdown.rs @@ -0,0 +1,376 @@ +use std::fmt::{Display, Formatter}; + +/// Generates a URL-friendly slug from heading text (e.g. "Hello World" → "hello-world"). +pub fn generate_heading_slug(text: &str) -> String { + text.trim() + .chars() + .filter_map(|c| { + if c.is_alphanumeric() || c == '-' || c == '_' { + Some(c.to_lowercase().next().unwrap_or(c)) + } else if c == ' ' { + Some('-') + } else { + None + } + }) + .collect() +} + +/// Returns true if the URL starts with a URI scheme (RFC 3986 §3.1). +fn has_uri_scheme(url: &str) -> bool { + let mut chars = url.chars(); + match chars.next() { + Some(c) if c.is_ascii_alphabetic() => {} + _ => return false, + } + for c in chars { + if c == ':' { + return true; + } + if !(c.is_ascii_alphanumeric() || c == '+' || c == '-' || c == '.') { + return false; + } + } + false +} + +/// Splits a relative URL into its path and `#fragment` parts. +/// Absolute URLs are returned as-is with no fragment. +pub fn split_local_url_fragment(url: &str) -> (&str, Option<&str>) { + if has_uri_scheme(url) { + return (url, None); + } + match url.find('#') { + Some(pos) => { + let path = &url[..pos]; + let fragment = &url[pos + 1..]; + ( + path, + if fragment.is_empty() { + None + } else { + Some(fragment) + }, + ) + } + None => (url, None), + } +} + +/// Indicates that the wrapped `String` is markdown text. +#[derive(Debug, Clone)] +pub struct MarkdownString(pub String); + +impl Display for MarkdownString { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0) + } +} + +/// Escapes markdown special characters in markdown text blocks. Markdown code blocks follow +/// different rules and `MarkdownInlineCode` or `MarkdownCodeBlock` should be used in that case. +/// +/// Also escapes the following markdown extensions: +/// +/// * `^` for superscripts +/// * `$` for inline math +/// * `~` for strikethrough +/// +/// Escape of some characters is unnecessary, because while they are involved in markdown syntax, +/// the other characters involved are escaped: +/// +/// * `!`, `]`, `(`, and `)` are used in link syntax, but `[` is escaped so these are parsed as +/// plaintext. +/// +/// * `;` is used in HTML entity syntax, but `&` is escaped, so they are parsed as plaintext. +/// +/// TODO: There is one escape this doesn't do currently. Period after numbers at the start of the +/// line (`[0-9]*\.`) should also be escaped to avoid it being interpreted as a list item. +pub struct MarkdownEscaped<'a>(pub &'a str); + +/// Implements `Display` to format markdown inline code (wrapped in backticks), handling code that +/// contains backticks and spaces. All whitespace is treated as a single space character. For text +/// that does not contain whitespace other than ' ', this escaping roundtrips through +/// pulldown-cmark. +/// +/// When used in tables, `|` should be escaped like `\|` in the text provided to this function. +pub struct MarkdownInlineCode<'a>(pub &'a str); + +/// Implements `Display` to format markdown code blocks, wrapped in 3 or more backticks as needed. +pub struct MarkdownCodeBlock<'a> { + pub tag: &'a str, + pub text: &'a str, +} + +impl Display for MarkdownEscaped<'_> { + fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result { + let mut start_of_unescaped = None; + for (ix, c) in self.0.char_indices() { + match c { + // Always escaped. + '\\' | '`' | '*' | '_' | '[' | '^' | '$' | '~' | '&' | + // TODO: these only need to be escaped when they are the first non-whitespace + // character of the line of a block. There should probably be both an `escape_block` + // which does this and an `escape_inline` method which does not escape these. + '#' | '+' | '=' | '-' => { + match start_of_unescaped { + None => {} + Some(start_of_unescaped) => { + write!(formatter, "{}", &self.0[start_of_unescaped..ix])?; + } + } + write!(formatter, "\\")?; + // Can include this char in the "unescaped" text since a + // backslash was just emitted. + start_of_unescaped = Some(ix); + } + // Escaped since `<` is used in opening HTML tags. `<` is used since Markdown + // supports HTML entities, and this allows the text to be used directly in HTML. + '<' => { + match start_of_unescaped { + None => {} + Some(start_of_unescaped) => { + write!(formatter, "{}", &self.0[start_of_unescaped..ix])?; + } + } + write!(formatter, "<")?; + start_of_unescaped = None; + } + // Escaped since `>` is used for blockquotes. `>` is used since Markdown supports + // HTML entities, and this allows the text to be used directly in HTML. + '>' => { + match start_of_unescaped { + None => {} + Some(start_of_unescaped) => { + write!(formatter, "{}", &self.0[start_of_unescaped..ix])?; + } + } + write!(formatter, ">")?; + start_of_unescaped = None; + } + _ => { + if start_of_unescaped.is_none() { + start_of_unescaped = Some(ix); + } + } + } + } + if let Some(start_of_unescaped) = start_of_unescaped { + write!(formatter, "{}", &self.0[start_of_unescaped..])?; + } + Ok(()) + } +} + +impl Display for MarkdownInlineCode<'_> { + fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result { + // Apache License 2.0, same as this crate. + // + // Copied from `pulldown-cmark-to-cmark-20.0.0` with modifications: + // + // * Handling of all whitespace. pulldown-cmark-to-cmark is anticipating + // `Code` events parsed by pulldown-cmark. + // + // https://github.com/Byron/pulldown-cmark-to-cmark/blob/3c850de2d3d1d79f19ca5f375e1089a653cf3ff7/src/lib.rs#L290 + + let mut all_whitespace = true; + let text = self + .0 + .chars() + .map(|c| { + if c.is_whitespace() { + ' ' + } else { + all_whitespace = false; + c + } + }) + .collect::(); + + // When inline code has leading and trailing ' ' characters, additional space is needed + // to escape it, unless all characters are space. + if all_whitespace { + write!(formatter, "`{text}`") + } else { + // More backticks are needed to delimit the inline code than the maximum number of + // backticks in a consecutive run. + let backticks = "`".repeat(count_max_consecutive_chars(&text, '`') + 1); + let space = match text.as_bytes() { + &[b'`', ..] | &[.., b'`'] => " ", // Space needed to separate backtick. + &[b' ', .., b' '] => " ", // Space needed to escape inner space. + _ => "", // No space needed. + }; + write!(formatter, "{backticks}{space}{text}{space}{backticks}") + } + } +} + +impl Display for MarkdownCodeBlock<'_> { + fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result { + let tag = self.tag; + let text = self.text; + let backticks = "`".repeat(3.max(count_max_consecutive_chars(text, '`') + 1)); + write!(formatter, "{backticks}{tag}\n{text}\n{backticks}\n") + } +} + +// Copied from `pulldown-cmark-to-cmark-20.0.0` with changed names. +// https://github.com/Byron/pulldown-cmark-to-cmark/blob/3c850de2d3d1d79f19ca5f375e1089a653cf3ff7/src/lib.rs#L1063 +// Apache License 2.0, same as this code. +fn count_max_consecutive_chars(text: &str, search: char) -> usize { + let mut in_search_chars = false; + let mut max_count = 0; + let mut cur_count = 0; + + for ch in text.chars() { + if ch == search { + cur_count += 1; + in_search_chars = true; + } else if in_search_chars { + max_count = max_count.max(cur_count); + cur_count = 0; + in_search_chars = false; + } + } + max_count.max(cur_count) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_markdown_escaped() { + let input = r#" + # Heading + + Another heading + === + + Another heading variant + --- + + Paragraph with [link](https://example.com) and `code`, *emphasis*, and ~strikethrough~. + + ``` + code block + ``` + + List with varying leaders: + - Item 1 + * Item 2 + + Item 3 + + Some math: $`\sqrt{3x-1}+(1+x)^2`$ + + HTML entity:   + "#; + + let expected = r#" + \# Heading + + Another heading + \=\=\= + + Another heading variant + \-\-\- + + Paragraph with \[link](https://example.com) and \`code\`, \*emphasis\*, and \~strikethrough\~. + + \`\`\` + code block + \`\`\` + + List with varying leaders: + \- Item 1 + \* Item 2 + \+ Item 3 + + Some math: \$\`\\sqrt{3x\-1}\+(1\+x)\^2\`\$ + + HTML entity: \  + "#; + + assert_eq!(MarkdownEscaped(input).to_string(), expected); + } + + #[test] + fn test_markdown_inline_code() { + assert_eq!(MarkdownInlineCode(" ").to_string(), "` `"); + assert_eq!(MarkdownInlineCode("text").to_string(), "`text`"); + assert_eq!(MarkdownInlineCode("text ").to_string(), "`text `"); + assert_eq!(MarkdownInlineCode(" text ").to_string(), "` text `"); + assert_eq!(MarkdownInlineCode("`").to_string(), "`` ` ``"); + assert_eq!(MarkdownInlineCode("``").to_string(), "``` `` ```"); + assert_eq!(MarkdownInlineCode("`text`").to_string(), "`` `text` ``"); + assert_eq!( + MarkdownInlineCode("some `text` no leading or trailing backticks").to_string(), + "``some `text` no leading or trailing backticks``" + ); + } + + #[test] + fn test_count_max_consecutive_chars() { + assert_eq!( + count_max_consecutive_chars("``a```b``", '`'), + 3, + "the highest seen consecutive segment of backticks counts" + ); + assert_eq!( + count_max_consecutive_chars("```a``b`", '`'), + 3, + "it can't be downgraded later" + ); + } + + #[test] + fn test_split_local_url_fragment() { + assert_eq!(split_local_url_fragment("#heading"), ("", Some("heading"))); + assert_eq!( + split_local_url_fragment("./file.md#heading"), + ("./file.md", Some("heading")) + ); + assert_eq!(split_local_url_fragment("./file.md"), ("./file.md", None)); + assert_eq!( + split_local_url_fragment("https://example.com#frag"), + ("https://example.com#frag", None) + ); + assert_eq!( + split_local_url_fragment("mailto:user@example.com"), + ("mailto:user@example.com", None) + ); + assert_eq!(split_local_url_fragment("#"), ("", None)); + assert_eq!( + split_local_url_fragment("../other.md#section"), + ("../other.md", Some("section")) + ); + assert_eq!( + split_local_url_fragment("123:not-a-scheme#frag"), + ("123:not-a-scheme", Some("frag")) + ); + } + + #[test] + fn test_generate_heading_slug() { + assert_eq!(generate_heading_slug("Hello World"), "hello-world"); + assert_eq!(generate_heading_slug("Hello World"), "hello--world"); + assert_eq!(generate_heading_slug("Hello-World"), "hello-world"); + assert_eq!( + generate_heading_slug("Some **bold** text"), + "some-bold-text" + ); + assert_eq!(generate_heading_slug("Let's try with Ü"), "lets-try-with-ü"); + assert_eq!( + generate_heading_slug("heading with 123 numbers"), + "heading-with-123-numbers" + ); + assert_eq!( + generate_heading_slug("What about (parens)?"), + "what-about-parens" + ); + assert_eq!( + generate_heading_slug(" leading spaces "), + "leading-spaces" + ); + } +} diff --git a/crates/gpui_zed_util/src/path_list.rs b/crates/gpui_zed_util/src/path_list.rs new file mode 100644 index 0000000000..af99f4c657 --- /dev/null +++ b/crates/gpui_zed_util/src/path_list.rs @@ -0,0 +1,233 @@ +use std::{ + hash::{Hash, Hasher}, + path::{Path, PathBuf}, + sync::Arc, +}; + +use crate::paths::SanitizedPath; +use itertools::Itertools; +use serde::{Deserialize, Serialize}; + +/// A list of absolute paths, with an associated display order. +/// +/// Two `PathList` values are considered equal if they contain the same paths, +/// regardless of the order in which those paths were originally provided. +/// +/// The paths can be retrieved in the original order using `ordered_paths()`. +#[derive(Default, Debug, Clone)] +pub struct PathList { + /// The paths, in lexicographic order. + paths: Arc<[PathBuf]>, + /// The order in which the paths were provided. + /// + /// See `ordered_paths()` for a way to get the paths in the original order. + order: Arc<[usize]>, +} + +impl PartialEq for PathList { + fn eq(&self, other: &Self) -> bool { + self.paths == other.paths + } +} + +impl Eq for PathList {} + +impl Hash for PathList { + fn hash(&self, state: &mut H) { + self.paths.hash(state); + } +} + +#[derive(Debug, Clone, Serialize, Deserialize)] +pub struct SerializedPathList { + pub paths: String, + pub order: String, +} + +impl PathList { + pub fn new>(paths: &[P]) -> Self { + let mut indexed_paths: Vec<(usize, PathBuf)> = paths + .iter() + .enumerate() + .map(|(ix, path)| (ix, SanitizedPath::new(path).into())) + .collect(); + indexed_paths.sort_by(|(_, a), (_, b)| a.cmp(b)); + let order = indexed_paths.iter().map(|e| e.0).collect::>().into(); + let paths = indexed_paths + .into_iter() + .map(|e| e.1) + .collect::>() + .into(); + Self { order, paths } + } + + pub fn is_empty(&self) -> bool { + self.paths.is_empty() + } + + /// Returns a new `PathList` with the given path removed. + pub fn without_path(&self, path_to_remove: &Path) -> PathList { + let paths: Vec = self + .ordered_paths() + .filter(|p| p.as_path() != path_to_remove) + .cloned() + .collect(); + PathList::new(&paths) + } + + /// Get the paths in lexicographic order. + pub fn paths(&self) -> &[PathBuf] { + self.paths.as_ref() + } + + /// Get the paths in the lexicographic order. + pub fn paths_owned(&self) -> Arc<[PathBuf]> { + self.paths.clone() + } + + /// Get the order in which the paths were provided. + pub fn order(&self) -> &[usize] { + self.order.as_ref() + } + + /// Get the paths in the original order. + pub fn ordered_paths(&self) -> impl Iterator { + self.order + .iter() + .zip(self.paths.iter()) + .sorted_by_key(|(i, _)| **i) + .map(|(_, path)| path) + } + + pub fn is_lexicographically_ordered(&self) -> bool { + self.order.iter().enumerate().all(|(i, &j)| i == j) + } + + pub fn deserialize(serialized: &SerializedPathList) -> Self { + let mut paths: Vec = if serialized.paths.is_empty() { + Vec::new() + } else { + serialized.paths.split('\n').map(PathBuf::from).collect() + }; + + let mut order: Vec = serialized + .order + .split(',') + .filter_map(|s| s.parse().ok()) + .collect(); + + if !paths.is_sorted() || order.len() != paths.len() { + order = (0..paths.len()).collect(); + paths.sort(); + } + + Self { + paths: paths.into(), + order: order.into(), + } + } + + pub fn serialize(&self) -> SerializedPathList { + use std::fmt::Write as _; + + let mut paths = String::new(); + for path in self.paths.iter() { + if !paths.is_empty() { + paths.push('\n'); + } + paths.push_str(&path.to_string_lossy()); + } + + let mut order = String::new(); + for ix in self.order.iter() { + if !order.is_empty() { + order.push(','); + } + write!(&mut order, "{}", *ix).unwrap(); + } + SerializedPathList { paths, order } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_path_list() { + let list1 = PathList::new(&["a/d", "a/c"]); + let list2 = PathList::new(&["a/c", "a/d"]); + + assert_eq!(list1.paths(), list2.paths(), "paths differ"); + assert_eq!(list1.order(), &[1, 0], "list1 order incorrect"); + assert_eq!(list2.order(), &[0, 1], "list2 order incorrect"); + + // Same paths in different order are equal (order is display-only). + assert_eq!( + list1, list2, + "same paths with different order should be equal" + ); + + let list1_deserialized = PathList::deserialize(&list1.serialize()); + assert_eq!(list1_deserialized, list1, "list1 deserialization failed"); + + let list2_deserialized = PathList::deserialize(&list2.serialize()); + assert_eq!(list2_deserialized, list2, "list2 deserialization failed"); + + assert_eq!( + list1.ordered_paths().collect_array().unwrap(), + [&PathBuf::from("a/d"), &PathBuf::from("a/c")], + "list1 ordered paths incorrect" + ); + assert_eq!( + list2.ordered_paths().collect_array().unwrap(), + [&PathBuf::from("a/c"), &PathBuf::from("a/d")], + "list2 ordered paths incorrect" + ); + } + + #[test] + fn test_path_list_ordering() { + let list = PathList::new(&["b", "a", "c"]); + assert_eq!( + list.paths(), + &[PathBuf::from("a"), PathBuf::from("b"), PathBuf::from("c")] + ); + assert_eq!(list.order(), &[1, 0, 2]); + assert!(!list.is_lexicographically_ordered()); + + let serialized = list.serialize(); + let deserialized = PathList::deserialize(&serialized); + assert_eq!(deserialized, list); + + assert_eq!( + deserialized.ordered_paths().collect_array().unwrap(), + [ + &PathBuf::from("b"), + &PathBuf::from("a"), + &PathBuf::from("c") + ] + ); + + let list = PathList::new(&["b", "c", "a"]); + assert_eq!( + list.paths(), + &[PathBuf::from("a"), PathBuf::from("b"), PathBuf::from("c")] + ); + assert_eq!(list.order(), &[2, 0, 1]); + assert!(!list.is_lexicographically_ordered()); + + let serialized = list.serialize(); + let deserialized = PathList::deserialize(&serialized); + assert_eq!(deserialized, list); + + assert_eq!( + deserialized.ordered_paths().collect_array().unwrap(), + [ + &PathBuf::from("b"), + &PathBuf::from("c"), + &PathBuf::from("a"), + ] + ); + } +} diff --git a/crates/gpui_zed_util/src/paths.rs b/crates/gpui_zed_util/src/paths.rs new file mode 100644 index 0000000000..47eb4eeca9 --- /dev/null +++ b/crates/gpui_zed_util/src/paths.rs @@ -0,0 +1,3587 @@ +use globset::{GlobBuilder, GlobSet, GlobSetBuilder}; +use itertools::Itertools; +use regex::Regex; +use serde::{Deserialize, Serialize}; +use std::borrow::Cow; +use std::cmp::Ordering; +use std::error::Error; +use std::fmt::{Display, Formatter}; +use std::mem; +use std::path::StripPrefixError; +use std::sync::Arc; +use std::{ + ffi::OsStr, + path::{Path, PathBuf}, + sync::LazyLock, +}; + +use crate::rel_path::RelPath; +use crate::rel_path::RelPathBuf; + +/// Returns the path to the user's home directory. +pub fn home_dir() -> &'static PathBuf { + static HOME_DIR: std::sync::OnceLock = std::sync::OnceLock::new(); + HOME_DIR.get_or_init(|| { + if cfg!(any(test, feature = "test-support")) { + if cfg!(target_os = "macos") { + PathBuf::from("/Users/zed") + } else if cfg!(target_os = "windows") { + PathBuf::from("C:\\Users\\zed") + } else { + PathBuf::from("/home/zed") + } + } else { + dirs::home_dir().expect("failed to determine home directory") + } + }) +} + +pub trait PathExt { + /// Compacts a given file path by replacing the user's home directory + /// prefix with a tilde (`~`). + /// + /// # Returns + /// + /// * A `PathBuf` containing the compacted file path. If the input path + /// does not have the user's home directory prefix, or if we are not on + /// Linux or macOS, the original path is returned unchanged. + fn compact(&self) -> PathBuf; + + /// Returns a file's extension or, if the file is hidden, its name without the leading dot + fn extension_or_hidden_file_name(&self) -> Option<&str>; + + fn try_from_bytes<'a>(bytes: &'a [u8]) -> anyhow::Result + where + Self: From<&'a Path>, + { + #[cfg(target_family = "wasm")] + { + std::str::from_utf8(bytes) + .map(Path::new) + .map(Into::into) + .map_err(Into::into) + } + #[cfg(unix)] + { + use std::os::unix::prelude::OsStrExt; + Ok(Self::from(Path::new(OsStr::from_bytes(bytes)))) + } + #[cfg(windows)] + { + use anyhow::Context; + use tendril::fmt::{Format, WTF8}; + WTF8::validate(bytes) + .then(|| { + // Safety: bytes are valid WTF-8 sequence. + Self::from(Path::new(unsafe { + OsStr::from_encoded_bytes_unchecked(bytes) + })) + }) + .with_context(|| format!("Invalid WTF-8 sequence: {bytes:?}")) + } + } + + /// Converts a local path to one that can be used inside of WSL. + /// Returns `None` if the path cannot be converted into a WSL one (network share). + fn local_to_wsl(&self) -> Option; + + /// Returns a file's "full" joined collection of extensions, in the case where a file does not + /// just have a singular extension but instead has multiple (e.g File.tar.gz, Component.stories.tsx) + /// + /// Will provide back the extensions joined together such as tar.gz or stories.tsx + fn multiple_extensions(&self) -> Option; + + /// Try to make a shell-safe representation of the path. + #[cfg(not(target_family = "wasm"))] + fn try_shell_safe(&self, shell_kind: crate::shell::ShellKind) -> anyhow::Result; +} + +impl> PathExt for T { + fn compact(&self) -> PathBuf { + #[cfg(target_family = "wasm")] + { + self.as_ref().to_path_buf() + } + #[cfg(not(target_family = "wasm"))] + if cfg!(any(target_os = "linux", target_os = "freebsd")) || cfg!(target_os = "macos") { + match self.as_ref().strip_prefix(home_dir().as_path()) { + Ok(relative_path) => { + let mut shortened_path = PathBuf::new(); + shortened_path.push("~"); + shortened_path.push(relative_path); + shortened_path + } + Err(_) => self.as_ref().to_path_buf(), + } + } else { + self.as_ref().to_path_buf() + } + } + + fn extension_or_hidden_file_name(&self) -> Option<&str> { + let path = self.as_ref(); + let file_name = path.file_name()?.to_str()?; + if file_name.starts_with('.') { + return file_name.strip_prefix('.'); + } + + path.extension() + .and_then(|e| e.to_str()) + .or_else(|| path.file_stem()?.to_str()) + } + + fn local_to_wsl(&self) -> Option { + // quite sketchy to convert this back to path at the end, but a lot of functions only accept paths + // todo: ideally rework them..? + let mut new_path = std::ffi::OsString::new(); + for component in self.as_ref().components() { + match component { + std::path::Component::Prefix(prefix) => { + let drive_letter = prefix.as_os_str().to_string_lossy().to_lowercase(); + let drive_letter = drive_letter.strip_suffix(':')?; + + new_path.push(format!("/mnt/{}", drive_letter)); + } + std::path::Component::RootDir => {} + std::path::Component::CurDir => { + new_path.push("/."); + } + std::path::Component::ParentDir => { + new_path.push("/.."); + } + std::path::Component::Normal(os_str) => { + new_path.push("/"); + new_path.push(os_str); + } + } + } + + Some(new_path.into()) + } + + fn multiple_extensions(&self) -> Option { + let path = self.as_ref(); + let file_name = path.file_name()?.to_str()?; + + let parts: Vec<&str> = file_name + .split('.') + // Skip the part with the file name extension + .skip(1) + .collect(); + + if parts.len() < 2 { + return None; + } + + Some(parts.into_iter().join(".")) + } + + #[cfg(not(target_family = "wasm"))] + fn try_shell_safe(&self, shell_kind: crate::shell::ShellKind) -> anyhow::Result { + use anyhow::Context; + let path_str = self + .as_ref() + .to_str() + .with_context(|| "Path contains invalid UTF-8")?; + shell_kind + .try_quote(path_str) + .as_deref() + .map(ToOwned::to_owned) + .context("Failed to quote path") + } +} + +pub fn path_ends_with(base: &Path, suffix: &Path) -> bool { + strip_path_suffix(base, suffix).is_some() +} + +/// Case-insensitive ASCII comparison of a path component to a literal +/// folder name. macOS and Windows use case-insensitive filesystems by +/// default, so a path like `.ZED/settings.json` resolves to the same +/// inode as the lowercase form. A case-sensitive `==` check would miss +/// those and let a malicious settings author bypass classifiers with +/// unusual casing. Callers should restrict `name` to ASCII; for ASCII +/// inputs `eq_ignore_ascii_case` is safe and stable across platforms. +pub fn component_matches_ignore_ascii_case(component: &OsStr, name: &str) -> bool { + component + .to_str() + .is_some_and(|s| s.eq_ignore_ascii_case(name)) +} + +pub fn strip_path_suffix<'a>(base: &'a Path, suffix: &Path) -> Option<&'a Path> { + if let Some(remainder) = base + .as_os_str() + .as_encoded_bytes() + .strip_suffix(suffix.as_os_str().as_encoded_bytes()) + && remainder + .last() + .is_none_or(|last_byte| std::path::is_separator(*last_byte as char)) + { + let os_str = unsafe { + OsStr::from_encoded_bytes_unchecked(&remainder[0..remainder.len().saturating_sub(1)]) + }; + return Some(Path::new(os_str)); + } + None +} + +/// In memory, this is identical to `Path`. On non-Windows conversions to this type are no-ops. On +/// windows, these conversions sanitize UNC paths by removing the `\\\\?\\` prefix. +#[derive(Eq, PartialEq, Hash, Ord, PartialOrd)] +#[repr(transparent)] +pub struct SanitizedPath(Path); + +impl SanitizedPath { + pub fn new + ?Sized>(path: &T) -> &Self { + #[cfg(not(target_os = "windows"))] + return Self::unchecked_new(path.as_ref()); + + #[cfg(target_os = "windows")] + return Self::unchecked_new(dunce::simplified(path.as_ref())); + } + + pub fn unchecked_new + ?Sized>(path: &T) -> &Self { + // safe because `Path` and `SanitizedPath` have the same repr and Drop impl + unsafe { mem::transmute::<&Path, &Self>(path.as_ref()) } + } + + pub fn from_arc(path: Arc) -> Arc { + // safe because `Path` and `SanitizedPath` have the same repr and Drop impl + #[cfg(not(target_os = "windows"))] + return unsafe { mem::transmute::, Arc>(path) }; + + #[cfg(target_os = "windows")] + { + let simplified = dunce::simplified(path.as_ref()); + if simplified == path.as_ref() { + // safe because `Path` and `SanitizedPath` have the same repr and Drop impl + unsafe { mem::transmute::, Arc>(path) } + } else { + Self::unchecked_new(simplified).into() + } + } + } + + pub fn new_arc + ?Sized>(path: &T) -> Arc { + Self::new(path).into() + } + + pub fn cast_arc(path: Arc) -> Arc { + // safe because `Path` and `SanitizedPath` have the same repr and Drop impl + unsafe { mem::transmute::, Arc>(path) } + } + + pub fn cast_arc_ref(path: &Arc) -> &Arc { + // safe because `Path` and `SanitizedPath` have the same repr and Drop impl + unsafe { mem::transmute::<&Arc, &Arc>(path) } + } + + pub fn starts_with(&self, prefix: &Self) -> bool { + self.0.starts_with(&prefix.0) + } + + pub fn as_path(&self) -> &Path { + &self.0 + } + + pub fn file_name(&self) -> Option<&std::ffi::OsStr> { + self.0.file_name() + } + + pub fn extension(&self) -> Option<&std::ffi::OsStr> { + self.0.extension() + } + + pub fn join>(&self, path: P) -> PathBuf { + self.0.join(path) + } + + pub fn parent(&self) -> Option<&Self> { + self.0.parent().map(Self::unchecked_new) + } + + pub fn strip_prefix(&self, base: &Self) -> Result<&Path, StripPrefixError> { + self.0.strip_prefix(base.as_path()) + } + + pub fn to_str(&self) -> Option<&str> { + self.0.to_str() + } + + pub fn to_path_buf(&self) -> PathBuf { + self.0.to_path_buf() + } +} + +impl std::fmt::Debug for SanitizedPath { + fn fmt(&self, formatter: &mut Formatter<'_>) -> std::fmt::Result { + std::fmt::Debug::fmt(&self.0, formatter) + } +} + +impl Display for SanitizedPath { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.0.display()) + } +} + +impl From<&SanitizedPath> for Arc { + fn from(sanitized_path: &SanitizedPath) -> Self { + let path: Arc = sanitized_path.0.into(); + // safe because `Path` and `SanitizedPath` have the same repr and Drop impl + unsafe { mem::transmute(path) } + } +} + +impl From<&SanitizedPath> for PathBuf { + fn from(sanitized_path: &SanitizedPath) -> Self { + sanitized_path.as_path().into() + } +} + +impl AsRef for SanitizedPath { + fn as_ref(&self) -> &Path { + &self.0 + } +} + +#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] +pub enum PathStyle { + Posix, + Windows, +} + +impl PathStyle { + #[cfg(target_os = "windows")] + pub const fn local() -> Self { + PathStyle::Windows + } + + #[cfg(not(target_os = "windows"))] + pub const fn local() -> Self { + PathStyle::Posix + } + + #[inline] + pub fn primary_separator(&self) -> &'static str { + match self { + PathStyle::Posix => "/", + PathStyle::Windows => "\\", + } + } + + pub fn separators(&self) -> &'static [&'static str] { + match self { + PathStyle::Posix => &["/"], + PathStyle::Windows => &["\\", "/"], + } + } + + pub fn separators_ch(&self) -> &'static [char] { + match self { + PathStyle::Posix => &['/'], + PathStyle::Windows => &['\\', '/'], + } + } + + pub fn is_absolute(&self, path_like: &str) -> bool { + path_like.starts_with('/') + || *self == PathStyle::Windows + && (path_like.starts_with('\\') + || path_like + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic()) + && path_like[1..] + .strip_prefix(':') + .is_some_and(|path| path.starts_with('/') || path.starts_with('\\'))) + } + + pub fn is_windows(&self) -> bool { + *self == PathStyle::Windows + } + + pub fn is_posix(&self) -> bool { + *self == PathStyle::Posix + } + + pub fn join(self, left: impl AsRef, right: impl AsRef) -> Option { + let right = right.as_ref().to_str()?; + if is_absolute(right, self) { + return None; + } + let left = left.as_ref().to_str()?; + if left.is_empty() { + Some(right.into()) + } else { + Some(format!( + "{left}{}{right}", + if left.ends_with(self.primary_separator()) { + "" + } else { + self.primary_separator() + } + )) + } + } + + pub fn join_path( + self, + left: impl AsRef, + right: impl AsRef, + ) -> anyhow::Result { + let left = left + .as_ref() + .to_str() + .ok_or_else(|| anyhow::anyhow!("Path contains invalid UTF-8"))?; + let right = right.as_ref(); + let right_string = right + .to_str() + .ok_or_else(|| anyhow::anyhow!("Path contains invalid UTF-8"))?; + let joined = self + .join(left, right_string) + .ok_or_else(|| anyhow::anyhow!("Path must be relative: {right:?}"))?; + Ok(PathBuf::from(self.normalize(&joined))) + } + + pub fn normalize(self, path_like: &str) -> String { + match self { + PathStyle::Windows => crate::normalize_path(Path::new(path_like)) + .to_string_lossy() + .into_owned(), + PathStyle::Posix => { + let is_absolute = path_like.starts_with('/'); + let remainder = if is_absolute { + path_like.trim_start_matches('/') + } else { + path_like + }; + + let mut components = Vec::new(); + for component in remainder.split(self.separators_ch()) { + match component { + "" | "." => {} + ".." => { + if components + .last() + .is_some_and(|component| *component != "..") + { + components.pop(); + } else if !is_absolute { + components.push(component); + } + } + component => components.push(component), + } + } + + let normalized = components.join(self.primary_separator()); + if is_absolute && normalized.is_empty() { + "/".to_string() + } else if is_absolute { + format!("/{normalized}") + } else { + normalized + } + } + } + } + + pub fn split(self, path_like: &str) -> (Option<&str>, &str) { + let Some(pos) = path_like.rfind(self.primary_separator()) else { + return (None, path_like); + }; + let filename_start = pos + self.primary_separator().len(); + ( + Some(&path_like[..filename_start]), + &path_like[filename_start..], + ) + } + + pub fn strip_prefix<'a>( + &self, + child: &'a Path, + parent: &'a Path, + ) -> Option> { + let parent = parent.to_str()?; + if parent.is_empty() { + return RelPath::new(child, *self).ok(); + } + let parent = self + .separators() + .iter() + .find_map(|sep| parent.strip_suffix(sep)) + .unwrap_or(parent); + let child = child.to_str()?; + + // Match behavior of std::path::Path, which is case-insensitive for drive letters (e.g., "C:" == "c:") + let stripped = if self.is_windows() + && child.as_bytes().get(1) == Some(&b':') + && parent.as_bytes().get(1) == Some(&b':') + && child.as_bytes()[0].eq_ignore_ascii_case(&parent.as_bytes()[0]) + { + child[2..].strip_prefix(&parent[2..])? + } else { + child.strip_prefix(parent)? + }; + if let Some(relative) = self + .separators() + .iter() + .find_map(|sep| stripped.strip_prefix(sep)) + { + RelPath::new(relative.as_ref(), *self).ok() + } else if stripped.is_empty() { + Some(Cow::Borrowed(RelPath::empty())) + } else { + None + } + } +} + +#[derive(Debug, Clone)] +pub struct RemotePathBuf { + style: PathStyle, + string: String, +} + +impl RemotePathBuf { + pub fn new(string: String, style: PathStyle) -> Self { + Self { style, string } + } + + pub fn from_str(path: &str, style: PathStyle) -> Self { + Self::new(path.to_string(), style) + } + + pub fn path_style(&self) -> PathStyle { + self.style + } + + pub fn to_proto(&self) -> String { + self.string.clone() + } +} + +impl Display for RemotePathBuf { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!(f, "{}", self.string) + } +} + +pub fn is_absolute(path_like: &str, path_style: PathStyle) -> bool { + path_like.starts_with('/') + || path_style == PathStyle::Windows + && (path_like.starts_with('\\') + || path_like + .chars() + .next() + .is_some_and(|c| c.is_ascii_alphabetic()) + && path_like[1..] + .strip_prefix(':') + .is_some_and(|path| path.starts_with('/') || path.starts_with('\\'))) +} + +#[derive(Debug, PartialEq)] +#[non_exhaustive] +pub struct NormalizeError; + +impl Error for NormalizeError {} + +impl std::fmt::Display for NormalizeError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("parent reference `..` points outside of base directory") + } +} + +/// Copied from stdlib where it's unstable. +/// +/// Normalize a path, including `..` without traversing the filesystem. +/// +/// Returns an error if normalization would leave leading `..` components. +/// +///
+/// +/// This function always resolves `..` to the "lexical" parent. +/// That is "a/b/../c" will always resolve to `a/c` which can change the meaning of the path. +/// In particular, `a/c` and `a/b/../c` are distinct on many systems because `b` may be a symbolic link, so its parent isn't `a`. +/// +///
+/// +/// [`path::absolute`](absolute) is an alternative that preserves `..`. +/// Or [`Path::canonicalize`] can be used to resolve any `..` by querying the filesystem. +pub fn normalize_lexically(path: &Path) -> Result { + use std::path::Component; + + let mut lexical = PathBuf::new(); + let mut iter = path.components().peekable(); + + // Find the root, if any, and add it to the lexical path. + // Here we treat the Windows path "C:\" as a single "root" even though + // `components` splits it into two: (Prefix, RootDir). + let root = match iter.peek() { + Some(Component::ParentDir) => return Err(NormalizeError), + Some(p @ Component::RootDir) | Some(p @ Component::CurDir) => { + lexical.push(p); + iter.next(); + lexical.as_os_str().len() + } + Some(Component::Prefix(prefix)) => { + lexical.push(prefix.as_os_str()); + iter.next(); + if let Some(p @ Component::RootDir) = iter.peek() { + lexical.push(p); + iter.next(); + } + lexical.as_os_str().len() + } + None => return Ok(PathBuf::new()), + Some(Component::Normal(_)) => 0, + }; + + for component in iter { + match component { + Component::RootDir => unreachable!(), + Component::Prefix(_) => return Err(NormalizeError), + Component::CurDir => continue, + Component::ParentDir => { + // It's an error if ParentDir causes us to go above the "root". + if lexical.as_os_str().len() == root { + return Err(NormalizeError); + } else { + lexical.pop(); + } + } + Component::Normal(path) => lexical.push(path), + } + } + Ok(lexical) +} + +/// A delimiter to use in `path_query:row_number:column_number` strings parsing. +pub const FILE_ROW_COLUMN_DELIMITER: char = ':'; + +const ROW_COL_CAPTURE_REGEX: &str = r"(?xs) + ([^\(]+)\:(?: + \((\d+)[,:](\d+)\) # filename:(row,column), filename:(row:column) + | + \((\d+)\)() # filename:(row) + ) + | + ([^\(]+)(?: + \((\d+)[,:](\d+)\) # filename(row,column), filename(row:column) + | + \((\d+)\)() # filename(row) + ) + \:*$ + | + (.+?)(?: + \:+(\d+)\:(\d+)\:*$ # filename:row:column + | + \:+(\d+)\:*()$ # filename:row + | + \:+()()$ + )"; + +/// A representation of a path-like string with optional row and column numbers. +/// Matching values example: `te`, `test.rs:22`, `te:22:5`, `test.c(22)`, `test.c(22,5)`etc. +#[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize, Hash)] +pub struct PathWithPosition { + pub path: PathBuf, + pub row: Option, + // Absent if row is absent. + pub column: Option, +} + +impl PathWithPosition { + /// Returns a PathWithPosition from a path. + pub fn from_path(path: PathBuf) -> Self { + Self { + path, + row: None, + column: None, + } + } + + /// Parses a string that possibly has `:row:column` or `(row, column)` suffix. + /// Parenthesis format is used by [MSBuild](https://learn.microsoft.com/en-us/visualstudio/msbuild/msbuild-diagnostic-format-for-tasks) compatible tools + /// Ignores trailing `:`s, so `test.rs:22:` is parsed as `test.rs:22`. + /// If the suffix parsing fails, the whole string is parsed as a path. + /// + /// Be mindful that `test_file:10:1:` is a valid posix filename. + /// `PathWithPosition` class assumes that the ending position-like suffix is **not** part of the filename. + /// + /// # Examples + /// + /// ``` + /// # use util::paths::PathWithPosition; + /// # use std::path::PathBuf; + /// assert_eq!(PathWithPosition::parse_str("test_file"), PathWithPosition { + /// path: PathBuf::from("test_file"), + /// row: None, + /// column: None, + /// }); + /// assert_eq!(PathWithPosition::parse_str("test_file:10"), PathWithPosition { + /// path: PathBuf::from("test_file"), + /// row: Some(10), + /// column: None, + /// }); + /// assert_eq!(PathWithPosition::parse_str("test_file.rs"), PathWithPosition { + /// path: PathBuf::from("test_file.rs"), + /// row: None, + /// column: None, + /// }); + /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1"), PathWithPosition { + /// path: PathBuf::from("test_file.rs"), + /// row: Some(1), + /// column: None, + /// }); + /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1:2"), PathWithPosition { + /// path: PathBuf::from("test_file.rs"), + /// row: Some(1), + /// column: Some(2), + /// }); + /// ``` + /// + /// # Expected parsing results when encounter ill-formatted inputs. + /// ``` + /// # use util::paths::PathWithPosition; + /// # use std::path::PathBuf; + /// assert_eq!(PathWithPosition::parse_str("test_file.rs:a"), PathWithPosition { + /// path: PathBuf::from("test_file.rs:a"), + /// row: None, + /// column: None, + /// }); + /// assert_eq!(PathWithPosition::parse_str("test_file.rs:a:b"), PathWithPosition { + /// path: PathBuf::from("test_file.rs:a:b"), + /// row: None, + /// column: None, + /// }); + /// assert_eq!(PathWithPosition::parse_str("test_file.rs"), PathWithPosition { + /// path: PathBuf::from("test_file.rs"), + /// row: None, + /// column: None, + /// }); + /// assert_eq!(PathWithPosition::parse_str("test_file.rs::1"), PathWithPosition { + /// path: PathBuf::from("test_file.rs"), + /// row: Some(1), + /// column: None, + /// }); + /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1::"), PathWithPosition { + /// path: PathBuf::from("test_file.rs"), + /// row: Some(1), + /// column: None, + /// }); + /// assert_eq!(PathWithPosition::parse_str("test_file.rs::1:2"), PathWithPosition { + /// path: PathBuf::from("test_file.rs"), + /// row: Some(1), + /// column: Some(2), + /// }); + /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1::2"), PathWithPosition { + /// path: PathBuf::from("test_file.rs:1"), + /// row: Some(2), + /// column: None, + /// }); + /// assert_eq!(PathWithPosition::parse_str("test_file.rs:1:2:3"), PathWithPosition { + /// path: PathBuf::from("test_file.rs:1"), + /// row: Some(2), + /// column: Some(3), + /// }); + /// ``` + pub fn parse_str(s: &str) -> Self { + let trimmed = s.trim(); + let path = Path::new(trimmed); + let Some(maybe_file_name_with_row_col) = path.file_name().unwrap_or_default().to_str() + else { + return Self { + path: Path::new(s).to_path_buf(), + row: None, + column: None, + }; + }; + if maybe_file_name_with_row_col.is_empty() { + return Self { + path: Path::new(s).to_path_buf(), + row: None, + column: None, + }; + } + + // Let's avoid repeated init cost on this. It is subject to thread contention, but + // so far this code isn't called from multiple hot paths. Getting contention here + // in the future seems unlikely. + static SUFFIX_RE: LazyLock = + LazyLock::new(|| Regex::new(ROW_COL_CAPTURE_REGEX).unwrap()); + match SUFFIX_RE + .captures(maybe_file_name_with_row_col) + .map(|caps| caps.extract()) + { + Some((_, [file_name, maybe_row, maybe_column])) => { + let row = maybe_row.parse::().ok(); + let column = maybe_column.parse::().ok(); + + let (_, suffix) = trimmed.split_once(file_name).unwrap(); + let path_without_suffix = &trimmed[..trimmed.len() - suffix.len()]; + + Self { + path: Path::new(path_without_suffix).to_path_buf(), + row, + column, + } + } + None => { + // The `ROW_COL_CAPTURE_REGEX` deals with separated digits only, + // but in reality there could be `foo/bar.py:22:in` inputs which we want to match too. + // The regex mentioned is not very extendable with "digit or random string" checks, so do this here instead. + let delimiter = ':'; + let mut path_parts = s + .rsplitn(3, delimiter) + .collect::>() + .into_iter() + .rev() + .fuse(); + let mut path_string = path_parts.next().expect("rsplitn should have the rest of the string as its last parameter that we reversed").to_owned(); + let mut row = None; + let mut column = None; + if let Some(maybe_row) = path_parts.next() { + if let Ok(parsed_row) = maybe_row.parse::() { + row = Some(parsed_row); + if let Some(parsed_column) = path_parts + .next() + .and_then(|maybe_col| maybe_col.parse::().ok()) + { + column = Some(parsed_column); + } + } else { + path_string.push(delimiter); + path_string.push_str(maybe_row); + } + } + for split in path_parts { + path_string.push(delimiter); + path_string.push_str(split); + } + + Self { + path: PathBuf::from(path_string), + row, + column, + } + } + } + } + + pub fn map_path( + self, + mapping: impl FnOnce(PathBuf) -> Result, + ) -> Result { + Ok(PathWithPosition { + path: mapping(self.path)?, + row: self.row, + column: self.column, + }) + } + + pub fn to_string(&self, path_to_string: &dyn Fn(&PathBuf) -> String) -> String { + let path_string = path_to_string(&self.path); + if let Some(row) = self.row { + if let Some(column) = self.column { + format!("{path_string}:{row}:{column}") + } else { + format!("{path_string}:{row}") + } + } else { + path_string + } + } +} + +#[derive(Clone)] +pub struct PathMatcher { + sources: Vec<(String, RelPathBuf, /*trailing separator*/ bool)>, + glob: GlobSet, + path_style: PathStyle, +} + +impl std::fmt::Debug for PathMatcher { + fn fmt(&self, f: &mut Formatter<'_>) -> std::fmt::Result { + f.debug_struct("PathMatcher") + .field("sources", &self.sources) + .field("path_style", &self.path_style) + .finish() + } +} + +impl PartialEq for PathMatcher { + fn eq(&self, other: &Self) -> bool { + self.sources.eq(&other.sources) + } +} + +impl Eq for PathMatcher {} + +impl PathMatcher { + pub fn new( + globs: impl IntoIterator>, + path_style: PathStyle, + ) -> Result { + let globs = globs + .into_iter() + .map(|as_str| { + GlobBuilder::new(as_str.as_ref()) + .backslash_escape(path_style.is_posix()) + .build() + }) + .collect::, _>>()?; + let sources = globs + .iter() + .filter_map(|glob| { + let glob = glob.glob(); + Some(( + glob.to_string(), + RelPath::new(glob.as_ref(), path_style) + .ok() + .map(std::borrow::Cow::into_owned)?, + glob.ends_with(path_style.separators_ch()), + )) + }) + .collect(); + let mut glob_builder = GlobSetBuilder::new(); + for single_glob in globs { + glob_builder.add(single_glob); + } + let glob = glob_builder.build()?; + Ok(PathMatcher { + glob, + sources, + path_style, + }) + } + + pub fn sources(&self) -> impl Iterator + Clone { + self.sources.iter().map(|(source, ..)| source.as_str()) + } + + pub fn is_match>(&self, other: P) -> bool { + let other = other.as_ref(); + if self + .sources + .iter() + .any(|(_, source, _)| other.starts_with(source) || other.ends_with(source)) + { + return true; + } + let other_path = other.display(self.path_style); + + if self.glob.is_match(&*other_path) { + return true; + } + + self.glob + .is_match(other_path.into_owned() + self.path_style.primary_separator()) + } + + pub fn is_match_std_path>(&self, other: P) -> bool { + let other = other.as_ref(); + if self.sources.iter().any(|(_, source, _)| { + other.starts_with(source.as_std_path()) || other.ends_with(source.as_std_path()) + }) { + return true; + } + self.glob.is_match(other) + } +} + +impl Default for PathMatcher { + fn default() -> Self { + Self { + path_style: PathStyle::local(), + glob: GlobSet::empty(), + sources: vec![], + } + } +} + +/// Compares two sequences of consecutive digits for natural sorting. +/// +/// This function is a core component of natural sorting that handles numeric comparison +/// in a way that feels natural to humans. It extracts and compares consecutive digit +/// sequences from two iterators, handling various cases like leading zeros and very large numbers. +/// +/// # Behavior +/// +/// The function implements the following comparison rules: +/// 1. Different numeric values: Compares by actual numeric value (e.g., "2" < "10") +/// 2. Leading zeros: When values are equal, longer sequence wins (e.g., "002" > "2") +/// 3. Large numbers: Falls back to string comparison for numbers that would overflow u128 +/// +/// # Examples +/// +/// ```text +/// "1" vs "2" -> Less (different values) +/// "2" vs "10" -> Less (numeric comparison) +/// "002" vs "2" -> Greater (leading zeros) +/// "10" vs "010" -> Less (leading zeros) +/// "999..." vs "1000..." -> Less (large number comparison) +/// ``` +/// +/// # Implementation Details +/// +/// 1. Extracts consecutive digits into strings +/// 2. Compares sequence lengths for leading zero handling +/// 3. For equal lengths, compares digit by digit +/// 4. For different lengths: +/// - Attempts numeric comparison first (for numbers up to 2^128 - 1) +/// - Falls back to string comparison if numbers would overflow +/// +/// The function advances both iterators past their respective numeric sequences, +/// regardless of the comparison result. +fn compare_numeric_segments( + a_iter: &mut std::iter::Peekable, + b_iter: &mut std::iter::Peekable, +) -> Ordering +where + I: Iterator, +{ + // Collect all consecutive digits into strings + let mut a_num_str = String::new(); + let mut b_num_str = String::new(); + + while let Some(&c) = a_iter.peek() { + if !c.is_ascii_digit() { + break; + } + + a_num_str.push(c); + a_iter.next(); + } + + while let Some(&c) = b_iter.peek() { + if !c.is_ascii_digit() { + break; + } + + b_num_str.push(c); + b_iter.next(); + } + + // First compare lengths (handle leading zeros) + match a_num_str.len().cmp(&b_num_str.len()) { + Ordering::Equal => { + // Same length, compare digit by digit + match a_num_str.cmp(&b_num_str) { + Ordering::Equal => Ordering::Equal, + ordering => ordering, + } + } + + // Different lengths but same value means leading zeros + ordering => { + // Try parsing as numbers first + if let (Ok(a_val), Ok(b_val)) = (a_num_str.parse::(), b_num_str.parse::()) { + match a_val.cmp(&b_val) { + Ordering::Equal => ordering, // Same value, longer one is greater (leading zeros) + ord => ord, + } + } else { + // If parsing fails (overflow), compare as strings + a_num_str.cmp(&b_num_str) + } + } + } +} + +/// Performs natural sorting comparison between two strings. +/// +/// Natural sorting is an ordering that handles numeric sequences in a way that matches human expectations. +/// For example, "file2" comes before "file10" (unlike standard lexicographic sorting). +/// +/// # Characteristics +/// +/// * Case-sensitive with lowercase priority: When comparing same letters, lowercase comes before uppercase +/// * Numbers are compared by numeric value, not character by character +/// * Leading zeros affect ordering when numeric values are equal +/// * Can handle numbers larger than u128::MAX (falls back to string comparison) +/// * When strings are equal case-insensitively, lowercase is prioritized (lowercase < uppercase) +/// +/// # Algorithm +/// +/// The function works by: +/// 1. Processing strings character by character in a case-insensitive manner +/// 2. When encountering digits, treating consecutive digits as a single number +/// 3. Comparing numbers by their numeric value rather than lexicographically +/// 4. For non-numeric characters, using case-insensitive comparison +/// 5. If everything is equal case-insensitively, using case-sensitive comparison as final tie-breaker +pub fn natural_sort(a: &str, b: &str) -> Ordering { + let mut a_iter = a.chars().peekable(); + let mut b_iter = b.chars().peekable(); + + loop { + match (a_iter.peek(), b_iter.peek()) { + (None, None) => { + return b.cmp(a); + } + (None, _) => return Ordering::Less, + (_, None) => return Ordering::Greater, + (Some(&a_char), Some(&b_char)) => { + if a_char.is_ascii_digit() && b_char.is_ascii_digit() { + match compare_numeric_segments(&mut a_iter, &mut b_iter) { + Ordering::Equal => continue, + ordering => return ordering, + } + } else { + match a_char + .to_ascii_lowercase() + .cmp(&b_char.to_ascii_lowercase()) + { + Ordering::Equal => { + a_iter.next(); + b_iter.next(); + } + ordering => return ordering, + } + } + } + } + } +} + +/// Case-insensitive natural sort without applying the final lowercase/uppercase tie-breaker. +/// This is useful when comparing individual path components where we want to keep walking +/// deeper components before deciding on casing. +fn natural_sort_no_tiebreak(a: &str, b: &str) -> Ordering { + if a.eq_ignore_ascii_case(b) { + Ordering::Equal + } else { + natural_sort(a, b) + } +} + +fn stem_and_extension(filename: &str) -> (Option<&str>, Option<&str>) { + if filename.is_empty() { + return (None, None); + } + + match filename.rsplit_once('.') { + // Case 1: No dot was found. The entire name is the stem. + None => (Some(filename), None), + + // Case 2: A dot was found. + Some((before, after)) => { + // This is the crucial check for dotfiles like ".bashrc". + // If `before` is empty, the dot was the first character. + // In that case, we revert to the "whole name is the stem" logic. + if before.is_empty() { + (Some(filename), None) + } else { + // Otherwise, we have a standard stem and extension. + (Some(before), Some(after)) + } + } + } +} + +/// Controls the lexicographic sorting of file and folder names. +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum SortOrder { + /// Case-insensitive natural sort with lowercase preferred in ties. + /// Numbers in file names are compared by value (e.g., `file2` before `file10`). + #[default] + Default, + /// Uppercase names are grouped before lowercase names, with case-insensitive + /// natural sort within each group. Dot-prefixed names sort before both groups. + Upper, + /// Lowercase names are grouped before uppercase names, with case-insensitive + /// natural sort within each group. Dot-prefixed names sort before both groups. + Lower, + /// Pure Unicode codepoint comparison. No case folding, no natural number sorting. + /// Uppercase ASCII sorts before lowercase. Accented characters sort after ASCII. + Unicode, +} + +/// Controls how files and directories are ordered relative to each other. +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum SortMode { + /// Directories are listed before files at each level. + #[default] + DirectoriesFirst, + /// Files and directories are interleaved alphabetically. + Mixed, + /// Files are listed before directories at each level. + FilesFirst, +} + +fn case_group_key(name: &str, order: SortOrder) -> u8 { + let first = match name.chars().next() { + Some(c) => c, + None => return 0, + }; + match order { + SortOrder::Upper if first.is_lowercase() => 1, + SortOrder::Upper => 0, + SortOrder::Lower if first.is_uppercase() => 1, + SortOrder::Lower => 0, + _ => 0, + } +} + +fn compare_strings(a: &str, b: &str, order: SortOrder) -> Ordering { + match order { + SortOrder::Unicode => a.cmp(b), + _ => natural_sort(a, b), + } +} + +fn compare_strings_no_tiebreak(a: &str, b: &str, order: SortOrder) -> Ordering { + match order { + SortOrder::Unicode => a.cmp(b), + _ => natural_sort_no_tiebreak(a, b), + } +} + +pub fn compare_rel_paths( + (path_a, a_is_file): (&RelPath, bool), + (path_b, b_is_file): (&RelPath, bool), +) -> Ordering { + compare_rel_paths_by( + (path_a, a_is_file), + (path_b, b_is_file), + SortMode::DirectoriesFirst, + SortOrder::Default, + ) +} + +pub fn compare_rel_paths_by( + (path_a, a_is_file): (&RelPath, bool), + (path_b, b_is_file): (&RelPath, bool), + mode: SortMode, + order: SortOrder, +) -> Ordering { + let needs_final_tiebreak = + mode != SortMode::DirectoriesFirst && !(std::ptr::eq(path_a, path_b) || path_a == path_b); + + let mut components_a = path_a.components(); + let mut components_b = path_b.components(); + + loop { + match (components_a.next(), components_b.next()) { + (Some(component_a), Some(component_b)) => { + let a_leaf_file = a_is_file && components_a.rest().is_empty(); + let b_leaf_file = b_is_file && components_b.rest().is_empty(); + + let file_dir_ordering = match mode { + SortMode::DirectoriesFirst => a_leaf_file.cmp(&b_leaf_file), + SortMode::FilesFirst => b_leaf_file.cmp(&a_leaf_file), + SortMode::Mixed => Ordering::Equal, + }; + + if !file_dir_ordering.is_eq() { + return file_dir_ordering; + } + + let (a_stem, a_ext) = if a_leaf_file { + stem_and_extension(component_a) + } else { + Default::default() + }; + let (b_stem, b_ext) = if b_leaf_file { + stem_and_extension(component_b) + } else { + Default::default() + }; + let a_key = if a_leaf_file { + a_stem + } else { + Some(component_a) + }; + let b_key = if b_leaf_file { + b_stem + } else { + Some(component_b) + }; + + let ordering = match (a_key, b_key) { + (Some(a), Some(b)) => { + let name_cmp = case_group_key(a, order) + .cmp(&case_group_key(b, order)) + .then_with(|| match mode { + SortMode::DirectoriesFirst => compare_strings(a, b, order), + _ => compare_strings_no_tiebreak(a, b, order), + }); + + let name_cmp = if mode == SortMode::Mixed { + name_cmp.then_with(|| match (a_leaf_file, b_leaf_file) { + (true, false) if a.eq_ignore_ascii_case(b) => Ordering::Greater, + (false, true) if a.eq_ignore_ascii_case(b) => Ordering::Less, + _ => Ordering::Equal, + }) + } else { + name_cmp + }; + + name_cmp.then_with(|| { + if a_leaf_file && b_leaf_file { + match order { + SortOrder::Unicode => { + a_ext.unwrap_or_default().cmp(b_ext.unwrap_or_default()) + } + _ => { + let a_ext_str = a_ext.unwrap_or_default().to_lowercase(); + let b_ext_str = b_ext.unwrap_or_default().to_lowercase(); + a_ext_str.cmp(&b_ext_str) + } + } + } else { + Ordering::Equal + } + }) + } + (Some(_), None) => Ordering::Greater, + (None, Some(_)) => Ordering::Less, + (None, None) => Ordering::Equal, + }; + + if !ordering.is_eq() { + return ordering; + } + } + (Some(_), None) => return Ordering::Greater, + (None, Some(_)) => return Ordering::Less, + (None, None) => { + if needs_final_tiebreak { + return compare_strings(path_a.as_unix_str(), path_b.as_unix_str(), order); + } + return Ordering::Equal; + } + } + } +} + +pub fn compare_paths( + (path_a, a_is_file): (&Path, bool), + (path_b, b_is_file): (&Path, bool), +) -> Ordering { + let mut components_a = path_a.components().peekable(); + let mut components_b = path_b.components().peekable(); + + loop { + match (components_a.next(), components_b.next()) { + (Some(component_a), Some(component_b)) => { + let a_is_file = components_a.peek().is_none() && a_is_file; + let b_is_file = components_b.peek().is_none() && b_is_file; + + let ordering = a_is_file.cmp(&b_is_file).then_with(|| { + let path_a = Path::new(component_a.as_os_str()); + let path_string_a = if a_is_file { + path_a.file_stem() + } else { + path_a.file_name() + } + .map(|s| s.to_string_lossy()); + + let path_b = Path::new(component_b.as_os_str()); + let path_string_b = if b_is_file { + path_b.file_stem() + } else { + path_b.file_name() + } + .map(|s| s.to_string_lossy()); + + let compare_components = match (path_string_a, path_string_b) { + (Some(a), Some(b)) => natural_sort(&a, &b), + (Some(_), None) => Ordering::Greater, + (None, Some(_)) => Ordering::Less, + (None, None) => Ordering::Equal, + }; + + compare_components.then_with(|| { + if a_is_file && b_is_file { + let ext_a = path_a.extension().unwrap_or_default(); + let ext_b = path_b.extension().unwrap_or_default(); + ext_a.cmp(ext_b) + } else { + Ordering::Equal + } + }) + }); + + if !ordering.is_eq() { + return ordering; + } + } + (Some(_), None) => break Ordering::Greater, + (None, Some(_)) => break Ordering::Less, + (None, None) => break Ordering::Equal, + } + } +} + +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct WslPath { + pub distro: String, + + // the reason this is an OsString and not any of the path types is that it needs to + // represent a unix path (with '/' separators) on windows. `from_path` does this by + // manually constructing it from the path components of a given windows path. + pub path: std::ffi::OsString, +} + +impl WslPath { + pub fn from_path>(path: P) -> Option { + if cfg!(not(target_os = "windows")) { + return None; + } + use std::{ + ffi::OsString, + path::{Component, Prefix}, + }; + + let mut components = path.as_ref().components(); + let Some(Component::Prefix(prefix)) = components.next() else { + return None; + }; + let (server, distro) = match prefix.kind() { + Prefix::UNC(server, distro) => (server, distro), + Prefix::VerbatimUNC(server, distro) => (server, distro), + _ => return None, + }; + let Some(Component::RootDir) = components.next() else { + return None; + }; + + let server_str = server.to_string_lossy(); + if server_str == "wsl.localhost" || server_str == "wsl$" { + let mut result = OsString::from(""); + for c in components { + use Component::*; + match c { + Prefix(p) => unreachable!("got {p:?}, but already stripped prefix"), + RootDir => unreachable!("got root dir, but already stripped root"), + CurDir => continue, + ParentDir => result.push("/.."), + Normal(s) => { + result.push("/"); + result.push(s); + } + } + } + if result.is_empty() { + result.push("/"); + } + Some(WslPath { + distro: distro.to_string_lossy().to_string(), + path: result, + }) + } else { + None + } + } +} + +/// Error returned when a [`url::Url`] cannot be converted into a [`PathBuf`] +/// via [`UrlExt::to_file_path_ext`]. +#[derive(Debug, Clone, Copy, PartialEq, Eq)] +pub struct ToFilePathError; + +impl std::fmt::Display for ToFilePathError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("failed to convert URL to file path") + } +} + +impl std::error::Error for ToFilePathError {} + +pub trait UrlExt { + /// A version of `url::Url::to_file_path` that does platform handling based on the provided `PathStyle` instead of the host platform. + /// + /// Prefer using this over `url::Url::to_file_path` when you need to handle paths in a cross-platform way as is the case for remoting interactions. + fn to_file_path_ext(&self, path_style: PathStyle) -> Result; +} + +impl UrlExt for url::Url { + // Copied from `url::Url::to_file_path`, but the `cfg` handling is replaced with runtime branching on `PathStyle` + fn to_file_path_ext(&self, source_path_style: PathStyle) -> Result { + if let Some(segments) = self.path_segments() { + let host = match self.host() { + None | Some(url::Host::Domain("localhost")) => None, + Some(_) if source_path_style.is_windows() && self.scheme() == "file" => { + self.host_str() + } + _ => return Err(ToFilePathError), + }; + + let str_len = self.as_str().len(); + let estimated_capacity = if source_path_style.is_windows() { + // remove scheme: - has possible \\ for hostname + str_len.saturating_sub(self.scheme().len() + 1) + } else { + // remove scheme:// + str_len.saturating_sub(self.scheme().len() + 3) + }; + return match source_path_style { + PathStyle::Posix => { + file_url_segments_to_pathbuf_posix(estimated_capacity, host, segments) + } + PathStyle::Windows => { + file_url_segments_to_pathbuf_windows(estimated_capacity, host, segments) + } + }; + } + + fn file_url_segments_to_pathbuf_posix( + estimated_capacity: usize, + host: Option<&str>, + segments: std::str::Split<'_, char>, + ) -> Result { + use percent_encoding::percent_decode; + + if host.is_some() { + return Err(ToFilePathError); + } + + let mut bytes = Vec::new(); + bytes + .try_reserve(estimated_capacity) + .map_err(|_| ToFilePathError)?; + + for segment in segments { + bytes.push(b'/'); + bytes.extend(percent_decode(segment.as_bytes())); + } + + // A windows drive letter must end with a slash. + if bytes.len() > 2 + && bytes[bytes.len() - 2].is_ascii_alphabetic() + && matches!(bytes[bytes.len() - 1], b':' | b'|') + { + bytes.push(b'/'); + } + + let path = String::from_utf8(bytes).map_err(|_| ToFilePathError)?; + debug_assert!( + PathStyle::Posix.is_absolute(&path), + "to_file_path() failed to produce an absolute Path" + ); + + Ok(PathBuf::from(path)) + } + + fn file_url_segments_to_pathbuf_windows( + estimated_capacity: usize, + host: Option<&str>, + mut segments: std::str::Split<'_, char>, + ) -> Result { + use percent_encoding::percent_decode_str; + let mut string = String::new(); + string + .try_reserve(estimated_capacity) + .map_err(|_| ToFilePathError)?; + if let Some(host) = host { + string.push_str(r"\\"); + string.push_str(host); + } else { + let first = segments.next().ok_or(ToFilePathError)?; + + match first.len() { + 2 => { + if !first.starts_with(|c| char::is_ascii_alphabetic(&c)) + || first.as_bytes()[1] != b':' + { + return Err(ToFilePathError); + } + + string.push_str(first); + } + + 4 => { + if !first.starts_with(|c| char::is_ascii_alphabetic(&c)) { + return Err(ToFilePathError); + } + let bytes = first.as_bytes(); + if bytes[1] != b'%' + || bytes[2] != b'3' + || (bytes[3] != b'a' && bytes[3] != b'A') + { + return Err(ToFilePathError); + } + + string.push_str(&first[0..1]); + string.push(':'); + } + + _ => return Err(ToFilePathError), + } + }; + + for segment in segments { + string.push('\\'); + + // Currently non-unicode windows paths cannot be represented + match percent_decode_str(segment).decode_utf8() { + Ok(s) => string.push_str(&s), + Err(..) => return Err(ToFilePathError), + } + } + // ensure our estimated capacity was good + if cfg!(test) { + debug_assert!( + string.len() <= estimated_capacity, + "len: {}, capacity: {}", + string.len(), + estimated_capacity + ); + } + debug_assert!( + PathStyle::Windows.is_absolute(&string), + "to_file_path() failed to produce an absolute Path" + ); + let path = PathBuf::from(string); + Ok(path) + } + Err(ToFilePathError) + } +} + +#[cfg(test)] +mod tests { + use crate::rel_path::rel_path; + + use super::*; + // perf annotations replaced with #[test] + + #[test] + fn test_join_path_uses_path_style_separator() { + let posix_path = PathStyle::Posix + .join_path(Path::new("/home/user/dev"), "worktrees") + .unwrap(); + let windows_path = PathStyle::Windows + .join_path(Path::new("C:\\Users\\user\\dev"), "worktrees") + .unwrap(); + + assert_eq!(posix_path, PathBuf::from("/home/user/dev/worktrees")); + assert_eq!( + windows_path.to_string_lossy(), + "C:\\Users\\user\\dev\\worktrees" + ); + } + + #[test] + fn test_normalize_uses_path_style_separator() { + assert_eq!( + PathStyle::Posix.normalize("/home/user/dev/../worktrees/./zed"), + "/home/user/worktrees/zed" + ); + assert_eq!( + PathStyle::Windows.normalize("C:\\Users\\user\\dev\\worktrees"), + "C:\\Users\\user\\dev\\worktrees" + ); + } + + fn rel_path_entry(path: &'static str, is_file: bool) -> (&'static RelPath, bool) { + (RelPath::unix(path).unwrap(), is_file) + } + + fn sorted_rel_paths( + mut paths: Vec<(&'static RelPath, bool)>, + mode: SortMode, + order: SortOrder, + ) -> Vec<(&'static RelPath, bool)> { + paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, mode, order)); + paths + } + + #[test] + fn compare_paths_with_dots() { + let mut paths = vec![ + (Path::new("test_dirs"), false), + (Path::new("test_dirs/1.46"), false), + (Path::new("test_dirs/1.46/bar_1"), true), + (Path::new("test_dirs/1.46/bar_2"), true), + (Path::new("test_dirs/1.45"), false), + (Path::new("test_dirs/1.45/foo_2"), true), + (Path::new("test_dirs/1.45/foo_1"), true), + ]; + paths.sort_by(|&a, &b| compare_paths(a, b)); + assert_eq!( + paths, + vec![ + (Path::new("test_dirs"), false), + (Path::new("test_dirs/1.45"), false), + (Path::new("test_dirs/1.45/foo_1"), true), + (Path::new("test_dirs/1.45/foo_2"), true), + (Path::new("test_dirs/1.46"), false), + (Path::new("test_dirs/1.46/bar_1"), true), + (Path::new("test_dirs/1.46/bar_2"), true), + ] + ); + let mut paths = vec![ + (Path::new("root1/one.txt"), true), + (Path::new("root1/one.two.txt"), true), + ]; + paths.sort_by(|&a, &b| compare_paths(a, b)); + assert_eq!( + paths, + vec![ + (Path::new("root1/one.txt"), true), + (Path::new("root1/one.two.txt"), true), + ] + ); + } + + #[test] + fn compare_paths_with_same_name_different_extensions() { + let mut paths = vec![ + (Path::new("test_dirs/file.rs"), true), + (Path::new("test_dirs/file.txt"), true), + (Path::new("test_dirs/file.md"), true), + (Path::new("test_dirs/file"), true), + (Path::new("test_dirs/file.a"), true), + ]; + paths.sort_by(|&a, &b| compare_paths(a, b)); + assert_eq!( + paths, + vec![ + (Path::new("test_dirs/file"), true), + (Path::new("test_dirs/file.a"), true), + (Path::new("test_dirs/file.md"), true), + (Path::new("test_dirs/file.rs"), true), + (Path::new("test_dirs/file.txt"), true), + ] + ); + } + + #[test] + fn compare_paths_case_semi_sensitive() { + let mut paths = vec![ + (Path::new("test_DIRS"), false), + (Path::new("test_DIRS/foo_1"), true), + (Path::new("test_DIRS/foo_2"), true), + (Path::new("test_DIRS/bar"), true), + (Path::new("test_DIRS/BAR"), true), + (Path::new("test_dirs"), false), + (Path::new("test_dirs/foo_1"), true), + (Path::new("test_dirs/foo_2"), true), + (Path::new("test_dirs/bar"), true), + (Path::new("test_dirs/BAR"), true), + ]; + paths.sort_by(|&a, &b| compare_paths(a, b)); + assert_eq!( + paths, + vec![ + (Path::new("test_dirs"), false), + (Path::new("test_dirs/bar"), true), + (Path::new("test_dirs/BAR"), true), + (Path::new("test_dirs/foo_1"), true), + (Path::new("test_dirs/foo_2"), true), + (Path::new("test_DIRS"), false), + (Path::new("test_DIRS/bar"), true), + (Path::new("test_DIRS/BAR"), true), + (Path::new("test_DIRS/foo_1"), true), + (Path::new("test_DIRS/foo_2"), true), + ] + ); + } + + #[test] + fn compare_paths_mixed_case_numeric_ordering() { + let mut entries = [ + (Path::new(".config"), false), + (Path::new("Dir1"), false), + (Path::new("dir01"), false), + (Path::new("dir2"), false), + (Path::new("Dir02"), false), + (Path::new("dir10"), false), + (Path::new("Dir10"), false), + ]; + + entries.sort_by(|&a, &b| compare_paths(a, b)); + + let ordered: Vec<&str> = entries + .iter() + .map(|(path, _)| path.to_str().unwrap()) + .collect(); + + assert_eq!( + ordered, + vec![ + ".config", "Dir1", "dir01", "dir2", "Dir02", "dir10", "Dir10" + ] + ); + } + + #[test] + fn compare_rel_paths_mixed_case_insensitive() { + // Test that mixed mode is case-insensitive + let mut paths = vec![ + (RelPath::unix("zebra.txt").unwrap(), true), + (RelPath::unix("Apple").unwrap(), false), + (RelPath::unix("banana.rs").unwrap(), true), + (RelPath::unix("Carrot").unwrap(), false), + (RelPath::unix("aardvark.txt").unwrap(), true), + ]; + paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default)); + // Case-insensitive: aardvark < Apple < banana < Carrot < zebra + assert_eq!( + paths, + vec![ + (RelPath::unix("aardvark.txt").unwrap(), true), + (RelPath::unix("Apple").unwrap(), false), + (RelPath::unix("banana.rs").unwrap(), true), + (RelPath::unix("Carrot").unwrap(), false), + (RelPath::unix("zebra.txt").unwrap(), true), + ] + ); + } + + #[test] + fn compare_rel_paths_files_first_basic() { + // Test that files come before directories + let mut paths = vec![ + (RelPath::unix("zebra.txt").unwrap(), true), + (RelPath::unix("Apple").unwrap(), false), + (RelPath::unix("banana.rs").unwrap(), true), + (RelPath::unix("Carrot").unwrap(), false), + (RelPath::unix("aardvark.txt").unwrap(), true), + ]; + paths + .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default)); + // Files first (case-insensitive), then directories (case-insensitive) + assert_eq!( + paths, + vec![ + (RelPath::unix("aardvark.txt").unwrap(), true), + (RelPath::unix("banana.rs").unwrap(), true), + (RelPath::unix("zebra.txt").unwrap(), true), + (RelPath::unix("Apple").unwrap(), false), + (RelPath::unix("Carrot").unwrap(), false), + ] + ); + } + + #[test] + fn compare_rel_paths_files_first_case_insensitive() { + // Test case-insensitive sorting within files and directories + let mut paths = vec![ + (RelPath::unix("Zebra.txt").unwrap(), true), + (RelPath::unix("apple").unwrap(), false), + (RelPath::unix("Banana.rs").unwrap(), true), + (RelPath::unix("carrot").unwrap(), false), + (RelPath::unix("Aardvark.txt").unwrap(), true), + ]; + paths + .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default)); + assert_eq!( + paths, + vec![ + (RelPath::unix("Aardvark.txt").unwrap(), true), + (RelPath::unix("Banana.rs").unwrap(), true), + (RelPath::unix("Zebra.txt").unwrap(), true), + (RelPath::unix("apple").unwrap(), false), + (RelPath::unix("carrot").unwrap(), false), + ] + ); + } + + #[test] + fn compare_rel_paths_files_first_numeric() { + // Test natural number sorting with files first + let mut paths = vec![ + (RelPath::unix("file10.txt").unwrap(), true), + (RelPath::unix("dir2").unwrap(), false), + (RelPath::unix("file2.txt").unwrap(), true), + (RelPath::unix("dir10").unwrap(), false), + (RelPath::unix("file1.txt").unwrap(), true), + ]; + paths + .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default)); + assert_eq!( + paths, + vec![ + (RelPath::unix("file1.txt").unwrap(), true), + (RelPath::unix("file2.txt").unwrap(), true), + (RelPath::unix("file10.txt").unwrap(), true), + (RelPath::unix("dir2").unwrap(), false), + (RelPath::unix("dir10").unwrap(), false), + ] + ); + } + + #[test] + fn compare_rel_paths_mixed_case() { + // Test case-insensitive sorting with varied capitalization + let mut paths = vec![ + (RelPath::unix("README.md").unwrap(), true), + (RelPath::unix("readme.txt").unwrap(), true), + (RelPath::unix("ReadMe.rs").unwrap(), true), + ]; + paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default)); + // All "readme" variants should group together, sorted by extension + assert_eq!( + paths, + vec![ + (RelPath::unix("README.md").unwrap(), true), + (RelPath::unix("ReadMe.rs").unwrap(), true), + (RelPath::unix("readme.txt").unwrap(), true), + ] + ); + } + + #[test] + fn compare_rel_paths_mixed_files_and_dirs() { + // Verify directories and files are still mixed + let mut paths = vec![ + (RelPath::unix("file2.txt").unwrap(), true), + (RelPath::unix("Dir1").unwrap(), false), + (RelPath::unix("file1.txt").unwrap(), true), + (RelPath::unix("dir2").unwrap(), false), + ]; + paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default)); + // Case-insensitive: dir1, dir2, file1, file2 (all mixed) + assert_eq!( + paths, + vec![ + (RelPath::unix("Dir1").unwrap(), false), + (RelPath::unix("dir2").unwrap(), false), + (RelPath::unix("file1.txt").unwrap(), true), + (RelPath::unix("file2.txt").unwrap(), true), + ] + ); + } + + #[test] + fn compare_rel_paths_mixed_same_name_different_case_file_and_dir() { + let mut paths = vec![ + (RelPath::unix("Hello.txt").unwrap(), true), + (RelPath::unix("hello").unwrap(), false), + ]; + paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default)); + assert_eq!( + paths, + vec![ + (RelPath::unix("hello").unwrap(), false), + (RelPath::unix("Hello.txt").unwrap(), true), + ] + ); + + let mut paths = vec![ + (RelPath::unix("hello").unwrap(), false), + (RelPath::unix("Hello.txt").unwrap(), true), + ]; + paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default)); + assert_eq!( + paths, + vec![ + (RelPath::unix("hello").unwrap(), false), + (RelPath::unix("Hello.txt").unwrap(), true), + ] + ); + } + + #[test] + fn compare_rel_paths_mixed_with_nested_paths() { + // Test that nested paths still work correctly + let mut paths = vec![ + (RelPath::unix("src/main.rs").unwrap(), true), + (RelPath::unix("Cargo.toml").unwrap(), true), + (RelPath::unix("src").unwrap(), false), + (RelPath::unix("target").unwrap(), false), + ]; + paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default)); + assert_eq!( + paths, + vec![ + (RelPath::unix("Cargo.toml").unwrap(), true), + (RelPath::unix("src").unwrap(), false), + (RelPath::unix("src/main.rs").unwrap(), true), + (RelPath::unix("target").unwrap(), false), + ] + ); + } + + #[test] + fn compare_rel_paths_files_first_with_nested() { + // Files come before directories, even with nested paths + let mut paths = vec![ + (RelPath::unix("src/lib.rs").unwrap(), true), + (RelPath::unix("README.md").unwrap(), true), + (RelPath::unix("src").unwrap(), false), + (RelPath::unix("tests").unwrap(), false), + ]; + paths + .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default)); + assert_eq!( + paths, + vec![ + (RelPath::unix("README.md").unwrap(), true), + (RelPath::unix("src").unwrap(), false), + (RelPath::unix("src/lib.rs").unwrap(), true), + (RelPath::unix("tests").unwrap(), false), + ] + ); + } + + #[test] + fn compare_rel_paths_mixed_dotfiles() { + // Test that dotfiles are handled correctly in mixed mode + let mut paths = vec![ + (RelPath::unix(".gitignore").unwrap(), true), + (RelPath::unix("README.md").unwrap(), true), + (RelPath::unix(".github").unwrap(), false), + (RelPath::unix("src").unwrap(), false), + ]; + paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default)); + assert_eq!( + paths, + vec![ + (RelPath::unix(".github").unwrap(), false), + (RelPath::unix(".gitignore").unwrap(), true), + (RelPath::unix("README.md").unwrap(), true), + (RelPath::unix("src").unwrap(), false), + ] + ); + } + + #[test] + fn compare_rel_paths_files_first_dotfiles() { + // Test that dotfiles come first when they're files + let mut paths = vec![ + (RelPath::unix(".gitignore").unwrap(), true), + (RelPath::unix("README.md").unwrap(), true), + (RelPath::unix(".github").unwrap(), false), + (RelPath::unix("src").unwrap(), false), + ]; + paths + .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default)); + assert_eq!( + paths, + vec![ + (RelPath::unix(".gitignore").unwrap(), true), + (RelPath::unix("README.md").unwrap(), true), + (RelPath::unix(".github").unwrap(), false), + (RelPath::unix("src").unwrap(), false), + ] + ); + } + + #[test] + fn compare_rel_paths_mixed_same_stem_different_extension() { + // Files with same stem but different extensions should sort by extension + let mut paths = vec![ + (RelPath::unix("file.rs").unwrap(), true), + (RelPath::unix("file.md").unwrap(), true), + (RelPath::unix("file.txt").unwrap(), true), + ]; + paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default)); + assert_eq!( + paths, + vec![ + (RelPath::unix("file.md").unwrap(), true), + (RelPath::unix("file.rs").unwrap(), true), + (RelPath::unix("file.txt").unwrap(), true), + ] + ); + } + + #[test] + fn compare_rel_paths_files_first_same_stem() { + // Same stem files should still sort by extension with files_first + let mut paths = vec![ + (RelPath::unix("main.rs").unwrap(), true), + (RelPath::unix("main.c").unwrap(), true), + (RelPath::unix("main").unwrap(), false), + ]; + paths + .sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::FilesFirst, SortOrder::Default)); + assert_eq!( + paths, + vec![ + (RelPath::unix("main.c").unwrap(), true), + (RelPath::unix("main.rs").unwrap(), true), + (RelPath::unix("main").unwrap(), false), + ] + ); + } + + #[test] + fn compare_rel_paths_mixed_deep_nesting() { + // Test sorting with deeply nested paths + let mut paths = vec![ + (RelPath::unix("a/b/c.txt").unwrap(), true), + (RelPath::unix("A/B.txt").unwrap(), true), + (RelPath::unix("a.txt").unwrap(), true), + (RelPath::unix("A.txt").unwrap(), true), + ]; + paths.sort_by(|&a, &b| compare_rel_paths_by(a, b, SortMode::Mixed, SortOrder::Default)); + assert_eq!( + paths, + vec![ + (RelPath::unix("a/b/c.txt").unwrap(), true), + (RelPath::unix("A/B.txt").unwrap(), true), + (RelPath::unix("a.txt").unwrap(), true), + (RelPath::unix("A.txt").unwrap(), true), + ] + ); + } + + #[test] + fn compare_rel_paths_upper() { + let directories_only_paths = vec![ + rel_path_entry("mixedCase", false), + rel_path_entry("Zebra", false), + rel_path_entry("banana", false), + rel_path_entry("ALLCAPS", false), + rel_path_entry("Apple", false), + rel_path_entry("dog", false), + rel_path_entry(".hidden", false), + rel_path_entry("Carrot", false), + ]; + assert_eq!( + sorted_rel_paths( + directories_only_paths, + SortMode::DirectoriesFirst, + SortOrder::Upper, + ), + vec![ + rel_path_entry(".hidden", false), + rel_path_entry("ALLCAPS", false), + rel_path_entry("Apple", false), + rel_path_entry("Carrot", false), + rel_path_entry("Zebra", false), + rel_path_entry("banana", false), + rel_path_entry("dog", false), + rel_path_entry("mixedCase", false), + ] + ); + + let file_and_directory_paths = vec![ + rel_path_entry("banana", false), + rel_path_entry("Apple.txt", true), + rel_path_entry("dog.md", true), + rel_path_entry("ALLCAPS", false), + rel_path_entry("file1.txt", true), + rel_path_entry("File2.txt", true), + rel_path_entry(".hidden", false), + ]; + assert_eq!( + sorted_rel_paths( + file_and_directory_paths.clone(), + SortMode::DirectoriesFirst, + SortOrder::Upper, + ), + vec![ + rel_path_entry(".hidden", false), + rel_path_entry("ALLCAPS", false), + rel_path_entry("banana", false), + rel_path_entry("Apple.txt", true), + rel_path_entry("File2.txt", true), + rel_path_entry("dog.md", true), + rel_path_entry("file1.txt", true), + ] + ); + assert_eq!( + sorted_rel_paths( + file_and_directory_paths.clone(), + SortMode::Mixed, + SortOrder::Upper, + ), + vec![ + rel_path_entry(".hidden", false), + rel_path_entry("ALLCAPS", false), + rel_path_entry("Apple.txt", true), + rel_path_entry("File2.txt", true), + rel_path_entry("banana", false), + rel_path_entry("dog.md", true), + rel_path_entry("file1.txt", true), + ] + ); + assert_eq!( + sorted_rel_paths( + file_and_directory_paths, + SortMode::FilesFirst, + SortOrder::Upper, + ), + vec![ + rel_path_entry("Apple.txt", true), + rel_path_entry("File2.txt", true), + rel_path_entry("dog.md", true), + rel_path_entry("file1.txt", true), + rel_path_entry(".hidden", false), + rel_path_entry("ALLCAPS", false), + rel_path_entry("banana", false), + ] + ); + + let natural_sort_paths = vec![ + rel_path_entry("file10.txt", true), + rel_path_entry("file1.txt", true), + rel_path_entry("file20.txt", true), + rel_path_entry("file2.txt", true), + ]; + assert_eq!( + sorted_rel_paths(natural_sort_paths, SortMode::Mixed, SortOrder::Upper,), + vec![ + rel_path_entry("file1.txt", true), + rel_path_entry("file2.txt", true), + rel_path_entry("file10.txt", true), + rel_path_entry("file20.txt", true), + ] + ); + + let accented_paths = vec![ + rel_path_entry("\u{00C9}something.txt", true), + rel_path_entry("zebra.txt", true), + rel_path_entry("Apple.txt", true), + ]; + assert_eq!( + sorted_rel_paths(accented_paths, SortMode::Mixed, SortOrder::Upper), + vec![ + rel_path_entry("Apple.txt", true), + rel_path_entry("\u{00C9}something.txt", true), + rel_path_entry("zebra.txt", true), + ] + ); + } + + #[test] + fn compare_rel_paths_lower() { + let directories_only_paths = vec![ + rel_path_entry("mixedCase", false), + rel_path_entry("Zebra", false), + rel_path_entry("banana", false), + rel_path_entry("ALLCAPS", false), + rel_path_entry("Apple", false), + rel_path_entry("dog", false), + rel_path_entry(".hidden", false), + rel_path_entry("Carrot", false), + ]; + assert_eq!( + sorted_rel_paths( + directories_only_paths, + SortMode::DirectoriesFirst, + SortOrder::Lower, + ), + vec![ + rel_path_entry(".hidden", false), + rel_path_entry("banana", false), + rel_path_entry("dog", false), + rel_path_entry("mixedCase", false), + rel_path_entry("ALLCAPS", false), + rel_path_entry("Apple", false), + rel_path_entry("Carrot", false), + rel_path_entry("Zebra", false), + ] + ); + + let file_and_directory_paths = vec![ + rel_path_entry("banana", false), + rel_path_entry("Apple.txt", true), + rel_path_entry("dog.md", true), + rel_path_entry("ALLCAPS", false), + rel_path_entry("file1.txt", true), + rel_path_entry("File2.txt", true), + rel_path_entry(".hidden", false), + ]; + assert_eq!( + sorted_rel_paths( + file_and_directory_paths.clone(), + SortMode::DirectoriesFirst, + SortOrder::Lower, + ), + vec![ + rel_path_entry(".hidden", false), + rel_path_entry("banana", false), + rel_path_entry("ALLCAPS", false), + rel_path_entry("dog.md", true), + rel_path_entry("file1.txt", true), + rel_path_entry("Apple.txt", true), + rel_path_entry("File2.txt", true), + ] + ); + assert_eq!( + sorted_rel_paths( + file_and_directory_paths.clone(), + SortMode::Mixed, + SortOrder::Lower, + ), + vec![ + rel_path_entry(".hidden", false), + rel_path_entry("banana", false), + rel_path_entry("dog.md", true), + rel_path_entry("file1.txt", true), + rel_path_entry("ALLCAPS", false), + rel_path_entry("Apple.txt", true), + rel_path_entry("File2.txt", true), + ] + ); + assert_eq!( + sorted_rel_paths( + file_and_directory_paths, + SortMode::FilesFirst, + SortOrder::Lower, + ), + vec![ + rel_path_entry("dog.md", true), + rel_path_entry("file1.txt", true), + rel_path_entry("Apple.txt", true), + rel_path_entry("File2.txt", true), + rel_path_entry(".hidden", false), + rel_path_entry("banana", false), + rel_path_entry("ALLCAPS", false), + ] + ); + } + + #[test] + fn compare_rel_paths_unicode() { + let directories_only_paths = vec![ + rel_path_entry("mixedCase", false), + rel_path_entry("Zebra", false), + rel_path_entry("banana", false), + rel_path_entry("ALLCAPS", false), + rel_path_entry("Apple", false), + rel_path_entry("dog", false), + rel_path_entry(".hidden", false), + rel_path_entry("Carrot", false), + ]; + assert_eq!( + sorted_rel_paths( + directories_only_paths, + SortMode::DirectoriesFirst, + SortOrder::Unicode, + ), + vec![ + rel_path_entry(".hidden", false), + rel_path_entry("ALLCAPS", false), + rel_path_entry("Apple", false), + rel_path_entry("Carrot", false), + rel_path_entry("Zebra", false), + rel_path_entry("banana", false), + rel_path_entry("dog", false), + rel_path_entry("mixedCase", false), + ] + ); + + let file_and_directory_paths = vec![ + rel_path_entry("banana", false), + rel_path_entry("Apple.txt", true), + rel_path_entry("dog.md", true), + rel_path_entry("ALLCAPS", false), + rel_path_entry("file1.txt", true), + rel_path_entry("File2.txt", true), + rel_path_entry(".hidden", false), + ]; + assert_eq!( + sorted_rel_paths( + file_and_directory_paths.clone(), + SortMode::DirectoriesFirst, + SortOrder::Unicode, + ), + vec![ + rel_path_entry(".hidden", false), + rel_path_entry("ALLCAPS", false), + rel_path_entry("banana", false), + rel_path_entry("Apple.txt", true), + rel_path_entry("File2.txt", true), + rel_path_entry("dog.md", true), + rel_path_entry("file1.txt", true), + ] + ); + assert_eq!( + sorted_rel_paths( + file_and_directory_paths.clone(), + SortMode::Mixed, + SortOrder::Unicode, + ), + vec![ + rel_path_entry(".hidden", false), + rel_path_entry("ALLCAPS", false), + rel_path_entry("Apple.txt", true), + rel_path_entry("File2.txt", true), + rel_path_entry("banana", false), + rel_path_entry("dog.md", true), + rel_path_entry("file1.txt", true), + ] + ); + assert_eq!( + sorted_rel_paths( + file_and_directory_paths, + SortMode::FilesFirst, + SortOrder::Unicode, + ), + vec![ + rel_path_entry("Apple.txt", true), + rel_path_entry("File2.txt", true), + rel_path_entry("dog.md", true), + rel_path_entry("file1.txt", true), + rel_path_entry(".hidden", false), + rel_path_entry("ALLCAPS", false), + rel_path_entry("banana", false), + ] + ); + + let numeric_paths = vec![ + rel_path_entry("file10.txt", true), + rel_path_entry("file1.txt", true), + rel_path_entry("file2.txt", true), + rel_path_entry("file20.txt", true), + ]; + assert_eq!( + sorted_rel_paths(numeric_paths, SortMode::Mixed, SortOrder::Unicode,), + vec![ + rel_path_entry("file1.txt", true), + rel_path_entry("file10.txt", true), + rel_path_entry("file2.txt", true), + rel_path_entry("file20.txt", true), + ] + ); + + let accented_paths = vec![ + rel_path_entry("\u{00C9}something.txt", true), + rel_path_entry("zebra.txt", true), + rel_path_entry("Apple.txt", true), + ]; + assert_eq!( + sorted_rel_paths(accented_paths, SortMode::Mixed, SortOrder::Unicode), + vec![ + rel_path_entry("Apple.txt", true), + rel_path_entry("zebra.txt", true), + rel_path_entry("\u{00C9}something.txt", true), + ] + ); + } + + #[test] + fn path_with_position_parse_posix_path() { + // Test POSIX filename edge cases + // Read more at https://en.wikipedia.org/wiki/Filename + assert_eq!( + PathWithPosition::parse_str("test_file"), + PathWithPosition { + path: PathBuf::from("test_file"), + row: None, + column: None + } + ); + + assert_eq!( + PathWithPosition::parse_str("a:bc:.zip:1"), + PathWithPosition { + path: PathBuf::from("a:bc:.zip"), + row: Some(1), + column: None + } + ); + + assert_eq!( + PathWithPosition::parse_str("one.second.zip:1"), + PathWithPosition { + path: PathBuf::from("one.second.zip"), + row: Some(1), + column: None + } + ); + + // Trim off trailing `:`s for otherwise valid input. + assert_eq!( + PathWithPosition::parse_str("test_file:10:1:"), + PathWithPosition { + path: PathBuf::from("test_file"), + row: Some(10), + column: Some(1) + } + ); + + assert_eq!( + PathWithPosition::parse_str("test_file.rs:"), + PathWithPosition { + path: PathBuf::from("test_file.rs"), + row: None, + column: None + } + ); + + assert_eq!( + PathWithPosition::parse_str("test_file.rs:1:"), + PathWithPosition { + path: PathBuf::from("test_file.rs"), + row: Some(1), + column: None + } + ); + + assert_eq!( + PathWithPosition::parse_str("ab\ncd"), + PathWithPosition { + path: PathBuf::from("ab\ncd"), + row: None, + column: None + } + ); + + assert_eq!( + PathWithPosition::parse_str("👋\nab"), + PathWithPosition { + path: PathBuf::from("👋\nab"), + row: None, + column: None + } + ); + + assert_eq!( + PathWithPosition::parse_str("Types.hs:(617,9)-(670,28):"), + PathWithPosition { + path: PathBuf::from("Types.hs"), + row: Some(617), + column: Some(9), + } + ); + + assert_eq!( + PathWithPosition::parse_str("main (1).log"), + PathWithPosition { + path: PathBuf::from("main (1).log"), + row: None, + column: None + } + ); + } + + #[test] + #[cfg(not(target_os = "windows"))] + fn path_with_position_parse_posix_path_with_suffix() { + assert_eq!( + PathWithPosition::parse_str("foo/bar:34:in"), + PathWithPosition { + path: PathBuf::from("foo/bar"), + row: Some(34), + column: None, + } + ); + assert_eq!( + PathWithPosition::parse_str("foo/bar.rs:1902:::15:"), + PathWithPosition { + path: PathBuf::from("foo/bar.rs:1902"), + row: Some(15), + column: None + } + ); + + assert_eq!( + PathWithPosition::parse_str("app-editors:zed-0.143.6:20240710-201212.log:34:"), + PathWithPosition { + path: PathBuf::from("app-editors:zed-0.143.6:20240710-201212.log"), + row: Some(34), + column: None, + } + ); + + assert_eq!( + PathWithPosition::parse_str("crates/file_finder/src/file_finder.rs:1902:13:"), + PathWithPosition { + path: PathBuf::from("crates/file_finder/src/file_finder.rs"), + row: Some(1902), + column: Some(13), + } + ); + + assert_eq!( + PathWithPosition::parse_str("crate/utils/src/test:today.log:34"), + PathWithPosition { + path: PathBuf::from("crate/utils/src/test:today.log"), + row: Some(34), + column: None, + } + ); + assert_eq!( + PathWithPosition::parse_str("/testing/out/src/file_finder.odin(7:15)"), + PathWithPosition { + path: PathBuf::from("/testing/out/src/file_finder.odin"), + row: Some(7), + column: Some(15), + } + ); + } + + #[test] + #[cfg(target_os = "windows")] + fn path_with_position_parse_windows_path() { + assert_eq!( + PathWithPosition::parse_str("crates\\utils\\paths.rs"), + PathWithPosition { + path: PathBuf::from("crates\\utils\\paths.rs"), + row: None, + column: None + } + ); + + assert_eq!( + PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs"), + PathWithPosition { + path: PathBuf::from("C:\\Users\\someone\\test_file.rs"), + row: None, + column: None + } + ); + + assert_eq!( + PathWithPosition::parse_str("C:\\Users\\someone\\main (1).log"), + PathWithPosition { + path: PathBuf::from("C:\\Users\\someone\\main (1).log"), + row: None, + column: None + } + ); + } + + #[test] + #[cfg(target_os = "windows")] + fn path_with_position_parse_windows_path_with_suffix() { + assert_eq!( + PathWithPosition::parse_str("crates\\utils\\paths.rs:101"), + PathWithPosition { + path: PathBuf::from("crates\\utils\\paths.rs"), + row: Some(101), + column: None + } + ); + + assert_eq!( + PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1:20"), + PathWithPosition { + path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"), + row: Some(1), + column: Some(20) + } + ); + + assert_eq!( + PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902,13)"), + PathWithPosition { + path: PathBuf::from("C:\\Users\\someone\\test_file.rs"), + row: Some(1902), + column: Some(13) + } + ); + + // Trim off trailing `:`s for otherwise valid input. + assert_eq!( + PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:13:"), + PathWithPosition { + path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"), + row: Some(1902), + column: Some(13) + } + ); + + assert_eq!( + PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:13:15:"), + PathWithPosition { + path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs:1902"), + row: Some(13), + column: Some(15) + } + ); + + assert_eq!( + PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs:1902:::15:"), + PathWithPosition { + path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs:1902"), + row: Some(15), + column: None + } + ); + + assert_eq!( + PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs(1902,13):"), + PathWithPosition { + path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"), + row: Some(1902), + column: Some(13), + } + ); + + assert_eq!( + PathWithPosition::parse_str("\\\\?\\C:\\Users\\someone\\test_file.rs(1902):"), + PathWithPosition { + path: PathBuf::from("\\\\?\\C:\\Users\\someone\\test_file.rs"), + row: Some(1902), + column: None, + } + ); + + assert_eq!( + PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs:1902:13:"), + PathWithPosition { + path: PathBuf::from("C:\\Users\\someone\\test_file.rs"), + row: Some(1902), + column: Some(13), + } + ); + + assert_eq!( + PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902,13):"), + PathWithPosition { + path: PathBuf::from("C:\\Users\\someone\\test_file.rs"), + row: Some(1902), + column: Some(13), + } + ); + + assert_eq!( + PathWithPosition::parse_str("C:\\Users\\someone\\test_file.rs(1902):"), + PathWithPosition { + path: PathBuf::from("C:\\Users\\someone\\test_file.rs"), + row: Some(1902), + column: None, + } + ); + + assert_eq!( + PathWithPosition::parse_str("crates/utils/paths.rs:101"), + PathWithPosition { + path: PathBuf::from("crates\\utils\\paths.rs"), + row: Some(101), + column: None, + } + ); + } + + #[test] + fn test_path_compact() { + let path: PathBuf = [ + home_dir().to_string_lossy().into_owned(), + "some_file.txt".to_string(), + ] + .iter() + .collect(); + if cfg!(any(target_os = "linux", target_os = "freebsd")) || cfg!(target_os = "macos") { + assert_eq!(path.compact().to_str(), Some("~/some_file.txt")); + } else { + assert_eq!(path.compact().to_str(), path.to_str()); + } + } + + #[test] + fn test_extension_or_hidden_file_name() { + // No dots in name + let path = Path::new("/a/b/c/file_name.rs"); + assert_eq!(path.extension_or_hidden_file_name(), Some("rs")); + + // Single dot in name + let path = Path::new("/a/b/c/file.name.rs"); + assert_eq!(path.extension_or_hidden_file_name(), Some("rs")); + + // Multiple dots in name + let path = Path::new("/a/b/c/long.file.name.rs"); + assert_eq!(path.extension_or_hidden_file_name(), Some("rs")); + + // Hidden file, no extension + let path = Path::new("/a/b/c/.gitignore"); + assert_eq!(path.extension_or_hidden_file_name(), Some("gitignore")); + + // Hidden file, with extension + let path = Path::new("/a/b/c/.eslintrc.js"); + assert_eq!(path.extension_or_hidden_file_name(), Some("eslintrc.js")); + } + + #[test] + // fn edge_of_glob() { + // let path = Path::new("/work/node_modules"); + // let path_matcher = + // PathMatcher::new(&["**/node_modules/**".to_owned()], PathStyle::Posix).unwrap(); + // assert!( + // path_matcher.is_match(path), + // "Path matcher should match {path:?}" + // ); + // } + + // #[test] + // fn file_in_dirs() { + // let path = Path::new("/work/.env"); + // let path_matcher = PathMatcher::new(&["**/.env".to_owned()], PathStyle::Posix).unwrap(); + // assert!( + // path_matcher.is_match(path), + // "Path matcher should match {path:?}" + // ); + // let path = Path::new("/work/package.json"); + // assert!( + // !path_matcher.is_match(path), + // "Path matcher should not match {path:?}" + // ); + // } + + // #[test] + // fn project_search() { + // let path = Path::new("/Users/someonetoignore/work/zed/zed.dev/node_modules"); + // let path_matcher = + // PathMatcher::new(&["**/node_modules/**".to_owned()], PathStyle::Posix).unwrap(); + // assert!( + // path_matcher.is_match(path), + // "Path matcher should match {path:?}" + // ); + // } + #[test] + #[cfg(target_os = "windows")] + fn test_sanitized_path() { + let path = Path::new("C:\\Users\\someone\\test_file.rs"); + let sanitized_path = SanitizedPath::new(path); + assert_eq!( + sanitized_path.to_string(), + "C:\\Users\\someone\\test_file.rs" + ); + + let path = Path::new("\\\\?\\C:\\Users\\someone\\test_file.rs"); + let sanitized_path = SanitizedPath::new(path); + assert_eq!( + sanitized_path.to_string(), + "C:\\Users\\someone\\test_file.rs" + ); + } + + #[test] + fn test_compare_numeric_segments() { + // Helper function to create peekable iterators and test + fn compare(a: &str, b: &str) -> Ordering { + let mut a_iter = a.chars().peekable(); + let mut b_iter = b.chars().peekable(); + + let result = compare_numeric_segments(&mut a_iter, &mut b_iter); + + // Verify iterators advanced correctly + assert!( + !a_iter.next().is_some_and(|c| c.is_ascii_digit()), + "Iterator a should have consumed all digits" + ); + assert!( + !b_iter.next().is_some_and(|c| c.is_ascii_digit()), + "Iterator b should have consumed all digits" + ); + + result + } + + // Basic numeric comparisons + assert_eq!(compare("0", "0"), Ordering::Equal); + assert_eq!(compare("1", "2"), Ordering::Less); + assert_eq!(compare("9", "10"), Ordering::Less); + assert_eq!(compare("10", "9"), Ordering::Greater); + assert_eq!(compare("99", "100"), Ordering::Less); + + // Leading zeros + assert_eq!(compare("0", "00"), Ordering::Less); + assert_eq!(compare("00", "0"), Ordering::Greater); + assert_eq!(compare("01", "1"), Ordering::Greater); + assert_eq!(compare("001", "1"), Ordering::Greater); + assert_eq!(compare("001", "01"), Ordering::Greater); + + // Same value different representation + assert_eq!(compare("000100", "100"), Ordering::Greater); + assert_eq!(compare("100", "0100"), Ordering::Less); + assert_eq!(compare("0100", "00100"), Ordering::Less); + + // Large numbers + assert_eq!(compare("9999999999", "10000000000"), Ordering::Less); + assert_eq!( + compare( + "340282366920938463463374607431768211455", // u128::MAX + "340282366920938463463374607431768211456" + ), + Ordering::Less + ); + assert_eq!( + compare( + "340282366920938463463374607431768211456", // > u128::MAX + "340282366920938463463374607431768211455" + ), + Ordering::Greater + ); + + // Iterator advancement verification + let mut a_iter = "123abc".chars().peekable(); + let mut b_iter = "456def".chars().peekable(); + + compare_numeric_segments(&mut a_iter, &mut b_iter); + + assert_eq!(a_iter.collect::(), "abc"); + assert_eq!(b_iter.collect::(), "def"); + } + + #[test] + fn test_natural_sort() { + // Basic alphanumeric + assert_eq!(natural_sort("a", "b"), Ordering::Less); + assert_eq!(natural_sort("b", "a"), Ordering::Greater); + assert_eq!(natural_sort("a", "a"), Ordering::Equal); + + // Case sensitivity + assert_eq!(natural_sort("a", "A"), Ordering::Less); + assert_eq!(natural_sort("A", "a"), Ordering::Greater); + assert_eq!(natural_sort("aA", "aa"), Ordering::Greater); + assert_eq!(natural_sort("aa", "aA"), Ordering::Less); + + // Numbers + assert_eq!(natural_sort("1", "2"), Ordering::Less); + assert_eq!(natural_sort("2", "10"), Ordering::Less); + assert_eq!(natural_sort("02", "10"), Ordering::Less); + assert_eq!(natural_sort("02", "2"), Ordering::Greater); + + // Mixed alphanumeric + assert_eq!(natural_sort("a1", "a2"), Ordering::Less); + assert_eq!(natural_sort("a2", "a10"), Ordering::Less); + assert_eq!(natural_sort("a02", "a2"), Ordering::Greater); + assert_eq!(natural_sort("a1b", "a1c"), Ordering::Less); + + // Multiple numeric segments + assert_eq!(natural_sort("1a2", "1a10"), Ordering::Less); + assert_eq!(natural_sort("1a10", "1a2"), Ordering::Greater); + assert_eq!(natural_sort("2a1", "10a1"), Ordering::Less); + + // Special characters + assert_eq!(natural_sort("a-1", "a-2"), Ordering::Less); + assert_eq!(natural_sort("a_1", "a_2"), Ordering::Less); + assert_eq!(natural_sort("a.1", "a.2"), Ordering::Less); + + // Unicode + assert_eq!(natural_sort("文1", "文2"), Ordering::Less); + assert_eq!(natural_sort("文2", "文10"), Ordering::Less); + assert_eq!(natural_sort("🔤1", "🔤2"), Ordering::Less); + + // Empty and special cases + assert_eq!(natural_sort("", ""), Ordering::Equal); + assert_eq!(natural_sort("", "a"), Ordering::Less); + assert_eq!(natural_sort("a", ""), Ordering::Greater); + assert_eq!(natural_sort(" ", " "), Ordering::Less); + + // Mixed everything + assert_eq!(natural_sort("File-1.txt", "File-2.txt"), Ordering::Less); + assert_eq!(natural_sort("File-02.txt", "File-2.txt"), Ordering::Greater); + assert_eq!(natural_sort("File-2.txt", "File-10.txt"), Ordering::Less); + assert_eq!(natural_sort("File_A1", "File_A2"), Ordering::Less); + assert_eq!(natural_sort("File_a1", "File_A1"), Ordering::Less); + } + + #[test] + fn test_compare_paths() { + // Helper function for cleaner tests + fn compare(a: &str, is_a_file: bool, b: &str, is_b_file: bool) -> Ordering { + compare_paths((Path::new(a), is_a_file), (Path::new(b), is_b_file)) + } + + // Basic path comparison + assert_eq!(compare("a", true, "b", true), Ordering::Less); + assert_eq!(compare("b", true, "a", true), Ordering::Greater); + assert_eq!(compare("a", true, "a", true), Ordering::Equal); + + // Files vs Directories + assert_eq!(compare("a", true, "a", false), Ordering::Greater); + assert_eq!(compare("a", false, "a", true), Ordering::Less); + assert_eq!(compare("b", false, "a", true), Ordering::Less); + + // Extensions + assert_eq!(compare("a.txt", true, "a.md", true), Ordering::Greater); + assert_eq!(compare("a.md", true, "a.txt", true), Ordering::Less); + assert_eq!(compare("a", true, "a.txt", true), Ordering::Less); + + // Nested paths + assert_eq!(compare("dir/a", true, "dir/b", true), Ordering::Less); + assert_eq!(compare("dir1/a", true, "dir2/a", true), Ordering::Less); + assert_eq!(compare("dir/sub/a", true, "dir/a", true), Ordering::Less); + + // Case sensitivity in paths + assert_eq!( + compare("Dir/file", true, "dir/file", true), + Ordering::Greater + ); + assert_eq!( + compare("dir/File", true, "dir/file", true), + Ordering::Greater + ); + assert_eq!(compare("dir/file", true, "Dir/File", true), Ordering::Less); + + // Hidden files and special names + assert_eq!(compare(".hidden", true, "visible", true), Ordering::Less); + assert_eq!(compare("_special", true, "normal", true), Ordering::Less); + assert_eq!(compare(".config", false, ".data", false), Ordering::Less); + + // Mixed numeric paths + assert_eq!( + compare("dir1/file", true, "dir2/file", true), + Ordering::Less + ); + assert_eq!( + compare("dir2/file", true, "dir10/file", true), + Ordering::Less + ); + assert_eq!( + compare("dir02/file", true, "dir2/file", true), + Ordering::Greater + ); + + // Root paths + assert_eq!(compare("/a", true, "/b", true), Ordering::Less); + assert_eq!(compare("/", false, "/a", true), Ordering::Less); + + // Complex real-world examples + assert_eq!( + compare("project/src/main.rs", true, "project/src/lib.rs", true), + Ordering::Greater + ); + assert_eq!( + compare( + "project/tests/test_1.rs", + true, + "project/tests/test_2.rs", + true + ), + Ordering::Less + ); + assert_eq!( + compare( + "project/v1.0.0/README.md", + true, + "project/v1.10.0/README.md", + true + ), + Ordering::Less + ); + } + + #[test] + fn test_natural_sort_case_sensitivity() { + std::thread::sleep(std::time::Duration::from_millis(100)); + // Same letter different case - lowercase should come first + assert_eq!(natural_sort("a", "A"), Ordering::Less); + assert_eq!(natural_sort("A", "a"), Ordering::Greater); + assert_eq!(natural_sort("a", "a"), Ordering::Equal); + assert_eq!(natural_sort("A", "A"), Ordering::Equal); + + // Mixed case strings + assert_eq!(natural_sort("aaa", "AAA"), Ordering::Less); + assert_eq!(natural_sort("AAA", "aaa"), Ordering::Greater); + assert_eq!(natural_sort("aAa", "AaA"), Ordering::Less); + + // Different letters + assert_eq!(natural_sort("a", "b"), Ordering::Less); + assert_eq!(natural_sort("A", "b"), Ordering::Less); + assert_eq!(natural_sort("a", "B"), Ordering::Less); + } + + #[test] + fn test_natural_sort_with_numbers() { + // Basic number ordering + assert_eq!(natural_sort("file1", "file2"), Ordering::Less); + assert_eq!(natural_sort("file2", "file10"), Ordering::Less); + assert_eq!(natural_sort("file10", "file2"), Ordering::Greater); + + // Numbers in different positions + assert_eq!(natural_sort("1file", "2file"), Ordering::Less); + assert_eq!(natural_sort("file1text", "file2text"), Ordering::Less); + assert_eq!(natural_sort("text1file", "text2file"), Ordering::Less); + + // Multiple numbers in string + assert_eq!(natural_sort("file1-2", "file1-10"), Ordering::Less); + assert_eq!(natural_sort("2-1file", "10-1file"), Ordering::Less); + + // Leading zeros + assert_eq!(natural_sort("file002", "file2"), Ordering::Greater); + assert_eq!(natural_sort("file002", "file10"), Ordering::Less); + + // Very large numbers + assert_eq!( + natural_sort("file999999999999999999999", "file999999999999999999998"), + Ordering::Greater + ); + + // u128 edge cases + + // Numbers near u128::MAX (340,282,366,920,938,463,463,374,607,431,768,211,455) + assert_eq!( + natural_sort( + "file340282366920938463463374607431768211454", + "file340282366920938463463374607431768211455" + ), + Ordering::Less + ); + + // Equal length numbers that overflow u128 + assert_eq!( + natural_sort( + "file340282366920938463463374607431768211456", + "file340282366920938463463374607431768211455" + ), + Ordering::Greater + ); + + // Different length numbers that overflow u128 + assert_eq!( + natural_sort( + "file3402823669209384634633746074317682114560", + "file340282366920938463463374607431768211455" + ), + Ordering::Greater + ); + + // Leading zeros with numbers near u128::MAX + assert_eq!( + natural_sort( + "file0340282366920938463463374607431768211455", + "file340282366920938463463374607431768211455" + ), + Ordering::Greater + ); + + // Very large numbers with different lengths (both overflow u128) + assert_eq!( + natural_sort( + "file999999999999999999999999999999999999999999999999", + "file9999999999999999999999999999999999999999999999999" + ), + Ordering::Less + ); + } + + #[test] + fn test_natural_sort_case_sensitive() { + // Numerically smaller values come first. + assert_eq!(natural_sort("File1", "file2"), Ordering::Less); + assert_eq!(natural_sort("file1", "File2"), Ordering::Less); + + // Numerically equal values: the case-insensitive comparison decides first. + // Case-sensitive comparison only occurs when both are equal case-insensitively. + assert_eq!(natural_sort("Dir1", "dir01"), Ordering::Less); + assert_eq!(natural_sort("dir2", "Dir02"), Ordering::Less); + assert_eq!(natural_sort("dir2", "dir02"), Ordering::Less); + + // Numerically equal and case-insensitively equal: + // the lexicographically smaller (case-sensitive) one wins. + assert_eq!(natural_sort("dir1", "Dir1"), Ordering::Less); + assert_eq!(natural_sort("dir02", "Dir02"), Ordering::Less); + assert_eq!(natural_sort("dir10", "Dir10"), Ordering::Less); + } + + #[test] + fn test_natural_sort_edge_cases() { + // Empty strings + assert_eq!(natural_sort("", ""), Ordering::Equal); + assert_eq!(natural_sort("", "a"), Ordering::Less); + assert_eq!(natural_sort("a", ""), Ordering::Greater); + + // Special characters + assert_eq!(natural_sort("file-1", "file_1"), Ordering::Less); + assert_eq!(natural_sort("file.1", "file_1"), Ordering::Less); + assert_eq!(natural_sort("file 1", "file_1"), Ordering::Less); + + // Unicode characters + // 9312 vs 9313 + assert_eq!(natural_sort("file①", "file②"), Ordering::Less); + // 9321 vs 9313 + assert_eq!(natural_sort("file⑩", "file②"), Ordering::Greater); + // 28450 vs 23383 + assert_eq!(natural_sort("file漢", "file字"), Ordering::Greater); + + // Mixed alphanumeric with special chars + assert_eq!(natural_sort("file-1a", "file-1b"), Ordering::Less); + assert_eq!(natural_sort("file-1.2", "file-1.10"), Ordering::Less); + assert_eq!(natural_sort("file-1.10", "file-1.2"), Ordering::Greater); + } + + #[test] + fn test_multiple_extensions() { + // No extensions + let path = Path::new("/a/b/c/file_name"); + assert_eq!(path.multiple_extensions(), None); + + // Only one extension + let path = Path::new("/a/b/c/file_name.tsx"); + assert_eq!(path.multiple_extensions(), None); + + // Stories sample extension + let path = Path::new("/a/b/c/file_name.stories.tsx"); + assert_eq!(path.multiple_extensions(), Some("stories.tsx".to_string())); + + // Longer sample extension + let path = Path::new("/a/b/c/long.app.tar.gz"); + assert_eq!(path.multiple_extensions(), Some("app.tar.gz".to_string())); + } + + #[test] + fn test_strip_path_suffix() { + let base = Path::new("/a/b/c/file_name"); + let suffix = Path::new("file_name"); + assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b/c"))); + + let base = Path::new("/a/b/c/file_name.tsx"); + let suffix = Path::new("file_name.tsx"); + assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b/c"))); + + let base = Path::new("/a/b/c/file_name.stories.tsx"); + let suffix = Path::new("c/file_name.stories.tsx"); + assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a/b"))); + + let base = Path::new("/a/b/c/long.app.tar.gz"); + let suffix = Path::new("b/c/long.app.tar.gz"); + assert_eq!(strip_path_suffix(base, suffix), Some(Path::new("/a"))); + + let base = Path::new("/a/b/c/long.app.tar.gz"); + let suffix = Path::new("/a/b/c/long.app.tar.gz"); + assert_eq!(strip_path_suffix(base, suffix), Some(Path::new(""))); + + let base = Path::new("/a/b/c/long.app.tar.gz"); + let suffix = Path::new("/a/b/c/no_match.app.tar.gz"); + assert_eq!(strip_path_suffix(base, suffix), None); + + let base = Path::new("/a/b/c/long.app.tar.gz"); + let suffix = Path::new("app.tar.gz"); + assert_eq!(strip_path_suffix(base, suffix), None); + } + + #[test] + fn test_strip_prefix() { + let expected = [ + ( + PathStyle::Posix, + "/a/b/c", + "/a/b", + Some(rel_path("c").to_arc()), + ), + ( + PathStyle::Posix, + "/a/b/c", + "/a/b/", + Some(rel_path("c").to_arc()), + ), + ( + PathStyle::Posix, + "/a/b/c", + "/", + Some(rel_path("a/b/c").to_arc()), + ), + (PathStyle::Posix, "/a/b/c", "", None), + (PathStyle::Posix, "/a/b//c", "/a/b/", None), + (PathStyle::Posix, "/a/bc", "/a/b", None), + ( + PathStyle::Posix, + "/a/b/c", + "/a/b/c", + Some(rel_path("").to_arc()), + ), + ( + PathStyle::Windows, + "C:\\a\\b\\c", + "C:\\a\\b", + Some(rel_path("c").to_arc()), + ), + ( + PathStyle::Windows, + "C:\\a\\b\\c", + "C:\\a\\b\\", + Some(rel_path("c").to_arc()), + ), + ( + PathStyle::Windows, + "C:\\a\\b\\c", + "C:\\", + Some(rel_path("a/b/c").to_arc()), + ), + (PathStyle::Windows, "C:\\a\\b\\c", "", None), + (PathStyle::Windows, "C:\\a\\b\\\\c", "C:\\a\\b\\", None), + (PathStyle::Windows, "C:\\a\\bc", "C:\\a\\b", None), + ( + PathStyle::Windows, + "C:\\a\\b/c", + "C:\\a\\b", + Some(rel_path("c").to_arc()), + ), + ( + PathStyle::Windows, + "C:\\a\\b/c", + "C:\\a\\b\\", + Some(rel_path("c").to_arc()), + ), + ( + PathStyle::Windows, + "C:\\a\\b/c", + "C:\\a\\b/", + Some(rel_path("c").to_arc()), + ), + ]; + let actual = expected.clone().map(|(style, child, parent, _)| { + ( + style, + child, + parent, + style + .strip_prefix(child.as_ref(), parent.as_ref()) + .map(|rel_path| rel_path.to_arc()), + ) + }); + pretty_assertions::assert_eq!(actual, expected); + } + + #[cfg(target_os = "windows")] + #[test] + fn test_wsl_path() { + use super::WslPath; + let path = "/a/b/c"; + assert_eq!(WslPath::from_path(&path), None); + + let path = r"\\wsl.localhost"; + assert_eq!(WslPath::from_path(&path), None); + + let path = r"\\wsl.localhost\Distro"; + assert_eq!( + WslPath::from_path(&path), + Some(WslPath { + distro: "Distro".to_owned(), + path: "/".into(), + }) + ); + + let path = r"\\wsl.localhost\Distro\blue"; + assert_eq!( + WslPath::from_path(&path), + Some(WslPath { + distro: "Distro".to_owned(), + path: "/blue".into() + }) + ); + + let path = r"\\wsl$\archlinux\tomato\.\paprika\..\aubergine.txt"; + assert_eq!( + WslPath::from_path(&path), + Some(WslPath { + distro: "archlinux".to_owned(), + path: "/tomato/paprika/../aubergine.txt".into() + }) + ); + + let path = r"\\windows.localhost\Distro\foo"; + assert_eq!(WslPath::from_path(&path), None); + } + + #[test] + fn test_url_to_file_path_ext_posix_basic() { + use super::UrlExt; + + let url = url::Url::parse("file:///home/user/file.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Posix), + Ok(PathBuf::from("/home/user/file.txt")) + ); + + let url = url::Url::parse("file:///").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Posix), + Ok(PathBuf::from("/")) + ); + + let url = url::Url::parse("file:///a/b/c/d/e").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Posix), + Ok(PathBuf::from("/a/b/c/d/e")) + ); + } + + #[test] + fn test_url_to_file_path_ext_posix_percent_encoding() { + use super::UrlExt; + + let url = url::Url::parse("file:///home/user/file%20with%20spaces.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Posix), + Ok(PathBuf::from("/home/user/file with spaces.txt")) + ); + + let url = url::Url::parse("file:///path%2Fwith%2Fencoded%2Fslashes").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Posix), + Ok(PathBuf::from("/path/with/encoded/slashes")) + ); + + let url = url::Url::parse("file:///special%23chars%3F.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Posix), + Ok(PathBuf::from("/special#chars?.txt")) + ); + } + + #[test] + fn test_url_to_file_path_ext_posix_localhost() { + use super::UrlExt; + + let url = url::Url::parse("file://localhost/home/user/file.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Posix), + Ok(PathBuf::from("/home/user/file.txt")) + ); + } + + #[test] + fn test_url_to_file_path_ext_posix_rejects_host() { + use super::UrlExt; + + let url = url::Url::parse("file://somehost/home/user/file.txt").unwrap(); + assert_eq!(url.to_file_path_ext(PathStyle::Posix), Err(ToFilePathError)); + } + + #[test] + fn test_url_to_file_path_ext_posix_windows_drive_letter() { + use super::UrlExt; + + let url = url::Url::parse("file:///C:").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Posix), + Ok(PathBuf::from("/C:/")) + ); + + let url = url::Url::parse("file:///D|").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Posix), + Ok(PathBuf::from("/D|/")) + ); + } + + #[test] + fn test_url_to_file_path_ext_windows_basic() { + use super::UrlExt; + + let url = url::Url::parse("file:///C:/Users/user/file.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Ok(PathBuf::from("C:\\Users\\user\\file.txt")) + ); + + let url = url::Url::parse("file:///D:/folder/subfolder/file.rs").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Ok(PathBuf::from("D:\\folder\\subfolder\\file.rs")) + ); + + let url = url::Url::parse("file:///C:/").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Ok(PathBuf::from("C:\\")) + ); + } + + #[test] + fn test_url_to_file_path_ext_windows_encoded_drive_letter() { + use super::UrlExt; + + let url = url::Url::parse("file:///C%3A/Users/file.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Ok(PathBuf::from("C:\\Users\\file.txt")) + ); + + let url = url::Url::parse("file:///c%3a/Users/file.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Ok(PathBuf::from("c:\\Users\\file.txt")) + ); + + let url = url::Url::parse("file:///D%3A/folder/file.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Ok(PathBuf::from("D:\\folder\\file.txt")) + ); + + let url = url::Url::parse("file:///d%3A/folder/file.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Ok(PathBuf::from("d:\\folder\\file.txt")) + ); + } + + #[test] + fn test_url_to_file_path_ext_windows_unc_path() { + use super::UrlExt; + + let url = url::Url::parse("file://server/share/path/file.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Ok(PathBuf::from("\\\\server\\share\\path\\file.txt")) + ); + + let url = url::Url::parse("file://server/share").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Ok(PathBuf::from("\\\\server\\share")) + ); + } + + #[test] + fn test_url_to_file_path_ext_windows_percent_encoding() { + use super::UrlExt; + + let url = url::Url::parse("file:///C:/Users/user/file%20with%20spaces.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Ok(PathBuf::from("C:\\Users\\user\\file with spaces.txt")) + ); + + let url = url::Url::parse("file:///C:/special%23chars%3F.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Ok(PathBuf::from("C:\\special#chars?.txt")) + ); + } + + #[test] + fn test_url_to_file_path_ext_windows_invalid_drive() { + use super::UrlExt; + + let url = url::Url::parse("file:///1:/path/file.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Err(ToFilePathError) + ); + + let url = url::Url::parse("file:///CC:/path/file.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Err(ToFilePathError) + ); + + let url = url::Url::parse("file:///C/path/file.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Err(ToFilePathError) + ); + + let url = url::Url::parse("file:///invalid").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Err(ToFilePathError) + ); + } + + #[test] + fn test_url_to_file_path_ext_non_file_scheme() { + use super::UrlExt; + + let url = url::Url::parse("http://example.com/path").unwrap(); + assert_eq!(url.to_file_path_ext(PathStyle::Posix), Err(ToFilePathError)); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Err(ToFilePathError) + ); + + let url = url::Url::parse("https://example.com/path").unwrap(); + assert_eq!(url.to_file_path_ext(PathStyle::Posix), Err(ToFilePathError)); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Err(ToFilePathError) + ); + } + + #[test] + fn test_url_to_file_path_ext_windows_localhost() { + use super::UrlExt; + + let url = url::Url::parse("file://localhost/C:/Users/file.txt").unwrap(); + assert_eq!( + url.to_file_path_ext(PathStyle::Windows), + Ok(PathBuf::from("C:\\Users\\file.txt")) + ); + } +} diff --git a/crates/gpui_zed_util/src/process.rs b/crates/gpui_zed_util/src/process.rs new file mode 100644 index 0000000000..eaf543dbd8 --- /dev/null +++ b/crates/gpui_zed_util/src/process.rs @@ -0,0 +1,92 @@ +use anyhow::{Context as _, Result}; +use std::process::Stdio; + +/// A wrapper around `smol::process::Child` that ensures all subprocesses +/// are killed when the process is terminated by using process groups. +pub struct Child { + process: smol::process::Child, +} + +impl std::ops::Deref for Child { + type Target = smol::process::Child; + + fn deref(&self) -> &Self::Target { + &self.process + } +} + +impl std::ops::DerefMut for Child { + fn deref_mut(&mut self) -> &mut Self::Target { + &mut self.process + } +} + +impl Child { + #[cfg(not(windows))] + pub fn spawn( + mut command: std::process::Command, + stdin: Stdio, + stdout: Stdio, + stderr: Stdio, + ) -> Result { + crate::set_pre_exec_to_start_new_session(&mut command); + let mut command = smol::process::Command::from(command); + let process = command + .stdin(stdin) + .stdout(stdout) + .stderr(stderr) + .spawn() + .with_context(|| { + format!( + "failed to spawn command {}", + crate::redact::redact_command(&format!("{command:?}")) + ) + })?; + Ok(Self { process }) + } + + #[cfg(windows)] + pub fn spawn( + command: std::process::Command, + stdin: Stdio, + stdout: Stdio, + stderr: Stdio, + ) -> Result { + // TODO(windows): create a job object and add the child process handle to it, + // see https://learn.microsoft.com/en-us/windows/win32/procthread/job-objects + let mut command = smol::process::Command::from(command); + let process = command + .stdin(stdin) + .stdout(stdout) + .stderr(stderr) + .spawn() + .with_context(|| { + format!( + "failed to spawn command {}", + crate::redact::redact_command(&format!("{command:?}")) + ) + })?; + + Ok(Self { process }) + } + + pub fn into_inner(self) -> smol::process::Child { + self.process + } + + #[cfg(not(windows))] + pub fn kill(&mut self) -> Result<()> { + let pid = self.process.id(); + unsafe { + libc::killpg(pid as i32, libc::SIGKILL); + } + Ok(()) + } + + #[cfg(windows)] + pub fn kill(&mut self) -> Result<()> { + // TODO(windows): terminate the job object in kill + self.process.kill()?; + Ok(()) + } +} diff --git a/crates/gpui_zed_util/src/redact.rs b/crates/gpui_zed_util/src/redact.rs new file mode 100644 index 0000000000..ad11f7618b --- /dev/null +++ b/crates/gpui_zed_util/src/redact.rs @@ -0,0 +1,49 @@ +use std::sync::LazyLock; + +static REDACT_REGEX: LazyLock = LazyLock::new(|| { + regex::Regex::new(r#"([A-Z_][A-Z0-9_]*)=("(?:[^"\\]|\\.)*"|'(?:[^'\\]|\\.)*'|\S+)"#).unwrap() +}); + +/// Whether a given environment variable name should have its value redacted +pub fn should_redact(env_var_name: &str) -> bool { + const REDACTED_SUFFIXES: &[&str] = &[ + "KEY", + "TOKEN", + "PASSWORD", + "SECRET", + "PASS", + "CREDENTIALS", + "LICENSE", + ]; + REDACTED_SUFFIXES + .iter() + .any(|suffix| env_var_name.ends_with(suffix)) +} + +/// Redact a string which could include a command with environment variables +pub fn redact_command(command: &str) -> String { + REDACT_REGEX + .replace_all(command, |caps: ®ex::Captures| { + let var_name = &caps[1]; + let value = &caps[2]; + if should_redact(var_name) { + format!(r#"{}="[REDACTED]""#, var_name) + } else { + format!("{}={}", var_name, value) + } + }) + .to_string() +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_redact_string_with_multiple_env_vars() { + let input = r#"failed to spawn command cd "/code/something" && ANTHROPIC_API_KEY="sk-ant-api03-WOOOO" COMMAND_MODE="unix2003" GEMINI_API_KEY="AIGEMINIFACE" HOME="/Users/foo""#; + let result = redact_command(input); + let expected = r#"failed to spawn command cd "/code/something" && ANTHROPIC_API_KEY="[REDACTED]" COMMAND_MODE="unix2003" GEMINI_API_KEY="[REDACTED]" HOME="/Users/foo""#; + assert_eq!(result, expected); + } +} diff --git a/crates/gpui_zed_util/src/rel_path.rs b/crates/gpui_zed_util/src/rel_path.rs new file mode 100644 index 0000000000..bd08473623 --- /dev/null +++ b/crates/gpui_zed_util/src/rel_path.rs @@ -0,0 +1,637 @@ +use crate::paths::{PathStyle, is_absolute}; +use anyhow::{Context as _, Result, anyhow}; +use serde::{Deserialize, Serialize}; +use std::{ + borrow::{Borrow, Cow}, + fmt, + ops::Deref, + path::{Path, PathBuf}, + sync::Arc, +}; + +/// A file system path that is guaranteed to be relative and normalized. +/// +/// This type can be used to represent paths in a uniform way, regardless of +/// whether they refer to Windows or POSIX file systems, and regardless of +/// the host platform. +/// +/// Internally, paths are stored in POSIX ('/'-delimited) format, but they can +/// be displayed in either POSIX or Windows format. +/// +/// Relative paths are also guaranteed to be valid unicode. +#[repr(transparent)] +#[derive(PartialEq, Eq, Hash, Serialize)] +pub struct RelPath(str); + +/// An owned representation of a file system path that is guaranteed to be +/// relative and normalized. +/// +/// This type is to [`RelPath`] as [`std::path::PathBuf`] is to [`std::path::Path`] +#[derive(PartialEq, Eq, Clone, Ord, PartialOrd, Serialize)] +pub struct RelPathBuf(String); + +impl RelPath { + /// Creates an empty [`RelPath`]. + pub fn empty() -> &'static Self { + Self::new_unchecked("") + } + + /// Converts a path with a given style into a [`RelPath`]. + /// + /// Returns an error if the path is absolute, or is not valid unicode. + /// + /// This method will normalize the path by removing `.` components, + /// processing `..` components, and removing trailing separators. It does + /// not allocate unless it's necessary to reformat the path. + #[track_caller] + pub fn new<'a>(path: &'a Path, path_style: PathStyle) -> Result> { + let mut path = path.to_str().context("non utf-8 path")?; + + let (prefixes, suffixes): (&[_], &[_]) = match path_style { + PathStyle::Posix => (&["./"], &['/']), + PathStyle::Windows => (&["./", ".\\"], &['/', '\\']), + }; + + while prefixes.iter().any(|prefix| path.starts_with(prefix)) { + path = &path[prefixes[0].len()..]; + } + while let Some(prefix) = path.strip_suffix(suffixes) + && !prefix.is_empty() + { + path = prefix; + } + + if is_absolute(path, path_style) { + return Err(anyhow!("absolute path not allowed: {path:?}")); + } + + let mut string = Cow::Borrowed(path); + if path_style == PathStyle::Windows && path.contains('\\') { + string = Cow::Owned(string.as_ref().replace('\\', "/")) + } + + let mut result = match string { + Cow::Borrowed(string) => Cow::Borrowed(Self::new_unchecked(string)), + Cow::Owned(string) => Cow::Owned(RelPathBuf(string)), + }; + + if result + .components() + .any(|component| component.is_empty() || component == "." || component == "..") + { + let mut normalized = RelPathBuf::new(); + for component in result.components() { + match component { + "" => {} + "." => {} + ".." => { + if !normalized.pop() { + return Err(anyhow!("path is not relative: {result:?}")); + } + } + other => normalized.push(RelPath::new_unchecked(other)), + } + } + result = Cow::Owned(normalized) + } + + Ok(result) + } + + /// Converts a path that is already normalized and uses '/' separators + /// into a [`RelPath`] . + /// + /// Returns an error if the path is not already in the correct format. + #[track_caller] + pub fn unix + ?Sized>(path: &S) -> anyhow::Result<&Self> { + let path = path.as_ref(); + match Self::new(path, PathStyle::Posix)? { + Cow::Borrowed(path) => Ok(path), + Cow::Owned(_) => Err(anyhow!("invalid relative path {path:?}")), + } + } + + fn new_unchecked(s: &str) -> &Self { + // Safety: `RelPath` is a transparent wrapper around `str`. + unsafe { &*(s as *const str as *const Self) } + } + + pub fn is_empty(&self) -> bool { + self.0.is_empty() + } + + pub fn components(&self) -> RelPathComponents<'_> { + RelPathComponents(&self.0) + } + + pub fn ancestors(&self) -> RelPathAncestors<'_> { + RelPathAncestors(Some(&self.0)) + } + + pub fn file_name(&self) -> Option<&str> { + self.components().next_back() + } + + pub fn file_stem(&self) -> Option<&str> { + Some(self.as_std_path().file_stem()?.to_str().unwrap()) + } + + pub fn extension(&self) -> Option<&str> { + Some(self.as_std_path().extension()?.to_str().unwrap()) + } + + pub fn parent(&self) -> Option<&Self> { + let mut components = self.components(); + components.next_back()?; + Some(components.rest()) + } + + pub fn starts_with(&self, other: &Self) -> bool { + self.strip_prefix(other).is_ok() + } + + pub fn ends_with(&self, other: &Self) -> bool { + self.0 + .strip_suffix(&other.0) + .is_some_and(|suffix| suffix.ends_with('/') || suffix.is_empty()) + } + + pub fn strip_prefix<'a>(&'a self, other: &Self) -> Result<&'a Self, StripPrefixError> { + if other.is_empty() { + return Ok(self); + } + if let Some(suffix) = self.0.strip_prefix(&other.0) { + if let Some(suffix) = suffix.strip_prefix('/') { + return Ok(Self::new_unchecked(suffix)); + } else if suffix.is_empty() { + return Ok(Self::empty()); + } + } + Err(StripPrefixError) + } + + pub fn len(&self) -> usize { + self.0.matches('/').count() + 1 + } + + pub fn last_n_components(&self, count: usize) -> Option<&Self> { + let len = self.len(); + if len >= count { + let mut components = self.components(); + for _ in 0..(len - count) { + components.next()?; + } + Some(components.rest()) + } else { + None + } + } + + pub fn join(&self, other: &Self) -> Arc { + let result = if self.0.is_empty() { + Cow::Borrowed(&other.0) + } else if other.0.is_empty() { + Cow::Borrowed(&self.0) + } else { + Cow::Owned(format!("{}/{}", &self.0, &other.0)) + }; + Arc::from(Self::new_unchecked(result.as_ref())) + } + + pub fn to_rel_path_buf(&self) -> RelPathBuf { + RelPathBuf(self.0.to_string()) + } + + pub fn to_arc(&self) -> Arc { + Arc::from(self) + } + + /// Convert the path into the wire representation. + pub fn to_proto(&self) -> String { + self.as_unix_str().to_owned() + } + + /// Load the path from its wire representation. + pub fn from_proto(path: &str) -> Result> { + Ok(Arc::from(Self::unix(path)?)) + } + + /// Convert the path into a string with the given path style. + /// + /// Whenever a path is presented to the user, it should be converted to + /// a string via this method. + pub fn display(&self, style: PathStyle) -> Cow<'_, str> { + match style { + PathStyle::Posix => Cow::Borrowed(&self.0), + PathStyle::Windows if self.0.contains('/') => Cow::Owned(self.0.replace('/', "\\")), + PathStyle::Windows => Cow::Borrowed(&self.0), + } + } + + /// Get the internal unix-style representation of the path. + /// + /// This should not be shown to the user. + pub fn as_unix_str(&self) -> &str { + &self.0 + } + + /// Interprets the path as a [`std::path::Path`], suitable for file system calls. + /// + /// This is guaranteed to be a valid path regardless of the host platform, because + /// the `/` is accepted as a path separator on windows. + /// + /// This should not be shown to the user. + pub fn as_std_path(&self) -> &Path { + Path::new(&self.0) + } +} + +#[derive(Debug)] +pub struct StripPrefixError; + +impl std::fmt::Display for StripPrefixError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + f.write_str("prefix not found") + } +} + +impl std::error::Error for StripPrefixError {} + +impl ToOwned for RelPath { + type Owned = RelPathBuf; + + fn to_owned(&self) -> Self::Owned { + self.to_rel_path_buf() + } +} + +impl Borrow for RelPathBuf { + fn borrow(&self) -> &RelPath { + self.as_rel_path() + } +} + +impl PartialOrd for RelPath { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +impl Ord for RelPath { + fn cmp(&self, other: &Self) -> std::cmp::Ordering { + self.components().cmp(other.components()) + } +} + +impl fmt::Debug for RelPath { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.0, f) + } +} + +impl fmt::Debug for RelPathBuf { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + fmt::Debug::fmt(&self.0, f) + } +} + +impl Default for RelPathBuf { + fn default() -> Self { + Self::new() + } +} + +impl RelPathBuf { + pub fn new() -> Self { + Self(String::new()) + } + + pub fn pop(&mut self) -> bool { + if let Some(ix) = self.0.rfind('/') { + self.0.truncate(ix); + true + } else if !self.is_empty() { + self.0.clear(); + true + } else { + false + } + } + + pub fn push(&mut self, path: &RelPath) { + if !self.is_empty() { + self.0.push('/'); + } + self.0.push_str(&path.0); + } + + pub fn as_rel_path(&self) -> &RelPath { + RelPath::new_unchecked(self.0.as_str()) + } + + pub fn set_extension(&mut self, extension: &str) -> bool { + if let Some(filename) = self.file_name() { + let mut filename = PathBuf::from(filename); + filename.set_extension(extension); + self.pop(); + self.0.push_str(filename.to_str().unwrap()); + true + } else { + false + } + } +} + +impl<'de> Deserialize<'de> for RelPathBuf { + fn deserialize(deserializer: D) -> std::result::Result + where + D: serde::Deserializer<'de>, + { + let path = String::deserialize(deserializer)?; + let rel_path = + RelPath::new(Path::new(&path), PathStyle::local()).map_err(serde::de::Error::custom)?; + Ok(rel_path.into_owned()) + } +} + +impl From for Arc { + fn from(value: RelPathBuf) -> Self { + Arc::from(value.as_rel_path()) + } +} + +impl AsRef for RelPathBuf { + fn as_ref(&self) -> &Path { + self.as_std_path() + } +} + +impl AsRef for RelPath { + fn as_ref(&self) -> &Path { + self.as_std_path() + } +} + +impl AsRef for RelPathBuf { + fn as_ref(&self) -> &RelPath { + self.as_rel_path() + } +} + +impl AsRef for RelPath { + fn as_ref(&self) -> &RelPath { + self + } +} + +impl Deref for RelPathBuf { + type Target = RelPath; + + fn deref(&self) -> &Self::Target { + self.as_ref() + } +} + +impl<'a> From<&'a RelPath> for Cow<'a, RelPath> { + fn from(value: &'a RelPath) -> Self { + Self::Borrowed(value) + } +} + +impl From<&RelPath> for Arc { + fn from(rel_path: &RelPath) -> Self { + let bytes: Arc = Arc::from(&rel_path.0); + unsafe { Arc::from_raw(Arc::into_raw(bytes) as *const RelPath) } + } +} + +#[cfg(any(test, feature = "test-support"))] +#[track_caller] +pub fn rel_path(path: &str) -> &RelPath { + RelPath::unix(path).unwrap() +} + +#[cfg(any(test, feature = "test-support"))] +#[track_caller] +pub fn rel_path_buf(path: &str) -> RelPathBuf { + RelPath::unix(path).unwrap().to_rel_path_buf() +} + +impl PartialEq for RelPath { + fn eq(&self, other: &str) -> bool { + self.0 == *other + } +} + +pub trait PathExt { + fn to_rel_path_buf(&self) -> Result; +} + +impl + ?Sized> PathExt for T { + fn to_rel_path_buf(&self) -> Result { + Ok(RelPath::new(self.as_ref(), PathStyle::local())?.into_owned()) + } +} + +#[derive(Default)] +pub struct RelPathComponents<'a>(&'a str); + +pub struct RelPathAncestors<'a>(Option<&'a str>); + +const SEPARATOR: char = '/'; + +impl<'a> RelPathComponents<'a> { + pub fn rest(&self) -> &'a RelPath { + RelPath::new_unchecked(self.0) + } +} + +impl<'a> Iterator for RelPathComponents<'a> { + type Item = &'a str; + + fn next(&mut self) -> Option { + if let Some(sep_ix) = self.0.find(SEPARATOR) { + let (head, tail) = self.0.split_at(sep_ix); + self.0 = &tail[1..]; + Some(head) + } else if self.0.is_empty() { + None + } else { + let result = self.0; + self.0 = ""; + Some(result) + } + } +} + +impl<'a> Iterator for RelPathAncestors<'a> { + type Item = &'a RelPath; + + fn next(&mut self) -> Option { + let result = self.0?; + if let Some(sep_ix) = result.rfind(SEPARATOR) { + self.0 = Some(&result[..sep_ix]); + } else if !result.is_empty() { + self.0 = Some(""); + } else { + self.0 = None; + } + Some(RelPath::new_unchecked(result)) + } +} + +impl<'a> DoubleEndedIterator for RelPathComponents<'a> { + fn next_back(&mut self) -> Option { + if let Some(sep_ix) = self.0.rfind(SEPARATOR) { + let (head, tail) = self.0.split_at(sep_ix); + self.0 = head; + Some(&tail[1..]) + } else if self.0.is_empty() { + None + } else { + let result = self.0; + self.0 = ""; + Some(result) + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + use itertools::Itertools; + use pretty_assertions::assert_matches; + + #[test] + fn test_rel_path_new() { + assert!(RelPath::new(Path::new("/"), PathStyle::local()).is_err()); + assert!(RelPath::new(Path::new("//"), PathStyle::local()).is_err()); + assert!(RelPath::new(Path::new("/foo/"), PathStyle::local()).is_err()); + + let path = RelPath::new("foo/".as_ref(), PathStyle::local()).unwrap(); + assert_eq!(path, rel_path("foo").into()); + assert_matches!(path, Cow::Borrowed(_)); + + let path = RelPath::new("foo\\".as_ref(), PathStyle::Windows).unwrap(); + assert_eq!(path, rel_path("foo").into()); + assert_matches!(path, Cow::Borrowed(_)); + + assert_eq!( + RelPath::new("foo/bar/../baz/./quux/".as_ref(), PathStyle::local()) + .unwrap() + .as_ref(), + rel_path("foo/baz/quux") + ); + + let path = RelPath::new("./foo/bar".as_ref(), PathStyle::Posix).unwrap(); + assert_eq!(path.as_ref(), rel_path("foo/bar")); + assert_matches!(path, Cow::Borrowed(_)); + + let path = RelPath::new(".\\foo".as_ref(), PathStyle::Windows).unwrap(); + assert_eq!(path, rel_path("foo").into()); + assert_matches!(path, Cow::Borrowed(_)); + + let path = RelPath::new("./.\\./foo/\\/".as_ref(), PathStyle::Windows).unwrap(); + assert_eq!(path, rel_path("foo").into()); + assert_matches!(path, Cow::Borrowed(_)); + + let path = RelPath::new("foo/./bar".as_ref(), PathStyle::Posix).unwrap(); + assert_eq!(path.as_ref(), rel_path("foo/bar")); + assert_matches!(path, Cow::Owned(_)); + + let path = RelPath::new("./foo/bar".as_ref(), PathStyle::Windows).unwrap(); + assert_eq!(path.as_ref(), rel_path("foo/bar")); + assert_matches!(path, Cow::Borrowed(_)); + + let path = RelPath::new(".\\foo\\bar".as_ref(), PathStyle::Windows).unwrap(); + assert_eq!(path.as_ref(), rel_path("foo/bar")); + assert_matches!(path, Cow::Owned(_)); + } + + #[test] + fn test_rel_path_components() { + let path = rel_path("foo/bar/baz"); + assert_eq!( + path.components().collect::>(), + vec!["foo", "bar", "baz"] + ); + assert_eq!( + path.components().rev().collect::>(), + vec!["baz", "bar", "foo"] + ); + + let path = rel_path(""); + let mut components = path.components(); + assert_eq!(components.next(), None); + } + + #[test] + fn test_rel_path_ancestors() { + let path = rel_path("foo/bar/baz"); + let mut ancestors = path.ancestors(); + assert_eq!(ancestors.next(), Some(rel_path("foo/bar/baz"))); + assert_eq!(ancestors.next(), Some(rel_path("foo/bar"))); + assert_eq!(ancestors.next(), Some(rel_path("foo"))); + assert_eq!(ancestors.next(), Some(rel_path(""))); + assert_eq!(ancestors.next(), None); + + let path = rel_path("foo"); + let mut ancestors = path.ancestors(); + assert_eq!(ancestors.next(), Some(rel_path("foo"))); + assert_eq!(ancestors.next(), Some(RelPath::empty())); + assert_eq!(ancestors.next(), None); + + let path = RelPath::empty(); + let mut ancestors = path.ancestors(); + assert_eq!(ancestors.next(), Some(RelPath::empty())); + assert_eq!(ancestors.next(), None); + } + + #[test] + fn test_rel_path_parent() { + assert_eq!(rel_path("foo/bar/baz").parent(), Some(rel_path("foo/bar"))); + assert_eq!(rel_path("foo").parent(), Some(RelPath::empty())); + assert_eq!(rel_path("").parent(), None); + } + + #[test] + fn test_rel_path_partial_ord_is_compatible_with_std() { + let test_cases = ["a/b/c", "relative/path/with/dot.", "relative/path/with.dot"]; + for [lhs, rhs] in test_cases.iter().array_combinations::<2>() { + assert_eq!( + Path::new(lhs).cmp(Path::new(rhs)), + RelPath::unix(lhs).unwrap().cmp(RelPath::unix(rhs).unwrap()) + ); + } + } + + #[test] + fn test_strip_prefix() { + let parent = rel_path(""); + let child = rel_path(".foo"); + + assert!(child.starts_with(parent)); + assert_eq!(child.strip_prefix(parent).unwrap(), child); + } + + #[test] + fn test_rel_path_constructors_absolute_path() { + assert!(RelPath::new(Path::new("/a/b"), PathStyle::Windows).is_err()); + assert!(RelPath::new(Path::new("\\a\\b"), PathStyle::Windows).is_err()); + assert!(RelPath::new(Path::new("/a/b"), PathStyle::Posix).is_err()); + assert!(RelPath::new(Path::new("C:/a/b"), PathStyle::Windows).is_err()); + assert!(RelPath::new(Path::new("C:\\a\\b"), PathStyle::Windows).is_err()); + assert!(RelPath::new(Path::new("C:/a/b"), PathStyle::Posix).is_ok()); + } + + #[test] + fn test_pop() { + let mut path = rel_path("a/b").to_rel_path_buf(); + path.pop(); + assert_eq!(path.as_rel_path().as_unix_str(), "a"); + path.pop(); + assert_eq!(path.as_rel_path().as_unix_str(), ""); + path.pop(); + assert_eq!(path.as_rel_path().as_unix_str(), ""); + } +} diff --git a/crates/gpui_zed_util/src/schemars.rs b/crates/gpui_zed_util/src/schemars.rs new file mode 100644 index 0000000000..8124ca8cfe --- /dev/null +++ b/crates/gpui_zed_util/src/schemars.rs @@ -0,0 +1,72 @@ +use schemars::{JsonSchema, transform::transform_subschemas}; + +const DEFS_PATH: &str = "#/$defs/"; + +/// Replaces the JSON schema definition for some type if it is in use (in the definitions list), and +/// returns a reference to it. +/// +/// This asserts that JsonSchema::schema_name() + "2" does not exist because this indicates that +/// there are multiple types that use this name, and unfortunately schemars APIs do not support +/// resolving this ambiguity - see +/// +/// This takes a closure for `schema` because some settings types are not available on the remote +/// server, and so will crash when attempting to access e.g. GlobalThemeRegistry. +pub fn replace_subschema( + generator: &mut schemars::SchemaGenerator, + schema: impl Fn() -> schemars::Schema, +) -> schemars::Schema { + let schema_name = T::schema_name(); + let definitions = generator.definitions_mut(); + assert!(!definitions.contains_key(&format!("{schema_name}2"))); + assert!(definitions.contains_key(schema_name.as_ref())); + definitions.insert(schema_name.to_string(), schema().to_value()); + schemars::Schema::new_ref(format!("{DEFS_PATH}{schema_name}")) +} + +/// Adds a new JSON schema definition and returns a reference to it. **Panics** if the name is +/// already in use. +pub fn add_new_subschema( + generator: &mut schemars::SchemaGenerator, + name: &str, + schema: serde_json::Value, +) -> schemars::Schema { + let old_definition = generator.definitions_mut().insert(name.to_string(), schema); + assert_eq!(old_definition, None); + schemars::Schema::new_ref(format!("{DEFS_PATH}{name}")) +} + +/// Defaults `additionalProperties` to `true`, as if `#[schemars(deny_unknown_fields)]` was on every +/// struct. Skips structs that have `additionalProperties` set (such as if #[serde(flatten)] is used +/// on a map). +#[derive(Clone)] +pub struct DefaultDenyUnknownFields; + +impl schemars::transform::Transform for DefaultDenyUnknownFields { + fn transform(&mut self, schema: &mut schemars::Schema) { + if let Some(object) = schema.as_object_mut() + && object.contains_key("properties") + && !object.contains_key("additionalProperties") + && !object.contains_key("unevaluatedProperties") + { + object.insert("additionalProperties".to_string(), false.into()); + } + transform_subschemas(self, schema); + } +} + +/// Defaults `allowTrailingCommas` to `true`, for use with `json-language-server`. +/// This can be applied to any schema that will be treated as `jsonc`. +/// +/// Note that this is non-recursive and only applied to the root schema. +#[derive(Clone)] +pub struct AllowTrailingCommas; + +impl schemars::transform::Transform for AllowTrailingCommas { + fn transform(&mut self, schema: &mut schemars::Schema) { + if let Some(object) = schema.as_object_mut() + && !object.contains_key("allowTrailingCommas") + { + object.insert("allowTrailingCommas".to_string(), true.into()); + } + } +} diff --git a/crates/gpui_zed_util/src/serde.rs b/crates/gpui_zed_util/src/serde.rs new file mode 100644 index 0000000000..4aa4bb1a49 --- /dev/null +++ b/crates/gpui_zed_util/src/serde.rs @@ -0,0 +1,7 @@ +pub const fn default_true() -> bool { + true +} + +pub fn is_default(value: &T) -> bool { + *value == T::default() +} diff --git a/crates/gpui_zed_util/src/shell.rs b/crates/gpui_zed_util/src/shell.rs new file mode 100644 index 0000000000..31bb08586c --- /dev/null +++ b/crates/gpui_zed_util/src/shell.rs @@ -0,0 +1,1051 @@ +use schemars::JsonSchema; +use serde::{Deserialize, Serialize}; +use std::{borrow::Cow, fmt, path::Path, sync::LazyLock}; + +/// Shell configuration to open the terminal with. +#[derive(Clone, Debug, Default, Serialize, Deserialize, PartialEq, Eq, JsonSchema, Hash)] +#[serde(rename_all = "snake_case")] +pub enum Shell { + /// Use the system's default terminal configuration in /etc/passwd + #[default] + System, + /// Use a specific program with no arguments. + Program(String), + /// Use a specific program with arguments. + WithArguments { + /// The program to run. + program: String, + /// The arguments to pass to the program. + args: Vec, + /// An optional string to override the title of the terminal tab + title_override: Option, + }, +} + +impl Shell { + pub fn program(&self) -> String { + match self { + Shell::Program(program) => program.clone(), + Shell::WithArguments { program, .. } => program.clone(), + Shell::System => get_system_shell(), + } + } + + pub fn program_and_args(&self) -> (String, &[String]) { + match self { + Shell::Program(program) => (program.clone(), &[]), + Shell::WithArguments { program, args, .. } => (program.clone(), args), + Shell::System => (get_system_shell(), &[]), + } + } + + pub fn shell_kind(&self, is_windows: bool) -> ShellKind { + match self { + Shell::Program(program) => ShellKind::new(program, is_windows), + Shell::WithArguments { program, .. } => ShellKind::new(program, is_windows), + Shell::System => ShellKind::system(), + } + } +} + +#[derive(Debug, Default, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)] +pub enum ShellKind { + #[default] + Posix, + Csh, + Tcsh, + Rc, + Fish, + /// Pre-installed "legacy" powershell for windows + PowerShell, + /// PowerShell 7.x + Pwsh, + Nushell, + Cmd, + Xonsh, + Elvish, +} + +pub fn get_system_shell() -> String { + if cfg!(windows) { + get_windows_system_shell() + } else { + std::env::var("SHELL").unwrap_or("/bin/sh".to_string()) + } +} + +pub fn get_default_system_shell() -> String { + if cfg!(windows) { + get_windows_system_shell() + } else { + "/bin/sh".to_string() + } +} + +/// Get the default system shell, preferring bash on Windows. +pub fn get_default_system_shell_preferring_bash() -> String { + if cfg!(windows) { + get_windows_bash().unwrap_or_else(get_windows_system_shell) + } else { + "/bin/sh".to_string() + } +} + +pub fn get_windows_bash() -> Option { + use std::path::PathBuf; + + fn find_bash_in_scoop() -> Option { + let bash_exe = + PathBuf::from(std::env::var_os("USERPROFILE")?).join("scoop\\shims\\bash.exe"); + bash_exe.exists().then_some(bash_exe) + } + + fn find_bash_in_git() -> Option { + // /path/to/git/cmd/git.exe/../../bin/bash.exe + let git = which::which("git").ok()?; + let git_bash = git.parent()?.parent()?.join("bin").join("bash.exe"); + git_bash.exists().then_some(git_bash) + } + + static BASH: LazyLock> = LazyLock::new(|| { + let bash = find_bash_in_scoop() + .or_else(find_bash_in_git) + .map(|p| p.to_string_lossy().into_owned()); + if let Some(ref path) = bash { + log::info!("Found bash at {}", path); + } + bash + }); + + (*BASH).clone() +} + +pub fn get_windows_system_shell() -> String { + use std::path::PathBuf; + + fn find_pwsh_in_programfiles(find_alternate: bool, find_preview: bool) -> Option { + #[cfg(target_pointer_width = "64")] + let env_var = if find_alternate { + "ProgramFiles(x86)" + } else { + "ProgramFiles" + }; + + #[cfg(target_pointer_width = "32")] + let env_var = if find_alternate { + "ProgramW6432" + } else { + "ProgramFiles" + }; + + let install_base_dir = PathBuf::from(std::env::var_os(env_var)?).join("PowerShell"); + install_base_dir + .read_dir() + .ok()? + .filter_map(Result::ok) + .filter(|entry| matches!(entry.file_type(), Ok(ft) if ft.is_dir())) + .filter_map(|entry| { + let dir_name = entry.file_name(); + let dir_name = dir_name.to_string_lossy(); + + let version = if find_preview { + let dash_index = dir_name.find('-')?; + if &dir_name[dash_index + 1..] != "preview" { + return None; + }; + dir_name[..dash_index].parse::().ok()? + } else { + dir_name.parse::().ok()? + }; + + let exe_path = entry.path().join("pwsh.exe"); + if exe_path.exists() { + Some((version, exe_path)) + } else { + None + } + }) + .max_by_key(|(version, _)| *version) + .map(|(_, path)| path) + } + + fn find_pwsh_in_msix(find_preview: bool) -> Option { + let msix_app_dir = + PathBuf::from(std::env::var_os("LOCALAPPDATA")?).join("Microsoft\\WindowsApps"); + if !msix_app_dir.exists() { + return None; + } + + let prefix = if find_preview { + "Microsoft.PowerShellPreview_" + } else { + "Microsoft.PowerShell_" + }; + msix_app_dir + .read_dir() + .ok()? + .filter_map(|entry| { + let entry = entry.ok()?; + if !matches!(entry.file_type(), Ok(ft) if ft.is_dir()) { + return None; + } + + if !entry.file_name().to_string_lossy().starts_with(prefix) { + return None; + } + + let exe_path = entry.path().join("pwsh.exe"); + exe_path.exists().then_some(exe_path) + }) + .next() + } + + fn find_pwsh_in_scoop() -> Option { + let pwsh_exe = + PathBuf::from(std::env::var_os("USERPROFILE")?).join("scoop\\shims\\pwsh.exe"); + pwsh_exe.exists().then_some(pwsh_exe) + } + + static SYSTEM_SHELL: LazyLock = LazyLock::new(|| { + let locations = [ + || find_pwsh_in_programfiles(false, false), + || find_pwsh_in_programfiles(true, false), + || find_pwsh_in_msix(false), + || find_pwsh_in_programfiles(false, true), + || find_pwsh_in_msix(true), + || find_pwsh_in_programfiles(true, true), + || find_pwsh_in_scoop(), + || which::which_global("pwsh.exe").ok(), + || which::which_global("powershell.exe").ok(), + ]; + + locations + .into_iter() + .find_map(|f| f()) + .map(|p| p.to_string_lossy().trim().to_owned()) + .inspect(|shell| log::info!("Found powershell in: {}", shell)) + .unwrap_or_else(|| { + log::warn!("Powershell not found, falling back to `cmd`"); + "cmd.exe".to_string() + }) + }); + + (*SYSTEM_SHELL).clone() +} + +impl fmt::Display for ShellKind { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + match self { + ShellKind::Posix => write!(f, "sh"), + ShellKind::Csh => write!(f, "csh"), + ShellKind::Tcsh => write!(f, "tcsh"), + ShellKind::Fish => write!(f, "fish"), + ShellKind::PowerShell => write!(f, "powershell"), + ShellKind::Pwsh => write!(f, "pwsh"), + ShellKind::Nushell => write!(f, "nu"), + ShellKind::Cmd => write!(f, "cmd"), + ShellKind::Rc => write!(f, "rc"), + ShellKind::Xonsh => write!(f, "xonsh"), + ShellKind::Elvish => write!(f, "elvish"), + } + } +} + +impl ShellKind { + pub fn system() -> Self { + Self::new(get_system_shell(), cfg!(windows)) + } + + /// Returns whether this shell's command chaining syntax can be parsed by brush-parser. + /// + /// This is used to determine if we can safely parse shell commands to extract sub-commands + /// for security purposes (e.g., preventing shell injection in "always allow" patterns). + /// + /// The brush-parser handles `;` (sequential execution) and `|` (piping), which are + /// supported by all common shells. It also handles `&&` and `||` for conditional + /// execution, `$()` and backticks for command substitution, and process substitution. + /// + /// # Shell Notes + /// + /// - **Nushell**: Uses `;` for sequential execution. The `and`/`or` keywords are boolean + /// operators on values (e.g., `$true and $false`), not command chaining operators. + /// - **Elvish**: Uses `;` to separate pipelines, which brush-parser handles. Elvish does + /// not have `&&` or `||` operators. Its `and`/`or` are special commands that operate + /// on values, not command chaining (e.g., `and $true $false`). + /// - **Rc (Plan 9)**: Uses `;` for sequential execution and `|` for piping. Does not + /// have `&&`/`||` operators for conditional chaining. + /// All current shell variants are listed here because brush-parser can handle + /// their syntax. If a new `ShellKind` variant is added, evaluate whether + /// brush-parser can safely parse its command chaining syntax before including + /// it. Omitting a variant will cause `tool_permissions::from_input` to deny + /// terminal commands that have `always_allow` patterns configured. + pub fn supports_posix_chaining(&self) -> bool { + matches!( + self, + ShellKind::Posix + | ShellKind::Fish + | ShellKind::PowerShell + | ShellKind::Pwsh + | ShellKind::Cmd + | ShellKind::Xonsh + | ShellKind::Csh + | ShellKind::Tcsh + | ShellKind::Nushell + | ShellKind::Elvish + | ShellKind::Rc + ) + } + + pub fn new(program: impl AsRef, is_windows: bool) -> Self { + let program = program.as_ref(); + let program = program + .file_stem() + .unwrap_or(program.as_os_str()) + .to_string_lossy(); + + match &*program { + "powershell" => ShellKind::PowerShell, + "pwsh" => ShellKind::Pwsh, + "cmd" => ShellKind::Cmd, + "nu" => ShellKind::Nushell, + "fish" => ShellKind::Fish, + "csh" => ShellKind::Csh, + "tcsh" => ShellKind::Tcsh, + "rc" => ShellKind::Rc, + "xonsh" => ShellKind::Xonsh, + "elvish" => ShellKind::Elvish, + "sh" | "bash" | "zsh" => ShellKind::Posix, + _ if is_windows => ShellKind::PowerShell, + // Some other shell detected, the user might install and use a + // unix-like shell. + _ => ShellKind::Posix, + } + } + + pub fn to_shell_variable(self, input: &str) -> String { + match self { + Self::PowerShell | Self::Pwsh => Self::to_powershell_variable(input), + Self::Cmd => Self::to_cmd_variable(input), + Self::Posix => input.to_owned(), + Self::Fish => input.to_owned(), + Self::Csh => input.to_owned(), + Self::Tcsh => input.to_owned(), + Self::Rc => input.to_owned(), + Self::Nushell => Self::to_nushell_variable(input), + Self::Xonsh => input.to_owned(), + Self::Elvish => input.to_owned(), + } + } + + fn to_cmd_variable(input: &str) -> String { + if let Some(var_str) = input.strip_prefix("${") { + if var_str.find(':').is_none() { + // If the input starts with "${", remove the trailing "}" + format!("%{}%", &var_str[..var_str.len() - 1]) + } else { + // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation, + // which will result in the task failing to run in such cases. + input.into() + } + } else if let Some(var_str) = input.strip_prefix('$') { + // If the input starts with "$", directly append to "$env:" + format!("%{}%", var_str) + } else { + // If no prefix is found, return the input as is + input.into() + } + } + + fn to_powershell_variable(input: &str) -> String { + if let Some(var_str) = input.strip_prefix("${") { + if var_str.find(':').is_none() { + // If the input starts with "${", remove the trailing "}" + format!("$env:{}", &var_str[..var_str.len() - 1]) + } else { + // `${SOME_VAR:-SOME_DEFAULT}`, we currently do not handle this situation, + // which will result in the task failing to run in such cases. + input.into() + } + } else if let Some(var_str) = input.strip_prefix('$') { + // If the input starts with "$", directly append to "$env:" + format!("$env:{}", var_str) + } else { + // If no prefix is found, return the input as is + input.into() + } + } + + fn to_nushell_variable(input: &str) -> String { + let mut result = String::new(); + let mut source = input; + let mut is_start = true; + + loop { + match source.chars().next() { + None => return result, + Some('$') => { + source = Self::parse_nushell_var(&source[1..], &mut result, is_start); + is_start = false; + } + Some(_) => { + is_start = false; + let chunk_end = source.find('$').unwrap_or(source.len()); + let (chunk, rest) = source.split_at(chunk_end); + result.push_str(chunk); + source = rest; + } + } + } + } + + fn parse_nushell_var<'a>(source: &'a str, text: &mut String, is_start: bool) -> &'a str { + if source.starts_with("env.") { + text.push('$'); + return source; + } + + match source.chars().next() { + Some('{') => { + let source = &source[1..]; + if let Some(end) = source.find('}') { + let var_name = &source[..end]; + if !var_name.is_empty() { + if !is_start { + text.push('('); + } + text.push_str("$env."); + text.push_str(var_name); + if !is_start { + text.push(')'); + } + &source[end + 1..] + } else { + text.push_str("${}"); + &source[end + 1..] + } + } else { + text.push_str("${"); + source + } + } + Some(c) if c.is_alphabetic() || c == '_' => { + let end = source + .find(|c: char| !c.is_alphanumeric() && c != '_') + .unwrap_or(source.len()); + let var_name = &source[..end]; + if !is_start { + text.push('('); + } + text.push_str("$env."); + text.push_str(var_name); + if !is_start { + text.push(')'); + } + &source[end..] + } + _ => { + text.push('$'); + source + } + } + } + + pub fn args_for_shell(&self, interactive: bool, combined_command: String) -> Vec { + match self { + ShellKind::PowerShell | ShellKind::Pwsh => vec!["-C".to_owned(), combined_command], + ShellKind::Cmd => vec![ + "/S".to_owned(), + "/C".to_owned(), + format!("\"{combined_command}\""), + ], + ShellKind::Posix + | ShellKind::Nushell + | ShellKind::Fish + | ShellKind::Csh + | ShellKind::Tcsh + | ShellKind::Rc + | ShellKind::Xonsh + | ShellKind::Elvish => interactive + .then(|| "-i".to_owned()) + .into_iter() + .chain(["-c".to_owned(), combined_command]) + .collect(), + } + } + + pub const fn command_prefix(&self) -> Option { + match self { + ShellKind::PowerShell | ShellKind::Pwsh => Some('&'), + ShellKind::Nushell => Some('^'), + ShellKind::Posix + | ShellKind::Csh + | ShellKind::Tcsh + | ShellKind::Rc + | ShellKind::Fish + | ShellKind::Cmd + | ShellKind::Xonsh + | ShellKind::Elvish => None, + } + } + + pub fn prepend_command_prefix<'a>(&self, command: &'a str) -> Cow<'a, str> { + match self.command_prefix() { + Some(prefix) if !command.starts_with(prefix) => { + Cow::Owned(format!("{prefix}{command}")) + } + _ => Cow::Borrowed(command), + } + } + + pub const fn sequential_commands_separator(&self) -> char { + match self { + ShellKind::Cmd => '&', + ShellKind::Posix + | ShellKind::Csh + | ShellKind::Tcsh + | ShellKind::Rc + | ShellKind::Fish + | ShellKind::PowerShell + | ShellKind::Pwsh + | ShellKind::Nushell + | ShellKind::Xonsh + | ShellKind::Elvish => ';', + } + } + + pub const fn sequential_and_commands_separator(&self) -> &'static str { + match self { + ShellKind::Cmd + | ShellKind::Posix + | ShellKind::Csh + | ShellKind::Tcsh + | ShellKind::Rc + | ShellKind::Fish + | ShellKind::Pwsh + | ShellKind::Xonsh => "&&", + ShellKind::PowerShell | ShellKind::Nushell | ShellKind::Elvish => ";", + } + } + + pub fn try_quote<'a>(&self, arg: &'a str) -> Option> { + match self { + ShellKind::PowerShell => Some(Self::quote_powershell(arg)), + ShellKind::Pwsh => Some(Self::quote_pwsh(arg)), + ShellKind::Cmd => Some(Self::quote_cmd(arg)), + ShellKind::Posix + | ShellKind::Csh + | ShellKind::Tcsh + | ShellKind::Rc + | ShellKind::Fish + | ShellKind::Nushell + | ShellKind::Xonsh + | ShellKind::Elvish => shlex::try_quote(arg).ok(), + } + } + + fn quote_windows(arg: &str, enclose: bool) -> Cow<'_, str> { + if arg.is_empty() { + return Cow::Borrowed("\"\""); + } + + let needs_quoting = arg.chars().any(|c| c == ' ' || c == '\t' || c == '"'); + if !needs_quoting { + return Cow::Borrowed(arg); + } + + let mut result = String::with_capacity(arg.len() + 2); + + if enclose { + result.push('"'); + } + + let chars: Vec = arg.chars().collect(); + let mut i = 0; + + while i < chars.len() { + if chars[i] == '\\' { + let mut num_backslashes = 0; + while i < chars.len() && chars[i] == '\\' { + num_backslashes += 1; + i += 1; + } + + if i < chars.len() && chars[i] == '"' { + // Backslashes followed by quote: double the backslashes and escape the quote + for _ in 0..(num_backslashes * 2 + 1) { + result.push('\\'); + } + result.push('"'); + i += 1; + } else if i >= chars.len() { + // Trailing backslashes: double them (they precede the closing quote) + for _ in 0..(num_backslashes * 2) { + result.push('\\'); + } + } else { + // Backslashes not followed by quote: output as-is + for _ in 0..num_backslashes { + result.push('\\'); + } + } + } else if chars[i] == '"' { + // Quote not preceded by backslash: escape it + result.push('\\'); + result.push('"'); + i += 1; + } else { + result.push(chars[i]); + i += 1; + } + } + + if enclose { + result.push('"'); + } + Cow::Owned(result) + } + + fn needs_quoting_powershell(s: &str) -> bool { + s.is_empty() + || s.chars().any(|c| { + c.is_whitespace() + || matches!( + c, + '"' | '`' + | '$' + | '&' + | '|' + | '<' + | '>' + | ';' + | '(' + | ')' + | '[' + | ']' + | '{' + | '}' + | ',' + | '\'' + | '@' + ) + }) + } + + fn need_quotes_powershell(arg: &str) -> bool { + let mut quote_count = 0; + for c in arg.chars() { + if c == '"' { + quote_count += 1; + } else if c.is_whitespace() && (quote_count % 2 == 0) { + return true; + } + } + false + } + + fn escape_powershell_quotes(s: &str) -> String { + let mut result = String::with_capacity(s.len() + 4); + result.push('\''); + for c in s.chars() { + if c == '\'' { + result.push('\''); + } + result.push(c); + } + result.push('\''); + result + } + + pub fn quote_powershell(arg: &str) -> Cow<'_, str> { + let ps_will_quote = Self::need_quotes_powershell(arg); + let crt_quoted = Self::quote_windows(arg, !ps_will_quote); + + if !Self::needs_quoting_powershell(arg) { + return crt_quoted; + } + + Cow::Owned(Self::escape_powershell_quotes(&crt_quoted)) + } + + pub fn quote_pwsh(arg: &str) -> Cow<'_, str> { + if arg.is_empty() { + return Cow::Borrowed("''"); + } + + if !Self::needs_quoting_powershell(arg) { + return Cow::Borrowed(arg); + } + + Cow::Owned(Self::escape_powershell_quotes(arg)) + } + + pub fn quote_cmd(arg: &str) -> Cow<'_, str> { + let crt_quoted = Self::quote_windows(arg, true); + + let needs_cmd_escaping = crt_quoted.contains(['"', '%', '^', '<', '>', '&', '|', '(', ')']); + + if !needs_cmd_escaping { + return crt_quoted; + } + + let mut result = String::with_capacity(crt_quoted.len() * 2); + for c in crt_quoted.chars() { + match c { + '^' | '"' | '<' | '>' | '&' | '|' | '(' | ')' => { + result.push('^'); + result.push(c); + } + '%' => { + result.push_str("%%cd:~,%"); + } + _ => result.push(c), + } + } + Cow::Owned(result) + } + + /// Quotes the given argument if necessary, taking into account the command prefix. + /// + /// In other words, this will consider quoting arg without its command prefix to not break the command. + /// You should use this over `try_quote` when you want to quote a shell command. + pub fn try_quote_prefix_aware<'a>(&self, arg: &'a str) -> Option> { + if let Some(char) = self.command_prefix() + && let Some(arg) = arg.strip_prefix(char) + { + // we have a command that is prefixed + for quote in ['\'', '"'] { + if let Some(arg) = arg + .strip_prefix(quote) + .and_then(|arg| arg.strip_suffix(quote)) + { + // and the command itself is wrapped as a literal, that + // means the prefix exists to interpret a literal as a + // command. So strip the quotes, quote the command, and + // re-add the quotes if they are missing after requoting + let quoted = self.try_quote(arg)?; + return Some(if quoted.starts_with(['\'', '"']) { + Cow::Owned(self.prepend_command_prefix("ed).into_owned()) + } else { + Cow::Owned( + self.prepend_command_prefix(&format!("{quote}{quoted}{quote}")) + .into_owned(), + ) + }); + } + } + return self + .try_quote(arg) + .map(|quoted| Cow::Owned(self.prepend_command_prefix("ed).into_owned())); + } + self.try_quote(arg).map(|quoted| match quoted { + unquoted @ Cow::Borrowed(_) => unquoted, + Cow::Owned(quoted) => Cow::Owned(self.prepend_command_prefix("ed).into_owned()), + }) + } + + pub fn split(&self, input: &str) -> Option> { + shlex::split(input) + } + + pub const fn activate_keyword(&self) -> &'static str { + match self { + ShellKind::Cmd => "", + ShellKind::Nushell => "overlay use", + ShellKind::PowerShell | ShellKind::Pwsh => ".", + ShellKind::Fish + | ShellKind::Csh + | ShellKind::Tcsh + | ShellKind::Posix + | ShellKind::Rc + | ShellKind::Xonsh + | ShellKind::Elvish => "source", + } + } + + pub const fn clear_screen_command(&self) -> &'static str { + match self { + ShellKind::Cmd => "cls", + ShellKind::Posix + | ShellKind::Csh + | ShellKind::Tcsh + | ShellKind::Rc + | ShellKind::Fish + | ShellKind::PowerShell + | ShellKind::Pwsh + | ShellKind::Nushell + | ShellKind::Xonsh + | ShellKind::Elvish => "clear", + } + } + + #[cfg(windows)] + /// We do not want to escape arguments if we are using CMD as our shell. + /// If we do we end up with too many quotes/escaped quotes for CMD to handle. + pub const fn tty_escape_args(&self) -> bool { + match self { + ShellKind::Cmd => false, + ShellKind::Posix + | ShellKind::Csh + | ShellKind::Tcsh + | ShellKind::Rc + | ShellKind::Fish + | ShellKind::PowerShell + | ShellKind::Pwsh + | ShellKind::Nushell + | ShellKind::Xonsh + | ShellKind::Elvish => true, + } + } +} + +#[cfg(test)] +mod tests { + use super::*; + + // Examples + // WSL + // wsl.exe --distribution NixOS --cd /home/user -- /usr/bin/zsh -c "echo hello" + // wsl.exe --distribution NixOS --cd /home/user -- /usr/bin/zsh -c "\"echo hello\"" | grep hello" + // wsl.exe --distribution NixOS --cd ~ env RUST_LOG=info,remote=debug .zed_wsl_server/zed-remote-server-dev-build proxy --identifier dev-workspace-53 + // PowerShell from Nushell + // nu -c overlay use "C:\Users\kubko\dev\python\39007\tests\.venv\Scripts\activate.nu"; ^"C:\Program Files\PowerShell\7\pwsh.exe" -C "C:\Users\kubko\dev\python\39007\tests\.venv\Scripts\python.exe -m pytest \"test_foo.py::test_foo\"" + // PowerShell from CMD + // cmd /C \" \"C:\\\\Users\\\\kubko\\\\dev\\\\python\\\\39007\\\\tests\\\\.venv\\\\Scripts\\\\activate.bat\"& \"C:\\\\Program Files\\\\PowerShell\\\\7\\\\pwsh.exe\" -C \"C:\\\\Users\\\\kubko\\\\dev\\\\python\\\\39007\\\\tests\\\\.venv\\\\Scripts\\\\python.exe -m pytest \\\"test_foo.py::test_foo\\\"\"\" + + #[test] + fn test_try_quote_powershell() { + let shell_kind = ShellKind::PowerShell; + assert_eq!( + shell_kind + .try_quote("C:\\Users\\johndoe\\dev\\python\\39007\\tests\\.venv\\Scripts\\python.exe -m pytest \"test_foo.py::test_foo\"") + .unwrap() + .into_owned(), + "'C:\\Users\\johndoe\\dev\\python\\39007\\tests\\.venv\\Scripts\\python.exe -m pytest \\\"test_foo.py::test_foo\\\"'".to_string() + ); + } + + #[test] + fn test_try_quote_cmd() { + let shell_kind = ShellKind::Cmd; + assert_eq!( + shell_kind + .try_quote("C:\\Users\\johndoe\\dev\\python\\39007\\tests\\.venv\\Scripts\\python.exe -m pytest \"test_foo.py::test_foo\"") + .unwrap() + .into_owned(), + "^\"C:\\Users\\johndoe\\dev\\python\\39007\\tests\\.venv\\Scripts\\python.exe -m pytest \\^\"test_foo.py::test_foo\\^\"^\"".to_string() + ); + } + + #[test] + fn test_try_quote_powershell_edge_cases() { + let shell_kind = ShellKind::PowerShell; + + // Empty string + assert_eq!( + shell_kind.try_quote("").unwrap().into_owned(), + "'\"\"'".to_string() + ); + + // String without special characters (no quoting needed) + assert_eq!(shell_kind.try_quote("simple").unwrap(), "simple"); + + // String with spaces + assert_eq!( + shell_kind.try_quote("hello world").unwrap().into_owned(), + "'hello world'".to_string() + ); + + // String with dollar signs + assert_eq!( + shell_kind.try_quote("$variable").unwrap().into_owned(), + "'$variable'".to_string() + ); + + // String with backticks + assert_eq!( + shell_kind.try_quote("test`command").unwrap().into_owned(), + "'test`command'".to_string() + ); + + // String with multiple special characters + assert_eq!( + shell_kind + .try_quote("test `\"$var`\" end") + .unwrap() + .into_owned(), + "'test `\\\"$var`\\\" end'".to_string() + ); + + // String with backslashes and colon (path without spaces doesn't need quoting) + assert_eq!( + shell_kind.try_quote("C:\\path\\to\\file").unwrap(), + "C:\\path\\to\\file" + ); + } + + #[test] + fn test_try_quote_cmd_edge_cases() { + let shell_kind = ShellKind::Cmd; + + // Empty string + assert_eq!( + shell_kind.try_quote("").unwrap().into_owned(), + "^\"^\"".to_string() + ); + + // String without special characters (no quoting needed) + assert_eq!(shell_kind.try_quote("simple").unwrap(), "simple"); + + // String with spaces + assert_eq!( + shell_kind.try_quote("hello world").unwrap().into_owned(), + "^\"hello world^\"".to_string() + ); + + // String with space and backslash (backslash not at end, so not doubled) + assert_eq!( + shell_kind.try_quote("path\\ test").unwrap().into_owned(), + "^\"path\\ test^\"".to_string() + ); + + // String ending with backslash (must be doubled before closing quote) + assert_eq!( + shell_kind.try_quote("test path\\").unwrap().into_owned(), + "^\"test path\\\\^\"".to_string() + ); + + // String ending with multiple backslashes (all doubled before closing quote) + assert_eq!( + shell_kind.try_quote("test path\\\\").unwrap().into_owned(), + "^\"test path\\\\\\\\^\"".to_string() + ); + + // String with embedded quote (quote is escaped, backslash before it is doubled) + assert_eq!( + shell_kind.try_quote("test\\\"quote").unwrap().into_owned(), + "^\"test\\\\\\^\"quote^\"".to_string() + ); + + // String with multiple backslashes before embedded quote (all doubled) + assert_eq!( + shell_kind + .try_quote("test\\\\\"quote") + .unwrap() + .into_owned(), + "^\"test\\\\\\\\\\^\"quote^\"".to_string() + ); + + // String with backslashes not before quotes (path without spaces doesn't need quoting) + assert_eq!( + shell_kind.try_quote("C:\\path\\to\\file").unwrap(), + "C:\\path\\to\\file" + ); + } + + #[test] + fn test_try_quote_nu_command() { + let shell_kind = ShellKind::Nushell; + assert_eq!( + shell_kind.try_quote("'uname'").unwrap().into_owned(), + "\"'uname'\"".to_string() + ); + assert_eq!( + shell_kind + .try_quote_prefix_aware("'uname'") + .unwrap() + .into_owned(), + "^\"'uname'\"".to_string() + ); + assert_eq!( + shell_kind.try_quote("^uname").unwrap().into_owned(), + "'^uname'".to_string() + ); + assert_eq!( + shell_kind + .try_quote_prefix_aware("^uname") + .unwrap() + .into_owned(), + "^uname".to_string() + ); + assert_eq!( + shell_kind.try_quote("^'uname'").unwrap().into_owned(), + "'^'\"'uname\'\"".to_string() + ); + assert_eq!( + shell_kind + .try_quote_prefix_aware("^'uname'") + .unwrap() + .into_owned(), + "^'uname'".to_string() + ); + assert_eq!( + shell_kind.try_quote("'uname a'").unwrap().into_owned(), + "\"'uname a'\"".to_string() + ); + assert_eq!( + shell_kind + .try_quote_prefix_aware("'uname a'") + .unwrap() + .into_owned(), + "^\"'uname a'\"".to_string() + ); + assert_eq!( + shell_kind.try_quote("^'uname a'").unwrap().into_owned(), + "'^'\"'uname a'\"".to_string() + ); + assert_eq!( + shell_kind + .try_quote_prefix_aware("^'uname a'") + .unwrap() + .into_owned(), + "^'uname a'".to_string() + ); + assert_eq!( + shell_kind.try_quote("uname").unwrap().into_owned(), + "uname".to_string() + ); + assert_eq!( + shell_kind + .try_quote_prefix_aware("uname") + .unwrap() + .into_owned(), + "uname".to_string() + ); + } + + #[test] + fn test_try_quote_single_quote_paths() { + let path_with_quote = r"C:\Temp\O'Brien\repo"; + let shlex_shells = [ + ShellKind::Posix, + ShellKind::Fish, + ShellKind::Csh, + ShellKind::Tcsh, + ShellKind::Rc, + ShellKind::Xonsh, + ShellKind::Elvish, + ShellKind::Nushell, + ]; + + for shell_kind in shlex_shells { + let quoted = shell_kind.try_quote(path_with_quote).unwrap().into_owned(); + assert_ne!(quoted, path_with_quote); + assert_eq!( + shlex::split("ed), + Some(vec![path_with_quote.to_string()]) + ); + + if shell_kind == ShellKind::Nushell { + let prefixed = shell_kind.prepend_command_prefix("ed); + assert!(prefixed.starts_with('^')); + } + } + + for shell_kind in [ShellKind::PowerShell, ShellKind::Pwsh] { + let quoted = shell_kind.try_quote(path_with_quote).unwrap().into_owned(); + assert!(quoted.starts_with('\'')); + assert!(quoted.ends_with('\'')); + assert!(quoted.contains("O''Brien")); + } + } +} diff --git a/crates/gpui_zed_util/src/shell_builder.rs b/crates/gpui_zed_util/src/shell_builder.rs new file mode 100644 index 0000000000..1d488d4456 --- /dev/null +++ b/crates/gpui_zed_util/src/shell_builder.rs @@ -0,0 +1,327 @@ +use std::borrow::Cow; + +use crate::shell::get_system_shell; +use crate::shell::{Shell, ShellKind}; + +/// ShellBuilder is used to turn a user-requested task into a +/// program that can be executed by the shell. +pub struct ShellBuilder { + /// The shell to run + program: String, + args: Vec, + interactive: bool, + /// Whether to redirect stdin to /dev/null for the spawned command as a subshell. + redirect_stdin: bool, + kind: ShellKind, +} + +impl ShellBuilder { + /// Create a new ShellBuilder as configured. + pub fn new(shell: &Shell, is_windows: bool) -> Self { + let (program, args) = match shell { + Shell::System => (get_system_shell(), Vec::new()), + Shell::Program(shell) => (shell.clone(), Vec::new()), + Shell::WithArguments { program, args, .. } => (program.clone(), args.clone()), + }; + + let kind = ShellKind::new(&program, is_windows); + Self { + program, + args, + interactive: true, + kind, + redirect_stdin: false, + } + } + pub fn non_interactive(mut self) -> Self { + self.interactive = false; + self + } + + /// Returns the label to show in the terminal tab + pub fn command_label(&self, command_to_use_in_label: &str) -> String { + if command_to_use_in_label.trim().is_empty() { + self.program.clone() + } else { + match self.kind { + ShellKind::PowerShell | ShellKind::Pwsh => { + format!("{} -C '{}'", self.program, command_to_use_in_label) + } + ShellKind::Cmd => { + format!("{} /C \"{}\"", self.program, command_to_use_in_label) + } + ShellKind::Posix + | ShellKind::Nushell + | ShellKind::Fish + | ShellKind::Csh + | ShellKind::Tcsh + | ShellKind::Rc + | ShellKind::Xonsh + | ShellKind::Elvish => { + let interactivity = if self.interactive { "-i " } else { "" }; + format!( + "{PROGRAM} {interactivity}-c '{command_to_use_in_label}'", + PROGRAM = self.program + ) + } + } + } + } + + pub fn redirect_stdin_to_dev_null(mut self) -> Self { + self.redirect_stdin = true; + self + } + + /// Returns the program and arguments to run this task in a shell. + pub fn build( + mut self, + task_command: Option, + task_args: &[String], + ) -> (String, Vec) { + if let Some(task_command) = task_command { + let task_command = if !task_args.is_empty() { + match self.kind.try_quote_prefix_aware(&task_command) { + Some(task_command) => task_command.into_owned(), + None => task_command, + } + } else { + task_command + }; + let mut combined_command = task_args.iter().fold(task_command, |mut command, arg| { + command.push(' '); + let shell_variable = self.kind.to_shell_variable(arg); + command.push_str(&match self.kind.try_quote(&shell_variable) { + Some(shell_variable) => shell_variable, + None => Cow::Owned(shell_variable), + }); + command + }); + if self.redirect_stdin { + match self.kind { + ShellKind::Fish => { + combined_command.insert_str(0, "begin; "); + combined_command.push_str("; end { + combined_command.insert(0, '('); + combined_command.push_str("\n) { + combined_command.insert_str(0, "$null | & {"); + combined_command.push('}'); + } + ShellKind::Cmd => { + combined_command.push_str("< NUL"); + } + } + } + + self.args + .extend(self.kind.args_for_shell(self.interactive, combined_command)); + } + + (self.program, self.args) + } + + // This should not exist, but our task infra is broken beyond repair right now + #[doc(hidden)] + pub fn build_no_quote( + mut self, + task_command: Option, + task_args: &[String], + ) -> (String, Vec) { + if let Some(task_command) = task_command { + let mut combined_command = task_args.iter().fold(task_command, |mut command, arg| { + command.push(' '); + command.push_str(&self.kind.to_shell_variable(arg)); + command + }); + if self.redirect_stdin { + match self.kind { + ShellKind::Fish => { + combined_command.insert_str(0, "begin; "); + combined_command.push_str("; end { + combined_command.insert(0, '('); + combined_command.push_str("\n) { + combined_command.insert_str(0, "$null | & {"); + combined_command.push('}'); + } + ShellKind::Cmd => { + combined_command.push_str("< NUL"); + } + } + } + + self.args + .extend(self.kind.args_for_shell(self.interactive, combined_command)); + } + + (self.program, self.args) + } + + /// Builds a `smol::process::Command` with the given task command and arguments. + /// + /// Prefer this over manually constructing a command with the output of `Self::build`, + /// as this method handles `cmd` weirdness on windows correctly. + pub fn build_smol_command( + self, + task_command: Option, + task_args: &[String], + ) -> smol::process::Command { + smol::process::Command::from(self.build_std_command(task_command, task_args)) + } + + /// Builds a `std::process::Command` with the given task command and arguments. + /// + /// Prefer this over manually constructing a command with the output of `Self::build`, + /// as this method handles `cmd` weirdness on windows correctly. + pub fn build_std_command( + self, + mut task_command: Option, + task_args: &[String], + ) -> std::process::Command { + #[cfg(windows)] + let kind = self.kind; + if task_args.is_empty() { + task_command = task_command + .as_ref() + .map(|cmd| self.kind.try_quote_prefix_aware(cmd).map(Cow::into_owned)) + .unwrap_or(task_command); + } + let (program, args) = self.build(task_command, task_args); + + let mut child = crate::command::new_std_command(program); + + #[cfg(windows)] + if kind == ShellKind::Cmd { + use std::os::windows::process::CommandExt; + + for arg in args { + child.raw_arg(arg); + } + } else { + child.args(args); + } + + #[cfg(not(windows))] + child.args(args); + + child + } + + pub fn kind(&self) -> ShellKind { + self.kind + } +} + +#[cfg(test)] +mod test { + use super::*; + + #[test] + fn test_nu_shell_variable_substitution() { + let shell = Shell::Program("nu".to_owned()); + let shell_builder = ShellBuilder::new(&shell, false); + + let (program, args) = shell_builder.build( + Some("echo".into()), + &[ + "${hello}".to_string(), + "$world".to_string(), + "nothing".to_string(), + "--$something".to_string(), + "$".to_string(), + "${test".to_string(), + ], + ); + + assert_eq!(program, "nu"); + assert_eq!( + args, + vec![ + "-i", + "-c", + "echo '$env.hello' '$env.world' nothing '--($env.something)' '$' '${test'" + ] + ); + } + + #[test] + fn redirect_stdin_to_dev_null_precedence() { + let shell = Shell::Program("nu".to_owned()); + let shell_builder = ShellBuilder::new(&shell, false); + + let (program, args) = shell_builder + .redirect_stdin_to_dev_null() + .build(Some("echo".into()), &["nothing".to_string()]); + + assert_eq!(program, "nu"); + assert_eq!(args, vec!["-i", "-c", "(echo nothing\n) Result> { + for (position, _) in output.match_indices('{') { + let candidate = &output[position..]; + let mut deserializer = serde_json::Deserializer::from_str(candidate); + if let Ok(env_map) = HashMap::::deserialize(&mut deserializer) { + return Ok(env_map); + } + } + anyhow::bail!("Failed to find JSON in shell output: {output}") +} + +pub fn print_env() { + let env_vars: HashMap = std::env::vars().collect(); + let json = serde_json::to_string_pretty(&env_vars).unwrap_or_else(|err| { + eprintln!("Error serializing environment variables: {}", err); + std::process::exit(1); + }); + println!("{}", json); +} + +/// Capture all environment variables from the login shell in the given directory. +pub async fn capture( + shell_path: impl AsRef, + args: &[String], + directory: impl AsRef, +) -> Result> { + #[cfg(windows)] + return capture_windows(shell_path.as_ref(), args, directory.as_ref()).await; + #[cfg(unix)] + return capture_unix(shell_path.as_ref(), args, directory.as_ref()).await; +} + +/// Try to parse the environment output before checking the exit status. +/// The user's shell rc files may contain commands that fail (e.g. editor +/// integrations that call posix_spawnp outside a real PTY), causing a +/// non-zero exit status even though `zed --printenv` ran successfully and +/// produced valid output on its separate fd. +fn parse_env_output( + env_output: &str, + status: &std::process::ExitStatus, + successful_capture_warning: impl FnOnce() -> String, + failed_capture_error: impl FnOnce() -> String, +) -> Result> { + match parse_env_map_from_noisy_output(env_output) { + Ok(env_map) => { + if !status.success() { + log::warn!("{}", successful_capture_warning()); + } + Ok(env_map) + } + Err(parse_error) => { + if !status.success() { + anyhow::bail!( + "{}. Failed to deserialize environment variables from json: {parse_error}. output: {env_output}", + failed_capture_error(), + ); + } + + anyhow::bail!( + "Failed to deserialize environment variables from json: {parse_error}. output: {env_output}" + ); + } + } +} + +#[cfg(unix)] +async fn capture_unix( + shell_path: &Path, + args: &[String], + directory: &Path, +) -> Result> { + use std::os::unix::process::CommandExt; + + use crate::command::new_std_command; + + let shell_kind = ShellKind::new(shell_path, false); + let quoted_zed_path = super::get_shell_safe_zed_path(shell_kind)?; + + let mut command_string = String::new(); + let mut command = new_std_command(shell_path); + command.args(args); + // In some shells, file descriptors greater than 2 cannot be used in interactive mode, + // so file descriptor 0 (stdin) is used instead. This impacts zsh, old bash; perhaps others. + // See: https://github.com/zed-industries/zed/pull/32136#issuecomment-2999645482 + const FD_STDIN: std::os::fd::RawFd = 0; + const FD_STDOUT: std::os::fd::RawFd = 1; + const FD_STDERR: std::os::fd::RawFd = 2; + + let (fd_num, redir) = match shell_kind { + ShellKind::Rc => (FD_STDIN, format!(">[1={}]", FD_STDIN)), // `[1=0]` + ShellKind::Nushell | ShellKind::Tcsh => (FD_STDOUT, "".to_string()), + // xonsh doesn't support redirecting to stdin, and control sequences are printed to + // stdout on startup + ShellKind::Xonsh => (FD_STDERR, "o>e".to_string()), + ShellKind::PowerShell => (FD_STDIN, format!(">{}", FD_STDIN)), + _ => (FD_STDIN, format!(">&{}", FD_STDIN)), // `>&0` + }; + + match shell_kind { + ShellKind::Csh | ShellKind::Tcsh => { + // For csh/tcsh, login shell requires passing `-` as 0th argument (instead of `-l`) + command.arg0("-"); + } + ShellKind::Fish => { + // in fish, asdf, direnv attach to the `fish_prompt` event + command_string.push_str("emit fish_prompt;"); + command.arg("-l"); + } + _ => { + command.arg("-l"); + } + } + + match shell_kind { + // Nushell does not allow non-interactive login shells. + // Instead of doing "-l -i -c ''" + // use "-l -e '; exit'" instead + ShellKind::Nushell => command.arg("-e"), + _ => command.args(["-i", "-c"]), + }; + + // Prefix with "./" if the path starts with "-" to prevent cd from interpreting it as a flag + let dir_str = directory.to_string_lossy(); + let dir_str = if dir_str.starts_with('-') { + format!("./{dir_str}").into() + } else { + dir_str + }; + let quoted_dir = shell_kind + .try_quote(&dir_str) + .context("unexpected null in directory name")?; + + // cd into the directory, triggering directory specific side-effects (asdf, direnv, etc) + command_string.push_str(&format!("cd {};", quoted_dir)); + if let Some(prefix) = shell_kind.command_prefix() { + command_string.push(prefix); + } + command_string.push_str(&format!("{} --printenv {}", quoted_zed_path, redir)); + + if let ShellKind::Nushell = shell_kind { + command_string.push_str("; exit"); + } + + command.arg(&command_string); + + super::set_pre_exec_to_start_new_session(&mut command); + + let (env_output, process_output) = spawn_and_read_fd(command, fd_num).await?; + let env_output = String::from_utf8_lossy(&env_output); + + parse_env_output( + &env_output, + &process_output.status, + || { + format!( + "login shell exited with {} but environment was captured successfully. stderr: {:?}", + process_output.status, + String::from_utf8_lossy(&process_output.stderr), + ) + }, + || { + format!( + "login shell exited with {}. stdout: {:?}, stderr: {:?}", + process_output.status, + String::from_utf8_lossy(&process_output.stdout), + String::from_utf8_lossy(&process_output.stderr), + ) + }, + ) +} + +#[cfg(unix)] +async fn spawn_and_read_fd( + mut command: std::process::Command, + child_fd: std::os::fd::RawFd, +) -> anyhow::Result<(Vec, std::process::Output)> { + use command_fds::{CommandFdExt, FdMapping}; + use std::{io::Read, process::Stdio}; + + let (mut reader, writer) = std::io::pipe()?; + + command.fd_mappings(vec![FdMapping { + parent_fd: writer.into(), + child_fd, + }])?; + + let process = smol::process::Command::from(command) + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()) + .spawn()?; + + let mut buffer = Vec::new(); + reader.read_to_end(&mut buffer)?; + + Ok((buffer, process.output().await?)) +} + +#[cfg(windows)] +async fn capture_windows( + shell_path: &Path, + args: &[String], + directory: &Path, +) -> Result> { + use std::process::Stdio; + + let zed_path = + std::env::current_exe().context("Failed to determine current zed executable path.")?; + + let shell_kind = ShellKind::new(shell_path, true); + // Prefix with "./" if the path starts with "-" to prevent cd from interpreting it as a flag + let directory_string = directory.display().to_string(); + let directory_string = if directory_string.starts_with('-') { + format!("./{directory_string}") + } else { + directory_string + }; + let zed_path_string = zed_path.display().to_string(); + let quote_for_shell = |value: &str| { + shell_kind + .try_quote(value) + .map(|quoted| quoted.into_owned()) + .context("unexpected null in directory name") + }; + let mut cmd = crate::command::new_command(shell_path); + cmd.args(args); + let quoted_directory = quote_for_shell(&directory_string)?; + let quoted_zed_path = quote_for_shell(&zed_path_string)?; + let cmd = match shell_kind { + ShellKind::Csh + | ShellKind::Tcsh + | ShellKind::Rc + | ShellKind::Fish + | ShellKind::Xonsh + | ShellKind::Posix => cmd.args([ + "-l", + "-i", + "-c", + &format!("cd {}; {} --printenv", quoted_directory, quoted_zed_path), + ]), + ShellKind::PowerShell | ShellKind::Pwsh => cmd.args([ + "-NonInteractive", + "-NoProfile", + "-Command", + &format!( + "Set-Location {}; & {} --printenv", + quoted_directory, quoted_zed_path + ), + ]), + ShellKind::Elvish => cmd.args([ + "-c", + &format!("cd {}; {} --printenv", quoted_directory, quoted_zed_path), + ]), + ShellKind::Nushell => { + let zed_command = shell_kind + .prepend_command_prefix("ed_zed_path) + .into_owned(); + cmd.args([ + "-c", + &format!("cd {}; {} --printenv", quoted_directory, zed_command), + ]) + } + ShellKind::Cmd => { + let dir = directory_string.trim_end_matches('\\'); + cmd.args(["/d", "/c", "cd", dir, "&&", &zed_path_string, "--printenv"]) + } + } + .stdin(Stdio::null()) + .stdout(Stdio::piped()) + .stderr(Stdio::piped()); + let output = cmd + .output() + .await + .with_context(|| format!("command {cmd:?}"))?; + let env_output = String::from_utf8_lossy(&output.stdout); + + parse_env_output( + &env_output, + &output.status, + || { + format!( + "Command {cmd:?} exited with {} but environment was captured successfully. stderr: {:?}", + output.status, + String::from_utf8_lossy(&output.stderr), + ) + }, + || { + format!( + "Command {cmd:?} failed with {}. stdout: {:?}, stderr: {:?}", + output.status, + String::from_utf8_lossy(&output.stdout), + String::from_utf8_lossy(&output.stderr), + ) + }, + ) +} + +#[cfg(test)] +mod tests { + use std::process::ExitStatus; + + use super::*; + + #[cfg(unix)] + fn exit_status(code: i32) -> ExitStatus { + use std::os::unix::process::ExitStatusExt; + + ExitStatus::from_raw(code << 8) + } + + #[cfg(windows)] + fn exit_status(code: u32) -> ExitStatus { + use std::os::windows::process::ExitStatusExt; + + ExitStatus::from_raw(code) + } + + #[test] + fn parse_env_output_accepts_valid_env_when_shell_exits_nonzero() { + let env_json = serde_json::json!({ + "PATH": "/usr/bin", + "SHELL": "/bin/zsh", + }); + let env_output = format!("shell startup noise\n{env_json}\nshell shutdown noise"); + + let env_map = parse_env_output( + &env_output, + &exit_status(1), + || "shell exited with 1 but environment was captured successfully".to_string(), + || panic!("failed capture error should not be evaluated for valid environment output"), + ) + .expect("valid environment output should be returned despite non-zero shell exit"); + assert_eq!(env_map.get("PATH").map(String::as_str), Some("/usr/bin")); + assert_eq!(env_map.get("SHELL").map(String::as_str), Some("/bin/zsh")); + } +} diff --git a/crates/gpui_zed_util/src/size.rs b/crates/gpui_zed_util/src/size.rs new file mode 100644 index 0000000000..c6ecebd548 --- /dev/null +++ b/crates/gpui_zed_util/src/size.rs @@ -0,0 +1,46 @@ +pub fn format_file_size(size: u64, use_decimal: bool) -> String { + if use_decimal { + if size < 1000 { + format!("{size}B") + } else if size < 1000 * 1000 { + format!("{:.1}KB", size as f64 / 1000.0) + } else { + format!("{:.1}MB", size as f64 / (1000.0 * 1000.0)) + } + } else if size < 1024 { + format!("{size}B") + } else if size < 1024 * 1024 { + format!("{:.1}KiB", size as f64 / 1024.0) + } else { + format!("{:.1}MiB", size as f64 / (1024.0 * 1024.0)) + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_format_file_size_decimal() { + assert_eq!(format_file_size(0, true), "0B"); + assert_eq!(format_file_size(999, true), "999B"); + assert_eq!(format_file_size(1000, true), "1.0KB"); + assert_eq!(format_file_size(1500, true), "1.5KB"); + assert_eq!(format_file_size(999999, true), "1000.0KB"); + assert_eq!(format_file_size(1000000, true), "1.0MB"); + assert_eq!(format_file_size(1500000, true), "1.5MB"); + assert_eq!(format_file_size(10000000, true), "10.0MB"); + } + + #[test] + fn test_format_file_size_binary() { + assert_eq!(format_file_size(0, false), "0B"); + assert_eq!(format_file_size(1023, false), "1023B"); + assert_eq!(format_file_size(1024, false), "1.0KiB"); + assert_eq!(format_file_size(1536, false), "1.5KiB"); + assert_eq!(format_file_size(1048575, false), "1024.0KiB"); + assert_eq!(format_file_size(1048576, false), "1.0MiB"); + assert_eq!(format_file_size(1572864, false), "1.5MiB"); + assert_eq!(format_file_size(10485760, false), "10.0MiB"); + } +} diff --git a/crates/gpui_zed_util/src/test.rs b/crates/gpui_zed_util/src/test.rs new file mode 100644 index 0000000000..717754e333 --- /dev/null +++ b/crates/gpui_zed_util/src/test.rs @@ -0,0 +1,80 @@ +mod assertions; +mod marked_text; + +pub use assertions::*; +pub use marked_text::*; + +use git2; +use std::ffi::OsStr; +use std::path::{Path, PathBuf}; +use tempfile::TempDir; + +pub struct TempTree { + _temp_dir: TempDir, + path: PathBuf, +} + +impl TempTree { + pub fn new(tree: serde_json::Value) -> Self { + let dir = TempDir::new().unwrap(); + let path = std::fs::canonicalize(dir.path()).unwrap(); + write_tree(path.as_path(), tree); + + Self { + _temp_dir: dir, + path, + } + } + + pub fn path(&self) -> &Path { + self.path.as_path() + } +} + +fn write_tree(path: &Path, tree: serde_json::Value) { + use serde_json::Value; + use std::fs; + + if let Value::Object(map) = tree { + for (name, contents) in map { + let mut path = PathBuf::from(path); + path.push(name); + match contents { + Value::Object(_) => { + fs::create_dir(&path).unwrap(); + + #[cfg(not(target_family = "wasm"))] + if path.file_name() == Some(OsStr::new(".git")) { + git2::Repository::init(path.parent().unwrap()).unwrap(); + } + + write_tree(&path, contents); + } + Value::Null => { + fs::create_dir(&path).unwrap(); + } + Value::String(contents) => { + fs::write(&path, contents).unwrap(); + } + _ => { + panic!("JSON object must contain only objects, strings, or null"); + } + } + } + } else { + panic!("You must pass a JSON object to this helper") + } +} + +pub fn sample_text(rows: usize, cols: usize, start_char: char) -> String { + let mut text = String::new(); + for row in 0..rows { + let c: char = (start_char as u32 + row as u32) as u8 as char; + let mut line = c.to_string().repeat(cols); + if row < rows - 1 { + line.push('\n'); + } + text += &line; + } + text +} diff --git a/crates/gpui_zed_util/src/test/assertions.rs b/crates/gpui_zed_util/src/test/assertions.rs new file mode 100644 index 0000000000..afb1397fa9 --- /dev/null +++ b/crates/gpui_zed_util/src/test/assertions.rs @@ -0,0 +1,62 @@ +pub enum SetEqError { + LeftMissing(T), + RightMissing(T), +} + +impl SetEqError { + pub fn map R>(self, update: F) -> SetEqError { + match self { + SetEqError::LeftMissing(missing) => SetEqError::LeftMissing(update(missing)), + SetEqError::RightMissing(missing) => SetEqError::RightMissing(update(missing)), + } + } +} + +#[macro_export] +macro_rules! set_eq { + ($left:expr,$right:expr) => {{ + use util::test::*; + + let left = $left; + let right = $right; + + let mut result = Ok(()); + for right_value in right.iter() { + if !left.contains(right_value) { + result = Err(SetEqError::LeftMissing(right_value.clone())); + break; + } + } + + if result.is_ok() { + for left_value in left.iter() { + if !right.contains(left_value) { + result = Err(SetEqError::RightMissing(left_value.clone())); + } + } + } + + result + }}; +} + +#[macro_export] +macro_rules! assert_set_eq { + ($left:expr,$right:expr) => {{ + use util::test::*; + use util::set_eq; + + let left = $left; + let right = $right; + + match set_eq!(&left, &right) { + Err(SetEqError::LeftMissing(missing)) => { + panic!("assertion failed: `(left == right)`\n left: {:?}\nright: {:?}\nleft does not contain {:?}", &left, &right, &missing); + }, + Err(SetEqError::RightMissing(missing)) => { + panic!("assertion failed: `(left == right)`\n left: {:?}\nright: {:?}\nright does not contain {:?}", &left, &right, &missing); + }, + _ => {} + } + }}; +} diff --git a/crates/gpui_zed_util/src/test/git.rs b/crates/gpui_zed_util/src/test/git.rs new file mode 100644 index 0000000000..e69de29bb2 diff --git a/crates/gpui_zed_util/src/test/marked_text.rs b/crates/gpui_zed_util/src/test/marked_text.rs new file mode 100644 index 0000000000..282a477935 --- /dev/null +++ b/crates/gpui_zed_util/src/test/marked_text.rs @@ -0,0 +1,281 @@ +use collections::HashMap; +use std::{cmp::Ordering, ops::Range}; + +/// Construct a string and a list of offsets within that string using a single +/// string containing embedded position markers. +pub fn marked_text_offsets_by( + marked_text: &str, + markers: Vec, +) -> (String, HashMap>) { + let mut extracted_markers: HashMap> = Default::default(); + let mut unmarked_text = String::new(); + + for char in marked_text.chars() { + if markers.contains(&char) { + let char_offsets = extracted_markers.entry(char).or_default(); + char_offsets.push(unmarked_text.len()); + } else { + unmarked_text.push(char); + } + } + + (unmarked_text, extracted_markers) +} + +/// Construct a string and a list of ranges within that string using a single +/// string containing embedded range markers, using arbitrary characters as +/// range markers. By using multiple different range markers, you can construct +/// ranges that overlap each other. +/// +/// The returned ranges will be grouped by their range marking characters. +pub fn marked_text_ranges_by( + marked_text: &str, + markers: Vec, +) -> (String, HashMap>>) { + let all_markers = markers.iter().flat_map(|m| m.markers()).collect(); + + let (unmarked_text, mut marker_offsets) = marked_text_offsets_by(marked_text, all_markers); + let range_lookup = markers + .into_iter() + .map(|marker| { + ( + marker.clone(), + match marker { + TextRangeMarker::Empty(empty_marker_char) => marker_offsets + .remove(&empty_marker_char) + .unwrap_or_default() + .into_iter() + .map(|empty_index| empty_index..empty_index) + .collect::>>(), + TextRangeMarker::Range(start_marker, end_marker) => { + let starts = marker_offsets.remove(&start_marker).unwrap_or_default(); + let ends = marker_offsets.remove(&end_marker).unwrap_or_default(); + assert_eq!(starts.len(), ends.len(), "marked ranges are unbalanced"); + starts + .into_iter() + .zip(ends) + .map(|(start, end)| { + assert!(end >= start, "marked ranges must be disjoint"); + start..end + }) + .collect::>>() + } + TextRangeMarker::ReverseRange(start_marker, end_marker) => { + let starts = marker_offsets.remove(&start_marker).unwrap_or_default(); + let ends = marker_offsets.remove(&end_marker).unwrap_or_default(); + assert_eq!(starts.len(), ends.len(), "marked ranges are unbalanced"); + starts + .into_iter() + .zip(ends) + .map(|(start, end)| { + assert!(end >= start, "marked ranges must be disjoint"); + end..start + }) + .collect::>>() + } + }, + ) + }) + .collect(); + + (unmarked_text, range_lookup) +} + +/// Construct a string and a list of ranges within that string using a single +/// string containing embedded range markers. The characters used to mark the +/// ranges are as follows: +/// +/// 1. To mark a range of text, surround it with the `«` and `»` angle brackets, +/// which can be typed on a US keyboard with the `alt-|` and `alt-shift-|` keys. +/// +/// ```text +/// foo «selected text» bar +/// ``` +/// +/// 2. To mark a single position in the text, use the `ˇ` caron, +/// which can be typed on a US keyboard with the `alt-shift-t` key. +/// +/// ```text +/// the cursors are hereˇ and hereˇ. +/// ``` +/// +/// 3. To mark a range whose direction is meaningful (like a selection), +/// put a caron character beside one of its bounds, on the inside: +/// +/// ```text +/// one «ˇreversed» selection and one «forwardˇ» selection +/// ``` +/// +/// Any • characters in the input string will be replaced with spaces. This makes +/// it easier to test cases with trailing spaces, which tend to get trimmed from the +/// source code. +#[track_caller] +pub fn marked_text_ranges( + marked_text: &str, + ranges_are_directed: bool, +) -> (String, Vec>) { + let mut unmarked_text = String::with_capacity(marked_text.len()); + let mut ranges = Vec::new(); + let mut prev_marked_ix = 0; + let mut current_range_start = None; + let mut current_range_cursor = None; + + let marked_text = marked_text.replace('•', " "); + for (marked_ix, marker) in marked_text.match_indices(&['«', '»', 'ˇ']) { + unmarked_text.push_str(&marked_text[prev_marked_ix..marked_ix]); + let unmarked_len = unmarked_text.len(); + let len = marker.len(); + prev_marked_ix = marked_ix + len; + + match marker { + "ˇ" => { + if current_range_start.is_some() { + if current_range_cursor.is_some() { + panic!("duplicate point marker 'ˇ' at index {marked_ix}"); + } + + current_range_cursor = Some(unmarked_len); + } else { + ranges.push(unmarked_len..unmarked_len); + } + } + "«" => { + if current_range_start.is_some() { + panic!("unexpected range start marker '«' at index {marked_ix}"); + } + current_range_start = Some(unmarked_len); + } + "»" => { + let current_range_start = if let Some(start) = current_range_start.take() { + start + } else { + panic!("unexpected range end marker '»' at index {marked_ix}"); + }; + + let mut reversed = false; + if let Some(current_range_cursor) = current_range_cursor.take() { + if current_range_cursor == current_range_start { + reversed = true; + } else if current_range_cursor != unmarked_len { + panic!("unexpected 'ˇ' marker in the middle of a range"); + } + } else if ranges_are_directed { + panic!("missing 'ˇ' marker to indicate range direction"); + } + + ranges.push(if reversed { + unmarked_len..current_range_start + } else { + current_range_start..unmarked_len + }); + } + _ => unreachable!(), + } + } + + unmarked_text.push_str(&marked_text[prev_marked_ix..]); + (unmarked_text, ranges) +} + +#[track_caller] +pub fn marked_text_offsets(marked_text: &str) -> (String, Vec) { + let (text, ranges) = marked_text_ranges(marked_text, false); + ( + text, + ranges + .into_iter() + .map(|range| { + assert_eq!(range.start, range.end); + range.start + }) + .collect(), + ) +} + +pub fn generate_marked_text( + unmarked_text: &str, + ranges: &[Range], + indicate_cursors: bool, +) -> String { + let mut marked_text = unmarked_text.to_string(); + for range in ranges.iter().rev() { + if indicate_cursors { + match range.start.cmp(&range.end) { + Ordering::Less => { + marked_text.insert_str(range.end, "ˇ»"); + marked_text.insert(range.start, '«'); + } + Ordering::Equal => { + marked_text.insert(range.start, 'ˇ'); + } + Ordering::Greater => { + marked_text.insert(range.start, '»'); + marked_text.insert_str(range.end, "«ˇ"); + } + } + } else { + match range.start.cmp(&range.end) { + Ordering::Equal => { + marked_text.insert(range.start, 'ˇ'); + } + _ => { + marked_text.insert(range.end, '»'); + marked_text.insert(range.start, '«'); + } + } + } + } + marked_text +} + +#[derive(Clone, Eq, PartialEq, Hash)] +pub enum TextRangeMarker { + Empty(char), + Range(char, char), + ReverseRange(char, char), +} + +impl TextRangeMarker { + fn markers(&self) -> Vec { + match self { + Self::Empty(m) => vec![*m], + Self::Range(l, r) => vec![*l, *r], + Self::ReverseRange(l, r) => vec![*l, *r], + } + } +} + +impl From for TextRangeMarker { + fn from(marker: char) -> Self { + Self::Empty(marker) + } +} + +impl From<(char, char)> for TextRangeMarker { + fn from((left_marker, right_marker): (char, char)) -> Self { + Self::Range(left_marker, right_marker) + } +} + +#[cfg(test)] +mod tests { + use super::{generate_marked_text, marked_text_ranges}; + + #[allow(clippy::reversed_empty_ranges)] + #[test] + fn test_marked_text() { + let (text, ranges) = marked_text_ranges("one «ˇtwo» «threeˇ» «ˇfour» fiveˇ six", true); + + assert_eq!(text, "one two three four five six"); + assert_eq!(ranges.len(), 4); + assert_eq!(ranges[0], 7..4); + assert_eq!(ranges[1], 8..13); + assert_eq!(ranges[2], 18..14); + assert_eq!(ranges[3], 23..23); + + assert_eq!( + generate_marked_text(&text, &ranges, true), + "one «ˇtwo» «threeˇ» «ˇfour» fiveˇ six" + ); + } +} diff --git a/crates/gpui_zed_util/src/time.rs b/crates/gpui_zed_util/src/time.rs new file mode 100644 index 0000000000..092d447dab --- /dev/null +++ b/crates/gpui_zed_util/src/time.rs @@ -0,0 +1,33 @@ +use std::time::Duration; + +pub fn duration_alt_display(duration: Duration) -> String { + let hours = duration.as_secs() / 3600; + let minutes = (duration.as_secs() % 3600) / 60; + let seconds = duration.as_secs() % 60; + + if hours > 0 { + format!("{hours}h {minutes}m {seconds}s") + } else if minutes > 0 { + format!("{minutes}m {seconds}s") + } else { + format!("{seconds}s") + } +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_duration_alt_display() { + use duration_alt_display as f; + assert_eq!("0s", f(Duration::from_secs(0))); + assert_eq!("59s", f(Duration::from_secs(59))); + assert_eq!("1m 0s", f(Duration::from_secs(60))); + assert_eq!("10m 0s", f(Duration::from_secs(600))); + assert_eq!("1h 0m 0s", f(Duration::from_secs(3600))); + assert_eq!("3h 2m 1s", f(Duration::from_secs(3600 * 3 + 60 * 2 + 1))); + assert_eq!("23h 59m 59s", f(Duration::from_secs(3600 * 24 - 1))); + assert_eq!("100h 0m 0s", f(Duration::from_secs(3600 * 100))); + } +} diff --git a/crates/gpui_zed_util/src/util.rs b/crates/gpui_zed_util/src/util.rs new file mode 100644 index 0000000000..3c4e3684a9 --- /dev/null +++ b/crates/gpui_zed_util/src/util.rs @@ -0,0 +1,1074 @@ +pub mod archive; +pub mod command; +pub mod disambiguate; +pub mod fs; +pub mod markdown; +pub mod path_list; +pub mod paths; +pub mod process; +pub mod redact; +pub mod rel_path; +pub mod schemars; +pub mod serde; +pub mod shell; +pub mod shell_builder; +pub mod shell_env; +pub mod size; +#[cfg(any(test, feature = "test-support"))] +pub mod test; +pub mod time; + +use anyhow::Result; +use itertools::Either; +use regex::Regex; +use std::path::{Path, PathBuf}; +use std::sync::LazyLock; +use std::{ + borrow::Cow, + cmp::{self, Ordering}, + ops::{Range, RangeInclusive}, +}; +use unicase::UniCase; + +pub use gpui_util::*; + +pub use take_until::*; + +pub use self::shell::{ + get_default_system_shell, get_default_system_shell_preferring_bash, get_system_shell, +}; + +#[inline] +pub const fn is_utf8_char_boundary(u8: u8) -> bool { + // This is bit magic equivalent to: b < 128 || b >= 192 + (u8 as i8) >= -0x40 +} + +pub fn truncate(s: &str, max_chars: usize) -> &str { + match s.char_indices().nth(max_chars) { + None => s, + Some((idx, _)) => &s[..idx], + } +} + +/// Removes characters from the end of the string if its length is greater than `max_chars` and +/// appends "..." to the string. Returns string unchanged if its length is smaller than max_chars. +pub fn truncate_and_trailoff(s: &str, max_chars: usize) -> String { + debug_assert!(max_chars >= 5); + + // If the string's byte length is <= max_chars, walking the string can be skipped since the + // number of chars is <= the number of bytes. + if s.len() <= max_chars { + return s.to_string(); + } + let truncation_ix = s.char_indices().map(|(i, _)| i).nth(max_chars); + match truncation_ix { + Some(index) => s[..index].to_string() + "…", + _ => s.to_string(), + } +} + +/// Removes characters from the front of the string if its length is greater than `max_chars` and +/// prepends the string with "...". Returns string unchanged if its length is smaller than max_chars. +pub fn truncate_and_remove_front(s: &str, max_chars: usize) -> String { + debug_assert!(max_chars >= 5); + + // If the string's byte length is <= max_chars, walking the string can be skipped since the + // number of chars is <= the number of bytes. + if s.len() <= max_chars { + return s.to_string(); + } + let suffix_char_length = max_chars.saturating_sub(1); + let truncation_ix = s + .char_indices() + .map(|(i, _)| i) + .nth_back(suffix_char_length); + match truncation_ix { + Some(index) if index > 0 => "…".to_string() + &s[index..], + _ => s.to_string(), + } +} + +/// Takes only `max_lines` from the string and, if there were more than `max_lines-1`, appends a +/// a newline and "..." to the string, so that `max_lines` are returned. +/// Returns string unchanged if its length is smaller than max_lines. +pub fn truncate_lines_and_trailoff(s: &str, max_lines: usize) -> String { + let mut lines = s.lines().take(max_lines).collect::>(); + if lines.len() > max_lines - 1 { + lines.pop(); + lines.join("\n") + "\n…" + } else { + lines.join("\n") + } +} + +/// Truncates the string at a character boundary, such that the result is less than `max_bytes` in +/// length. +pub fn truncate_to_byte_limit(s: &str, max_bytes: usize) -> &str { + if s.len() < max_bytes { + return s; + } + + for i in (0..max_bytes).rev() { + if s.is_char_boundary(i) { + return &s[..i]; + } + } + + "" +} + +/// Takes a prefix of complete lines which fit within the byte limit. If the first line is longer +/// than the limit, truncates at a character boundary. +pub fn truncate_lines_to_byte_limit(s: &str, max_bytes: usize) -> &str { + if s.len() < max_bytes { + return s; + } + + for i in (0..max_bytes).rev() { + if s.is_char_boundary(i) && s.as_bytes()[i] == b'\n' { + // Since the i-th character is \n, valid to slice at i + 1. + return &s[..i + 1]; + } + } + + truncate_to_byte_limit(s, max_bytes) +} + +#[test] +fn test_truncate_lines_to_byte_limit() { + let text = "Line 1\nLine 2\nLine 3\nLine 4"; + + // Limit that includes all lines + assert_eq!(truncate_lines_to_byte_limit(text, 100), text); + + // Exactly the first line + assert_eq!(truncate_lines_to_byte_limit(text, 7), "Line 1\n"); + + // Limit between lines + assert_eq!(truncate_lines_to_byte_limit(text, 13), "Line 1\n"); + assert_eq!(truncate_lines_to_byte_limit(text, 20), "Line 1\nLine 2\n"); + + // Limit before first newline + assert_eq!(truncate_lines_to_byte_limit(text, 6), "Line "); + + // Test with non-ASCII characters + let text_utf8 = "Line 1\nLíne 2\nLine 3"; + assert_eq!( + truncate_lines_to_byte_limit(text_utf8, 15), + "Line 1\nLíne 2\n" + ); +} + +/// Extend a sorted vector with a sorted sequence of items, maintaining the vector's sort order and +/// enforcing a maximum length. This also de-duplicates items. Sort the items according to the given callback. Before calling this, +/// both `vec` and `new_items` should already be sorted according to the `cmp` comparator. +pub fn extend_sorted(vec: &mut Vec, new_items: I, limit: usize, mut cmp: F) +where + I: IntoIterator, + F: FnMut(&T, &T) -> Ordering, +{ + let mut start_index = 0; + for new_item in new_items { + if let Err(i) = vec[start_index..].binary_search_by(|m| cmp(m, &new_item)) { + let index = start_index + i; + if vec.len() < limit { + vec.insert(index, new_item); + } else if index < vec.len() { + vec.pop(); + vec.insert(index, new_item); + } + start_index = index; + } + } +} + +pub fn truncate_to_bottom_n_sorted_by(items: &mut Vec, limit: usize, compare: &F) +where + F: Fn(&T, &T) -> Ordering, +{ + if limit == 0 { + items.clear(); + } + if items.len() <= limit { + items.sort_by(compare); + return; + } + // When limit is near to items.len() it may be more efficient to sort the whole list and + // truncate, rather than always doing selection first as is done below. It's hard to analyze + // where the threshold for this should be since the quickselect style algorithm used by + // `select_nth_unstable_by` makes the prefix partially sorted, and so its work is not wasted - + // the expected number of comparisons needed by `sort_by` is less than it is for some arbitrary + // unsorted input. + items.select_nth_unstable_by(limit, compare); + items.truncate(limit); + items.sort_by(compare); +} + +/// Prevents execution of the application with root privileges on Unix systems. +/// +/// This function checks if the current process is running with root privileges +/// and terminates the program with an error message unless explicitly allowed via the +/// `ZED_ALLOW_ROOT` environment variable. +#[cfg(unix)] +pub fn prevent_root_execution() { + let is_root = nix::unistd::geteuid().is_root(); + let allow_root = std::env::var("ZED_ALLOW_ROOT").is_ok_and(|val| val == "true"); + + if is_root && !allow_root { + eprintln!( + "\ +Error: Running Zed as root or via sudo is unsupported. + Doing so (even once) may subtly break things for all subsequent non-root usage of Zed. + It is untested and not recommended, don't complain when things break. + If you wish to proceed anyways, set `ZED_ALLOW_ROOT=true` in your environment." + ); + std::process::exit(1); + } +} + +#[cfg(unix)] +fn load_shell_from_passwd() -> Result<()> { + let buflen = match unsafe { libc::sysconf(libc::_SC_GETPW_R_SIZE_MAX) } { + n if n < 0 => 1024, + n => n as usize, + }; + let mut buffer = Vec::with_capacity(buflen); + + let mut pwd: std::mem::MaybeUninit = std::mem::MaybeUninit::uninit(); + let mut result: *mut libc::passwd = std::ptr::null_mut(); + + let uid = unsafe { libc::getuid() }; + let status = unsafe { + libc::getpwuid_r( + uid, + pwd.as_mut_ptr(), + buffer.as_mut_ptr() as *mut libc::c_char, + buflen, + &mut result, + ) + }; + anyhow::ensure!(!result.is_null(), "passwd entry for uid {} not found", uid); + + // SAFETY: If `getpwuid_r` doesn't error, we have the entry here. + let entry = unsafe { pwd.assume_init() }; + + anyhow::ensure!( + status == 0, + "call to getpwuid_r failed. uid: {}, status: {}", + uid, + status + ); + anyhow::ensure!( + entry.pw_uid == uid, + "passwd entry has different uid ({}) than getuid ({}) returned", + entry.pw_uid, + uid, + ); + + let shell = unsafe { std::ffi::CStr::from_ptr(entry.pw_shell).to_str().unwrap() }; + let should_set_shell = std::env::var("SHELL").map_or(true, |shell_env| { + shell_env != shell && !std::path::Path::new(&shell_env).exists() + }); + + if should_set_shell { + log::info!( + "updating SHELL environment variable to value from passwd entry: {:?}", + shell, + ); + unsafe { std::env::set_var("SHELL", shell) }; + } + + Ok(()) +} + +/// Returns a shell escaped path for the current zed executable +pub fn get_shell_safe_zed_path(shell_kind: shell::ShellKind) -> anyhow::Result { + use anyhow::Context as _; + use paths::PathExt; + let mut zed_path = + std::env::current_exe().context("Failed to determine current zed executable path.")?; + if cfg!(target_os = "linux") + && !zed_path.is_file() + && let Some(truncated) = zed_path + .clone() + .file_name() + .and_then(|s| s.to_str()) + .and_then(|n| n.strip_suffix(" (deleted)")) + { + // Might have been deleted during update; let's use the new binary if there is one. + zed_path.set_file_name(truncated); + } + + zed_path + .try_shell_safe(shell_kind) + .context("Failed to shell-escape Zed executable path.") +} + +/// Returns a path for the zed cli executable, this function +/// should be called from the zed executable, not zed-cli. +pub fn get_zed_cli_path() -> Result { + use anyhow::Context as _; + let zed_path = + std::env::current_exe().context("Failed to determine current zed executable path.")?; + let parent = zed_path + .parent() + .context("Failed to determine parent directory of zed executable path.")?; + + let possible_locations: &[&str] = if cfg!(target_os = "macos") { + // On macOS, the zed executable and zed-cli are inside the app bundle, + // so here ./cli is for both installed and development builds. + &["./cli"] + } else if cfg!(target_os = "windows") { + // bin/zed.exe is for installed builds, ./cli.exe is for development builds. + &["bin/zed.exe", "./cli.exe"] + } else if cfg!(target_os = "linux") || cfg!(target_os = "freebsd") { + // bin is the standard, ./cli is for the target directory in development builds. + &["../bin/zed", "./cli"] + } else { + anyhow::bail!("unsupported platform for determining zed-cli path"); + }; + + possible_locations + .iter() + .find_map(|p| { + parent + .join(p) + .canonicalize() + .ok() + .filter(|p| p != &zed_path) + }) + .with_context(|| { + format!( + "could not find zed-cli from any of: {}", + possible_locations.join(", ") + ) + }) +} + +#[cfg(unix)] +pub async fn load_login_shell_environment() -> Result<()> { + use anyhow::Context as _; + + load_shell_from_passwd().log_err(); + + // If possible, we want to `cd` in the user's `$HOME` to trigger programs + // such as direnv, asdf, mise, ... to adjust the PATH. These tools often hook + // into shell's `cd` command (and hooks) to manipulate env. + // We do this so that we get the env a user would have when spawning a shell + // in home directory. + for (name, value) in shell_env::capture(get_system_shell(), &[], paths::home_dir()) + .await + .with_context(|| format!("capturing environment with {:?}", get_system_shell()))? + { + // Skip SHLVL to prevent it from polluting Zed's process environment. + // The login shell used for env capture increments SHLVL, and if we propagate it, + // terminals spawned by Zed will inherit it and increment again, causing SHLVL + // to start at 2 instead of 1 (and increase by 2 on each reload). + if name == "SHLVL" { + continue; + } + unsafe { std::env::set_var(&name, &value) }; + } + + log::info!( + "set environment variables from shell:{}, path:{}", + std::env::var("SHELL").unwrap_or_default(), + std::env::var("PATH").unwrap_or_default(), + ); + + Ok(()) +} + +/// Configures the process to start a new session, to prevent interactive shells from taking control +/// of the terminal. +/// +/// For more details: +pub fn set_pre_exec_to_start_new_session( + command: &mut std::process::Command, +) -> &mut std::process::Command { + // safety: code in pre_exec should be signal safe. + // https://man7.org/linux/man-pages/man7/signal-safety.7.html + #[cfg(unix)] + unsafe { + use std::os::unix::process::CommandExt; + command.pre_exec(|| { + libc::setsid(); + Ok(()) + }); + }; + command +} + +pub fn merge_json_lenient_value_into( + source: serde_json_lenient::Value, + target: &mut serde_json_lenient::Value, +) { + match (source, target) { + (serde_json_lenient::Value::Object(source), serde_json_lenient::Value::Object(target)) => { + for (key, value) in source { + if let Some(target) = target.get_mut(&key) { + merge_json_lenient_value_into(value, target); + } else { + target.insert(key, value); + } + } + } + + (serde_json_lenient::Value::Array(source), serde_json_lenient::Value::Array(target)) => { + for value in source { + target.push(value); + } + } + + (source, target) => *target = source, + } +} + +pub fn merge_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) { + use serde_json::Value; + + match (source, target) { + (Value::Object(source), Value::Object(target)) => { + for (key, value) in source { + if let Some(target) = target.get_mut(&key) { + merge_json_value_into(value, target); + } else { + target.insert(key, value); + } + } + } + + (Value::Array(source), Value::Array(target)) => { + for value in source { + target.push(value); + } + } + + (source, target) => *target = source, + } +} + +pub fn merge_non_null_json_value_into(source: serde_json::Value, target: &mut serde_json::Value) { + use serde_json::Value; + if let Value::Object(source_object) = source { + let target_object = if let Value::Object(target) = target { + target + } else { + *target = Value::Object(Default::default()); + target.as_object_mut().unwrap() + }; + for (key, value) in source_object { + if let Some(target) = target_object.get_mut(&key) { + merge_non_null_json_value_into(value, target); + } else if !value.is_null() { + target_object.insert(key, value); + } + } + } else if !source.is_null() { + *target = source + } +} + +pub fn expanded_and_wrapped_usize_range( + range: Range, + additional_before: usize, + additional_after: usize, + wrap_length: usize, +) -> impl Iterator { + let start_wraps = range.start < additional_before; + let end_wraps = wrap_length < range.end + additional_after; + if start_wraps && end_wraps { + Either::Left(0..wrap_length) + } else if start_wraps { + let wrapped_start = (range.start + wrap_length).saturating_sub(additional_before); + if wrapped_start <= range.end { + Either::Left(0..wrap_length) + } else { + Either::Right((0..range.end + additional_after).chain(wrapped_start..wrap_length)) + } + } else if end_wraps { + let wrapped_end = range.end + additional_after - wrap_length; + if range.start <= wrapped_end { + Either::Left(0..wrap_length) + } else { + Either::Right((0..wrapped_end).chain(range.start - additional_before..wrap_length)) + } + } else { + Either::Left((range.start - additional_before)..(range.end + additional_after)) + } +} + +/// Yields `[i, i + 1, i - 1, i + 2, ..]`, each modulo `wrap_length` and bounded by +/// `additional_before` and `additional_after`. If the wrapping causes overlap, duplicates are not +/// emitted. If wrap_length is 0, nothing is yielded. +pub fn wrapped_usize_outward_from( + start: usize, + additional_before: usize, + additional_after: usize, + wrap_length: usize, +) -> impl Iterator { + let mut count = 0; + let mut after_offset = 1; + let mut before_offset = 1; + + std::iter::from_fn(move || { + count += 1; + if count > wrap_length { + None + } else if count == 1 { + Some(start % wrap_length) + } else if after_offset <= additional_after && after_offset <= before_offset { + let value = (start + after_offset) % wrap_length; + after_offset += 1; + Some(value) + } else if before_offset <= additional_before { + let value = (start + wrap_length - before_offset) % wrap_length; + before_offset += 1; + Some(value) + } else if after_offset <= additional_after { + let value = (start + after_offset) % wrap_length; + after_offset += 1; + Some(value) + } else { + None + } + }) +} + +#[cfg(any(test, feature = "test-support"))] +mod rng { + use rand::prelude::*; + + pub struct RandomCharIter { + rng: T, + simple_text: bool, + } + + impl RandomCharIter { + pub fn new(rng: T) -> Self { + Self { + rng, + simple_text: std::env::var("SIMPLE_TEXT").is_ok_and(|v| !v.is_empty()), + } + } + + pub fn with_simple_text(mut self) -> Self { + self.simple_text = true; + self + } + } + + impl Iterator for RandomCharIter { + type Item = char; + + fn next(&mut self) -> Option { + if self.simple_text { + return if self.rng.random_range(0..100) < 5 { + Some('\n') + } else { + Some(self.rng.random_range(b'a'..b'z' + 1).into()) + }; + } + + match self.rng.random_range(0..100) { + // whitespace + 0..=19 => [' ', '\n', '\r', '\t'].choose(&mut self.rng).copied(), + // two-byte greek letters + 20..=32 => char::from_u32(self.rng.random_range(('α' as u32)..('ω' as u32 + 1))), + // // three-byte characters + 33..=45 => ['✋', '✅', '❌', '❎', '⭐'] + .choose(&mut self.rng) + .copied(), + // // four-byte characters + 46..=58 => ['🍐', '🏀', '🍗', '🎉'].choose(&mut self.rng).copied(), + // ascii letters + _ => Some(self.rng.random_range(b'a'..b'z' + 1).into()), + } + } + } +} +#[cfg(any(test, feature = "test-support"))] +pub use rng::RandomCharIter; + +/// Get an embedded file as a string. +pub fn asset_str(path: &str) -> Cow<'static, str> { + match A::get(path).expect(path).data { + Cow::Borrowed(bytes) => Cow::Borrowed(std::str::from_utf8(bytes).unwrap()), + Cow::Owned(bytes) => Cow::Owned(String::from_utf8(bytes).unwrap()), + } +} + +pub trait RangeExt { + fn sorted(&self) -> Self; + fn to_inclusive(&self) -> RangeInclusive; + fn overlaps(&self, other: &Range) -> bool; + fn contains_inclusive(&self, other: &Range) -> bool; +} + +impl RangeExt for Range { + fn sorted(&self) -> Self { + cmp::min(&self.start, &self.end).clone()..cmp::max(&self.start, &self.end).clone() + } + + fn to_inclusive(&self) -> RangeInclusive { + self.start.clone()..=self.end.clone() + } + + fn overlaps(&self, other: &Range) -> bool { + self.start < other.end && other.start < self.end + } + + fn contains_inclusive(&self, other: &Range) -> bool { + self.start <= other.start && other.end <= self.end + } +} + +impl RangeExt for RangeInclusive { + fn sorted(&self) -> Self { + cmp::min(self.start(), self.end()).clone()..=cmp::max(self.start(), self.end()).clone() + } + + fn to_inclusive(&self) -> RangeInclusive { + self.clone() + } + + fn overlaps(&self, other: &Range) -> bool { + self.start() < &other.end && &other.start <= self.end() + } + + fn contains_inclusive(&self, other: &Range) -> bool { + self.start() <= &other.start && &other.end <= self.end() + } +} + +/// A way to sort strings with starting numbers numerically first, falling back to alphanumeric one, +/// case-insensitive. +/// +/// This is useful for turning regular alphanumerically sorted sequences as `1-abc, 10, 11-def, .., 2, 21-abc` +/// into `1-abc, 2, 10, 11-def, .., 21-abc` +#[derive(Debug, PartialEq, Eq)] +pub struct NumericPrefixWithSuffix<'a>(Option, &'a str); + +impl<'a> NumericPrefixWithSuffix<'a> { + pub fn from_numeric_prefixed_str(str: &'a str) -> Self { + let i = str.chars().take_while(|c| c.is_ascii_digit()).count(); + let (prefix, remainder) = str.split_at(i); + + let prefix = prefix.parse().ok(); + Self(prefix, remainder) + } +} + +/// When dealing with equality, we need to consider the case of the strings to achieve strict equality +/// to handle cases like "a" < "A" instead of "a" == "A". +impl Ord for NumericPrefixWithSuffix<'_> { + fn cmp(&self, other: &Self) -> Ordering { + match (self.0, other.0) { + (None, None) => UniCase::new(self.1) + .cmp(&UniCase::new(other.1)) + .then_with(|| self.1.cmp(other.1).reverse()), + (None, Some(_)) => Ordering::Greater, + (Some(_), None) => Ordering::Less, + (Some(a), Some(b)) => a.cmp(&b).then_with(|| { + UniCase::new(self.1) + .cmp(&UniCase::new(other.1)) + .then_with(|| self.1.cmp(other.1).reverse()) + }), + } + } +} + +impl PartialOrd for NumericPrefixWithSuffix<'_> { + fn partial_cmp(&self, other: &Self) -> Option { + Some(self.cmp(other)) + } +} + +fn emoji_regex() -> &'static Regex { + static EMOJI_REGEX: LazyLock = + LazyLock::new(|| Regex::new("(\\p{Emoji}|\u{200D})").unwrap()); + &EMOJI_REGEX +} + +/// Returns true if the given string consists of emojis only. +/// E.g. "👨‍👩‍👧‍👧👋" will return true, but "👋!" will return false. +pub fn word_consists_of_emojis(s: &str) -> bool { + let mut prev_end = 0; + for capture in emoji_regex().find_iter(s) { + if capture.start() != prev_end { + return false; + } + prev_end = capture.end(); + } + prev_end == s.len() +} + +/// Similar to `str::split`, but also provides byte-offset ranges of the results. Unlike +/// `str::split`, this is not generic on pattern types and does not return an `Iterator`. +pub fn split_str_with_ranges<'s>( + s: &'s str, + pat: &dyn Fn(char) -> bool, +) -> Vec<(Range, &'s str)> { + let mut result = Vec::new(); + let mut start = 0; + + for (i, ch) in s.char_indices() { + if pat(ch) { + if i > start { + result.push((start..i, &s[start..i])); + } + start = i + ch.len_utf8(); + } + } + + if s.len() > start { + result.push((start..s.len(), &s[start..s.len()])); + } + + result +} + +pub fn default() -> D { + Default::default() +} + +#[derive(Debug)] +pub enum ConnectionResult { + Timeout, + ConnectionReset, + Result(anyhow::Result), +} + +impl ConnectionResult { + pub fn into_response(self) -> anyhow::Result { + match self { + ConnectionResult::Timeout => anyhow::bail!("Request timed out"), + ConnectionResult::ConnectionReset => anyhow::bail!("Server reset the connection"), + ConnectionResult::Result(r) => r, + } + } +} + +impl From> for ConnectionResult { + fn from(result: anyhow::Result) -> Self { + ConnectionResult::Result(result) + } +} + +/// Normalizes a path by resolving `.` and `..` components without +/// requiring the path to exist on disk (unlike `canonicalize`). +pub fn normalize_path(path: &Path) -> PathBuf { + use std::path::Component; + let mut components = path.components().peekable(); + let mut ret = if let Some(c @ Component::Prefix(..)) = components.peek().cloned() { + components.next(); + PathBuf::from(c.as_os_str()) + } else { + PathBuf::new() + }; + + for component in components { + match component { + Component::Prefix(..) => unreachable!(), + Component::RootDir => { + ret.push(component.as_os_str()); + } + Component::CurDir => {} + Component::ParentDir => { + ret.pop(); + } + Component::Normal(c) => { + ret.push(c); + } + } + } + ret +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn test_extend_sorted() { + let mut vec = vec![]; + + extend_sorted(&mut vec, vec![21, 17, 13, 8, 1, 0], 5, |a, b| b.cmp(a)); + assert_eq!(vec, &[21, 17, 13, 8, 1]); + + extend_sorted(&mut vec, vec![101, 19, 17, 8, 2], 8, |a, b| b.cmp(a)); + assert_eq!(vec, &[101, 21, 19, 17, 13, 8, 2, 1]); + + extend_sorted(&mut vec, vec![1000, 19, 17, 9, 5], 8, |a, b| b.cmp(a)); + assert_eq!(vec, &[1000, 101, 21, 19, 17, 13, 9, 8]); + } + + #[test] + fn test_truncate_to_bottom_n_sorted_by() { + let mut vec: Vec = vec![5, 2, 3, 4, 1]; + truncate_to_bottom_n_sorted_by(&mut vec, 10, &u32::cmp); + assert_eq!(vec, &[1, 2, 3, 4, 5]); + + vec = vec![5, 2, 3, 4, 1]; + truncate_to_bottom_n_sorted_by(&mut vec, 5, &u32::cmp); + assert_eq!(vec, &[1, 2, 3, 4, 5]); + + vec = vec![5, 2, 3, 4, 1]; + truncate_to_bottom_n_sorted_by(&mut vec, 4, &u32::cmp); + assert_eq!(vec, &[1, 2, 3, 4]); + + vec = vec![5, 2, 3, 4, 1]; + truncate_to_bottom_n_sorted_by(&mut vec, 1, &u32::cmp); + assert_eq!(vec, &[1]); + + vec = vec![5, 2, 3, 4, 1]; + truncate_to_bottom_n_sorted_by(&mut vec, 0, &u32::cmp); + assert!(vec.is_empty()); + } + + #[test] + fn test_iife() { + fn option_returning_function() -> Option<()> { + None + } + + let foo = maybe!({ + option_returning_function()?; + Some(()) + }); + + assert_eq!(foo, None); + } + + #[test] + fn test_truncate_and_trailoff() { + assert_eq!(truncate_and_trailoff("", 5), ""); + assert_eq!(truncate_and_trailoff("aaaaaa", 7), "aaaaaa"); + assert_eq!(truncate_and_trailoff("aaaaaa", 6), "aaaaaa"); + assert_eq!(truncate_and_trailoff("aaaaaa", 5), "aaaaa…"); + assert_eq!(truncate_and_trailoff("èèèèèè", 7), "èèèèèè"); + assert_eq!(truncate_and_trailoff("èèèèèè", 6), "èèèèèè"); + assert_eq!(truncate_and_trailoff("èèèèèè", 5), "èèèèè…"); + } + + #[test] + fn test_truncate_and_remove_front() { + assert_eq!(truncate_and_remove_front("", 5), ""); + assert_eq!(truncate_and_remove_front("aaaaaa", 7), "aaaaaa"); + assert_eq!(truncate_and_remove_front("aaaaaa", 6), "aaaaaa"); + assert_eq!(truncate_and_remove_front("aaaaaa", 5), "…aaaaa"); + assert_eq!(truncate_and_remove_front("èèèèèè", 7), "èèèèèè"); + assert_eq!(truncate_and_remove_front("èèèèèè", 6), "èèèèèè"); + assert_eq!(truncate_and_remove_front("èèèèèè", 5), "…èèèèè"); + } + + #[test] + fn test_numeric_prefix_str_method() { + let target = "1a"; + assert_eq!( + NumericPrefixWithSuffix::from_numeric_prefixed_str(target), + NumericPrefixWithSuffix(Some(1), "a") + ); + + let target = "12ab"; + assert_eq!( + NumericPrefixWithSuffix::from_numeric_prefixed_str(target), + NumericPrefixWithSuffix(Some(12), "ab") + ); + + let target = "12_ab"; + assert_eq!( + NumericPrefixWithSuffix::from_numeric_prefixed_str(target), + NumericPrefixWithSuffix(Some(12), "_ab") + ); + + let target = "1_2ab"; + assert_eq!( + NumericPrefixWithSuffix::from_numeric_prefixed_str(target), + NumericPrefixWithSuffix(Some(1), "_2ab") + ); + + let target = "1.2"; + assert_eq!( + NumericPrefixWithSuffix::from_numeric_prefixed_str(target), + NumericPrefixWithSuffix(Some(1), ".2") + ); + + let target = "1.2_a"; + assert_eq!( + NumericPrefixWithSuffix::from_numeric_prefixed_str(target), + NumericPrefixWithSuffix(Some(1), ".2_a") + ); + + let target = "12.2_a"; + assert_eq!( + NumericPrefixWithSuffix::from_numeric_prefixed_str(target), + NumericPrefixWithSuffix(Some(12), ".2_a") + ); + + let target = "12a.2_a"; + assert_eq!( + NumericPrefixWithSuffix::from_numeric_prefixed_str(target), + NumericPrefixWithSuffix(Some(12), "a.2_a") + ); + } + + #[test] + fn test_numeric_prefix_with_suffix() { + let mut sorted = vec!["1-abc", "10", "11def", "2", "21-abc"]; + sorted.sort_by_key(|s| NumericPrefixWithSuffix::from_numeric_prefixed_str(s)); + assert_eq!(sorted, ["1-abc", "2", "10", "11def", "21-abc"]); + + for numeric_prefix_less in ["numeric_prefix_less", "aaa", "~™£"] { + assert_eq!( + NumericPrefixWithSuffix::from_numeric_prefixed_str(numeric_prefix_less), + NumericPrefixWithSuffix(None, numeric_prefix_less), + "String without numeric prefix `{numeric_prefix_less}` should not be converted into NumericPrefixWithSuffix" + ) + } + } + + #[test] + fn test_word_consists_of_emojis() { + let words_to_test = vec![ + ("👨‍👩‍👧‍👧👋🥒", true), + ("👋", true), + ("!👋", false), + ("👋!", false), + ("👋 ", false), + (" 👋", false), + ("Test", false), + ]; + + for (text, expected_result) in words_to_test { + assert_eq!(word_consists_of_emojis(text), expected_result); + } + } + + #[test] + fn test_truncate_lines_and_trailoff() { + let text = r#"Line 1 +Line 2 +Line 3"#; + + assert_eq!( + truncate_lines_and_trailoff(text, 2), + r#"Line 1 +…"# + ); + + assert_eq!( + truncate_lines_and_trailoff(text, 3), + r#"Line 1 +Line 2 +…"# + ); + + assert_eq!( + truncate_lines_and_trailoff(text, 4), + r#"Line 1 +Line 2 +Line 3"# + ); + } + + #[test] + fn test_expanded_and_wrapped_usize_range() { + // Neither wrap + assert_eq!( + expanded_and_wrapped_usize_range(2..4, 1, 1, 8).collect::>(), + (1..5).collect::>() + ); + // Start wraps + assert_eq!( + expanded_and_wrapped_usize_range(2..4, 3, 1, 8).collect::>(), + ((0..5).chain(7..8)).collect::>() + ); + // Start wraps all the way around + assert_eq!( + expanded_and_wrapped_usize_range(2..4, 5, 1, 8).collect::>(), + (0..8).collect::>() + ); + // Start wraps all the way around and past 0 + assert_eq!( + expanded_and_wrapped_usize_range(2..4, 10, 1, 8).collect::>(), + (0..8).collect::>() + ); + // End wraps + assert_eq!( + expanded_and_wrapped_usize_range(3..5, 1, 4, 8).collect::>(), + (0..1).chain(2..8).collect::>() + ); + // End wraps all the way around + assert_eq!( + expanded_and_wrapped_usize_range(3..5, 1, 5, 8).collect::>(), + (0..8).collect::>() + ); + // End wraps all the way around and past the end + assert_eq!( + expanded_and_wrapped_usize_range(3..5, 1, 10, 8).collect::>(), + (0..8).collect::>() + ); + // Both start and end wrap + assert_eq!( + expanded_and_wrapped_usize_range(3..5, 4, 4, 8).collect::>(), + (0..8).collect::>() + ); + } + + #[test] + fn test_wrapped_usize_outward_from() { + // No wrapping + assert_eq!( + wrapped_usize_outward_from(4, 2, 2, 10).collect::>(), + vec![4, 5, 3, 6, 2] + ); + // Wrapping at end + assert_eq!( + wrapped_usize_outward_from(8, 2, 3, 10).collect::>(), + vec![8, 9, 7, 0, 6, 1] + ); + // Wrapping at start + assert_eq!( + wrapped_usize_outward_from(1, 3, 2, 10).collect::>(), + vec![1, 2, 0, 3, 9, 8] + ); + // All values wrap around + assert_eq!( + wrapped_usize_outward_from(5, 10, 10, 8).collect::>(), + vec![5, 6, 4, 7, 3, 0, 2, 1] + ); + // None before / after + assert_eq!( + wrapped_usize_outward_from(3, 0, 0, 8).collect::>(), + vec![3] + ); + // Starting point already wrapped + assert_eq!( + wrapped_usize_outward_from(15, 2, 2, 10).collect::>(), + vec![5, 6, 4, 7, 3] + ); + // wrap_length of 0 + assert_eq!( + wrapped_usize_outward_from(4, 2, 2, 0).collect::>(), + Vec::::new() + ); + } + + #[test] + fn test_split_with_ranges() { + let input = "hi"; + let result = split_str_with_ranges(input, &|c| c == ' '); + + assert_eq!(result.len(), 1); + assert_eq!(result[0], (0..2, "hi")); + + let input = "héllo🦀world"; + let result = split_str_with_ranges(input, &|c| c == '🦀'); + + assert_eq!(result.len(), 2); + assert_eq!(result[0], (0..6, "héllo")); // 'é' is 2 bytes + assert_eq!(result[1], (10..15, "world")); // '🦀' is 4 bytes + } +} diff --git a/flake.nix b/flake.nix index d924d89ca7..906aba24f4 100644 --- a/flake.nix +++ b/flake.nix @@ -25,12 +25,15 @@ pkgs = nixpkgs.legacyPackages.${system}; inherit (pkgs) lib; - toolchain = fenix.packages.${system}.latest.withComponents [ - "cargo" - "rustc" - "rust-src" - "rustfmt" - "clippy" + toolchain = fenix.packages.${system}.combine [ + (fenix.packages.${system}.latest.withComponents [ + "cargo" + "rustc" + "rust-src" + "rustfmt" + "clippy" + ]) + fenix.packages.${system}.targets.wasm32-unknown-unknown.latest.rust-std ]; craneLib = (crane.mkLib pkgs).overrideToolchain toolchain; @@ -105,18 +108,41 @@ packages.default = gpui; devShells.default = pkgs.mkShell { - inputsFrom = [ gpui ]; + # Provide rustup's cargo/rustc proxy (so `cargo +toolchain` works for + # the MSRV and WASM-atomics CI checks) plus all the native build deps. packages = [ - toolchain + pkgs.rustup pkgs.cargo-machete pkgs.taplo pkgs.typos pkgs.just - ]; + pkgs.nushell + pkgs.cmake + pkgs.pkg-config + pkgs.rustPlatform.bindgenHook + pkgs.fontconfig + pkgs.freetype + pkgs.openssl + pkgs.zlib + ] ++ lib.optionals pkgs.stdenv.isDarwin [ + pkgs.apple-sdk_15 + (pkgs.darwinMinVersionHook "11.0") + ] ++ lib.optionals pkgs.stdenv.isLinux linuxLibs; shellHook = '' export RUST_BACKTRACE=1 - export RUST_SRC_PATH="${toolchain}/lib/rustlib/src/rust/library" + ${lib.optionalString pkgs.stdenv.isDarwin '' + # Use the real Xcode SDK (not the nix apple-sdk stub) so that + # `xcrun` can find the system Metal toolchain used by gpui_macos + # to compile its .metal shaders. + export DEVELOPER_DIR=/Applications/Xcode.app/Contents/Developer + # The nix `apple-sdk`/xcbuild package installs a stub `xcrun` + # that doesn't know about the system Metal toolchain. Prefer the + # real /usr/bin/xcrun. + mkdir -p /tmp/gpui-ce-bin + ln -sf /usr/bin/xcrun /tmp/gpui-ce-bin/xcrun + export PATH="/tmp/gpui-ce-bin:$PATH" + ''} ${lib.optionalString pkgs.stdenv.isLinux '' export LD_LIBRARY_PATH="${lib.makeLibraryPath linuxLibs}:$LD_LIBRARY_PATH" ''} diff --git a/justfile b/justfile index 80dcd190ef..c14846fae3 100644 --- a/justfile +++ b/justfile @@ -403,12 +403,33 @@ publish dry="false": error make {msg: "CARGO_REGISTRY_TOKEN is not set"} } + # Topological publish order. Vendored support crates first, then core, + # then renderers/platform leaves, with gpui_platform LAST (it has + # target-conditional deps on every platform crate). let crates = [ + "crates/gpui_ce_util/Cargo.toml" + "crates/gpui_collections/Cargo.toml" + "crates/gpui_derive_refineable/Cargo.toml" + "crates/gpui_refineable/Cargo.toml" + "crates/gpui_sum_tree/Cargo.toml" + "crates/gpui_scheduler/Cargo.toml" + "crates/gpui_media/Cargo.toml" + "crates/gpui_zed_util/Cargo.toml" + + # core "crates/gpui_shared_string/Cargo.toml" "crates/gpui_macros/Cargo.toml" "crates/gpui/Cargo.toml" + + # renderers / platform leaves "crates/gpui_wgpu/Cargo.toml" "crates/gpui_tokio/Cargo.toml" + "crates/gpui_macos/Cargo.toml" + "crates/gpui_linux/Cargo.toml" + "crates/gpui_windows/Cargo.toml" + "crates/gpui_web/Cargo.toml" + "crates/gpui_elements/Cargo.toml" + "crates/gpui_platform/Cargo.toml" ] diff --git a/tooling/perf/src/main.rs b/tooling/perf/src/main.rs index 243658e508..5359a4a0ce 100644 --- a/tooling/perf/src/main.rs +++ b/tooling/perf/src/main.rs @@ -349,7 +349,9 @@ fn get_tests(t_bin: &str) -> impl ExactSizeIterator { ); let out = test_list - .chunks_exact_mut(2) + .as_chunks_mut::<2>() + .0 + .iter_mut() .map(|pair| { // Be resilient against changes to these constants. if consts::SUF_NORMAL < consts::SUF_MDATA { diff --git a/typos.toml b/typos.toml index 004f42d80b..6d12e81a6a 100644 --- a/typos.toml +++ b/typos.toml @@ -24,6 +24,8 @@ extend-ignore-re = [ check-filename = true [default.extend-words] +# Test key prefix used in sum_tree tests (keys starting with "ba") +ba = "ba" # Screen capture library (zed-scap) scap = "scap" # Win32 FORMATETC struct field: Pointer to DVTARGETDEVICE