diff --git a/.github/workflows/triage_queue_board.yml b/.github/workflows/triage_queue_board.yml index 2898283baac..378d30fceb0 100644 --- a/.github/workflows/triage_queue_board.yml +++ b/.github/workflows/triage_queue_board.yml @@ -1,4 +1,4 @@ -# Sync GitHub project #87 to the current second-line triage shift's issues +# Sync GitHub project #87 to the current triage shift's issues name: Issue Triage Queue Board diff --git a/Cargo.lock b/Cargo.lock index 9bd8b4cc56f..3165936c56b 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -314,7 +314,7 @@ dependencies = [ "text", "theme", "theme_settings", - "thiserror 2.0.17", + "thiserror 2.0.21", "ui", "unindent", "url", @@ -329,16 +329,16 @@ dependencies = [ [[package]] name = "agent-client-protocol" -version = "5.1.0" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c60cfd8cddbb23d9e30f51dca5316b4cea769ba55900db1fa8951dca4f28d02d" +checksum = "32339d83e679c8092ec69d2f18e84448f4acf09b46a753e48f3e9265f920acb1" dependencies = [ "agent-client-protocol-derive", "agent-client-protocol-schema", "anyhow", "futures 0.3.34", "futures-concurrency", - "rustc-hash 2.1.1", + "rustc-hash 2.1.3", "schemars 1.0.4", "serde", "serde_json", @@ -348,9 +348,9 @@ dependencies = [ [[package]] name = "agent-client-protocol-derive" -version = "5.1.0" +version = "5.2.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b296716e42d77d38aef7f645cbe0765287b0e0a84722cb9f8ac39e6cdcecdb2a" +checksum = "05a39fd0d81daab854d25144e82e31006b87c554818beb695f0edb576e9c54c4" dependencies = [ "quote", "syn 3.0.3", @@ -358,9 +358,9 @@ dependencies = [ [[package]] name = "agent-client-protocol-schema" -version = "1.16.0" +version = "1.17.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e20d2c4af6eb08f6a4f562520bdd939a4af803255fec461dd523638c22f5b265" +checksum = "3fd595be39fc4f9c8170872e5d10d81b44cb6dca44bcc66daba0d34412d4237d" dependencies = [ "anyhow", "derive_more", @@ -404,7 +404,7 @@ dependencies = [ "task", "tempfile", "terminal", - "thiserror 2.0.17", + "thiserror 2.0.21", "ui", "util", "uuid", @@ -708,7 +708,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2f6660fb4ff692ef4937b1b4e74ab3d378653d8588389587d91f96a296907ea0" dependencies = [ "cssparser 0.37.0", - "html5ever", + "html5ever 0.39.0", "maplit", "url", ] @@ -804,7 +804,7 @@ dependencies = [ "serde", "serde_json", "strum 0.28.0", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -955,16 +955,6 @@ dependencies = [ "util", ] -[[package]] -name = "async-attributes" -version = "1.1.2" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "a3203e79f4dd9bdda415ed03cf14dae5a2bf775c683a00f94e9cd1faf0f596e5" -dependencies = [ - "quote", - "syn 1.0.109", -] - [[package]] name = "async-broadcast" version = "0.7.2" @@ -1177,7 +1167,6 @@ version = "1.13.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2c8e079a4ab67ae52b7403632e4618815d6db36d2a010cfe41b02c1b1578f93b" dependencies = [ - "async-attributes", "async-channel 1.9.0", "async-global-executor", "async-io", @@ -1279,7 +1268,7 @@ dependencies = [ "crc32fast", "futures-lite 2.6.1", "pin-project", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -1288,7 +1277,7 @@ version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a860072022177f903e59730004fb5dc13db9275b79bb2aef7ba8ce831956c233" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "futures-sink", "futures-util", "memchr", @@ -1368,7 +1357,7 @@ dependencies = [ "parking_lot", "rodio", "settings", - "thiserror 2.0.17", + "thiserror 2.0.21", "util", ] @@ -1472,7 +1461,7 @@ dependencies = [ "num-traits", "pastey 0.1.1", "rayon", - "thiserror 2.0.17", + "thiserror 2.0.21", "v_frame", "y4m", ] @@ -1518,7 +1507,7 @@ dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", "aws-types", - "bytes 1.11.1", + "bytes 1.12.1", "fastrand 2.3.0", "hex", "http 1.3.1", @@ -1544,9 +1533,9 @@ dependencies = [ [[package]] name = "aws-lc-rs" -version = "1.18.1" +version = "1.19.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b281d307588d634de920874890732659e2e7672f72b5e10e81badc1a8a83621e" +checksum = "048006790404103c488e6c5616b3e7e702a71292aadda08e8f7698a9e0d2eb53" dependencies = [ "aws-lc-sys", "untrusted 0.7.1", @@ -1555,9 +1544,9 @@ dependencies = [ [[package]] name = "aws-lc-sys" -version = "0.45.0" +version = "0.47.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9bff6c3b54fad79a2e60b8102caf565819711497c1f5f092f49508e2f5c31b27" +checksum = "8bfbe32ac36b3c428696ce315464181bc4029d689fd58e3f2a4e58c252242f52" dependencies = [ "cc", "cmake", @@ -1581,7 +1570,7 @@ dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", "aws-types", - "bytes 1.11.1", + "bytes 1.12.1", "bytes-utils", "fastrand 2.3.0", "http 0.2.12", @@ -1612,7 +1601,7 @@ dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", "aws-types", - "bytes 1.11.1", + "bytes 1.12.1", "fastrand 2.3.0", "http 0.2.12", "http 1.3.1", @@ -1638,7 +1627,7 @@ dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", "aws-types", - "bytes 1.11.1", + "bytes 1.12.1", "fastrand 2.3.0", "http 0.2.12", "http 1.3.1", @@ -1666,7 +1655,7 @@ dependencies = [ "aws-smithy-types", "aws-smithy-xml", "aws-types", - "bytes 1.11.1", + "bytes 1.12.1", "fastrand 2.3.0", "hex", "hmac", @@ -1697,7 +1686,7 @@ dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", "aws-types", - "bytes 1.11.1", + "bytes 1.12.1", "fastrand 2.3.0", "http 0.2.12", "http 1.3.1", @@ -1721,7 +1710,7 @@ dependencies = [ "aws-smithy-runtime-api", "aws-smithy-types", "aws-types", - "bytes 1.11.1", + "bytes 1.12.1", "fastrand 2.3.0", "http 0.2.12", "http 1.3.1", @@ -1765,7 +1754,7 @@ dependencies = [ "aws-smithy-http", "aws-smithy-runtime-api", "aws-smithy-types", - "bytes 1.11.1", + "bytes 1.12.1", "crypto-bigint 0.5.5", "form_urlencoded", "hex", @@ -1801,7 +1790,7 @@ checksum = "a764fa7222922f6c0af8eea478b0ef1ba5ce1222af97e01f33ca5e957bd7f3b9" dependencies = [ "aws-smithy-http", "aws-smithy-types", - "bytes 1.11.1", + "bytes 1.12.1", "crc-fast", "hex", "http 1.3.1", @@ -1821,7 +1810,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "faf09d74e5e32f76b8762da505a3cd59303e367a664ca67295387baa8c1d7548" dependencies = [ "aws-smithy-types", - "bytes 1.11.1", + "bytes 1.12.1", "crc32fast", ] @@ -1834,7 +1823,7 @@ dependencies = [ "aws-smithy-eventstream", "aws-smithy-runtime-api", "aws-smithy-types", - "bytes 1.11.1", + "bytes 1.12.1", "bytes-utils", "futures-core", "futures-util", @@ -1913,7 +1902,7 @@ dependencies = [ "aws-smithy-observability", "aws-smithy-runtime-api", "aws-smithy-types", - "bytes 1.11.1", + "bytes 1.12.1", "fastrand 2.3.0", "http 0.2.12", "http 1.3.1", @@ -1935,7 +1924,7 @@ dependencies = [ "aws-smithy-async", "aws-smithy-runtime-api-macros", "aws-smithy-types", - "bytes 1.11.1", + "bytes 1.12.1", "http 0.2.12", "http 1.3.1", "pin-project-lite", @@ -1973,7 +1962,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "53f93074121a1be41317b9aa607143ae17900631f7f59a99f2b905d519d6783b" dependencies = [ "base64-simd", - "bytes 1.11.1", + "bytes 1.12.1", "bytes-utils", "futures-core", "http 0.2.12", @@ -2034,7 +2023,7 @@ dependencies = [ "axum-core", "base64 0.21.7", "bitflags 1.3.2", - "bytes 1.11.1", + "bytes 1.12.1", "futures-util", "headers", "http 0.2.12", @@ -2067,7 +2056,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "759fa577a247914fd3f7f76d62972792636412fbfd634cd452f6a385a74d2d2c" dependencies = [ "async-trait", - "bytes 1.11.1", + "bytes 1.12.1", "futures-util", "http 0.2.12", "http-body 0.4.6", @@ -2110,6 +2099,12 @@ version = "0.22.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "72b3254f16251a8381aa12e40e3c4d2f0199f8c6508fbecb9d91f575e0fbb8c6" +[[package]] +name = "base64" +version = "0.23.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ac07cdecf99051d9a5238b80f35af32cdeba5b336e55d957b318b50137e18da5" + [[package]] name = "base64-simd" version = "0.8.0" @@ -2139,7 +2134,7 @@ dependencies = [ "serde", "serde_json", "strum 0.28.0", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -2237,7 +2232,7 @@ dependencies = [ "proc-macro2", "quote", "regex", - "rustc-hash 2.1.1", + "rustc-hash 2.1.3", "shlex 1.3.0", "syn 2.0.117", ] @@ -2403,7 +2398,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "553c5d846a6ba5150c65e3b1b8ec073bcf1abc20f9b7220de384a4443ea4e20a" dependencies = [ "borsh-derive", - "bytes 1.11.1", + "bytes 1.12.1", "cfg_aliases", ] @@ -2439,7 +2434,7 @@ dependencies = [ "cached", "indenter", "peg", - "thiserror 2.0.17", + "thiserror 2.0.21", "tracing", "utf8-chars", ] @@ -2558,9 +2553,9 @@ dependencies = [ [[package]] name = "bytes" -version = "1.11.1" +version = "1.12.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1e748733b7cbc798e1434b6ac524f0c1ff2ab456fe201501e6497c8417a4fc33" +checksum = "fc652a48c352aef3ea3aed32080501cf3ef6ed5da78602a020c991775b0aff04" [[package]] name = "bytes-utils" @@ -2568,7 +2563,7 @@ version = "0.1.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7dafe3a8757b027e2be6e4e5601ed563c55989fcf1546e933c66c8eb3a058d35" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "either", ] @@ -2598,7 +2593,7 @@ dependencies = [ "cached_proc_macro_types", "hashbrown 0.15.5", "once_cell", - "thiserror 2.0.17", + "thiserror 2.0.21", "web-time", ] @@ -2744,7 +2739,7 @@ dependencies = [ "semver", "serde", "serde_json", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -2779,7 +2774,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "eadd868a2ce9ca38de7eeafdcec9c7065ef89b42b32f0839278d55f35c54d1ff" dependencies = [ "heck 0.4.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "proc-macro2", "quote", @@ -3086,7 +3081,7 @@ dependencies = [ "telemetry", "telemetry_events", "text", - "thiserror 2.0.17", + "thiserror 2.0.21", "time", "tiny_http", "tokio", @@ -3124,7 +3119,7 @@ dependencies = [ "parking_lot", "serde", "serde_json", - "thiserror 2.0.17", + "thiserror 2.0.21", "tokio-rustls", "yawc", ] @@ -3171,7 +3166,7 @@ version = "0.3.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fa961b519f0b462e3a3b4a34b64d119eeaca1d59af726fe450bbba07a9fc0a1" dependencies = [ - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -3344,8 +3339,8 @@ name = "collections" version = "0.1.0" dependencies = [ "gpui_util", - "indexmap 2.14.0", - "rustc-hash 2.1.1", + "indexmap 2.14.2", + "rustc-hash 2.1.3", ] [[package]] @@ -3366,7 +3361,7 @@ version = "4.6.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba5a308b75df32fe02788e748662718f03fde005016435c444eea572398219fd" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "memchr", ] @@ -3377,7 +3372,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f849b92c694fe237ecd8fafd1ba0df7ae0d45c1df6daeb7f68ed4220d51640bd" dependencies = [ "nix 0.30.1", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -3843,7 +3838,7 @@ dependencies = [ "linebender_resource_handle", "log", "rangemap", - "rustc-hash 2.1.1", + "rustc-hash 2.1.3", "self_cell", "skrifa 0.40.0", "smol_str", @@ -3972,7 +3967,7 @@ dependencies = [ "postcard", "pulley-interpreter", "regalloc2", - "rustc-hash 2.1.1", + "rustc-hash 2.1.3", "serde", "serde_derive", "sha2", @@ -4114,7 +4109,7 @@ dependencies = [ "serde", "serde_json", "smol", - "thiserror 2.0.17", + "thiserror 2.0.21", "url", ] @@ -4280,19 +4275,6 @@ dependencies = [ "typenum", ] -[[package]] -name = "cssparser" -version = "0.36.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dae61cf9c0abb83bd659dab65b7e4e38d8236824c85f0f804f173567bda257d2" -dependencies = [ - "cssparser-macros", - "dtoa-short", - "itoa", - "phf 0.13.1", - "smallvec", -] - [[package]] name = "cssparser" version = "0.37.0" @@ -4305,13 +4287,26 @@ dependencies = [ ] [[package]] -name = "cssparser-macros" -version = "0.6.1" +name = "cssparser" +version = "0.38.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "13b588ba4ac1a99f7f2964d24b3d896ddc6bf847ee3855dbd4366f058cfcd331" +checksum = "11119743ad110e8c1bdccd930d7f5c30c99e5fc76a7b63ec9807e84eef0c5f59" +dependencies = [ + "cssparser-macros", + "dtoa-short", + "itoa", + "phf 0.14.0", + "smallvec", +] + +[[package]] +name = "cssparser-macros" +version = "0.7.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d045de693cb712d0b22c6a64be5b953f67b3ce00ab5ad3dd5d8b441886ab8e1a" dependencies = [ "quote", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] @@ -4364,7 +4359,7 @@ checksum = "d74b6bcf49ebbd91f1b1875b706ea46545032a14003b5557b7dfa4bbeba6766e" dependencies = [ "cc", "codespan-reporting", - "indexmap 2.14.0", + "indexmap 2.14.2", "proc-macro2", "quote", "scratch", @@ -4379,7 +4374,7 @@ checksum = "94ca2ad69673c4b35585edfa379617ac364bccd0ba0adf319811ba3a74ffa48a" dependencies = [ "clap", "codespan-reporting", - "indexmap 2.14.0", + "indexmap 2.14.2", "proc-macro2", "quote", "syn 2.0.117", @@ -4397,7 +4392,7 @@ version = "1.0.187" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "2a8ebf0b6138325af3ec73324cb3a48b64d57721f17291b151206782e61f66cd" dependencies = [ - "indexmap 2.14.0", + "indexmap 2.14.2", "proc-macro2", "quote", "syn 2.0.117", @@ -4962,7 +4957,7 @@ dependencies = [ "futures-util", "generational-box", "longest-increasing-subsequence", - "rustc-hash 2.1.1", + "rustc-hash 2.1.3", "rustversion", "serde", "slab", @@ -5082,7 +5077,7 @@ checksum = "c278cf01d971a2ce2e4a97f2af1c13706e111c2c05636a88f93520b61c75b3cb" dependencies = [ "documented-macros", "phf 0.13.1", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -5138,24 +5133,24 @@ dependencies = [ [[package]] name = "dugong" -version = "0.8.0-alpha.5" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "49e042d0154d5b36580c5151b45baeb008e5fdb00a918ea203e85f24f2c921e6" +checksum = "4994fa1094ddf0d95bdf4c6615367779fc2af7ae1d4d8e336334cf07245ace7a" dependencies = [ "dugong-graphlib", - "rustc-hash 2.1.1", + "rustc-hash 2.1.3", "serde", "serde_json", ] [[package]] name = "dugong-graphlib" -version = "0.8.0-alpha.5" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "219fd4382e892b3eb905d02a7cfb30ca60a7dad662a554b4aebf056f270c7649" +checksum = "eb6a3100cd9ceabcec9e7e6345e30c63e72f65423316314707c5c070a003d751" dependencies = [ "hashbrown 0.17.1", - "rustc-hash 2.1.1", + "rustc-hash 2.1.3", "serde", "serde_json", ] @@ -5245,7 +5240,7 @@ dependencies = [ "postage", "pretty_assertions", "project", - "pulldown-cmark 0.13.4", + "pulldown-cmark 0.13.6", "rand 0.9.4", "regex", "release_channel", @@ -5257,7 +5252,7 @@ dependencies = [ "telemetry", "telemetry_events", "text", - "thiserror 2.0.17", + "thiserror 2.0.21", "toml 0.9.8", "ui", "util", @@ -6036,7 +6031,7 @@ dependencies = [ "snippet_provider", "task", "theme_settings", - "thiserror 2.0.17", + "thiserror 2.0.21", "tokio", "toml 0.9.8", "tree-sitter", @@ -6378,12 +6373,6 @@ version = "0.3.2" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8ce81f49ae8a0482e4c55ea62ebbd7e5a686af544c00b9d090bba3ff9be97b3d" -[[package]] -name = "float_next_after" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "8bf7cc16383c4b8d58b9905a8509f02926ce3058053c056376248d958c9df1e8" - [[package]] name = "fluent-uri" version = "0.4.1" @@ -6589,7 +6578,7 @@ dependencies = [ "telemetry", "tempfile", "text", - "thiserror 2.0.17", + "thiserror 2.0.21", "trash", "unicode-normalization", "util", @@ -6930,7 +6919,7 @@ dependencies = [ "derive_more", "derive_setters", "gh-workflow-macros", - "indexmap 2.14.0", + "indexmap 2.14.2", "merge", "serde", "serde_json", @@ -6972,7 +6961,7 @@ checksum = "0bf7f043f89559805f8c7cacc432749b2fa0d0a0a9ee46ce47164ed5ba7f126c" dependencies = [ "fnv", "hashbrown 0.16.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "stable_deref_trait", ] @@ -7018,7 +7007,7 @@ dependencies = [ "sum_tree", "tempfile", "text", - "thiserror 2.0.17", + "thiserror 2.0.21", "time", "url", "urlencoding", @@ -7354,7 +7343,7 @@ dependencies = [ "hashbrown 0.16.1", "log", "presser", - "thiserror 2.0.17", + "thiserror 2.0.21", "windows 0.62.2", ] @@ -7396,7 +7385,8 @@ dependencies = [ "itertools 0.14.0", "libc", "log", - "lyon", + "lyon_extra", + "lyon_path", "num_cpus", "objc2 0.6.3", "objc2-core-foundation", @@ -7429,7 +7419,8 @@ dependencies = [ "subsecond", "sum_tree", "taffy", - "thiserror 2.0.17", + "thiserror 2.0.21", + "tiny-skia-path", "ttf-parser", "unicode-segmentation", "url", @@ -7478,7 +7469,7 @@ dependencies = [ "parking_lot", "pathfinder_geometry", "smallvec", - "thiserror 2.0.17", + "thiserror 2.0.21", "zed-font-kit", ] @@ -7583,6 +7574,7 @@ dependencies = [ "raw-window-handle", "scheduler", "semver", + "serde_json", "smallvec", "strum 0.28.0", "uuid", @@ -7686,6 +7678,7 @@ dependencies = [ "gpui_util", "image", "itertools 0.14.0", + "js-sys", "log", "naga", "parking_lot", @@ -7759,9 +7752,9 @@ dependencies = [ [[package]] name = "granit-parser" -version = "1.0.0" +version = "2.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c60388b03522b86e24b6b45952255279936b08a871775156fc89c94e792d21d8" +checksum = "05f05586d4d4df3d47123207826c40b252728b438a1a07bad3c01ee6bea401df" dependencies = [ "arraydeque", "smallvec", @@ -7791,7 +7784,7 @@ dependencies = [ "debug-ignore", "fixedbitset", "guppy-workspace-hack", - "indexmap 2.14.0", + "indexmap 2.14.2", "itertools 0.15.0", "nested", "once_cell", @@ -7817,13 +7810,13 @@ version = "0.3.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0beca50380b1fc32983fc1cb4587bfa4bb9e78fc259aad4a0032d2080309222d" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "fnv", "futures-core", "futures-sink", "futures-util", "http 0.2.12", - "indexmap 2.14.0", + "indexmap 2.14.2", "slab", "tokio", "tokio-util", @@ -7837,12 +7830,12 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ef8e5e5a340588f4452631496976cf8636d4a7ecf600239fdc27615d2530bc16" dependencies = [ "atomic-waker", - "bytes 1.11.1", + "bytes 1.12.1", "fnv", "futures-core", "futures-sink", "http 1.3.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "slab", "tokio", "tokio-util", @@ -8009,7 +8002,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "06683b93020a07e3dbcf5f8c0f6d40080d725bea7936fc01ad345c01b97dc270" dependencies = [ "base64 0.21.7", - "bytes 1.11.1", + "bytes 1.12.1", "headers-core", "http 0.2.12", "httpdate", @@ -8140,7 +8133,18 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "46a1761807faccc9a19e86944bbf40610014066306f96edcdedc2fb714bcb7b8" dependencies = [ "log", - "markup5ever", + "markup5ever 0.39.0", +] + +[[package]] +name = "html5ever" +version = "0.40.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "456a1a377e608e555d22ddab27ac0114bc7a7b4199078108e34c2aeae6c9b130" +dependencies = [ + "log", + "markup5ever 0.40.0", + "memchr", ] [[package]] @@ -8148,7 +8152,7 @@ name = "html_to_markdown" version = "0.1.0" dependencies = [ "anyhow", - "html5ever", + "html5ever 0.39.0", "indoc", "markup5ever_rcdom", "pretty_assertions", @@ -8164,7 +8168,7 @@ dependencies = [ "memchr", "pastey 0.1.1", "phf 0.13.1", - "phf_codegen", + "phf_codegen 0.13.1", "serde_json", ] @@ -8174,7 +8178,7 @@ version = "0.2.12" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "601cbb57e577e2f5ef5be8e7b83f0f63994f25aa94d673e54a92d5c516d101f1" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "fnv", "itoa", ] @@ -8185,7 +8189,7 @@ version = "1.3.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f4a85d31aea989eead29a3aaf9e1115a180df8282431156e533de47660892565" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "fnv", "itoa", ] @@ -8196,7 +8200,7 @@ version = "0.4.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7ceab25649e9960c0311ea418d17bee82c0dcec1bd053b5f9a66e265a693bed2" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "http 0.2.12", "pin-project-lite", ] @@ -8207,7 +8211,7 @@ version = "1.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "1efedce1fb8e6913f23e0c92de8e62cd5b772a67e7b3946df930a62566c93184" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "http 1.3.1", ] @@ -8217,7 +8221,7 @@ version = "0.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b021d93e26becf5dc7e1b75b1bed1fd93124b374ceb73f43d4d4eafec896a64a" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "futures-core", "http 1.3.1", "http-body 1.0.1", @@ -8235,7 +8239,7 @@ name = "http_client" version = "0.1.0" dependencies = [ "anyhow", - "bytes 1.11.1", + "bytes 1.12.1", "futures 0.3.34", "http 1.3.1", "http-body 1.0.1", @@ -8269,7 +8273,7 @@ dependencies = [ "log", "percent-encoding", "proxyvars", - "thiserror 2.0.17", + "thiserror 2.0.21", "url", ] @@ -8303,7 +8307,7 @@ version = "0.14.32" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41dfc780fdec9373c01bae43289ea34c972e40ee3c9f6b3c8801a35f35586ce7" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "futures-channel", "futures-core", "futures-util", @@ -8328,7 +8332,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "27b501faa50e7a26c3d3560ca625132f4078a17771f4810baf70475ae48cbe43" dependencies = [ "atomic-waker", - "bytes 1.11.1", + "bytes 1.12.1", "futures-channel", "futures-core", "h2 0.4.19", @@ -8378,7 +8382,7 @@ version = "0.5.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "d6183ddfa99b85da61a140bea0efc93fdf56ceaa041b37d553518030827f9905" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "hyper 0.14.32", "native-tls", "tokio", @@ -8392,7 +8396,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3c6995591a8f1380fcb4ba966a252a4b29188d51d2b89e3a252f5305be65aea8" dependencies = [ "base64 0.22.1", - "bytes 1.11.1", + "bytes 1.12.1", "futures-channel", "futures-core", "futures-util", @@ -8441,31 +8445,6 @@ dependencies = [ "strum 0.28.0", ] -[[package]] -name = "icu_collator" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "59eea194d189ca897bcb960fd2130f9e7d53998460d4d32e85a60b10d5507cf4" -dependencies = [ - "icu_collator_data", - "icu_collections", - "icu_locale_core", - "icu_locale_fallback", - "icu_normalizer", - "icu_properties", - "icu_provider", - "smallvec", - "utf16_iter", - "utf8_iter", - "zerovec", -] - -[[package]] -name = "icu_collator_data" -version = "2.3.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f7d7e54efdddeb1208c08dd5d32b53a879ac00d2d3d051b2255fd26821d16368" - [[package]] name = "icu_collections" version = "2.3.0" @@ -8525,9 +8504,6 @@ dependencies = [ "icu_properties", "icu_provider", "smallvec", - "utf16_iter", - "utf8_iter", - "write16", "zerovec", ] @@ -8775,9 +8751,9 @@ dependencies = [ [[package]] name = "indexmap" -version = "2.14.0" +version = "2.14.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d466e9454f08e4a911e14806c24e16fba1b4c121d1ea474396f396069cf949d9" +checksum = "cc4e190f5d26ca7051642629da2c52fc03bde85a03197c99408dcd291734c855" dependencies = [ "equivalent", "hashbrown 0.17.1", @@ -9126,7 +9102,7 @@ dependencies = [ "jni-sys 0.4.1", "log", "simd_cesu8", - "thiserror 2.0.17", + "thiserror 2.0.21", "walkdir", "windows-link 0.2.1", ] @@ -9206,9 +9182,9 @@ dependencies = [ [[package]] name = "json5" -version = "1.3.1" +version = "1.3.7" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "733a844dbd6fef128e98cb4487b887cb55454d92cd9994b1bafe004fabbe670c" +checksum = "0348cde6df2b507ba3c3753beba226baba8567af588d6568cdb9877f02c75b60" dependencies = [ "serde", "ucd-trie", @@ -9309,30 +9285,30 @@ dependencies = [ [[package]] name = "jupyter-protocol" -version = "1.4.0" +version = "2.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4649647741f9794a7a02e3be976f1b248ba28a37dbfc626d5089316fd4fbf4c8" +checksum = "cf199c30e61505042f5c0d79a33b5a71c552ea8b64243ff3498b1f4592d8e692" dependencies = [ "async-trait", - "bytes 1.11.1", + "bytes 1.12.1", "chrono", "futures 0.3.34", "serde", "serde_json", - "thiserror 2.0.17", + "thiserror 2.0.21", "uuid", ] [[package]] name = "jupyter-websocket-client" -version = "1.1.0" +version = "3.0.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "7c2ae4d8d5344f69bf9734b264e969c2139e30e932ce9b6455de9f65663ed614" +checksum = "f31dc36df1907d5350072e2d404ed815ac92c33e10c7fb2205b4eb67ed1b23f6" dependencies = [ "anyhow", "async-trait", "async-tungstenite", - "bytes 1.11.1", + "bytes 1.12.1", "futures 0.3.34", "jupyter-protocol", "serde", @@ -9342,6 +9318,26 @@ dependencies = [ "uuid", ] +[[package]] +name = "jupyter-zmq-client" +version = "3.0.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "6fb9fa2584acd956d0044dcb1c85d94e8c9147a5b59d3f1074c842eb14d6a609" +dependencies = [ + "async-dispatcher", + "aws-lc-rs", + "bytes 1.12.1", + "data-encoding", + "dirs", + "jupyter-protocol", + "serde", + "serde_json", + "smol", + "thiserror 2.0.21", + "uuid", + "zeromq", +] + [[package]] name = "keymap_editor" version = "0.1.0" @@ -9437,9 +9433,9 @@ dependencies = [ [[package]] name = "lalrpop-util" -version = "0.23.1" +version = "0.23.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "884f3e747ed2dcee867cda1b0c31a048f9e20de2d916a248949319921a2e666e" +checksum = "364b49d1c98c07972e16fe1346463becc08bcd663da04e6e37ab1bea068dce6a" [[package]] name = "language" @@ -9582,7 +9578,7 @@ dependencies = [ "log", "parking_lot", "serde_json", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -9603,7 +9599,7 @@ dependencies = [ "serde", "serde_json", "strum 0.28.0", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -9689,7 +9685,7 @@ dependencies = [ "semver", "serde", "serde_json", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -10050,7 +10046,7 @@ source = "git+https://github.com/zed-industries/livekit-rust-sdks?rev=fbda05eb27 dependencies = [ "base64 0.22.1", "bmrng", - "bytes 1.11.1", + "bytes 1.12.1", "chrono", "futures-util", "lazy_static", @@ -10299,25 +10295,6 @@ dependencies = [ "logos-codegen 0.16.1", ] -[[package]] -name = "lol_html" -version = "3.0.1" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "5adbb62638edf7e6bc88835cd3ea388bdd53382af42045da0e414ea78aa0c91a" -dependencies = [ - "bitflags 2.13.1", - "cfg-if", - "cssparser 0.36.0", - "encoding_rs", - "foldhash 0.2.0", - "hashbrown 0.17.1", - "memchr", - "mime", - "precomputed-hash", - "selectors", - "thiserror 2.0.17", -] - [[package]] name = "longest-increasing-subsequence" version = "0.1.0" @@ -10446,42 +10423,21 @@ dependencies = [ "workspace", ] -[[package]] -name = "lyon" -version = "1.0.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dbcb7d54d54c8937364c9d41902d066656817dce1e03a44e5533afebd1ef4352" -dependencies = [ - "lyon_algorithms", - "lyon_extra", - "lyon_tessellation", -] - -[[package]] -name = "lyon_algorithms" -version = "1.0.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f4c0829e28c4f336396f250d850c3987e16ce6db057ffe047ce0dd54aab6b647" -dependencies = [ - "lyon_path", - "num-traits", -] - [[package]] name = "lyon_extra" -version = "1.0.3" +version = "1.1.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1ca94c7bf1e2557c2798989c43416822c12fc5dcc5e17cc3307ef0e71894a955" +checksum = "7755f08423275157ad1680aaecc9ccb7e0cc633da3240fea2d1522935cc15c72" dependencies = [ "lyon_path", - "thiserror 1.0.69", + "thiserror 2.0.21", ] [[package]] name = "lyon_geom" -version = "1.0.17" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "4e16770d760c7848b0c1c2d209101e408207a65168109509f8483837a36cf2e7" +checksum = "4336502e29e32af93cf2dad2214ed6003c17ceb5bd499df77b1de663b9042b92" dependencies = [ "arrayvec", "euclid", @@ -10490,25 +10446,14 @@ dependencies = [ [[package]] name = "lyon_path" -version = "1.0.16" +version = "1.0.19" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "1aeca86bcfd632a15984ba029b539ffb811e0a70bf55e814ef8b0f54f506fdeb" +checksum = "5c463f9c428b7fc5ec885dcd39ce4aa61e29111d0e33483f6f98c74e89d8621e" dependencies = [ "lyon_geom", "num-traits", ] -[[package]] -name = "lyon_tessellation" -version = "1.0.16" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f3f586142e1280335b1bc89539f7c97dd80f08fc43e9ab1b74ef0a42b04aa353" -dependencies = [ - "float_next_after", - "lyon_path", - "num-traits", -] - [[package]] name = "mac-notification-sys" version = "0.6.15" @@ -10547,14 +10492,14 @@ checksum = "fc04a4c58212d57930a24bf47d3fa87485264a3a054e9c10e042eb373573ad3c" [[package]] name = "manatee" -version = "0.8.0-alpha.5" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "9741945d2b000ec5182e0c35edcff22cb592a3eda4e6efe34663718e3e54617f" +checksum = "f9a23acfcb976e41a388d6e6461c43a2bd6da9ab2a0703b6f77b9d609dd70a59" dependencies = [ - "indexmap 2.14.0", + "indexmap 2.14.2", "libm", - "rustc-hash 2.1.1", - "thiserror 2.0.17", + "rustc-hash 2.1.3", + "thiserror 2.0.21", ] [[package]] @@ -10575,7 +10520,7 @@ dependencies = [ "fs", "gpui", "gpui_platform", - "html5ever", + "html5ever 0.39.0", "image", "indoc", "language", @@ -10585,7 +10530,7 @@ dependencies = [ "markup5ever_rcdom", "mermaid_render", "node_runtime", - "pulldown-cmark 0.13.4", + "pulldown-cmark 0.13.6", "settings", "smallvec", "stacksafe", @@ -10629,7 +10574,18 @@ checksum = "7122d987ec5f704ee56f6e5b41a7d93722e9aae27ae07cafa4036c4d3f9757de" dependencies = [ "log", "tendril", - "web_atoms", + "web_atoms 0.2.6", +] + +[[package]] +name = "markup5ever" +version = "0.40.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "0ab3dc68ac4a0f5719e560136778c1ee716e296030d75dbd4484e37e39e3a842" +dependencies = [ + "log", + "tendril", + "web_atoms 0.3.0", ] [[package]] @@ -10638,8 +10594,8 @@ version = "0.39.0+unofficial" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "3ac010f19d6c4af81eeb4018a39d7a115de9d285af45c126a4ac02e6fc5716b7" dependencies = [ - "html5ever", - "markup5ever", + "html5ever 0.39.0", + "markup5ever 0.39.0", "tendril", "xml5ever", ] @@ -10780,6 +10736,7 @@ name = "mermaid_render" version = "0.1.0" dependencies = [ "anyhow", + "assets", "gpui", "mermaid_render", "merman", @@ -10792,70 +10749,119 @@ dependencies = [ [[package]] name = "merman" -version = "0.8.0-alpha.5" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "263b2e923bce36d7e5d799af599e762f0160f0e6f3a397564e913ef35d7718f6" +checksum = "e95a601a95395f286f1f7775ba00c352a11c85ab4debe3bdbef5fa0426a21809" dependencies = [ + "merman-analysis", + "merman-ascii", "merman-core", + "merman-editor-core", "merman-render", "serde_json", - "thiserror 2.0.17", + "thiserror 2.0.21", +] + +[[package]] +name = "merman-analysis" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "882ce663eb2f27f327204e46beeb0cbe69952eff735119a8cc189ffa339a27cc" +dependencies = [ + "merman-core", + "serde", + "serde-saphyr", + "serde_json", + "thiserror 2.0.21", +] + +[[package]] +name = "merman-ascii" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "9ef6776b79df107d266f5dd2f5227c4e4549a5c36533550e45bf73848bb31cb3" +dependencies = [ + "dugong", + "merman-core", + "rustc-hash 2.1.3", + "serde", + "serde_json", + "thiserror 2.0.21", + "unicode-segmentation", + "unicode-width 0.2.2", ] [[package]] name = "merman-core" -version = "0.8.0-alpha.5" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dae7b72e61bbc56c7bebb94ef0fa831886d66057d17298338b2a3cac6ab71def" +checksum = "9c65e0018fccd603956d97daf22c76f9877513d49aea9655a91240e503c5d17b" dependencies = [ + "cssparser 0.38.0", "euclid", "granit-parser", + "html5ever 0.40.1", "htmlize", - "indexmap 2.14.0", + "indexmap 2.14.2", "json5", "lalrpop-util", - "lol_html", - "rustc-hash 2.1.1", + "rustc-hash 2.1.3", "ryu-js", "serde", "serde_json", - "thiserror 2.0.17", - "unicode-general-category", + "thiserror 2.0.21", + "unicode-segmentation", + "unicode-width 0.2.2", "url", ] [[package]] -name = "merman-render" -version = "0.8.0-alpha.5" +name = "merman-editor-core" +version = "0.9.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "cd17bfdd6866df20f34a8697eba00e0b86efa734de0b6a629b07a755d748fd68" +checksum = "97e3cdc39dfdc5dd88e76e66566a75f4935cfad28fe4776e18067daa1aa11647" dependencies = [ - "base64 0.22.1", - "cssparser 0.36.0", + "merman-analysis", + "merman-core", + "serde", +] + +[[package]] +name = "merman-render" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "3cf1f994f9fe91cd7f5e0fbb4f7c9982585813c79aacad50d9351a23ee4d1520" +dependencies = [ + "base64 0.23.1", + "cssparser 0.38.0", "data-url", "dugong", - "icu_collator", - "icu_locale_core", - "indexmap 2.14.0", + "indexmap 2.14.2", "kurbo", "libm", "manatee", "merman-core", - "pulldown-cmark 0.13.4", - "quick-xml 0.41.0", + "merman-unicode-linebreak", + "pulldown-cmark 0.13.6", + "quick-xml 0.42.0", "roughr-merman", - "roxmltree 0.21.1", - "rustc-hash 2.1.1", + "roxmltree 0.21.2", + "rustc-hash 2.1.3", "ryu-js", "serde", "serde_json", "svgtypes", - "thiserror 2.0.17", - "unicode-linebreak", + "thiserror 2.0.21", "unicode-segmentation", "unicode-width 0.2.2", ] +[[package]] +name = "merman-unicode-linebreak" +version = "0.9.3" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5a3f1647028ecc1f9e0c6bafd851d8915a38ce8f93877f46b5157d35ad3903c3" + [[package]] name = "micromap" version = "0.3.0" @@ -10966,7 +10972,7 @@ dependencies = [ "scroll", "serde", "serde_json", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -10983,7 +10989,7 @@ dependencies = [ "parking_lot", "polling", "scroll", - "thiserror 2.0.17", + "thiserror 2.0.21", "uds", ] @@ -11144,7 +11150,7 @@ dependencies = [ "codespan-reporting", "half", "hashbrown 0.17.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "libm", "log", "naga-types", @@ -11152,7 +11158,7 @@ dependencies = [ "once_cell", "rustc-hash 1.1.0", "spirv", - "thiserror 2.0.17", + "thiserror 2.0.21", "unicode-ident", ] @@ -11162,9 +11168,9 @@ version = "30.0.0" source = "git+https://github.com/gfx-rs/wgpu?rev=cddb2f5d80dc0009b2ef6767635140cacf90a007#cddb2f5d80dc0009b2ef6767635140cacf90a007" dependencies = [ "hashbrown 0.17.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "rustc-hash 1.1.0", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -11195,9 +11201,9 @@ dependencies = [ [[package]] name = "nbformat" -version = "1.2.0" +version = "3.0.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d4983a40792c45e8639f77ef8e4461c55679cbc618f4b9e83830e8c7e79c8383" +checksum = "b2c06543f305caee515923b125a737c4d58079c063e25701f93f45077bb8d622" dependencies = [ "anyhow", "chrono", @@ -11312,12 +11318,18 @@ dependencies = [ "serde_json", "smol", "tempfile", - "thiserror 2.0.17", + "thiserror 2.0.21", "util", "watch", "which", ] +[[package]] +name = "nohash-hasher" +version = "0.2.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "2bf50223579dc7cdcfb3bfcacf7069ff68243f8c363f62ffa99cf000a6b9c451" + [[package]] name = "nom" version = "7.1.3" @@ -12019,7 +12031,7 @@ checksum = "2e5a6c098c7a3b6547378093f5cc30bc54fd361ce711e05293a5cc589562739b" dependencies = [ "crc32fast", "hashbrown 0.17.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "memchr", ] @@ -12032,7 +12044,7 @@ dependencies = [ "arc-swap", "async-trait", "base64 0.22.1", - "bytes 1.11.1", + "bytes 1.12.1", "cargo_metadata", "cfg-if", "chrono", @@ -12189,7 +12201,7 @@ dependencies = [ "serde", "serde_json", "strum 0.28.0", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -12227,7 +12239,7 @@ dependencies = [ "serde", "serde_json", "settings", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -12645,7 +12657,7 @@ version = "0.9.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a14e2757d877c0f607a82ce1b8560e224370f159d66c5d52eb55ea187ef0350e" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "chrono", "pbjson", "pbjson-build", @@ -13244,7 +13256,7 @@ checksum = "8701b58ea97060d5e5b155d383a69952a60943f0e6dfe30b04c287beb0b27455" dependencies = [ "fixedbitset", "hashbrown 0.15.5", - "indexmap 2.14.0", + "indexmap 2.14.2", ] [[package]] @@ -13277,6 +13289,17 @@ dependencies = [ "serde", ] +[[package]] +name = "phf" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "010378780309880b08997fae13be7834dba947d36393bd372f2b1556deb2a2f6" +dependencies = [ + "phf_macros 0.14.0", + "phf_shared 0.14.0", + "serde", +] + [[package]] name = "phf_codegen" version = "0.13.1" @@ -13287,6 +13310,16 @@ dependencies = [ "phf_shared 0.13.1", ] +[[package]] +name = "phf_codegen" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b585a510fb76fdebead6897982ef2a03a21d8e6cbcca904999742a4afc6ffe" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", +] + [[package]] name = "phf_generator" version = "0.11.3" @@ -13307,6 +13340,16 @@ dependencies = [ "phf_shared 0.13.1", ] +[[package]] +name = "phf_generator" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "aeb62e0959d5a1bebc965f4d15d9e2b7cea002b6b0f5ba8cde6cc26738467100" +dependencies = [ + "fastrand 2.3.0", + "phf_shared 0.14.0", +] + [[package]] name = "phf_macros" version = "0.11.3" @@ -13333,6 +13376,19 @@ dependencies = [ "syn 2.0.117", ] +[[package]] +name = "phf_macros" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "5fa8d0ca26d424d27630da600c6624696e7dec8bf7b3b492b383c5dc49e5e085" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", + "proc-macro2", + "quote", + "syn 2.0.117", +] + [[package]] name = "phf_shared" version = "0.11.3" @@ -13351,6 +13407,15 @@ dependencies = [ "siphasher 1.0.1", ] +[[package]] +name = "phf_shared" +version = "0.14.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "c6fd9027e2d9319be6349febd1db4e8d02aa544921200c9b777720ac34a3aa89" +dependencies = [ + "siphasher 1.0.1", +] + [[package]] name = "picker" version = "0.1.0" @@ -13509,7 +13574,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7da1d65da6dd5d1e44199ac0f58712d241c0f439f80adea8924d832384087f85" dependencies = [ "base64 0.22.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "quick-xml 0.41.0", "serde", "time", @@ -13820,7 +13885,7 @@ dependencies = [ "log", "process-reader", "serde", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -13896,7 +13961,7 @@ dependencies = [ "gpui", "http_client", "image", - "indexmap 2.14.0", + "indexmap 2.14.2", "itertools 0.14.0", "language", "log", @@ -14075,7 +14140,7 @@ dependencies = [ "memchr", "parking_lot", "protobuf", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -14156,7 +14221,7 @@ version = "0.14.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "528ac67416ff8646872a3c02cad9cc4ee5dc9f9540c9b10771855c95cb2e5ae1" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "prost-derive", ] @@ -14250,13 +14315,13 @@ version = "0.9.1" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4f25a07a73c6717f0b9bbbd685918f5df9815f7efba450b83d9c9dea41f0e3a1" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "miette", "prost", "prost-reflect", "prost-types", "protox-parse", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -14268,7 +14333,7 @@ dependencies = [ "logos 0.15.1", "miette", "prost-types", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -14281,7 +14346,7 @@ dependencies = [ "percent-encoding", "piper", "proptest", - "thiserror 2.0.17", + "thiserror 2.0.21", "tokio", "url", ] @@ -14320,9 +14385,9 @@ dependencies = [ [[package]] name = "pulldown-cmark" -version = "0.13.4" +version = "0.13.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e9f068eba8e7071c5f9511831b44f32c740d5adf574e990f946ddb53db2f314e" +checksum = "3db2be46835f013dd3f4fa7f5f7402c537787b54ebb6fe2b94bbdd7e2669bb7b" dependencies = [ "bitflags 2.13.1", "memchr", @@ -14425,21 +14490,30 @@ dependencies = [ "memchr", ] +[[package]] +name = "quick-xml" +version = "0.42.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "41b1177fdf999d2321d3fb46ff47159d9c1fb9ad66a4879f8c50a0b504615e9b" +dependencies = [ + "memchr", +] + [[package]] name = "quinn" version = "0.11.9" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "b9e20a958963c291dc322d98411f541009df2ced7b5a4f2bd52337638cfccf20" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "cfg_aliases", "pin-project-lite", "quinn-proto", "quinn-udp", - "rustc-hash 2.1.1", + "rustc-hash 2.1.3", "rustls", "socket2 0.6.5", - "thiserror 2.0.17", + "thiserror 2.0.21", "tokio", "tracing", "web-time", @@ -14451,17 +14525,17 @@ version = "0.11.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "a9746dbde176634f4f2f1faf2404e30a31b2bc1e9cafb5329c95d8177a18c9fc" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "getrandom 0.4.1", "lru-slab", "rand 0.10.2", "rand_pcg 0.10.2", "ring", - "rustc-hash 2.1.1", + "rustc-hash 2.1.3", "rustls", "rustls-pki-types", "slab", - "thiserror 2.0.17", + "thiserror 2.0.21", "tinyvec", "tracing", "web-time", @@ -14697,7 +14771,7 @@ dependencies = [ "rand 0.9.4", "rand_chacha 0.9.0", "simd_helpers", - "thiserror 2.0.17", + "thiserror 2.0.21", "v_frame", "wasm-bindgen", ] @@ -14855,7 +14929,7 @@ checksum = "a4e608c6638b9c18977b00b475ac1f28d14e84b27d8d42f70e0bf1e3dec127ac" dependencies = [ "getrandom 0.2.16", "libredox", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -14912,7 +14986,7 @@ dependencies = [ "bumpalo", "hashbrown 0.17.1", "log", - "rustc-hash 2.1.1", + "rustc-hash 2.1.3", "serde", "smallvec", ] @@ -14985,7 +15059,7 @@ dependencies = [ "smol", "telemetry", "tempfile", - "thiserror 2.0.17", + "thiserror 2.0.21", "util", "which", ] @@ -15078,7 +15152,7 @@ dependencies = [ "terminal", "theme", "theme_settings", - "thiserror 2.0.17", + "thiserror 2.0.21", "toml_edit 0.22.27", "unindent", "util", @@ -15119,6 +15193,7 @@ dependencies = [ "indoc", "jupyter-protocol", "jupyter-websocket-client", + "jupyter-zmq-client", "language", "languages", "log", @@ -15129,7 +15204,6 @@ dependencies = [ "picker", "project", "remote", - "runtimelib", "serde", "serde_json", "settings", @@ -15158,7 +15232,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "dd67538700a17451e7cba03ac727fb961abb7607553461627b97de0b89cf4a62" dependencies = [ "base64 0.21.7", - "bytes 1.11.1", + "bytes 1.12.1", "encoding_rs", "futures-core", "futures-util", @@ -15198,7 +15272,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9d0946410b9f7b082a427e4ef5c8ff541a88b357bc6c637c40db3a68ac70a36f" dependencies = [ "base64 0.22.1", - "bytes 1.11.1", + "bytes 1.12.1", "futures-channel", "futures-core", "futures-util", @@ -15236,7 +15310,7 @@ name = "reqwest_client" version = "0.1.0" dependencies = [ "anyhow", - "bytes 1.11.1", + "bytes 1.12.1", "futures 0.3.34", "gpui_util", "http_client", @@ -15336,7 +15410,7 @@ dependencies = [ "num-rational", "rtrb", "symphonia", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -15361,13 +15435,14 @@ dependencies = [ [[package]] name = "roughr-merman" -version = "0.12.3" +version = "0.12.6" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "0a1b0137cf48e915300be3fe4cf9f8f9a2af242ebf41b6f8fa716c2fd482f00b" +checksum = "e197669bd3b80a7952e04bd8226f71a266c5e1d456dc48e4d576e32c57570e36" dependencies = [ "euclid", "num-traits", "palette", + "ryu-js", "svgtypes", ] @@ -15379,9 +15454,9 @@ checksum = "6c20b6793b5c2fa6553b250154b78d6d0db37e72700ae35fad9387a46f487c97" [[package]] name = "roxmltree" -version = "0.21.1" +version = "0.21.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f1964b10c76125c36f8afe190065a4bf9a87bf324842c05701330bba9f1cacbb" +checksum = "9da7f59328b09405b181fee1018925fad50f157afb43c0c0f5c522c256dd5907" dependencies = [ "memchr", ] @@ -15457,32 +15532,6 @@ version = "0.3.5" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fae8ee26b0371a29a77d2b2d6b3ae13aa81def6f9bf1b1b92a32d279a5e709b7" -[[package]] -name = "runtimelib" -version = "1.4.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "fa84884e45ed4a1e663120cef3fc11f14d1a2a1933776e1c31599f7bd2dd0c9e" -dependencies = [ - "async-dispatcher", - "async-std", - "aws-lc-rs", - "base64 0.22.1", - "bytes 1.11.1", - "chrono", - "data-encoding", - "dirs", - "futures 0.3.34", - "glob", - "jupyter-protocol", - "serde", - "serde_json", - "shellexpand", - "smol", - "thiserror 2.0.17", - "uuid", - "zeromq", -] - [[package]] name = "rust-embed" version = "8.11.0" @@ -15544,9 +15593,9 @@ checksum = "08d43f7aa6b08d49f382cde6a7982047c3426db949b1424bc4b7ec9ae12c6ce2" [[package]] name = "rustc-hash" -version = "2.1.1" +version = "2.1.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "357703d41365b4b27c590e3ed91eabb1b663f07c4c084095e60cbed4362dff0d" +checksum = "6b1e7f9a428571be2dc5bc0505c13fb6bf936822b894ec87abf8a08a4e51742d" [[package]] name = "rustc_version" @@ -15730,15 +15779,15 @@ checksum = "9774ba4a74de5f7b1c1451ed6cd5285a32eddb5cccb8cc655a4e50009e06477f" [[package]] name = "ryu-js" -version = "1.0.2" +version = "1.0.3" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "dd29631678d6fb0903b69223673e122c32e9ae559d0960a38d574695ebc0ea15" +checksum = "04d056b875a9d2e6cb9a61d127afee9ac5999b9f87bcb32079d1318e505be714" [[package]] name = "saa" -version = "5.4.9" +version = "5.6.2" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "da0ba8adb63e0deebd0744d8fc5bea394c08029159deaf680513fec1a3949144" +checksum = "bd85992a680de788217d9c70b74aa7685b108cf1aba02f728fb27f1b27199ad1" [[package]] name = "same-file" @@ -15770,9 +15819,9 @@ dependencies = [ [[package]] name = "scc" -version = "3.5.6" +version = "3.8.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "e4bd9d1727de391b6982925d830baad51692fa2aa6e337733c03d95121ca2793" +checksum = "5d5f8ca67c4f6208caf824037a6a9df0211b4e0937fccc4f543441f294d04511" dependencies = [ "saa", "sdd", @@ -15835,7 +15884,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "82d20c4491bc164fa2f6c5d44565947a52ad80b9505d8e36f8d54c27c739fcd0" dependencies = [ "dyn-clone", - "indexmap 2.14.0", + "indexmap 2.14.2", "ref-cast", "schemars_derive", "serde", @@ -15892,9 +15941,12 @@ dependencies = [ [[package]] name = "sdd" -version = "4.6.2" +version = "4.8.11" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c25da4ae64b24edfcb0b0d30b96b2b0dbc64ec63aefeb6ec35bfc5ef167e5c9e" +checksum = "a31877eee03686b905845993b5d9809a220c9dd5a10e9d6021d7ca67384c9070" +dependencies = [ + "saa", +] [[package]] name = "sea-bae" @@ -15930,7 +15982,7 @@ dependencies = [ "serde_json", "sqlx", "strum 0.26.3", - "thiserror 2.0.17", + "thiserror 2.0.21", "time", "tracing", "url", @@ -16082,25 +16134,6 @@ dependencies = [ "libc", ] -[[package]] -name = "selectors" -version = "0.37.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "2cfaaa6035167f0e604e42723c7650d59ee269ef220d7bbe0565602c8a0173b9" -dependencies = [ - "bitflags 2.13.1", - "cssparser 0.36.0", - "derive_more", - "log", - "new_debug_unreachable", - "phf 0.13.1", - "phf_codegen", - "precomputed-hash", - "rustc-hash 2.1.1", - "servo_arc", - "smallvec", -] - [[package]] name = "self_cell" version = "1.2.2" @@ -16133,6 +16166,19 @@ dependencies = [ "serde_derive", ] +[[package]] +name = "serde-saphyr" +version = "2.1.1" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "d43fb82d550b07e6f929a58d7d0935182602f48ddead875f5ee313c41c8f07fe" +dependencies = [ + "base64 0.22.1", + "nohash-hasher", + "num-traits", + "serde_core", + "zmij", +] + [[package]] name = "serde_bytes" version = "0.11.19" @@ -16185,11 +16231,12 @@ dependencies = [ [[package]] name = "serde_json" -version = "1.0.151" +version = "1.0.154" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c841b55ecdae098c80dcae9cf767f6f8a0c2cdb3416bbef72181df4d0fe73f14" +checksum = "e7e9cc8b1b85264074fbcc02a88680c4096b1e47df8f739dceb03bf482f04bd6" dependencies = [ - "indexmap 2.14.0", + "foldhash 0.2.0", + "indexmap 2.14.2", "itoa", "memchr", "serde", @@ -16203,7 +16250,7 @@ version = "0.2.4" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0e033097bf0d2b59a62b42c18ebbb797503839b26afdda2c4e1415cb6c813540" dependencies = [ - "indexmap 2.14.0", + "indexmap 2.14.2", "itoa", "memchr", "ryu", @@ -16273,7 +16320,7 @@ dependencies = [ "chrono", "hex", "indexmap 1.9.3", - "indexmap 2.14.0", + "indexmap 2.14.2", "jiff", "schemars 0.9.0", "schemars 1.0.4", @@ -16301,7 +16348,7 @@ version = "0.9.34+deprecated" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6a8b1a1a2ebf674015cc02edccce75287f1a0130d394307b36743c2f5d504b47" dependencies = [ - "indexmap 2.14.0", + "indexmap 2.14.2", "itoa", "ryu", "serde", @@ -16314,22 +16361,13 @@ version = "0.10.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "7b4db627b98b36d4203a7b458cf3573730f2bb591b28871d916dfa9efabfd41f" dependencies = [ - "indexmap 2.14.0", + "indexmap 2.14.2", "itoa", "ryu", "serde", "unsafe-libyaml", ] -[[package]] -name = "servo_arc" -version = "0.4.3" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "170fb83ab34de17dc69aa7c67482b22218ddb85da56546f9bd6b929e32a05930" -dependencies = [ - "stable_deref_trait", -] - [[package]] name = "session" version = "0.1.0" @@ -16726,7 +16764,7 @@ checksum = "297f631f50729c8c99b84667867963997ec0b50f32b2a7dbcab828ef0541e8bb" dependencies = [ "num-bigint", "num-traits", - "thiserror 2.0.17", + "thiserror 2.0.21", "time", ] @@ -17044,7 +17082,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ee6798b1838b6a0f69c007c133b8df5866302197e404e8b6ee8ed3e3a5e68dc6" dependencies = [ "base64 0.22.1", - "bytes 1.11.1", + "bytes 1.12.1", "chrono", "crc", "crossbeam-queue", @@ -17056,7 +17094,7 @@ dependencies = [ "futures-util", "hashbrown 0.15.5", "hashlink 0.10.0", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "memchr", "once_cell", @@ -17066,7 +17104,7 @@ dependencies = [ "serde_json", "sha2", "smallvec", - "thiserror 2.0.17", + "thiserror 2.0.21", "time", "tokio", "tokio-stream", @@ -17124,7 +17162,7 @@ dependencies = [ "base64 0.22.1", "bitflags 2.13.1", "byteorder", - "bytes 1.11.1", + "bytes 1.12.1", "chrono", "crc", "digest", @@ -17152,7 +17190,7 @@ dependencies = [ "smallvec", "sqlx-core", "stringprep", - "thiserror 2.0.17", + "thiserror 2.0.21", "time", "tracing", "uuid", @@ -17192,7 +17230,7 @@ dependencies = [ "smallvec", "sqlx-core", "stringprep", - "thiserror 2.0.17", + "thiserror 2.0.21", "time", "tracing", "uuid", @@ -17219,7 +17257,7 @@ dependencies = [ "serde", "serde_urlencoded", "sqlx-core", - "thiserror 2.0.17", + "thiserror 2.0.21", "time", "tracing", "url", @@ -17311,6 +17349,18 @@ dependencies = [ "serde", ] +[[package]] +name = "string_cache" +version = "0.11.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "ffa8a5dbe8b3f0bbe29d4c3225daafaeead63afdc1b65fc4c01a1384166038e6" +dependencies = [ + "new_debug_unreachable", + "parking_lot", + "phf_shared 0.14.0", + "precomputed-hash", +] + [[package]] name = "string_cache_codegen" version = "0.6.1" @@ -17323,6 +17373,18 @@ dependencies = [ "quote", ] +[[package]] +name = "string_cache_codegen" +version = "0.11.2" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "928dcdf75e47626b3617a976ec205d9f057584c371c1f23b782129268d0e6edc" +dependencies = [ + "phf_generator 0.14.0", + "phf_shared 0.14.0", + "proc-macro2", + "quote", +] + [[package]] name = "stringprep" version = "0.1.5" @@ -17392,7 +17454,7 @@ dependencies = [ "memmap2", "serde", "subsecond-types", - "thiserror 2.0.17", + "thiserror 2.0.21", "wasm-bindgen", "wasm-bindgen-futures", "web-sys", @@ -17822,7 +17884,7 @@ dependencies = [ "editor", "fuzzy", "gpui", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "picker", "project", @@ -17929,7 +17991,7 @@ version = "0.7.3" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ed071c670382e85fc2f48ae706492d8c338f4f89bf72520d32f8abfe880aade" dependencies = [ - "thiserror 2.0.17", + "thiserror 2.0.21", "windows 0.61.3", "windows-version", ] @@ -18009,7 +18071,7 @@ dependencies = [ "task", "theme", "theme_settings", - "thiserror 2.0.17", + "thiserror 2.0.21", "url", "urlencoding", "util", @@ -18106,7 +18168,7 @@ dependencies = [ "serde_json_lenient", "strum 0.28.0", "syntax_theme", - "thiserror 2.0.17", + "thiserror 2.0.21", "uuid", ] @@ -18130,7 +18192,7 @@ dependencies = [ "clap", "collections", "gpui", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "palette", "serde", @@ -18196,11 +18258,11 @@ dependencies = [ [[package]] name = "thiserror" -version = "2.0.17" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "f63587ca0f12b72a0600bcba1d40081f830876000bb46dd2337a3051618f4fc8" +checksum = "09e52cb86a36cede5cb101bf8908837b3e4c6e5e59fe7fd85c23fb56200d189e" dependencies = [ - "thiserror-impl 2.0.17", + "thiserror-impl 2.0.21", ] [[package]] @@ -18216,13 +18278,13 @@ dependencies = [ [[package]] name = "thiserror-impl" -version = "2.0.17" +version = "2.0.21" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "3ff15c8ecd7de3849db632e14d18d2571fa09dfc5ed93479bc4485c7a517c913" +checksum = "fe5197923287db20a58125f0bc85c062f7f2c892de97b18c356f9efb14b28524" dependencies = [ "proc-macro2", "quote", - "syn 2.0.117", + "syn 3.0.3", ] [[package]] @@ -18418,11 +18480,11 @@ dependencies = [ [[package]] name = "tokio" -version = "1.52.1" +version = "1.54.1" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b67dee974fe86fd92cc45b7a95fdd2f99a36a6d7b0d431a231178d3d670bbcc6" +checksum = "b52fd3255258d26fac7264ab5a76b53c13367136dc011d3d6ad4f8ed070396a3" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "libc", "mio", "parking_lot", @@ -18532,7 +18594,7 @@ version = "0.7.18" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9ae9cec805b01e8fc3fd2fe289f89149a9b66dd16786abd8b19cfa7b48cb0098" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "futures-core", "futures-io", "futures-sink", @@ -18567,7 +18629,7 @@ version = "0.9.8" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "f0dc8b1fb61449e27716ec0e1bdf0f6b8f3e8f6b05391e8497b8b6d7804ea6d8" dependencies = [ - "indexmap 2.14.0", + "indexmap 2.14.2", "serde_core", "serde_spanned 1.0.3", "toml_datetime 0.7.3", @@ -18600,7 +18662,7 @@ version = "0.22.27" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "41fe8c660ae4257887cf66394862d21dbca4a6ddd26f04a3560410406a2f819a" dependencies = [ - "indexmap 2.14.0", + "indexmap 2.14.2", "serde", "serde_spanned 0.6.9", "toml_datetime 0.6.11", @@ -18614,7 +18676,7 @@ version = "0.23.7" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "6485ef6d0d9b5d0ec17244ff7eb05310113c3f316f2d14200d4de56b3cb98f8d" dependencies = [ - "indexmap 2.14.0", + "indexmap 2.14.2", "toml_datetime 0.7.3", "toml_parser", "winnow 0.7.13", @@ -18707,7 +18769,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "61c5bb1d698276a2443e5ecfabc1008bf15a36c12e6a7176e7bf089ea9131140" dependencies = [ "bitflags 2.13.1", - "bytes 1.11.1", + "bytes 1.12.1", "futures-core", "futures-util", "http 0.2.12", @@ -18726,7 +18788,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "4cfcf7e2740e6fc6d4d688b4ef00650406bb94adf4731e43c096c3a19fe40840" dependencies = [ "bitflags 2.13.1", - "bytes 1.11.1", + "bytes 1.12.1", "futures-util", "http 1.3.1", "http-body 1.0.1", @@ -19135,7 +19197,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "9e3dac10fd62eaf6617d3a904ae222845979aec67c615d1c842b4002c7666fb9" dependencies = [ "byteorder", - "bytes 1.11.1", + "bytes 1.12.1", "data-encoding", "http 0.2.12", "httparse", @@ -19153,7 +19215,7 @@ version = "0.28.0" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "8628dcc84e5a09eb3d8423d6cb682965dea9133204e8fb3efee74c2a0c259442" dependencies = [ - "bytes 1.11.1", + "bytes 1.12.1", "data-encoding", "http 1.3.1", "httparse", @@ -19162,7 +19224,7 @@ dependencies = [ "rustls", "rustls-pki-types", "sha1", - "thiserror 2.0.17", + "thiserror 2.0.21", "utf-8", ] @@ -19399,14 +19461,15 @@ checksum = "8ecb6da28b8a351d773b68d5825ac39017e680750f980f3a1a85cd8dd28a47c1" [[package]] name = "url" -version = "2.5.7" +version = "2.5.8" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "08bc136a29a3d1758e07a9cca267be308aeebf5cfd5a10f3f67ab2097683ef5b" +checksum = "ff67a8a4397373c3ef660812acab3268222035010ab8680ec4215f38ba3d0eed" dependencies = [ "form_urlencoded", "idna", "percent-encoding", "serde", + "serde_derive", ] [[package]] @@ -19429,7 +19492,7 @@ dependencies = [ "kurbo", "log", "pico-args", - "roxmltree 0.21.1", + "roxmltree 0.21.2", "rustybuzz", "simplecss", "siphasher 1.0.1", @@ -19448,12 +19511,6 @@ version = "0.7.6" source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "09cc8ee72d2a9becf2f2febe0205bbed8fc6615b7cb429ad062dc7b7ddd036a9" -[[package]] -name = "utf16_iter" -version = "1.0.5" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "c8232dd3cdaed5356e0f716d285e4b40b932ac434100fe9b7e0e8e935b9e6246" - [[package]] name = "utf8-chars" version = "3.0.6" @@ -19895,7 +19952,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "0fd83062c17b9f4985d438603cde0a5e8c5c8198201a6937f778b607924c7da2" dependencies = [ "anyhow", - "indexmap 2.14.0", + "indexmap 2.14.2", "serde", "serde_derive", "serde_json", @@ -19913,7 +19970,7 @@ dependencies = [ "anyhow", "auditable-serde", "flate2", - "indexmap 2.14.0", + "indexmap 2.14.2", "serde", "serde_derive", "serde_json", @@ -19930,7 +19987,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "bb0e353e6a2fbdc176932bbaab493762eb1255a7900fe0fea1a2f96c296cc909" dependencies = [ "anyhow", - "indexmap 2.14.0", + "indexmap 2.14.2", "wasm-encoder 0.244.0", "wasmparser 0.244.0", ] @@ -19942,7 +19999,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5d1880dd9a848aa68f387966256c34ad49abb4607e3cfa35720d2723d0591cd3" dependencies = [ "anyhow", - "indexmap 2.14.0", + "indexmap 2.14.2", "wasm-encoder 0.254.2", "wasmparser 0.254.2", ] @@ -19978,7 +20035,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "84e5df6dba6c0d7fafc63a450f1738451ed7a0b52295d83e868218fa286bf708" dependencies = [ "bitflags 2.13.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "semver", ] @@ -19990,7 +20047,7 @@ checksum = "0f51cad774fb3c9461ab9bccc9c62dfb7388397b5deda31bf40e8108ccd678b2" dependencies = [ "bitflags 2.13.1", "hashbrown 0.15.5", - "indexmap 2.14.0", + "indexmap 2.14.2", "semver", ] @@ -20002,7 +20059,7 @@ checksum = "47b807c72e1bac69382b3a6fb3dbe8ea4c0ed87ff5629b8685ae6b9a611028fe" dependencies = [ "bitflags 2.13.1", "hashbrown 0.15.5", - "indexmap 2.14.0", + "indexmap 2.14.2", "semver", ] @@ -20014,7 +20071,7 @@ checksum = "c5ff8685b587722894b6f25958fc608d315b93b8d23647bfb567664e7006d757" dependencies = [ "bitflags 2.13.1", "hashbrown 0.17.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "semver", "serde", ] @@ -20097,7 +20154,7 @@ dependencies = [ "cranelift-entity", "gimli 0.33.0", "hashbrown 0.17.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "object 0.39.1", "postcard", @@ -20176,7 +20233,7 @@ dependencies = [ "pulley-interpreter", "smallvec", "target-lexicon", - "thiserror 2.0.17", + "thiserror 2.0.21", "wasmparser 0.254.2", "wasmtime-environ", "wasmtime-internal-core", @@ -20251,7 +20308,7 @@ dependencies = [ "anyhow", "bitflags 2.13.1", "heck 0.5.0", - "indexmap 2.14.0", + "indexmap 2.14.2", "wit-component 0.254.2", "wit-parser 0.254.2", ] @@ -20264,13 +20321,13 @@ checksum = "3ef0d3ec88f9406bc5e498848489c49ff515577500acc9f03fa93d0883dce435" dependencies = [ "async-trait", "bitflags 2.13.1", - "bytes 1.11.1", + "bytes 1.12.1", "cap-primitives", "futures 0.3.34", "rand 0.10.2", "rustix", "rustix-linux-procfs", - "thiserror 2.0.17", + "thiserror 2.0.21", "tokio", "tracing", "url", @@ -20287,7 +20344,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "fe7dfc924e222e15455bd6d445ff7065a4595fffc7698c7bbc01acc0ed6c0421" dependencies = [ "async-trait", - "bytes 1.11.1", + "bytes 1.12.1", "futures 0.3.34", "tracing", "wasmtime", @@ -20316,7 +20373,7 @@ dependencies = [ "nom 7.1.3", "pori", "regex", - "thiserror 2.0.17", + "thiserror 2.0.21", ] [[package]] @@ -20446,9 +20503,21 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "ba8b815c1b593dc0baf78dd0f4fc8fdb2de53198fb1163738093e9a311c33fb3" dependencies = [ "phf 0.13.1", - "phf_codegen", - "string_cache", - "string_cache_codegen", + "phf_codegen 0.13.1", + "string_cache 0.9.0", + "string_cache_codegen 0.6.1", +] + +[[package]] +name = "web_atoms" +version = "0.3.0" +source = "registry+https://github.com/rust-lang/crates.io-index" +checksum = "7572660c8890448ba236b7376f27e389c6a7e1c70195622faced601f855c0ada" +dependencies = [ + "phf 0.14.0", + "phf_codegen 0.14.0", + "string_cache 0.11.0", + "string_cache_codegen 0.11.2", ] [[package]] @@ -20580,7 +20649,7 @@ dependencies = [ "cfg_aliases", "document-features", "hashbrown 0.17.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "naga", "naga-types", @@ -20590,7 +20659,7 @@ dependencies = [ "rustc-hash 1.1.0", "scopeguard", "smallvec", - "thiserror 2.0.17", + "thiserror 2.0.21", "wgpu-core-deps-apple", "wgpu-core-deps-emscripten", "wgpu-core-deps-linux-android-bsd", @@ -20682,7 +20751,7 @@ dependencies = [ "renderdoc-sys", "smallvec", "static_assertions", - "thiserror 2.0.17", + "thiserror 2.0.21", "wasm-bindgen", "wayland-sys", "web-sys", @@ -20748,6 +20817,7 @@ dependencies = [ "collections", "command_palette", "gpui", + "project", "settings", "theme", "theme_settings", @@ -20874,7 +20944,7 @@ dependencies = [ "ctrlc", "parking_lot", "rayon", - "thiserror 2.0.17", + "thiserror 2.0.21", "windows 0.61.3", "windows-future 0.2.1", ] @@ -21688,7 +21758,7 @@ checksum = "d8a39a15d1ae2077688213611209849cad40e9e5cccf6e61951a425850677ff3" dependencies = [ "anyhow", "heck 0.4.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "wasm-metadata 0.201.0", "wit-bindgen-core 0.22.0", "wit-component 0.201.0", @@ -21702,7 +21772,7 @@ checksum = "9d0809dc5ba19e2e98661bf32fc0addc5a3ca5bf3a6a7083aa6ba484085ff3ce" dependencies = [ "anyhow", "heck 0.5.0", - "indexmap 2.14.0", + "indexmap 2.14.2", "prettyplease", "syn 2.0.117", "wasm-metadata 0.227.1", @@ -21718,7 +21788,7 @@ checksum = "b7c566e0f4b284dd6561c786d9cb0142da491f46a9fbed79ea69cdad5db17f21" dependencies = [ "anyhow", "heck 0.5.0", - "indexmap 2.14.0", + "indexmap 2.14.2", "prettyplease", "syn 2.0.117", "wasm-metadata 0.244.0", @@ -21778,7 +21848,7 @@ checksum = "421c0c848a0660a8c22e2fd217929a0191f14476b68962afd2af89fd22e39825" dependencies = [ "anyhow", "bitflags 2.13.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "serde", "serde_derive", @@ -21797,7 +21867,7 @@ checksum = "635c3adc595422cbf2341a17fb73a319669cc8d33deed3a48368a841df86b676" dependencies = [ "anyhow", "bitflags 2.13.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "serde", "serde_derive", @@ -21816,7 +21886,7 @@ checksum = "9d66ea20e9553b30172b5e831994e35fbde2d165325bec84fc43dbf6f4eb9cb2" dependencies = [ "anyhow", "bitflags 2.13.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "serde", "serde_derive", @@ -21835,7 +21905,7 @@ checksum = "1c96b3cea6838dbea55173baa56991fcb087896c321b0a770db201e5a0bd3506" dependencies = [ "anyhow", "bitflags 2.13.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "serde", "serde_derive", @@ -21854,7 +21924,7 @@ checksum = "196d3ecfc4b759a8573bf86a9b3f8996b304b3732e4c7de81655f875f6efdca6" dependencies = [ "anyhow", "id-arena", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "semver", "serde", @@ -21872,7 +21942,7 @@ checksum = "ddf445ed5157046e4baf56f9138c124a0824d4d1657e7204d71886ad8ce2fc11" dependencies = [ "anyhow", "id-arena", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "semver", "serde", @@ -21890,7 +21960,7 @@ checksum = "ecc8ac4bc1dc3381b7f59c34f00b67e18f910c2c0f50015669dde7def656a736" dependencies = [ "anyhow", "id-arena", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "semver", "serde", @@ -21909,7 +21979,7 @@ dependencies = [ "anyhow", "hashbrown 0.17.1", "id-arena", - "indexmap 2.14.0", + "indexmap 2.14.2", "log", "semver", "serde", @@ -22035,12 +22105,6 @@ dependencies = [ "windows-link 0.2.1", ] -[[package]] -name = "write16" -version = "1.0.0" -source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "d1890f4022759daae28ed4fe62859b1236caebfc61ede2f63ed4e695f3f6d936" - [[package]] name = "writeable" version = "0.6.4" @@ -22187,7 +22251,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "5ab627f34ff61b80d756180d556f9c68801d836d271b3b8c094504ceca69d221" dependencies = [ "log", - "markup5ever", + "markup5ever 0.39.0", ] [[package]] @@ -22215,7 +22279,7 @@ dependencies = [ "compliance", "gh-workflow", "guppy", - "indexmap 2.14.0", + "indexmap 2.14.2", "indoc", "itertools 0.14.0", "regex", @@ -22224,7 +22288,7 @@ dependencies = [ "serde_yaml", "strum 0.28.0", "tempfile", - "thiserror 2.0.17", + "thiserror 2.0.21", "tokio", "toml 0.9.8", "toml_edit 0.22.27", @@ -22267,7 +22331,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index" checksum = "35e709a1923e34cf52d5b1466653b8da2f0360bccfbdd9870c5bf78732d4faad" dependencies = [ "base64 0.22.1", - "bytes 1.11.1", + "bytes 1.12.1", "flate2", "futures 0.3.34", "getrandom 0.2.16", @@ -22282,7 +22346,7 @@ dependencies = [ "rand 0.8.6", "send_wrapper", "sha1", - "thiserror 2.0.17", + "thiserror 2.0.21", "tokio", "tokio-rustls", "tokio-util", @@ -22432,7 +22496,7 @@ dependencies = [ [[package]] name = "zed" -version = "1.29.0" +version = "1.30.0" dependencies = [ "acp_thread", "acp_tools", @@ -22640,7 +22704,7 @@ version = "0.12.15-zed" source = "git+https://github.com/zed-industries/reqwest.git?rev=33bc764aa15ff7b200bf7c93bd96e24878d53e14#33bc764aa15ff7b200bf7c93bd96e24878d53e14" dependencies = [ "base64 0.22.1", - "bytes 1.11.1", + "bytes 1.12.1", "encoding_rs", "futures-core", "futures-util", @@ -22869,25 +22933,26 @@ dependencies = [ [[package]] name = "zeromq" -version = "0.5.0" +version = "0.7.0" source = "registry+https://github.com/rust-lang/crates.io-index" -checksum = "b32e1e46c4e278efd0c1153f2db0113924b9bc5fff9f9221853d035e2d26fadf" +checksum = "55b31ad37d1aad854ddc8c4f16b637259ce95f757f6c32f05447279c68ed9e2a" dependencies = [ "async-dispatcher", + "async-io", "async-std", "async-trait", "asynchronous-codec", - "bytes 1.11.1", + "bytes 1.12.1", "crossbeam-queue", "futures 0.3.34", + "futures-channel", "log", - "num-traits", - "once_cell", "parking_lot", - "rand 0.9.4", + "rand 0.10.2", "regex", "scc", - "thiserror 1.0.69", + "socket2 0.6.5", + "thiserror 2.0.21", "uuid", ] @@ -22946,7 +23011,7 @@ dependencies = [ "crc32fast", "flate2", "getrandom 0.4.1", - "indexmap 2.14.0", + "indexmap 2.14.2", "memchr", "nix 0.31.3", "typed-path", diff --git a/Cargo.toml b/Cargo.toml index 2c21684341f..31427aed639 100644 --- a/Cargo.toml +++ b/Cargo.toml @@ -535,7 +535,7 @@ accesskit = { version = "0.24.0", features = ["enumn"] } accesskit_macos = "0.26.0" accesskit_unix = "0.22" accesskit_windows = "0.34" -agent-client-protocol = { version = "=5.1.0", features = ["schemars", "unstable", "unstable_protocol_v2"] } +agent-client-protocol = { version = "=5.2.0", features = ["schemars", "unstable", "unstable_protocol_v2"] } aho-corasick = "1.1" alacritty_terminal = { git = "https://github.com/zed-industries/alacritty", rev = "4c129667ce56611becdc82de6e28218c80e2e88f" } any_vec = "0.14" @@ -684,8 +684,8 @@ itertools = "0.14.0" js-sys = "0.3" jsonschema = { version = "0.51", default-features = false } jsonwebtoken = { version = "10.0", default-features = false } -jupyter-protocol = "1.4.0" -jupyter-websocket-client = "1.1.0" +jupyter-protocol = "2.0.3" +jupyter-websocket-client = "3.0.0" libc = "0.2" libsqlite3-sys = { version = "0.30.1", features = ["bundled"] } libwebrtc = "0.3.26" @@ -697,12 +697,12 @@ lsp-types = { git = "https://github.com/zed-industries/lsp-types", rev = "82d7fc mach2 = "0.6" markup5ever_rcdom = "0.39" mdbook = { version = "=0.4.40", default-features = false, features = ["search"] } -merman = { version = "=0.8.0-alpha.5", default-features = false } +merman = { version = "=0.9.3", default-features = false } mime = "0.3.17" minidumper = "0.11" moka = { version = "0.12.10", features = ["sync"] } nanoid = "0.4" -nbformat = "1.2.0" +nbformat = "3.0.0" nix = "0.30" notify-rust = "4" nucleo = { package = "nucleo-matcher", version = "0.3" } @@ -882,7 +882,7 @@ resvg = { version = "0.46.0", default-features = false, features = [ "raster-images", ] } rsa = { version = "0.9", default-features = false, features = ["std", "u64_digit"] } -runtimelib = { version = "1.4.0", default-features = false, features = [ +jupyter-zmq-client = { version = "3.0.0", default-features = false, features = [ "async-dispatcher-runtime", "aws-lc-rs" ] } rust-embed = { version = "8.11", features = ["include-exclude", "compression"] } diff --git a/README.md b/README.md index 9f641fb3841..8d7ccd1d093 100644 --- a/README.md +++ b/README.md @@ -1,3 +1,5 @@ +> [!IMPORTANT] +> Remove this line to confirm you've reviewed this PR before submitting. # Zed [![Zed](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/zed-industries/zed/main/assets/badge/v0.json)](https://zed.dev) diff --git a/assets/settings/default.json b/assets/settings/default.json index eb13c39315f..802c0f2f387 100644 --- a/assets/settings/default.json +++ b/assets/settings/default.json @@ -618,6 +618,8 @@ "fullscreen_mode": "native", // Titlebar related settings "title_bar": { + // When to show the title bar: "always" | "never" | "hide_in_full_screen". + "show": "always", // Whether to show git status indicators on the branch icon in the titlebar. "show_branch_status_icon": false, // Whether to show the branch name button in the titlebar. @@ -1621,8 +1623,8 @@ // Whether to pre-fill the file finder's query with the text selected in the // focused item (e.g. an editor or a terminal) when it is opened. // - // Default: true - "prefill_query_from_selection": true, + // Default: false + "prefill_query_from_selection": false, }, // Whether or not to remove any trailing whitespace from lines of a buffer // before saving it. diff --git a/crates/acp_thread/src/acp_thread.rs b/crates/acp_thread/src/acp_thread.rs index f2372f23ac6..7498d4ced32 100644 --- a/crates/acp_thread/src/acp_thread.rs +++ b/crates/acp_thread/src/acp_thread.rs @@ -3199,6 +3199,7 @@ pub enum ToolCallContent { source: acp_v2::Diff, render: DiffPatch, }, + SessionReference(acp_v2::SessionReference), Other { source: acp_v2::ToolCallContent, markdown: Entity, @@ -3213,6 +3214,7 @@ enum PreparedToolCallContent { meta: Option, }, DiffPatch(acp_v2::Diff), + SessionReference(acp_v2::SessionReference), Other(acp_v2::ToolCallContent), } @@ -3235,6 +3237,13 @@ impl PreparedToolCallContent { terminal: terminals.resolve(&acp_v2::TerminalId::new(terminal_id.0), cx)?, meta, }, + acp_v1::ToolCallContent::Session(acp_v1::SessionReference { + session_id, + meta, + .. + }) => { + Self::SessionReference(acp_v2::SessionReference::new(session_id.0).meta(meta)) + } _ => continue, }; prepared.push(content); @@ -3265,6 +3274,7 @@ impl PreparedToolCallContent { terminal: terminals.resolve(&terminal.terminal_id, cx)?, meta: terminal.meta, }), + acp_v2::ToolCallContent::Session(reference) => Ok(Self::SessionReference(reference)), other => Ok(Self::Other(other)), } } @@ -3314,6 +3324,9 @@ impl ToolCallContent { render: DiffPatch::new(&source, language_registry, cx), source, }, + PreparedToolCallContent::SessionReference(reference) => { + Self::SessionReference(reference) + } PreparedToolCallContent::Other(source) => Self::Other { source, markdown: ContentBlock::create_markdown( @@ -3371,6 +3384,10 @@ impl ToolCallContent { } *source = new_source; } + ( + Self::SessionReference(reference), + PreparedToolCallContent::SessionReference(new_reference), + ) => *reference = new_reference, (Self::Other { source, .. }, PreparedToolCallContent::Other(new_source)) => { *source = new_source; } @@ -3388,6 +3405,7 @@ impl ToolCallContent { source.changes.iter().map(diff_change_label).join("\n"), Self::patch_preview(source) ), + Self::SessionReference(reference) => format!("Session {}", reference.session_id), Self::Other { markdown, .. } => markdown.read(cx).source().to_string(), } } @@ -3397,7 +3415,10 @@ impl ToolCallContent { Self::ContentBlock { block, .. } => block.markdown(), Self::DiffPatch { render, .. } => render.fallback.as_ref(), Self::Other { markdown, .. } => Some(markdown), - Self::Diff(_) | Self::LegacyDiff { .. } | Self::Terminal { .. } => None, + Self::Diff(_) + | Self::LegacyDiff { .. } + | Self::Terminal { .. } + | Self::SessionReference(_) => None, } } @@ -7313,10 +7334,15 @@ impl AcpThread { if self.plans.remove(&identity).is_none() { return; } - // A user dismissal (no visible plan) stays in effect; only an agent removing the - // plan on screen moves the panel to the next most recently changed plan. Empty plans - // are skipped because the panel hides them, which would mask a non-empty one. - if self.visible_plan.as_ref() == Some(&identity) { + self.fall_back_from_visible_plan(&identity, cx); + cx.notify(); + } + + /// A user dismissal (no visible plan) stays in effect; only an agent removing or emptying + /// the plan on screen moves the panel to the next most recently changed plan. Empty plans + /// are skipped because the panel hides them, which would mask a non-empty one. + fn fall_back_from_visible_plan(&mut self, identity: &PlanIdentity, cx: &App) { + if self.visible_plan.as_ref() == Some(identity) { self.visible_plan = self .plans .iter() @@ -7324,7 +7350,6 @@ impl AcpThread { .max_by_key(|(_, plan)| plan.last_changed) .map(|(identity, _)| identity.clone()); } - cx.notify(); } fn replace_plan( @@ -7341,7 +7366,11 @@ impl AcpThread { if is_new || changed || identity == PlanIdentity::Legacy { self.plan_change_count += 1; plan.last_changed = self.plan_change_count; - self.visible_plan = Some(identity); + if plan.is_empty(cx) { + self.fall_back_from_visible_plan(&identity, cx); + } else { + self.visible_plan = Some(identity); + } } cx.notify(); } @@ -7355,6 +7384,9 @@ impl AcpThread { { entries .retain(|entry| !matches!(entry.source.status, acp_v2::PlanEntryStatus::Completed)); + if entries.is_empty() { + self.fall_back_from_visible_plan(&PlanIdentity::Legacy, cx); + } } cx.notify(); } @@ -9107,7 +9139,6 @@ mod tests { reordered, appended, vec![original[0].clone()], - vec![], ] { thread.upsert_plan_items( acp_v2::PlanItems::new("plan", original.clone()), @@ -9129,6 +9160,20 @@ mod tests { assert_eq!(first.content, markdown); } } + + thread.clear_plan(cx); + thread.upsert_plan_items(acp_v2::PlanItems::new("plan", vec![]), None, cx); + assert!( + thread.plan().is_none(), + "emptying a plan does not reopen it" + ); + assert!( + thread + .plan_by_id(&"plan".into()) + .expect("plan") + .entries() + .is_empty() + ); }); } @@ -9162,19 +9207,14 @@ mod tests { ); assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("b".into()))); thread.upsert_plan_items(acp_v2::PlanItems::new("empty", vec![]), None, cx); - assert!( - thread - .plan() - .expect("selected empty plan") - .entries() - .is_empty() - ); - thread.upsert_plan_items(acp_v2::PlanItems::new("a", entries.clone()), None, cx); assert_eq!( thread.visible_plan, - Some(PlanIdentity::Keyed("empty".into())) + Some(PlanIdentity::Keyed("b".into())), + "a new empty plan does not hide the visible one" ); - let mut changed = entries; + thread.upsert_plan_items(acp_v2::PlanItems::new("a", entries.clone()), None, cx); + assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("b".into()))); + let mut changed = entries.clone(); changed[0].content = "Changed".into(); thread.upsert_plan_items(acp_v2::PlanItems::new("a", changed), None, cx); assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("a".into()))); @@ -9183,11 +9223,38 @@ mod tests { first_markdown ); thread.upsert_plan_items(acp_v2::PlanItems::new("b", vec![]), None, cx); - assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("b".into()))); + assert_eq!( + thread.visible_plan, + Some(PlanIdentity::Keyed("a".into())), + "emptying a hidden plan does not select it" + ); + thread.upsert_plan_items(acp_v2::PlanItems::new("c", entries.clone()), None, cx); + assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("c".into()))); + thread.upsert_plan_items(acp_v2::PlanItems::new("c", vec![]), None, cx); + assert_eq!( + thread.visible_plan, + Some(PlanIdentity::Keyed("a".into())), + "emptying the visible plan falls back to the most recently changed non-empty plan" + ); assert!( thread - .plan() - .expect("clearing older B selects empty B") + .plan_by_id(&"c".into()) + .expect("empty C retained") + .entries() + .is_empty(), + "the empty update still replaces C's content" + ); + thread.upsert_plan_items(acp_v2::PlanItems::new("c", entries), None, cx); + assert_eq!(thread.visible_plan, Some(PlanIdentity::Keyed("c".into()))); + assert_eq!(thread.plan().expect("C refilled").entries().len(), 1); + thread.clear_plan(cx); + thread.upsert_plan_items(acp_v2::PlanItems::new("b", vec![]), None, cx); + thread.upsert_plan_items(acp_v2::PlanItems::new("d", vec![]), None, cx); + assert!(thread.plan().is_none(), "empty plans do not undo dismissal"); + assert!( + thread + .plan_by_id(&"b".into()) + .expect("empty B retained") .entries() .is_empty() ); @@ -10611,6 +10678,49 @@ mod tests { }); } + #[gpui::test] + fn test_tool_content_session_references_are_kept_from_v1_and_v2(cx: &mut TestAppContext) { + init_test(cx); + cx.update(|cx| { + let languages = Arc::new(LanguageRegistry::test(cx.background_executor().clone())); + let meta = acp_v2::Meta::from_iter([("revision".into(), 1.into())]); + let mut prepared = PreparedToolCallContent::prepare( + vec![acp_v1::ToolCallContent::Session( + acp_v1::SessionReference::new("from-v1").meta(meta.clone()), + )], + ToolTerminalResolver::registered(&HashMap::default()), + cx, + ) + .expect("prepare v1 content"); + prepared.extend( + PreparedToolCallContent::prepare_v2( + vec![acp_v2::ToolCallContent::Session( + acp_v2::SessionReference::new("from-v2"), + )], + ToolTerminalResolver::registered(&HashMap::default()), + cx, + ) + .expect("prepare v2 content"), + ); + let content: Vec<_> = prepared + .into_iter() + .map(|content| ToolCallContent::from_prepared(content, &languages, cx)) + .collect(); + let [ + ToolCallContent::SessionReference(from_v1), + ToolCallContent::SessionReference(from_v2), + ] = content.as_slice() + else { + panic!("expected two session references, got {content:?}"); + }; + assert_eq!( + from_v1, + &acp_v2::SessionReference::new("from-v1").meta(meta) + ); + assert_eq!(from_v2, &acp_v2::SessionReference::new("from-v2")); + }); + } + #[gpui::test] async fn test_tool_call_content_preserves_embedded_text_resource( cx: &mut gpui::TestAppContext, diff --git a/crates/acp_thread/src/terminal.rs b/crates/acp_thread/src/terminal.rs index abf82c73282..9b9914407f0 100644 --- a/crates/acp_thread/src/terminal.rs +++ b/crates/acp_thread/src/terminal.rs @@ -267,7 +267,10 @@ impl SandboxWrap { .filter_map(|path| sandbox::HostFilesystemLocation::capture(path).ok()) .collect::>(); let fs = if self.allow_fs_write { - sandbox::SandboxFsPolicy::Unrestricted { protected_paths } + sandbox::SandboxFsPolicy::Unrestricted { + protected_paths, + protected_file_names: Vec::new(), + } } else { // Project worktree paths are captured fresh; user-approved grants are // rebuilt via the verifying reopen (or captured when legacy bare @@ -302,6 +305,7 @@ impl SandboxWrap { sandbox::SandboxFsPolicy::Restricted { writable_paths, protected_paths, + protected_file_names: Vec::new(), } }; let network = match &self.network { diff --git a/crates/agent/src/sandboxing.rs b/crates/agent/src/sandboxing.rs index da160b27502..01fc6bb5b35 100644 --- a/crates/agent/src/sandboxing.rs +++ b/crates/agent/src/sandboxing.rs @@ -161,6 +161,7 @@ pub fn settings_sandbox_policy(persistent: &SandboxPermissions) -> SandboxPolicy let fs = if persistent.allow_fs_write_all { SandboxFsPolicy::Unrestricted { protected_paths: Vec::new(), + protected_file_names: Vec::new(), } } else { SandboxFsPolicy::Restricted { @@ -176,6 +177,7 @@ pub fn settings_sandbox_policy(persistent: &SandboxPermissions) -> SandboxPolicy .filter_map(acp_thread::granted_write_path_to_location_or_log), ), protected_paths: Vec::new(), + protected_file_names: Vec::new(), } }; let network = if persistent.allow_all_hosts { @@ -439,6 +441,7 @@ impl ThreadSandboxGrants { let fs = if self.allow_fs_write_all { SandboxFsPolicy::Unrestricted { protected_paths: Vec::new(), + protected_file_names: Vec::new(), } } else { SandboxFsPolicy::Restricted { @@ -454,6 +457,7 @@ impl ThreadSandboxGrants { .filter_map(acp_thread::granted_write_path_to_location_or_log), ), protected_paths: Vec::new(), + protected_file_names: Vec::new(), } }; let network = if self.network_any_host { @@ -699,6 +703,7 @@ mod tests { .map(|p| HostFilesystemLocation::capture(p).expect("capture temp dir")) .collect(), protected_paths: Vec::new(), + protected_file_names: Vec::new(), }, network: if hosts.is_empty() { SandboxNetPolicy::Blocked @@ -813,6 +818,7 @@ mod tests { HostFilesystemLocation::capture(build_dir.path()).expect("capture temp dir") ], protected_paths: Vec::new(), + protected_file_names: Vec::new(), } ); assert_eq!( @@ -829,6 +835,7 @@ mod tests { SandboxFsPolicy::Restricted { writable_paths: Vec::new(), protected_paths: Vec::new(), + protected_file_names: Vec::new(), } ); assert_eq!(empty.network, SandboxNetPolicy::Blocked); @@ -841,6 +848,7 @@ mod tests { policy.fs, SandboxFsPolicy::Unrestricted { protected_paths: Vec::new(), + protected_file_names: Vec::new(), } ); assert_eq!(policy.network, SandboxNetPolicy::Unrestricted); @@ -865,6 +873,7 @@ mod tests { HostFilesystemLocation::capture(log_dir.path()).expect("capture temp dir") ], protected_paths: Vec::new(), + protected_file_names: Vec::new(), } ); assert_eq!( @@ -884,6 +893,7 @@ mod tests { policy.fs, SandboxFsPolicy::Unrestricted { protected_paths: Vec::new(), + protected_file_names: Vec::new(), } ); assert_eq!(policy.network, SandboxNetPolicy::Unrestricted); diff --git a/crates/agent/src/thread.rs b/crates/agent/src/thread.rs index a6513bfce7a..c86acc7a7a0 100644 --- a/crates/agent/src/thread.rs +++ b/crates/agent/src/thread.rs @@ -3479,6 +3479,7 @@ impl Thread { | LanguageModelCompletionEvent::Thinking { .. } | LanguageModelCompletionEvent::RedactedThinking { .. } | LanguageModelCompletionEvent::ReasoningDetails(_) + | LanguageModelCompletionEvent::InputTransformations(_) | LanguageModelCompletionEvent::ToolUse(_) | LanguageModelCompletionEvent::ToolUseJsonParseError { .. } | LanguageModelCompletionEvent::StartMessage { .. } @@ -3736,7 +3737,7 @@ impl Thread { Stop(StopReason::Refusal) => return Err(CompletionError::Refusal.into()), Stop(StopReason::MaxTokens) => return Err(CompletionError::MaxTokens.into()), Stop(StopReason::ToolUse | StopReason::EndTurn) => {} - Started | Queued { .. } | Compaction(_) => {} + Started | Queued { .. } | Compaction(_) | InputTransformations(_) => {} } Ok(None) diff --git a/crates/agent/src/tools/grep_tool.rs b/crates/agent/src/tools/grep_tool.rs index 712afae23d1..bde2e1a5e8f 100644 --- a/crates/agent/src/tools/grep_tool.rs +++ b/crates/agent/src/tools/grep_tool.rs @@ -34,6 +34,9 @@ pub const fn default_context_lines() -> u32 { /// - Results are paginated with 20 matches per page. Use the optional 'offset' parameter to request subsequent pages. /// - DO NOT use HTML entities solely to escape characters in the tool parameters. #[derive(Debug, Serialize, Deserialize, JsonSchema)] +// Reject unknown fields so that a mistyped scoping parameter (e.g. `path`) fails loudly instead +// of being silently dropped, which would widen the search to the whole project. +#[serde(deny_unknown_fields)] pub struct GrepToolInput { /// A regex pattern to search for in the entire project. Note that the regex will be parsed by the Rust `regex` crate. /// @@ -593,6 +596,41 @@ mod tests { ); } + // An unknown input field must not be dropped silently: a mistyped scoping parameter + // (here `path`) would otherwise turn a scoped search into a project-wide one. + #[gpui::test] + async fn test_grep_tool_rejects_unknown_input_fields(cx: &mut TestAppContext) { + init_test(cx); + cx.executor().allow_parking(); + + let fs = FakeFs::new(cx.executor()); + fs.insert_tree(path!("/root"), json!({ "notes.md": "section 1.11\n" })) + .await; + + let project = Project::test(fs.clone(), [path!("/root").as_ref()], cx).await; + + let tool = Arc::new(GrepTool { project }); + let task = cx.update(|cx| { + tool.run( + ToolInput::ready(json!({ + "regex": "1\\.11", + "path": "/root/notes.md", + "context_lines": 4, + })), + ToolCallEventStream::test().0, + cx, + ) + }); + + let error = task + .await + .expect_err("grep input with unknown fields should be rejected"); + assert!( + error.contains("unknown field `path`") && error.contains("include_pattern"), + "unexpected error message: {error}" + ); + } + // The grep tool streams a clickable `file://` ResourceLink and a tool-call // location for every match so each result opens the file at the matched line // in the agent panel. The model-facing text output stays link-free. diff --git a/crates/agent_servers/src/acp.rs b/crates/agent_servers/src/acp.rs index 970dc0f5533..b8a647edcf1 100644 --- a/crates/agent_servers/src/acp.rs +++ b/crates/agent_servers/src/acp.rs @@ -1158,32 +1158,35 @@ fn handle_v2_complete_elicitation( }) } +#[cfg(test)] +fn set_acp_beta(enabled: bool, cx: &mut App) { + use gpui::UpdateGlobal as _; + + cx.update_flags( + false, + if enabled { + vec!["acp-beta".into()] + } else { + vec![] + }, + ); + settings::SettingsStore::update_global(cx, |store, cx| { + store.update_user_settings(cx, |settings| { + settings + .feature_flags + .get_or_insert_default() + .insert("acp-beta".into(), if enabled { "on" } else { "off" }.into()); + }); + }); + assert_eq!(cx.has_flag::(), enabled); +} + #[cfg(all(test, unix))] mod selection_tests { use super::*; - use gpui::{TestAppContext, UpdateGlobal as _}; + use gpui::TestAppContext; use serde_json::json; - pub(super) fn set_beta(enabled: bool, cx: &mut App) { - cx.update_flags( - false, - if enabled { - vec!["acp-beta".into()] - } else { - vec![] - }, - ); - settings::SettingsStore::update_global(cx, |store, cx| { - store.update_user_settings(cx, |settings| { - settings - .feature_flags - .get_or_insert_default() - .insert("acp-beta".into(), if enabled { "on" } else { "off" }.into()); - }); - }); - assert_eq!(cx.has_flag::(), enabled); - } - #[gpui::test] async fn beta_selection_uses_fresh_v1_fallback_only_for_version_mismatch( cx: &mut TestAppContext, @@ -1262,7 +1265,7 @@ mod selection_tests { (true, "", true, None, "2"), ] { cx.update(|cx| { - set_beta(beta, cx); + set_acp_beta(beta, cx); }); let trace = directory.path().join("connections"); std::fs::write(&trace, "").expect("clear trace"); @@ -1326,7 +1329,7 @@ done connection.clone().downcast::().is_some(), v2 ); - cx.update(|cx| set_beta(false, cx)); + cx.update(|cx| set_acp_beta(false, cx)); assert_eq!( connection.clone().downcast::().is_some(), v2 @@ -1433,7 +1436,7 @@ done (true, true, true), (true, false, false), ] { - cx.update(|cx| set_beta(beta, cx)); + cx.update(|cx| set_acp_beta(beta, cx)); let command = AgentServerCommand { path: "npx".into(), args: vec![ diff --git a/crates/agent_servers/src/acp/v1.rs b/crates/agent_servers/src/acp/v1.rs index 0d50e196dc1..a514ccc3cbe 100644 --- a/crates/agent_servers/src/acp/v1.rs +++ b/crates/agent_servers/src/acp/v1.rs @@ -28,9 +28,7 @@ use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _}; use futures::channel::mpsc; use futures::future::Shared; use futures::{Future, FutureExt as _}; -use project::agent_server_store::{ - AgentServerCommand, AgentServerStore, AllAgentServersSettings, CustomAgentServerSettings, -}; +use project::agent_server_store::{AgentServerCommand, AgentServerStore, AllAgentServersSettings}; use project::{AgentId, Project}; use serde::Deserialize; use settings::{AgentConfigOptionValue, SettingsStore}; @@ -120,6 +118,26 @@ impl AcpConnectionDefaults { self.config_options.borrow().get(config_id).cloned() } + fn initial_config_options(&self) -> Vec { + let config_options = self.config_options.borrow(); + let mut entries = config_options.iter().collect::>(); + entries.sort_by_key(|(config_id, _)| *config_id); + entries + .into_iter() + .map(|(config_id, value)| { + let value = match value { + AgentConfigOptionValue::ValueId(value_id) => { + acp::SessionConfigOptionValue::value_id(value_id.clone()) + } + AgentConfigOptionValue::Boolean(value) => { + acp::SessionConfigOptionValue::boolean(*value) + } + }; + acp::InitialSessionConfigOption::new(config_id.clone(), value) + }) + .collect() + } + fn set( &self, mode: Option, @@ -140,21 +158,11 @@ impl AcpConnectionDefaults { return; }; - let default_config_options = match agent_settings { - CustomAgentServerSettings::Custom { - default_config_options, - .. - } - | CustomAgentServerSettings::Registry { - default_config_options, - .. - } => default_config_options.clone(), - }; self.set( agent_settings .default_mode() .map(acp_v2::SessionConfigValueId::new), - default_config_options, + agent_settings.default_config_options().clone(), ); } @@ -913,6 +921,16 @@ impl AcpConnection { self.agent_capabilities.session_capabilities.close.is_some() } + /// `session/options` is still a draft, so Zed only uses it with the ACP beta flag. + fn agent_supports_initial_config_options(&self, cx: &App) -> bool { + cx.has_flag::() + && self + .agent_capabilities + .session_capabilities + .options + .is_some() + } + /// `rpc_call` gets a receiver that resolves once its response has been applied, and /// holds the agent's later messages until then (see `ordered_response`). With /// `replays_history`, the response ends a history replay. @@ -1326,13 +1344,18 @@ impl AgentConnection for AcpConnection { }; let name = self.id.0.clone(); let mcp_servers = mcp_servers_for_project(&project, cx); + let sends_initial_config_options = self.agent_supports_initial_config_options(cx); cx.spawn(async move |cx| { let (response_sender, response_received) = futures::channel::oneshot::channel(); let (registered, registration_finished) = futures::channel::oneshot::channel(); - let request = self - .connection - .prepare_request(directories.into_new_session_request(mcp_servers)); + let mut request = directories.into_new_session_request(mcp_servers); + if sends_initial_config_options { + // The default-application pass below still runs, so defaults the agent ignored + // here (for example, ones that depend on another option) get another chance. + request = request.config_options(self.defaults.initial_config_options()); + } + let request = self.connection.prepare_request(request); let cancellation = request.cancellation_handle(); request .on_receiving_result({ @@ -6426,6 +6449,27 @@ mod tests { ); } + #[test] + fn initial_config_options_are_sorted_and_typed() { + let defaults = AcpConnectionDefaults::new( + None, + HashMap::from_iter([ + ( + "model".to_string(), + AgentConfigOptionValue::ValueId("large".to_string()), + ), + ("fast".to_string(), AgentConfigOptionValue::Boolean(true)), + ]), + ); + assert_eq!( + serde_json::to_value(defaults.initial_config_options()).expect("serialize"), + serde_json::json!([ + {"configId": "fast", "type": "boolean", "value": true}, + {"configId": "model", "value": "large"}, + ]) + ); + } + #[gpui::test] async fn settings_changes_refresh_active_connection_defaults(cx: &mut gpui::TestAppContext) { cx.update(|cx| { @@ -7307,7 +7351,7 @@ exec cat >/dev/null ); for enabled in [false, true] { - cx.update(|cx| crate::acp::selection_tests::set_beta(enabled, cx)); + cx.update(|cx| crate::acp::set_acp_beta(enabled, cx)); let command = AgentServerCommand { path: "/bin/sh".into(), args: vec!["-c".into(), script.clone()], diff --git a/crates/agent_servers/src/acp/v2.rs b/crates/agent_servers/src/acp/v2.rs index 9622b042ca0..add4ad3a66f 100644 --- a/crates/agent_servers/src/acp/v2.rs +++ b/crates/agent_servers/src/acp/v2.rs @@ -20,6 +20,7 @@ use agent_client_protocol::{ }; use anyhow::{Context as _, Result, anyhow}; use collections::HashMap; +use feature_flags::{AcpBetaFeatureFlag, FeatureFlagAppExt as _}; use futures::{ FutureExt as _, channel::mpsc, @@ -30,7 +31,7 @@ use project::{ AgentId, AgentServerStore, Project, agent_server_store::{AgentServerCommand, AllAgentServersSettings}, }; -use settings::SettingsStore; +use settings::{AgentConfigOptionValue, SettingsStore}; use std::{any::Any, cell::RefCell, rc::Rc, sync::Arc}; use task::SpawnInTerminal; use util::ResultExt as _; @@ -825,6 +826,45 @@ impl AcpV2Connection { Ok(()) } + /// `session/options` is still a draft, so Zed only uses it with the ACP beta flag. + fn supports_initial_config_options(&self, cx: &App) -> bool { + cx.has_flag::() + && self + .initialize_response + .capabilities + .session + .as_ref() + .is_some_and(|session| session.options.is_some()) + } + + fn initial_config_options(&self, cx: &App) -> Vec { + let Some(settings_store) = cx.try_global::() else { + return Vec::new(); + }; + let Some(defaults) = settings_store + .get::(None) + .get(self.id.as_ref()) + else { + return Vec::new(); + }; + let mut entries = defaults.default_config_options().iter().collect::>(); + entries.sort_by_key(|(config_id, _)| *config_id); + entries + .into_iter() + .map(|(config_id, value)| { + let value = match value { + AgentConfigOptionValue::ValueId(value_id) => { + acp::SessionConfigOptionValue::id(value_id.clone()) + } + AgentConfigOptionValue::Boolean(value) => { + acp::SessionConfigOptionValue::boolean(*value) + } + }; + acp::InitialSessionConfigOption::new(config_id.clone(), value) + }) + .collect() + } + async fn apply_new_session_defaults( &self, thread: &Entity, @@ -1293,9 +1333,14 @@ impl AgentConnection for AcpV2Connection { Ok(context) => context, Err(error) => return Task::ready(Err(error)), }; - let request = acp::NewSessionRequest::new(context.cwd.clone()) + let mut request = acp::NewSessionRequest::new(context.cwd.clone()) .additional_directories(context.additional_directories.clone()) .mcp_servers(context.mcp_servers.clone()); + if self.supports_initial_config_options(cx) { + // `apply_new_session_defaults` still runs after creation, so defaults the agent + // ignored here (for example, ones that depend on another option) get another chance. + request = request.config_options(self.initial_config_options(cx)); + } let request = self.connection.prepare_request(request); let request_id = request.id().clone(); let (response, applied) = Self::ordered_prepared_response( @@ -2984,6 +3029,81 @@ mod tests { ); } + #[gpui::test] + async fn v2_new_session_sends_defaults_as_initial_config_options(cx: &mut TestAppContext) { + use settings::AgentConfigOptionValue::{Boolean, ValueId}; + + let harness = SessionHarness::new( + acp::AgentCapabilities::new().session( + acp::SessionCapabilities::new().options(acp::SessionOptionsCapabilities::new()), + ), + vec![], + vec![], + cx, + ) + .await; + // Toggling the flag rewrites user settings, which drops the overridden defaults. + let set_beta_with_defaults = |enabled, cx: &mut TestAppContext| { + cx.update(|cx| crate::acp::set_acp_beta(enabled, cx)); + set_startup_defaults( + HashMap::from_iter([ + ("model".into(), ValueId("large".into())), + ("enabled".into(), Boolean(true)), + ]), + cx, + ); + }; + set_beta_with_defaults(false, cx); + let mut creation = harness.create(cx); + let (request, _) = harness.new_request(&mut creation, cx).await; + assert!( + request.config_options.is_empty(), + "initial config options require the ACP beta flag" + ); + harness + .new_responses + .try_send(Ok(acp::NewSessionResponse::new("without-beta"))) + .expect("new response"); + bounded(creation, cx).await.expect("initialized"); + + set_beta_with_defaults(true, cx); + let mut creation = harness.create(cx); + let (request, _) = harness.new_request(&mut creation, cx).await; + assert_eq!( + request.config_options, + vec![ + acp::InitialSessionConfigOption::new( + "enabled", + acp::SessionConfigOptionValue::boolean(true), + ), + acp::InitialSessionConfigOption::new( + "model", + acp::SessionConfigOptionValue::id("large"), + ), + ] + ); + harness + .new_responses + .try_send(Ok(initial_response().config_options(vec![ + acp::SessionConfigOption::select( + "model", + "Model", + "large", + vec![ + acp::SessionConfigSelectOption::new("small", "Small"), + acp::SessionConfigSelectOption::new("large", "Large"), + ], + ), + acp::SessionConfigOption::boolean("enabled", "Enabled", true), + ]))) + .expect("new response"); + bounded(creation, cx).await.expect("initialized"); + assert!( + harness.config_requests.is_empty(), + "defaults the agent applied are not sent again" + ); + } + #[gpui::test] async fn v2_new_session_applies_defaults_before_delivery(cx: &mut TestAppContext) { use settings::AgentConfigOptionValue::{Boolean, ValueId}; @@ -3020,7 +3140,11 @@ mod tests { ), ]; let mut creation = harness.create(cx); - harness.new_request(&mut creation, cx).await; + let (request, _) = harness.new_request(&mut creation, cx).await; + assert!( + request.config_options.is_empty(), + "initial config options require the options capability" + ); harness .new_responses .try_send(Ok(initial_response().config_options(offered.clone()))) diff --git a/crates/agent_ui/src/buffer_codegen.rs b/crates/agent_ui/src/buffer_codegen.rs index 636758c7abb..03fdff7fb89 100644 --- a/crates/agent_ui/src/buffer_codegen.rs +++ b/crates/agent_ui/src/buffer_codegen.rs @@ -1356,6 +1356,7 @@ impl CodegenAlternative { | LanguageModelCompletionEvent::Thinking { .. } | LanguageModelCompletionEvent::RedactedThinking { .. } | LanguageModelCompletionEvent::ReasoningDetails(_) + | LanguageModelCompletionEvent::InputTransformations(_) | LanguageModelCompletionEvent::Compaction(_), ) => {} Err(error) => { @@ -1431,6 +1432,7 @@ impl CodegenAlternative { | LanguageModelCompletionEvent::RedactedThinking { .. } | LanguageModelCompletionEvent::StartMessage { .. } | LanguageModelCompletionEvent::ReasoningDetails(_) + | LanguageModelCompletionEvent::InputTransformations(_) | LanguageModelCompletionEvent::Compaction(_), ) => None, Err(error) => Some(Err(error)), diff --git a/crates/agent_ui/src/conversation_view.rs b/crates/agent_ui/src/conversation_view.rs index e4e42dd9606..5cf39a7e00f 100644 --- a/crates/agent_ui/src/conversation_view.rs +++ b/crates/agent_ui/src/conversation_view.rs @@ -9840,10 +9840,11 @@ pub(crate) mod tests { assert!(cx.debug_bounds("plan-status-All Done").is_none()); thread.update(cx, |thread, cx| { thread.upsert_plan_items(acp_v2::PlanItems::new("status-plan", vec![]), None, cx); + assert!(thread.plan().is_none()); assert!( thread - .plan() - .expect("empty selected plan") + .plan_by_id(&"status-plan".into()) + .expect("emptied plan") .entries() .is_empty() ); @@ -20565,6 +20566,64 @@ pub(crate) mod tests { ); } + #[gpui::test] + async fn test_tool_call_session_reference_opens_its_session(cx: &mut TestAppContext) { + init_test(cx); + let connection = StubAgentConnection::new(); + let (conversation_view, cx) = + setup_conversation_view(StubAgentServer::new(connection.clone()), cx).await; + add_to_workspace_with_size(conversation_view.clone(), true, cx); + let root = + active_thread(&conversation_view, cx).read_with(cx, |view, _| view.thread.clone()); + let root_session_id = root.read_with(cx, |thread, _| thread.session_id().clone()); + let child = conversation_view.update(cx, |view, cx| { + create_test_acp_subagent( + root_session_id.clone(), + "child", + Rc::new(connection.clone()), + view.project.clone(), + cx, + ) + }); + child.update(cx, |child, cx| { + child + .update_subagent_association( + &acp_v2::SubagentUpdate::new("child").title("Investigator"), + cx, + ) + .expect("ACP subagent") + }); + root.update(cx, |root, cx| root.register_subagent(child.clone(), cx)); + root.update(cx, |root, cx| { + root.upsert_wire_tool_call( + acp_v2::ToolCallUpdate::new("delegate") + .title("Delegate") + .status(acp_v2::ToolCallStatus::Completed) + .content(vec![ + acp_v2::SessionReference::new("child").into(), + acp_v2::SessionReference::new("unknown").into(), + ]), + cx, + ) + }) + .expect("tool call"); + conversation_view.update(cx, |view, cx| view.expand_tool_call("delegate".into(), cx)); + cx.run_until_parked(); + + assert!( + cx.debug_bounds("tool-call-session-reference-0-1").is_none(), + "an unknown session is not a link" + ); + let link = cx + .debug_bounds("tool-call-session-reference-0-0") + .expect("the reference links to its session"); + cx.simulate_click(link.center(), gpui::Modifiers::default()); + cx.run_until_parked(); + let active_session_id = active_thread(&conversation_view, cx) + .read_with(cx, |view, cx| view.thread.read(cx).session_id().clone()); + assert_eq!(active_session_id, acp_v2::SessionId::new("child")); + } + #[gpui::test] async fn test_first_message_to_an_acp_subagent_shows_its_card(cx: &mut TestAppContext) { init_test(cx); diff --git a/crates/agent_ui/src/conversation_view/thread_view.rs b/crates/agent_ui/src/conversation_view/thread_view.rs index 86e51a58b54..f03c8b8ae80 100644 --- a/crates/agent_ui/src/conversation_view/thread_view.rs +++ b/crates/agent_ui/src/conversation_view/thread_view.rs @@ -7710,6 +7710,7 @@ impl ThreadView { !markdown.read(cx).source().is_empty() }) } + ToolCallContent::SessionReference(_) => true, ToolCallContent::Other { markdown, .. } => { !markdown.read(cx).source().is_empty() } @@ -11922,6 +11923,9 @@ impl ThreadView { }) .into_any_element() } + ToolCallContent::SessionReference(reference) => { + self.render_tool_call_session_reference(entry_ix, context_ix, reference, cx) + } ToolCallContent::Other { markdown, .. } => self.render_markdown_output( markdown.clone(), entry_ix, @@ -11934,6 +11938,58 @@ impl ThreadView { } } + fn render_tool_call_session_reference( + &self, + entry_ix: usize, + context_ix: usize, + reference: &acp_v2::SessionReference, + cx: &Context, + ) -> AnyElement { + let element_id = format!("tool-call-session-reference-{entry_ix}-{context_ix}"); + let participant = match self.session_participant_label(&reference.session_id, cx) { + Some(label) => div() + .debug_selector({ + let element_id = element_id.clone(); + move || element_id + }) + .child( + Button::new(SharedString::from(element_id), label) + .label_size(LabelSize::Small) + .tooltip(Tooltip::text("Open Session")) + .on_click(cx.listener({ + let session_id = reference.session_id.clone(); + move |this, _, window, cx| { + let Some(server_view) = this.server_view.upgrade() else { + return; + }; + server_view.update(cx, |view, cx| { + view.navigate_to_thread(session_id.clone(), window, cx) + }); + } + })), + ) + .into_any_element(), + // The reference is display-only, so a session this conversation has no thread for + // is shown rather than loaded. + None => Label::new("Unavailable Session") + .size(LabelSize::Small) + .color(Color::Muted) + .into_any_element(), + }; + + h_flex() + .px_2() + .py_1() + .gap_1p5() + .child( + Icon::new(IconName::ForwardArrow) + .size(IconSize::Small) + .color(Color::Muted), + ) + .child(participant) + .into_any_element() + } + fn render_output_content_block( &self, entry_ix: usize, diff --git a/crates/agent_ui/src/model_search.rs b/crates/agent_ui/src/model_search.rs index 988b220048d..e478838084d 100644 --- a/crates/agent_ui/src/model_search.rs +++ b/crates/agent_ui/src/model_search.rs @@ -1,7 +1,7 @@ use std::cmp::Reverse; use collections::HashSet; -use fuzzy_nucleo::StringMatchCandidate; +use fuzzy_nucleo::{Case, StringMatchCandidate, StringMatchOptions}; use gpui::BackgroundExecutor; use ordered_float::OrderedFloat; @@ -41,24 +41,23 @@ async fn match_names_with_metadata( query: &str, executor: BackgroundExecutor, ) -> Vec { - let cancel_flag = Default::default(); let (mut name_matches, mut metadata_matches) = futures::join!( fuzzy_nucleo::match_strings_async( names, query, - fuzzy_nucleo::Case::Ignore, - fuzzy_nucleo::LengthPenalty::On, - names.len(), - &cancel_flag, + StringMatchOptions { + case: Case::Ignore, + ..Default::default() + }, executor.clone(), ), fuzzy_nucleo::match_strings_async( candidates, query, - fuzzy_nucleo::Case::Ignore, - fuzzy_nucleo::LengthPenalty::On, - candidates.len(), - &cancel_flag, + StringMatchOptions { + case: Case::Ignore, + ..Default::default() + }, executor, ), ); diff --git a/crates/agent_ui/src/threads_archive_view.rs b/crates/agent_ui/src/threads_archive_view.rs index 2e909f1ea31..15ed40e93d1 100644 --- a/crates/agent_ui/src/threads_archive_view.rs +++ b/crates/agent_ui/src/threads_archive_view.rs @@ -28,7 +28,7 @@ use picker::{ Picker, PickerDelegate, highlighted_match_with_paths::{HighlightedMatch, HighlightedMatchWithPaths}, }; -use platform_title_bar::apply_title_bar_insets; +use platform_title_bar::{SidebarWindowControls, TitleBarSettings, apply_title_bar_insets}; use project::{AgentId, AgentServerStore}; use settings::Settings as _; use theme::ActiveTheme; @@ -859,30 +859,36 @@ impl ThreadsArchiveView { fn render_header(&self, window: &Window, cx: &mut Context) -> impl IntoElement { let has_query = !self.filter_editor.read(cx).text(cx).is_empty(); - let sidebar_on_left = matches!( - AgentSettings::get_global(cx).sidebar_side(), - settings::SidebarSide::Left - ); - let sidebar_on_right = !sidebar_on_left; - let not_fullscreen = !window.is_fullscreen() && !window.is_simple_fullscreen(); - let traffic_lights = cfg!(target_os = "macos") && not_fullscreen && sidebar_on_left; - let left_window_controls = !cfg!(target_os = "macos") && not_fullscreen && sidebar_on_left; - let right_window_controls = - !cfg!(target_os = "macos") && not_fullscreen && sidebar_on_right; - let header_height = platform_title_bar_height(window); + let SidebarWindowControls { + traffic_lights, + left: left_window_controls, + right: right_window_controls, + } = SidebarWindowControls::new(AgentSettings::get_global(cx).sidebar_side(), window, cx); + let title_bar_visible = TitleBarSettings::is_title_bar_visible(window, cx); + let header_height = if title_bar_visible { + platform_title_bar_height(window) + } else { + Tab::container_height(cx) + }; let show_focus_keybinding = self.selection.is_some() && !self.filter_editor.focus_handle(cx).is_focused(window); h_flex() + .debug_selector(|| "threads-archive-header".into()) .h(header_height) - .map(|header| match window.window_decorations() { - Decorations::Client { .. } => apply_title_bar_insets( - header, - left_window_controls, - right_window_controls, - false, - ), - Decorations::Server => header.mt_px().pb_px(), + .map(|header| { + if !title_bar_visible { + return header.mt_px(); + } + match window.window_decorations() { + Decorations::Client { .. } => apply_title_bar_insets( + header, + left_window_controls, + right_window_controls, + false, + ), + Decorations::Server => header.mt_px().pb_px(), + } }) .when(left_window_controls, |this| { this.children(Self::render_left_window_controls(window, cx)) @@ -906,6 +912,7 @@ impl ThreadsArchiveView { }) .child( h_flex() + .debug_selector(|| "threads-archive-header-search".into()) .ml_1() .min_w_0() .w_full() diff --git a/crates/agent_ui_benchmarks/benches/model_search.rs b/crates/agent_ui_benchmarks/benches/model_search.rs index ff039205510..419eab473c0 100644 --- a/crates/agent_ui_benchmarks/benches/model_search.rs +++ b/crates/agent_ui_benchmarks/benches/model_search.rs @@ -1,7 +1,7 @@ use std::{cmp::Reverse, fmt, sync::Arc, time::Duration}; use collections::HashSet; -use fuzzy_nucleo::{Case, LengthPenalty, StringMatch, StringMatchCandidate}; +use fuzzy_nucleo::{Case, StringMatch, StringMatchCandidate, StringMatchOptions}; use gpui::{BenchAppContext, SharedString}; use ordered_float::OrderedFloat; @@ -118,20 +118,12 @@ fn expected_values(options: &[OptionValue], query: &str) -> Vec { .enumerate() .map(|(index, option)| candidates(index, option)) .unzip(); - let mut names = fuzzy_nucleo::match_strings( - &names, - query, - Case::Ignore, - LengthPenalty::On, - options.len(), - ); - let mut metadata = fuzzy_nucleo::match_strings( - &metadata, - query, - Case::Ignore, - LengthPenalty::On, - options.len(), - ); + let match_options = StringMatchOptions { + case: Case::Ignore, + ..Default::default() + }; + let mut names = fuzzy_nucleo::match_strings(&names, query, match_options); + let mut metadata = fuzzy_nucleo::match_strings(&metadata, query, match_options); let sorting_key = |matched: &StringMatch| (Reverse(OrderedFloat(matched.score)), matched.candidate_id); names.sort_unstable_by_key(sorting_key); diff --git a/crates/anthropic/src/anthropic.rs b/crates/anthropic/src/anthropic.rs index c6cc106a953..499ef71c90a 100644 --- a/crates/anthropic/src/anthropic.rs +++ b/crates/anthropic/src/anthropic.rs @@ -15,6 +15,8 @@ use serde::{Deserialize, Serialize}; use strum::EnumString; use thiserror::Error; +pub use language_model_core::InputTransformation; + pub mod batches; pub mod completion; @@ -1182,6 +1184,10 @@ pub struct Response { #[serde(default, skip_serializing_if = "Option::is_none")] pub stop_sequence: Option, pub usage: Usage, + /// Changes the API made to the request before the model read it. Only sent + /// with the [`THINKING_BINDING_CONTROLS_BETA_HEADER`] beta header. + #[serde(default, skip_serializing_if = "Vec::is_empty")] + pub input_transformations: Vec, } #[derive(Debug, Serialize, Deserialize)] diff --git a/crates/anthropic/src/completion.rs b/crates/anthropic/src/completion.rs index e4eb0303a19..117d2e4e2fe 100644 --- a/crates/anthropic/src/completion.rs +++ b/crates/anthropic/src/completion.rs @@ -108,6 +108,7 @@ pub async fn collect_compaction_result( | LanguageModelCompletionEvent::ToolUseJsonParseError { .. } | LanguageModelCompletionEvent::StartMessage { .. } | LanguageModelCompletionEvent::ReasoningDetails(_) + | LanguageModelCompletionEvent::InputTransformations(_) | LanguageModelCompletionEvent::Compaction(CompactionUpdate::Started) | LanguageModelCompletionEvent::Compaction(CompactionUpdate::SummaryDelta(_)) => {} } @@ -728,14 +729,20 @@ impl AnthropicEventMapper { } Event::MessageStart { message } => { update_usage(&mut self.usage, &message.usage); - vec![ + let mut events = vec![ Ok(LanguageModelCompletionEvent::UsageUpdate(convert_usage( &self.usage, ))), Ok(LanguageModelCompletionEvent::StartMessage { message_id: message.id, }), - ] + ]; + if !message.input_transformations.is_empty() { + events.push(Ok(LanguageModelCompletionEvent::InputTransformations( + message.input_transformations, + ))); + } + events } Event::MessageDelta { delta, usage } => { update_usage(&mut self.usage, &usage); @@ -1852,6 +1859,67 @@ mod tests { ); } + #[test] + fn test_event_mapper_preserves_all_input_transformations() { + let mut mapper = AnthropicEventMapper::new(ANTHROPIC_PROVIDER_NAME, ANTHROPIC_PROVIDER_ID); + let start_event: Event = serde_json::from_value(serde_json::json!({ + "type": "message_start", + "message": { + "id": "msg_1", + "type": "message", + "role": "assistant", + "content": [], + "model": "claude-fable-5-1", + "usage": { "input_tokens": 10, "output_tokens": 0 }, + "input_transformations": [ + { + "type": "thinking_dropped", + "path": "messages.1.content.0", + "reason": "prefix_binding_mismatch" + }, + { + "type": "thinking_mismatch_allowed", + "path": "messages.3.content.0", + "reason": "prefix_binding_mismatch" + }, + { + "type": "some_future_transformation", + "path": "messages.5.content.0", + "reason": "some_future_reason" + } + ] + } + })) + .unwrap(); + + let events = mapper + .map_event(start_event) + .into_iter() + .collect::, _>>() + .unwrap(); + + assert_eq!( + events.last(), + Some(&LanguageModelCompletionEvent::InputTransformations(vec![ + crate::InputTransformation { + kind: "thinking_dropped".into(), + path: "messages.1.content.0".into(), + reason: "prefix_binding_mismatch".into(), + }, + crate::InputTransformation { + kind: "thinking_mismatch_allowed".into(), + path: "messages.3.content.0".into(), + reason: "prefix_binding_mismatch".into(), + }, + crate::InputTransformation { + kind: "some_future_transformation".into(), + path: "messages.5.content.0".into(), + reason: "some_future_reason".into(), + }, + ])) + ); + } + #[test] fn test_event_mapper_rejects_compaction_delta_before_start() { let mut mapper = AnthropicEventMapper::new(ANTHROPIC_PROVIDER_NAME, ANTHROPIC_PROVIDER_ID); diff --git a/crates/cli/src/cli.rs b/crates/cli/src/cli.rs index d7ad0b347ed..5ffe0af3265 100644 --- a/crates/cli/src/cli.rs +++ b/crates/cli/src/cli.rs @@ -72,6 +72,8 @@ pub enum CliRequest { SetOpenBehavior { behavior: CliBehaviorSetting, }, + /// Print a diagnostic snapshot of the app's GPUI and platform state. + DebugState, } #[derive(Debug, Serialize, Deserialize)] diff --git a/crates/cli/src/main.rs b/crates/cli/src/main.rs index a14495666dd..6d1bacdf645 100644 --- a/crates/cli/src/main.rs +++ b/crates/cli/src/main.rs @@ -128,6 +128,10 @@ struct Args { /// Will attempt to give the correct command to run #[arg(long)] system_specs: bool, + /// Print a JSON snapshot of the running Zed's GPUI and platform state + /// (windows, displays, frame scheduling, cursor), for debugging. + #[arg(long)] + debug_state: bool, /// Open the project in a dev container. /// /// Automatically triggers "Reopen in Dev Container" if a `.devcontainer/` @@ -684,7 +688,11 @@ fn run() -> Result<()> { cwd: env::current_dir().ok(), }; - tx.send(open_request)?; + tx.send(if args.debug_state { + CliRequest::DebugState + } else { + open_request + })?; while let Ok(response) = rx.recv() { match response { diff --git a/crates/client/src/telemetry.rs b/crates/client/src/telemetry.rs index a08dfb44bd6..72426132a1c 100644 --- a/crates/client/src/telemetry.rs +++ b/crates/client/src/telemetry.rs @@ -62,6 +62,7 @@ struct TelemetryState { worktrees_with_project_type_events_sent: HashSet, os_name: String, + desktop_environment: Option, app_version: String, os_version: Option, @@ -106,7 +107,36 @@ static DOTNET_PROJECT_FILES_REGEX: LazyLock = LazyLock::new(|| { Regex::new(r"^(global\.json|Directory\.Build\.props|.*\.(csproj|fsproj|vbproj|sln))$").unwrap() }); -pub fn os_name() -> String { +/// Returns the OS name, including the display server the platform connected to. +#[cfg_attr( + not(any(target_os = "linux", target_os = "freebsd")), + expect(unused_variables) +)] +pub fn os_name(cx: &App) -> String { + #[cfg(target_os = "macos")] + { + "macOS".to_string() + } + #[cfg(target_os = "linux")] + { + format!("Linux {}", cx.compositor_name()) + } + #[cfg(target_os = "freebsd")] + { + format!("FreeBSD {}", cx.compositor_name()) + } + + #[cfg(target_os = "windows")] + { + "Windows".to_string() + } +} + +/// Returns the OS name, guessing the display server from the environment. +/// +/// Prefer [`os_name`] once an [`App`] exists; the platform may connect to a +/// different display server than the environment suggests. +pub fn guessed_os_name() -> String { #[cfg(target_os = "macos")] { "macOS".to_string() @@ -206,7 +236,10 @@ impl Telemetry { worktrees_with_project_type_events_sent: HashSet::new(), os_version: None, - os_name: os_name(), + os_name: os_name(cx), + desktop_environment: cx + .graphical_environment() + .and_then(|environment| environment.desktop_environment()), app_version: release_channel::AppVersion::global(cx).to_string(), subscribers: Vec::new(), })); @@ -365,7 +398,7 @@ impl Telemetry { state.installation_id = installation_id.map(|id| id.into()); state.session_id = Some(session_id); state.app_version = release_channel::AppVersion::global(cx).to_string(); - state.os_name = os_name(); + state.os_name = os_name(cx); } pub fn metrics_enabled(self: &Arc) -> bool { @@ -688,6 +721,7 @@ impl Telemetry { is_staff: state.is_staff, app_version: state.app_version.clone(), os_name: state.os_name.clone(), + desktop_environment: state.desktop_environment.clone(), os_version: state.os_version.clone(), architecture: state.architecture.to_string(), diff --git a/crates/collab/src/api/events.rs b/crates/collab/src/api/events.rs index 0c1419144d4..bfcb8a3ad51 100644 --- a/crates/collab/src/api/events.rs +++ b/crates/collab/src/api/events.rs @@ -148,6 +148,12 @@ fn for_snowflake( map.insert("app_version".to_string(), body.app_version.clone().into()); map.insert("os_name".to_string(), body.os_name.clone().into()); map.insert("os_version".to_string(), body.os_version.clone().into()); + if let Some(desktop_environment) = body.desktop_environment.as_ref() { + map.insert( + "desktop_environment".to_string(), + desktop_environment.clone().into(), + ); + } map.insert("architecture".to_string(), body.architecture.clone().into()); map.insert( "release_channel".to_string(), diff --git a/crates/command_palette/src/command_palette.rs b/crates/command_palette/src/command_palette.rs index 4d4117755d6..f2b4c5851c1 100644 --- a/crates/command_palette/src/command_palette.rs +++ b/crates/command_palette/src/command_palette.rs @@ -618,10 +618,10 @@ impl PickerDelegate for CommandPaletteDelegate { let mut matches = fuzzy_nucleo::match_strings_async( &candidates, &query, - fuzzy_nucleo::Case::Smart, - fuzzy_nucleo::LengthPenalty::On, - 10000, - &Default::default(), + fuzzy_nucleo::StringMatchOptions { + max_results: fuzzy_nucleo::MaxResults::limit::<10_000>(), + ..Default::default() + }, executor, ) .await; diff --git a/crates/editor/src/document_colors.rs b/crates/editor/src/document_colors.rs index cc7619caadc..3fcf534392f 100644 --- a/crates/editor/src/document_colors.rs +++ b/crates/editor/src/document_colors.rs @@ -25,7 +25,6 @@ pub(super) struct LspColorData { #[derive(Debug, Default)] struct BufferColors { colors: Vec<(Range, DocumentColor, InlayId)>, - inlay_colors: HashMap, } impl LspColorData { @@ -40,52 +39,48 @@ impl LspColorData { &mut self, new_render_mode: DocumentColorsRenderMode, ) -> Option { - if self.render_mode == new_render_mode { + let old_render_mode = self.render_mode; + if old_render_mode == new_render_mode { return None; } self.render_mode = new_render_mode; - match new_render_mode { - DocumentColorsRenderMode::Inlay => Some(InlaySplice { - to_remove: Vec::new(), - to_insert: self - .buffer_colors - .values() - .flat_map(|buffer_colors| buffer_colors.colors.iter()) - .map(|(range, color, id)| { - Inlay::color( - id.id(), - range.start, - Rgba { - r: color.color.red, - g: color.color.green, - b: color.color.blue, - a: color.color.alpha, - }, - ) - }) - .collect(), - }), - DocumentColorsRenderMode::None => Some(InlaySplice { - to_remove: self - .buffer_colors - .drain() - .flat_map(|(_, buffer_colors)| buffer_colors.inlay_colors) - .map(|(id, _)| id) - .collect(), - to_insert: Vec::new(), - }), - DocumentColorsRenderMode::Border | DocumentColorsRenderMode::Background => { - Some(InlaySplice { - to_remove: self - .buffer_colors - .iter_mut() - .flat_map(|(_, buffer_colors)| buffer_colors.inlay_colors.drain()) - .map(|(id, _)| id) - .collect(), - to_insert: Vec::new(), + let to_remove = if old_render_mode == DocumentColorsRenderMode::Inlay { + self.buffer_colors + .values() + .flat_map(|buffer_colors| buffer_colors.colors.iter()) + .map(|(_, _, id)| *id) + .collect() + } else { + Vec::new() + }; + let to_insert = match new_render_mode { + DocumentColorsRenderMode::Inlay => self + .buffer_colors + .values() + .flat_map(|buffer_colors| buffer_colors.colors.iter()) + .map(|(range, color, id)| { + Inlay::color( + id.id(), + range.start, + Rgba { + r: color.color.red, + g: color.color.green, + b: color.color.blue, + a: color.color.alpha, + }, + ) }) + .collect(), + DocumentColorsRenderMode::None => { + self.buffer_colors.clear(); + Vec::new() } - } + DocumentColorsRenderMode::Border | DocumentColorsRenderMode::Background => Vec::new(), + }; + Some(InlaySplice { + to_remove, + to_insert, + }) } fn set_colors( @@ -97,12 +92,6 @@ impl LspColorData { if buffer_colors.colors == colors { return false; } - - buffer_colors.inlay_colors = colors - .iter() - .enumerate() - .map(|(i, (_, _, id))| (*id, i)) - .collect(); buffer_colors.colors = colors; true } @@ -438,7 +427,7 @@ mod tests { }; use futures::StreamExt; - use gpui::{Rgba, TestAppContext}; + use gpui::{Entity, Rgba, TestAppContext, VisualTestContext}; use language::FakeLspAdapter; use languages::rust_lang; use project::{FakeFs, Project}; @@ -450,18 +439,12 @@ mod tests { }; use crate::{ - Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT, actions::MoveToEnd, editor_tests::init_test, + Editor, LSP_REQUEST_DEBOUNCE_TIMEOUT, + actions::MoveToEnd, + editor_settings::DocumentColorsRenderMode, + editor_tests::{init_test, update_test_editor_settings}, }; - fn extract_color_inlays(editor: &Editor, cx: &gpui::App) -> Vec { - editor - .all_inlays(cx) - .into_iter() - .filter_map(|inlay| inlay.get_color()) - .map(Rgba::from) - .collect() - } - #[gpui::test(iterations = 10)] async fn test_document_colors(cx: &mut TestAppContext) { let expected_color = Rgba { @@ -599,6 +582,7 @@ mod tests { "Should have an initial inlay" ); }); + assert_color_render_modes(&editor, &[expected_color], cx); // opening another file in a split should not influence the LSP query counter workspace.update_in(cx, |workspace, window, cx| { @@ -768,5 +752,72 @@ mod tests { "Should clear all colors when the server returns an empty response" ); }); + assert_color_render_modes(&editor, &[], cx); + } + + fn assert_color_render_modes( + editor: &Entity, + expected_colors: &[Rgba], + cx: &mut VisualTestContext, + ) { + for _ in 0..2 { + for render_mode in [ + DocumentColorsRenderMode::Inlay, + DocumentColorsRenderMode::Border, + DocumentColorsRenderMode::Inlay, + DocumentColorsRenderMode::Background, + DocumentColorsRenderMode::Inlay, + DocumentColorsRenderMode::None, + DocumentColorsRenderMode::Inlay, + ] { + update_test_editor_settings(cx, &|settings| { + settings.lsp_document_colors = Some(render_mode); + }); + cx.executor().advance_clock(LSP_REQUEST_DEBOUNCE_TIMEOUT); + cx.run_until_parked(); + editor.update_in(cx, |editor, window, cx| { + let expected_inlays = if render_mode == DocumentColorsRenderMode::Inlay { + expected_colors + } else { + &[] + }; + assert_eq!( + extract_color_inlays(editor, cx), + expected_inlays, + "Unexpected inlays in {render_mode:?} mode", + ); + let snapshot = editor.snapshot(window, cx); + let (actual_mode, highlights) = editor + .colors + .as_ref() + .unwrap() + .editor_display_highlights(&snapshot); + assert_eq!(actual_mode, render_mode); + let expected_highlights = match render_mode { + DocumentColorsRenderMode::Border | DocumentColorsRenderMode::Background => { + expected_colors + } + DocumentColorsRenderMode::None | DocumentColorsRenderMode::Inlay => &[], + }; + assert_eq!( + highlights + .into_iter() + .map(|(_, color)| Rgba::from(color)) + .collect::>(), + expected_highlights, + "Unexpected highlights in {render_mode:?} mode", + ); + }); + } + } + } + + fn extract_color_inlays(editor: &Editor, cx: &gpui::App) -> Vec { + editor + .all_inlays(cx) + .into_iter() + .filter_map(|inlay| inlay.get_color()) + .map(Rgba::from) + .collect() } } diff --git a/crates/editor/src/editor_tests.rs b/crates/editor/src/editor_tests.rs index c8da5a119f7..ff4c0e33a12 100644 --- a/crates/editor/src/editor_tests.rs +++ b/crates/editor/src/editor_tests.rs @@ -80,6 +80,7 @@ use workspace::{ Pane, SplitDirection, ToolbarItemLocation, ViewId, Workspace, item::{FollowEvent, FollowableItem, Item, ItemHandle, SaveOptions}, register_project_item, + security_modal::SecurityModal, }; fn display_ranges(editor: &Editor, cx: &mut Context<'_, Editor>) -> Vec> { @@ -46902,6 +46903,80 @@ async fn test_tab_list_indent(cx: &mut TestAppContext) { cx.assert_editor_state(expected); } +#[gpui::test] +async fn test_stay_in_restricted_mode_is_remembered(cx: &mut TestAppContext) { + init_test(cx, |_| {}); + cx.update(|cx| { + cx.set_global(db::AppDatabase::test_new()); + project::trusted_worktrees::init(HashMap::default(), cx); + }); + + let fs = FakeFs::new(cx.executor()); + fs.insert_tree( + path!("/projects"), + json!({ + "declined": {"main.rs": "", "nested": {"lib.rs": ""}}, + "other": {"main.rs": ""}, + }), + ) + .await; + + for (project_path, expect_prompt) in [ + (path!("/projects/declined"), true), + (path!("/projects/declined"), false), + (path!("/projects/declined/nested"), true), + (path!("/projects/other"), true), + (path!("/projects/other"), false), + ] { + let project = + Project::test_with_worktree_trust(fs.clone(), [project_path.as_ref()], cx).await; + let worktree_store = project.read_with(cx, |project, _| project.worktree_store()); + let worktree_id = project.read_with(cx, |project, cx| { + project + .worktrees(cx) + .next() + .expect("project should have a worktree") + .read(cx) + .id() + }); + let trusted_worktrees = cx + .update(|cx| TrustedWorktrees::try_get_global(cx).expect("trust global should exist")); + assert!(!trusted_worktrees.update(cx, |store, cx| { + store.can_trust(&worktree_store, worktree_id, cx) + })); + + let (multi_workspace, window_cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx)); + let workspace = multi_workspace.read_with(window_cx, |multi_workspace, _| { + multi_workspace.workspace().clone() + }); + let has_modal = |window_cx: &mut VisualTestContext| { + workspace.read_with(window_cx, |workspace, cx| { + workspace.active_modal::(cx).is_some() + }) + }; + + workspace.update_in(window_cx, |workspace, window, cx| { + workspace.show_worktree_trust_security_modal(false, window, cx); + }); + window_cx.run_until_parked(); + assert_eq!(has_modal(window_cx), expect_prompt, "{project_path}"); + + if !expect_prompt { + window_cx.dispatch_action(workspace::ToggleWorktreeSecurity); + window_cx.run_until_parked(); + assert!(has_modal(window_cx), "{project_path}"); + } + window_cx.dispatch_action(workspace::ToggleWorktreeSecurity); + window_cx.run_until_parked(); + assert!(!has_modal(window_cx), "{project_path}"); + + assert!(!trusted_worktrees.update(window_cx, |store, cx| { + store.can_trust(&worktree_store, worktree_id, cx) + })); + } +} + #[gpui::test] async fn test_local_worktree_trust(cx: &mut TestAppContext) { init_test(cx, |_| {}); diff --git a/crates/editor/src/element.rs b/crates/editor/src/element.rs index 2c3370a81bc..3dee38a8cf7 100644 --- a/crates/editor/src/element.rs +++ b/crates/editor/src/element.rs @@ -5083,7 +5083,7 @@ impl EditorElement { } fn paint_background(&self, layout: &EditorLayout, window: &mut Window, cx: &mut App) { - window.paint_layer(layout.hitbox.bounds, |window| { + window.paint_layer(|window| { let scroll_top = layout.position_map.scroll_position.y; let gutter_bg = cx.theme().colors().editor_gutter_background; window.paint_quad(fill(layout.gutter_hitbox.bounds, gutter_bg)); @@ -5406,7 +5406,7 @@ impl EditorElement { } let line_height = layout.position_map.line_height; - window.paint_layer(layout.gutter_hitbox.bounds, |window| { + window.paint_layer(|window| { for (hunk, hitbox) in &layout.display_hunks { let hunk_to_paint = match hunk { DisplayDiffHunk::Folded { .. } => { @@ -5619,35 +5619,33 @@ impl EditorElement { window: &mut Window, cx: &mut App, ) { - window.paint_layer(layout.gutter_hitbox.bounds, |window| { - window.with_element_namespace("crease_toggles", |window| { - for crease_toggle in layout.crease_toggles.iter_mut().flatten() { - crease_toggle.paint(window, cx); - } - }); - - window.with_element_namespace("expand_toggles", |window| { - for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() { - expand_toggle.paint(window, cx); - } - }); - - for bookmark in layout.bookmarks.iter_mut() { - bookmark.paint(window, cx); - } - - for breakpoint in layout.breakpoints.iter_mut() { - breakpoint.paint(window, cx); - } - - for test_indicator in layout.test_indicators.iter_mut() { - test_indicator.paint(window, cx); - } - - if let Some(diff_review_button) = layout.diff_review_button.as_mut() { - diff_review_button.paint(window, cx); + window.with_element_namespace("crease_toggles", |window| { + for crease_toggle in layout.crease_toggles.iter_mut().flatten() { + crease_toggle.paint(window, cx); } }); + + window.with_element_namespace("expand_toggles", |window| { + for (expand_toggle, _) in layout.expand_toggles.iter_mut().flatten() { + expand_toggle.paint(window, cx); + } + }); + + for bookmark in layout.bookmarks.iter_mut() { + bookmark.paint(window, cx); + } + + for breakpoint in layout.breakpoints.iter_mut() { + breakpoint.paint(window, cx); + } + + for test_indicator in layout.test_indicators.iter_mut() { + test_indicator.paint(window, cx); + } + + if let Some(diff_review_button) = layout.diff_review_button.as_mut() { + diff_review_button.paint(window, cx); + } } fn paint_gutter_highlights( @@ -5685,7 +5683,7 @@ impl EditorElement { let highlight_width = 0.275 * layout.position_map.line_height; let highlight_corner_radii = Corners::all(0.05 * layout.position_map.line_height); - window.paint_layer(layout.gutter_hitbox.bounds, |window| { + window.paint_layer(|window| { for (range, color) in &layout.highlighted_gutter_ranges { let start_row = if range.start.row() < layout.visible_display_row_range.start { layout.visible_display_row_range.start - DisplayRow(1) @@ -5729,11 +5727,9 @@ impl EditorElement { return; }; - window.paint_layer(layout.gutter_hitbox.bounds, |window| { - for mut blame_element in blamed_display_rows.into_iter() { - blame_element.paint(window, cx); - } - }) + for mut blame_element in blamed_display_rows.into_iter() { + blame_element.paint(window, cx); + } } fn populate_point_diagnostics( @@ -5975,7 +5971,7 @@ impl EditorElement { window: &mut Window, cx: &mut App, ) -> SmallVec<[Range; 32]> { - window.paint_layer(layout.position_map.text_hitbox.bounds, |window| { + window.paint_layer(|window| { let mut invisible_display_ranges = SmallVec::<[Range; 32]>::new(); let line_end_overshoot = 0.15 * layout.position_map.line_height; for (range, color) in &layout.highlighted_ranges { @@ -6072,7 +6068,7 @@ impl EditorElement { // A softer than perfect black let redaction_color = gpui::rgb(0x0e1111); - window.paint_layer(layout.position_map.text_hitbox.bounds, |window| { + window.paint_layer(|window| { for range in layout.redacted_ranges.iter() { self.paint_highlighted_range( range.clone(), @@ -6173,7 +6169,7 @@ impl EditorElement { }, }; - window.paint_layer(hitbox.bounds, |window| { + window.paint_layer(|window| { window.paint_quad(quad( hitbox.bounds, Corners::default(), @@ -6676,9 +6672,7 @@ impl EditorElement { fn paint_inline_blame(&mut self, layout: &mut EditorLayout, window: &mut Window, cx: &mut App) { if let Some(mut blame_layout) = layout.inline_blame_layout.take() { - window.paint_layer(layout.position_map.text_hitbox.bounds, |window| { - blame_layout.element.paint(window, cx); - }) + blame_layout.element.paint(window, cx); } } @@ -6689,9 +6683,7 @@ impl EditorElement { cx: &mut App, ) { if let Some(mut inline_code_actions) = layout.inline_code_actions.take() { - window.paint_layer(layout.position_map.text_hitbox.bounds, |window| { - inline_code_actions.paint(window, cx); - }) + inline_code_actions.paint(window, cx); } } @@ -6711,54 +6703,48 @@ impl EditorElement { let minimap_hitbox = layout.thumb_layout.hitbox.clone(); let dragging_minimap = self.editor.read(cx).scroll_manager.is_dragging_minimap(); - window.paint_layer(layout.thumb_layout.hitbox.bounds, |window| { - window.with_element_namespace("minimap", |window| { - layout.minimap.paint(window, cx); - if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds { - let minimap_thumb_color = match layout.thumb_layout.thumb_state { - ScrollbarThumbState::Idle => { - cx.theme().colors().minimap_thumb_background - } - ScrollbarThumbState::Hovered => { - cx.theme().colors().minimap_thumb_hover_background - } - ScrollbarThumbState::Dragging => { - cx.theme().colors().minimap_thumb_active_background - } - }; - let minimap_thumb_border = match layout.thumb_border_style { - MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH), - MinimapThumbBorder::LeftOnly => Edges { - left: ScrollbarLayout::BORDER_WIDTH, - ..Default::default() - }, - MinimapThumbBorder::LeftOpen => Edges { - right: ScrollbarLayout::BORDER_WIDTH, - top: ScrollbarLayout::BORDER_WIDTH, - bottom: ScrollbarLayout::BORDER_WIDTH, - ..Default::default() - }, - MinimapThumbBorder::RightOpen => Edges { - left: ScrollbarLayout::BORDER_WIDTH, - top: ScrollbarLayout::BORDER_WIDTH, - bottom: ScrollbarLayout::BORDER_WIDTH, - ..Default::default() - }, - MinimapThumbBorder::None => Default::default(), - }; + window.with_element_namespace("minimap", |window| { + layout.minimap.paint(window, cx); + if let Some(thumb_bounds) = layout.thumb_layout.thumb_bounds { + let minimap_thumb_color = match layout.thumb_layout.thumb_state { + ScrollbarThumbState::Idle => cx.theme().colors().minimap_thumb_background, + ScrollbarThumbState::Hovered => { + cx.theme().colors().minimap_thumb_hover_background + } + ScrollbarThumbState::Dragging => { + cx.theme().colors().minimap_thumb_active_background + } + }; + let minimap_thumb_border = match layout.thumb_border_style { + MinimapThumbBorder::Full => Edges::all(ScrollbarLayout::BORDER_WIDTH), + MinimapThumbBorder::LeftOnly => Edges { + left: ScrollbarLayout::BORDER_WIDTH, + ..Default::default() + }, + MinimapThumbBorder::LeftOpen => Edges { + right: ScrollbarLayout::BORDER_WIDTH, + top: ScrollbarLayout::BORDER_WIDTH, + bottom: ScrollbarLayout::BORDER_WIDTH, + ..Default::default() + }, + MinimapThumbBorder::RightOpen => Edges { + left: ScrollbarLayout::BORDER_WIDTH, + top: ScrollbarLayout::BORDER_WIDTH, + bottom: ScrollbarLayout::BORDER_WIDTH, + ..Default::default() + }, + MinimapThumbBorder::None => Default::default(), + }; - window.paint_layer(minimap_hitbox.bounds, |window| { - window.paint_quad(quad( - thumb_bounds, - Corners::default(), - minimap_thumb_color, - minimap_thumb_border, - cx.theme().colors().minimap_thumb_border, - BorderStyle::Solid, - )); - }); - } - }); + window.paint_quad(quad( + thumb_bounds, + Corners::default(), + minimap_thumb_color, + minimap_thumb_border, + cx.theme().colors().minimap_thumb_border, + BorderStyle::Solid, + )); + } }); if dragging_minimap { diff --git a/crates/editor/src/element/header.rs b/crates/editor/src/element/header.rs index cb12d33f17d..5cd09185db3 100644 --- a/crates/editor/src/element/header.rs +++ b/crates/editor/src/element/header.rs @@ -432,42 +432,36 @@ impl StickyHeaders { let line_height = layout.position_map.line_height; for line in self.lines.iter_mut().rev() { - window.paint_layer( - Bounds::new( + window.paint_layer(|window| { + let gutter_bounds = Bounds::new( layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset), - size(line.hitbox.size.width, line_height), - ), - |window| { - let gutter_bounds = Bounds::new( - layout.gutter_hitbox.origin + point(Pixels::ZERO, line.offset), - size(layout.gutter_hitbox.size.width, line_height), - ); - window.paint_quad(fill(gutter_bounds, self.gutter_background)); + size(layout.gutter_hitbox.size.width, line_height), + ); + window.paint_quad(fill(gutter_bounds, self.gutter_background)); - let text_bounds = Bounds::new( - layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset), - size(line.available_text_width, line_height), - ); - window.paint_quad(fill(text_bounds, self.content_background)); + let text_bounds = Bounds::new( + layout.position_map.text_hitbox.origin + point(Pixels::ZERO, line.offset), + size(line.available_text_width, line_height), + ); + window.paint_quad(fill(text_bounds, self.content_background)); - if line.hitbox.is_hovered(window) { - let hover_overlay = cx.theme().colors().panel_overlay_hover; - window.paint_quad(fill(gutter_bounds, hover_overlay)); - window.paint_quad(fill(text_bounds, hover_overlay)); - } + if line.hitbox.is_hovered(window) { + let hover_overlay = cx.theme().colors().panel_overlay_hover; + window.paint_quad(fill(gutter_bounds, hover_overlay)); + window.paint_quad(fill(text_bounds, hover_overlay)); + } - line.paint( - layout, - self.gutter_right_padding, - line.available_text_width, - layout.content_origin, - line_height, - whitespace_setting, - window, - cx, - ); - }, - ); + line.paint( + layout, + self.gutter_right_padding, + line.available_text_width, + layout.content_origin, + line_height, + whitespace_setting, + window, + cx, + ); + }); window.set_cursor_style(CursorStyle::IBeam, &line.hitbox); } diff --git a/crates/feedback/src/feedback.rs b/crates/feedback/src/feedback.rs index 16c91ce769d..6fb59d9874d 100644 --- a/crates/feedback/src/feedback.rs +++ b/crates/feedback/src/feedback.rs @@ -49,8 +49,8 @@ pub fn init(cx: &mut App) { cx.observe_new(|workspace: &mut Workspace, _, _| { workspace .register_action(|_, _: &CopySystemSpecsIntoClipboard, window, cx| { - let specs = - SystemSpecs::new(window, cx, telemetry::os_name(), telemetry::os_version()); + let os_name = telemetry::os_name(cx); + let specs = SystemSpecs::new(window, cx, os_name, telemetry::os_version()); cx.spawn_in(window, async move |_, cx| { let specs = specs.await.to_string(); @@ -85,8 +85,8 @@ pub fn init(cx: &mut App) { cx.open_url(REQUEST_FEATURE_URL); }) .register_action(move |_, _: &FileBugReport, window, cx| { - let specs = - SystemSpecs::new(window, cx, telemetry::os_name(), telemetry::os_version()); + let os_name = telemetry::os_name(cx); + let specs = SystemSpecs::new(window, cx, os_name, telemetry::os_version()); cx.spawn_in(window, async move |_, cx| { let specs = specs.await; cx.update(|_, cx| { @@ -97,8 +97,8 @@ pub fn init(cx: &mut App) { .detach(); }) .register_action(move |_, _: &EmailZed, window, cx| { - let specs = - SystemSpecs::new(window, cx, telemetry::os_name(), telemetry::os_version()); + let os_name = telemetry::os_name(cx); + let specs = SystemSpecs::new(window, cx, os_name, telemetry::os_version()); cx.spawn_in(window, async move |_, cx| { let specs = specs.await; cx.update(|_, cx| { diff --git a/crates/file_finder/src/file_finder.rs b/crates/file_finder/src/file_finder.rs index 16dd78c8405..15bf39a6cde 100644 --- a/crates/file_finder/src/file_finder.rs +++ b/crates/file_finder/src/file_finder.rs @@ -801,7 +801,6 @@ fn matching_history_items<'a>( ); let mut matching_history_paths = HashMap::default(); for (worktree, candidates) in history_items_by_worktrees { - let max_results = candidates.len() + 1; let worktree_root_name = worktree_name_by_id .as_ref() .and_then(|w| w.get(&worktree).cloned()); @@ -812,8 +811,7 @@ fn matching_history_items<'a>( worktree.to_usize(), worktree_root_name, query.path_query(), - fuzzy_nucleo::Case::Ignore, - max_results, + Default::default(), path_style, ) .into_iter() @@ -1358,9 +1356,11 @@ impl FileFinderDelegate { candidate_sets.as_slice(), query.path_query(), &relative_to, - fuzzy_nucleo::Case::Ignore, - 100, - &cancel_flag, + fuzzy_nucleo::PathMatchOptions { + max_results: fuzzy_nucleo::MaxResults::limit::<100>(), + cancel_flag: Some(&cancel_flag), + ..Default::default() + }, cx.background_executor().clone(), ) .await diff --git a/crates/file_finder/src/file_finder_tests.rs b/crates/file_finder/src/file_finder_tests.rs index 59cff873c66..ffb6dbde575 100644 --- a/crates/file_finder/src/file_finder_tests.rs +++ b/crates/file_finder/src/file_finder_tests.rs @@ -5734,6 +5734,17 @@ fn select_range_in_active_editor( async fn test_seed_query_from_editor_selection(cx: &mut TestAppContext) { let app_state = init_test(cx); + cx.update(|cx| { + let settings = *FileFinderSettings::get_global(cx); + FileFinderSettings::override_global( + FileFinderSettings { + prefill_query_from_selection: true, + ..settings + }, + cx, + ); + }); + app_state .fs .as_fake() @@ -5773,6 +5784,17 @@ async fn test_seed_query_from_editor_selection(cx: &mut TestAppContext) { async fn test_no_seed_query_without_selection(cx: &mut TestAppContext) { let app_state = init_test(cx); + cx.update(|cx| { + let settings = *FileFinderSettings::get_global(cx); + FileFinderSettings::override_global( + FileFinderSettings { + prefill_query_from_selection: true, + ..settings + }, + cx, + ); + }); + app_state .fs .as_fake() @@ -5808,6 +5830,17 @@ async fn test_no_seed_query_without_selection(cx: &mut TestAppContext) { async fn test_seed_query_flattens_multiline_selection(cx: &mut TestAppContext) { let app_state = init_test(cx); + cx.update(|cx| { + let settings = *FileFinderSettings::get_global(cx); + FileFinderSettings::override_global( + FileFinderSettings { + prefill_query_from_selection: true, + ..settings + }, + cx, + ); + }); + app_state .fs .as_fake() diff --git a/crates/fs/src/fs_watcher.rs b/crates/fs/src/fs_watcher.rs index c9c75fb2cc8..79d45c2b8a7 100644 --- a/crates/fs/src/fs_watcher.rs +++ b/crates/fs/src/fs_watcher.rs @@ -19,6 +19,8 @@ pub use diagnostics::{ WatchDiagnosticEvent, WatchRecording, WatchRoot, WatchSnapshot, WatcherSnapshot, }; +const MAX_DISPATCH_BATCH_SIZE: usize = 256; + #[derive(Clone, Copy, Debug, PartialEq, Eq, serde::Serialize)] pub enum OsWatcherKind { Native, @@ -964,6 +966,7 @@ impl OsWatcher { let mut rescan_history = diagnostics::RescanHistory::default(); while let Ok(first) = event_rx.recv().await { dispatch_batch(kind, &state, &mut rescan_history, first, &event_rx); + smol::future::yield_now().await; } } }); @@ -1454,7 +1457,12 @@ fn dispatch_batch( // all dispatched; ordinary events still run. let mut rescan_dispatched = false; - for event in std::iter::once(first).chain(std::iter::from_fn(|| event_rx.try_recv().ok())) { + // The backend can keep producing events faster than we dispatch them, so + // don't wait for an empty queue before giving other tasks a turn. + for event in std::iter::once(first) + .chain(std::iter::from_fn(|| event_rx.try_recv().ok())) + .take(MAX_DISPATCH_BATCH_SIZE) + { if event .as_ref() .is_ok_and(|event| event.need_rescan() && event.paths.is_empty()) @@ -2255,6 +2263,43 @@ mod tests { ); } + #[test] + fn dispatch_batches_are_bounded_without_losing_or_reordering_events() { + let (watcher, fired) = recording_watcher(); + let (event_tx, event_rx) = async_channel::unbounded(); + let rescan = || notify::Event::new(EventKind::Other).set_flag(notify::event::Flag::Rescan); + for _ in 0..MAX_DISPATCH_BATCH_SIZE { + event_tx.try_send(Ok(rescan())).expect("enqueue rescan"); + } + let expected = (0..MAX_DISPATCH_BATCH_SIZE * 2 + 3) + .map(|index| if index % 2 == 0 { "/repo/a" } else { "/repo/b" }) + .collect::>(); + for path in &expected { + event_tx + .try_send(Ok(modify_event(&format!("{path}/file.txt")))) + .expect("enqueue event"); + } + + let first = event_rx.try_recv().expect("first rescan"); + watcher.dispatch_batch(first, &event_rx); + assert_eq!(fired.lock().len(), 3); + assert_eq!(event_rx.len(), expected.len()); + fired.lock().clear(); + + let first = event_rx.try_recv().expect("first event"); + watcher.dispatch_batch(first, &event_rx); + assert_eq!( + fired.lock().as_slice(), + &expected[..MAX_DISPATCH_BATCH_SIZE] + ); + assert_eq!(event_rx.len(), expected.len() - MAX_DISPATCH_BATCH_SIZE); + + while let Ok(first) = event_rx.try_recv() { + watcher.dispatch_batch(first, &event_rx); + } + assert_eq!(fired.lock().as_slice(), expected.as_slice()); + } + #[test] fn queued_rescans_are_coalesced_without_dropping_normal_events() { let (watcher, fired) = recording_watcher(); diff --git a/crates/fuzzy_nucleo/benches/match_benchmark.rs b/crates/fuzzy_nucleo/benches/match_benchmark.rs index da74af15f5a..c4ab2821d98 100644 --- a/crates/fuzzy_nucleo/benches/match_benchmark.rs +++ b/crates/fuzzy_nucleo/benches/match_benchmark.rs @@ -178,10 +178,11 @@ fn bench_string_matching(criterion: &mut Criterion) { foreground_executor.block_on(fuzzy_nucleo::match_strings_async( &candidates, query, - fuzzy_nucleo::Case::Ignore, - fuzzy_nucleo::LengthPenalty::On, - size, - &cancel, + fuzzy_nucleo::StringMatchOptions { + cancel_flag: Some(&cancel), + case: fuzzy_nucleo::Case::Ignore, + ..Default::default() + }, background_executor.clone(), )) }, @@ -304,8 +305,10 @@ fn bench_path_matching(criterion: &mut Criterion) { 0, None, query, - case, - size, + fuzzy_nucleo::PathMatchOptions { + case, + ..Default::default() + }, PathStyle::Unix, ) }, diff --git a/crates/fuzzy_nucleo/src/fuzzy_nucleo.rs b/crates/fuzzy_nucleo/src/fuzzy_nucleo.rs index 9080d102a2e..79cfe852d8e 100644 --- a/crates/fuzzy_nucleo/src/fuzzy_nucleo.rs +++ b/crates/fuzzy_nucleo/src/fuzzy_nucleo.rs @@ -2,16 +2,29 @@ mod matcher; mod paths; mod strings; +use std::{ + num::NonZeroUsize, + sync::atomic::{self, AtomicBool}, +}; + use fuzzy::CharBag; use nucleo::pattern::{AtomKind, CaseMatching, Normalization, Pattern}; pub use paths::{ - PathMatch, PathMatchCandidate, PathMatchCandidateSet, match_fixed_path_set, match_path_sets, + PathMatch, PathMatchCandidate, PathMatchCandidateSet, PathMatchOptions, match_fixed_path_set, + match_path_sets, +}; +pub use strings::{ + StringMatch, StringMatchCandidate, StringMatchOptions, match_strings, match_strings_async, }; -pub use strings::{StringMatch, StringMatchCandidate, match_strings, match_strings_async}; pub(crate) struct Cancelled; +#[inline] +pub(crate) fn is_cancelled(cancel_flag: Option<&AtomicBool>, ordering: atomic::Ordering) -> bool { + cancel_flag.is_some_and(|flag| flag.load(ordering)) +} + #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum Case { Smart, @@ -32,6 +45,29 @@ impl Case { } } +/// How many of the best matches to return. +#[derive(Copy, Clone, Debug, Default, PartialEq, Eq)] +pub enum MaxResults { + /// Every match. + #[default] + All, + /// At most this many. + Limit(NonZeroUsize), +} + +impl MaxResults { + pub const fn limit() -> Self { + Self::Limit(const { NonZeroUsize::new(LIMIT).expect("limit must be non-zero") }) + } + + pub(crate) fn resolve(self, candidate_count: usize) -> usize { + match self { + Self::All => candidate_count, + Self::Limit(limit) => limit.get().min(candidate_count), + } + } +} + #[derive(Copy, Clone, Debug, PartialEq, Eq)] pub enum LengthPenalty { On, diff --git a/crates/fuzzy_nucleo/src/paths.rs b/crates/fuzzy_nucleo/src/paths.rs index 46c88f797d4..71d8c702380 100644 --- a/crates/fuzzy_nucleo/src/paths.rs +++ b/crates/fuzzy_nucleo/src/paths.rs @@ -14,7 +14,10 @@ use nucleo::pattern::Pattern; use fuzzy::CharBag; use crate::matcher::{self, LENGTH_PENALTY}; -use crate::{Cancelled, Case, Query, case_penalty, count_case_mismatches, positions_from_sorted}; +use crate::{ + Cancelled, Case, MaxResults, Query, case_penalty, count_case_mismatches, is_cancelled, + positions_from_sorted, +}; #[derive(Clone, Debug)] pub struct PathMatchCandidate<'a> { @@ -42,6 +45,27 @@ impl<'a> PathMatchCandidate<'a> { } } +/// Options for [`match_fixed_path_set`] and [`match_path_sets`]. +#[derive(Copy, Clone, Debug)] +pub struct PathMatchOptions<'a> { + /// Defaults to all matches. Prefer a limit when matching whole worktrees. + pub max_results: MaxResults, + /// Return nothing if this gets set while matching. + pub cancel_flag: Option<&'a AtomicBool>, + /// Defaults to [`Case::Ignore`]. + pub case: Case, +} + +impl Default for PathMatchOptions<'_> { + fn default() -> Self { + Self { + max_results: MaxResults::All, + cancel_flag: None, + case: Case::Ignore, + } + } +} + #[derive(Clone, Debug)] pub struct PathMatch { pub score: f64, @@ -157,7 +181,7 @@ fn path_match_helper<'a>( root_is_file: bool, relative_to: &Option>, path_style: PathStyle, - cancel_flag: &AtomicBool, + cancel_flag: Option<&AtomicBool>, ) -> Result<(), Cancelled> { let mut candidate_buf = if !path_prefix.is_empty() && !root_is_file { let mut s = path_prefix.display(path_style).to_string(); @@ -173,7 +197,7 @@ fn path_match_helper<'a>( for candidate in candidates { buf.clear(); matched_chars.clear(); - if cancel_flag.load(atomic::Ordering::Relaxed) { + if is_cancelled(cancel_flag, atomic::Ordering::Relaxed) { return Err(Cancelled); } @@ -240,10 +264,14 @@ pub fn match_fixed_path_set( worktree_id: usize, worktree_root_name: Option>, query: &str, - case: Case, - max_results: usize, + options: PathMatchOptions<'_>, path_style: PathStyle, ) -> Vec { + let PathMatchOptions { + max_results, + cancel_flag, + case, + } = options; let Some(query) = Query::build(query, case) else { return Vec::new(); }; @@ -252,13 +280,14 @@ pub fn match_fixed_path_set( config.set_match_paths(); let mut matcher = matcher::get_matcher(config); + let max_results = max_results.resolve(candidates.len()); let root_is_file = worktree_root_name.is_some() && candidates.iter().all(|c| c.path.is_empty()); let path_prefix = worktree_root_name.unwrap_or_else(|| RelPath::empty_arc()); let mut results = Vec::new(); - path_match_helper( + let outcome = path_match_helper( &mut matcher, &query, candidates.into_iter(), @@ -268,11 +297,13 @@ pub fn match_fixed_path_set( root_is_file, &None, path_style, - &AtomicBool::new(false), - ) - .ok(); - gpui_util::truncate_to_bottom_n_sorted_by(&mut results, max_results, &|a, b| b.cmp(a)); + cancel_flag, + ); matcher::return_matcher(matcher); + if outcome.is_err() || is_cancelled(cancel_flag, atomic::Ordering::Acquire) { + return Vec::new(); + } + gpui_util::truncate_to_bottom_n_sorted_by(&mut results, max_results, &|a, b| b.cmp(a)); results } @@ -280,11 +311,14 @@ pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>( candidate_sets: &'a [Set], query: &str, relative_to: &Option>, - case: Case, - max_results: usize, - cancel_flag: &AtomicBool, + options: PathMatchOptions<'_>, executor: BackgroundExecutor, ) -> Vec { + let PathMatchOptions { + max_results, + cancel_flag, + case, + } = options; let path_count: usize = candidate_sets.iter().map(|s| s.len()).sum(); if path_count == 0 { return Vec::new(); @@ -302,10 +336,11 @@ pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>( return Vec::new(); }; + let max_results = max_results.resolve(path_count); let num_cpus = executor.num_cpus().min(path_count); let segment_size = path_count.div_ceil(num_cpus); let mut segment_results = (0..num_cpus) - .map(|_| Vec::with_capacity(max_results)) + .map(|_| Vec::with_capacity(max_results.min(segment_size))) .collect::>(); let mut config = nucleo::Config::DEFAULT; config.set_match_paths(); @@ -361,7 +396,7 @@ pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>( .await; matcher::return_matchers(matchers); - if cancel_flag.load(atomic::Ordering::Acquire) { + if is_cancelled(cancel_flag, atomic::Ordering::Acquire) { return Vec::new(); } @@ -369,3 +404,111 @@ pub async fn match_path_sets<'a, Set: PathMatchCandidateSet<'a>>( gpui_util::truncate_to_bottom_n_sorted_by(&mut results, max_results, &|a, b| b.cmp(a)); results } + +#[cfg(test)] +mod tests { + use super::*; + + struct TestCandidateSet { + candidates: Vec>, + } + + impl<'a> PathMatchCandidateSet<'a> for TestCandidateSet { + type Candidates = std::iter::Cloned>>; + + fn id(&self) -> usize { + 0 + } + + fn len(&self) -> usize { + self.candidates.len() + } + + fn root_is_file(&self) -> bool { + false + } + + fn prefix(&self) -> Arc { + RelPath::empty_arc() + } + + fn candidates(&'a self, start: usize) -> Self::Candidates { + self.candidates + .get(start..) + .unwrap_or_default() + .iter() + .cloned() + } + + fn path_style(&self) -> PathStyle { + PathStyle::Unix + } + } + + fn candidates(paths: &[&'static str]) -> Vec> { + paths + .iter() + .map(|&path| { + PathMatchCandidate::new(RelPath::from_unix_str(path).unwrap(), false, None) + }) + .collect() + } + + #[test] + fn test_fixed_path_set_cancellation() { + let paths = ["src/main.rs", "src/lib.rs"]; + let uncancelled = match_fixed_path_set( + candidates(&paths), + 0, + None, + "main", + Default::default(), + PathStyle::Unix, + ); + assert_eq!(uncancelled.len(), 1); + + let cancel = AtomicBool::new(true); + let cancelled = match_fixed_path_set( + candidates(&paths), + 0, + None, + "main", + PathMatchOptions { + cancel_flag: Some(&cancel), + ..Default::default() + }, + PathStyle::Unix, + ); + assert!(cancelled.is_empty()); + } + + #[gpui::test] + async fn test_path_sets_cancellation(executor: BackgroundExecutor) { + let candidate_sets = [TestCandidateSet { + candidates: candidates(&["src/main.rs", "src/lib.rs"]), + }]; + let uncancelled = match_path_sets( + &candidate_sets, + "main", + &None, + Default::default(), + executor.clone(), + ) + .await; + assert_eq!(uncancelled.len(), 1); + + let cancel = AtomicBool::new(true); + let cancelled = match_path_sets( + &candidate_sets, + "main", + &None, + PathMatchOptions { + cancel_flag: Some(&cancel), + ..Default::default() + }, + executor, + ) + .await; + assert!(cancelled.is_empty()); + } +} diff --git a/crates/fuzzy_nucleo/src/strings.rs b/crates/fuzzy_nucleo/src/strings.rs index 2486afb7ce0..99f1b6d5f0e 100644 --- a/crates/fuzzy_nucleo/src/strings.rs +++ b/crates/fuzzy_nucleo/src/strings.rs @@ -10,7 +10,8 @@ use gpui::{BackgroundExecutor, SharedString}; use nucleo::Utf32Str; use crate::{ - Cancelled, Case, LengthPenalty, Query, case_penalty, count_case_mismatches, + Cancelled, Case, LengthPenalty, MaxResults, Query, case_penalty, count_case_mismatches, + is_cancelled, matcher::{self, LENGTH_PENALTY}, positions_from_sorted, }; @@ -97,21 +98,49 @@ impl Ord for StringMatch { } } +/// Options for [`match_strings`] and [`match_strings_async`]. +#[derive(Copy, Clone, Debug)] +pub struct StringMatchOptions<'a> { + /// Defaults to all matches. + pub max_results: MaxResults, + /// Return nothing if this gets set while matching. Empty queries ignore it. + pub cancel_flag: Option<&'a AtomicBool>, + /// Defaults to [`Case::Smart`]. + pub case: Case, + /// Defaults to [`LengthPenalty::On`]. + pub length_penalty: LengthPenalty, +} + +impl Default for StringMatchOptions<'_> { + fn default() -> Self { + Self { + max_results: MaxResults::All, + cancel_flag: None, + case: Case::Smart, + length_penalty: LengthPenalty::On, + } + } +} + pub async fn match_strings_async( candidates: &[T], query: &str, - case: Case, - length_penalty: LengthPenalty, - max_results: usize, - cancel_flag: &AtomicBool, + options: StringMatchOptions<'_>, executor: BackgroundExecutor, ) -> Vec where T: Borrow + Sync, { - if candidates.is_empty() || max_results == 0 { + let StringMatchOptions { + max_results, + cancel_flag, + case, + length_penalty, + } = options; + if candidates.is_empty() { return Vec::new(); } + let max_results = max_results.resolve(candidates.len()); let Some(query) = Query::build(query, case) else { return empty_query_results(candidates, max_results); @@ -120,8 +149,9 @@ where let num_cpus = executor.num_cpus().min(candidates.len()); let base_size = candidates.len() / num_cpus; let remainder = candidates.len() % num_cpus; + let segment_capacity = max_results.min(candidates.len().div_ceil(num_cpus)); let mut segment_results = (0..num_cpus) - .map(|_| Vec::with_capacity(max_results.min(candidates.len()))) + .map(|_| Vec::with_capacity(segment_capacity)) .collect::>(); let config = nucleo::Config::DEFAULT; @@ -156,7 +186,7 @@ where matcher::return_matchers(matchers); - if cancel_flag.load(atomic::Ordering::Acquire) { + if is_cancelled(cancel_flag, atomic::Ordering::Acquire) { return Vec::new(); } @@ -168,16 +198,21 @@ where pub fn match_strings( candidates: &[T], query: &str, - case: Case, - length_penalty: LengthPenalty, - max_results: usize, + options: StringMatchOptions<'_>, ) -> Vec where T: Borrow, { - if candidates.is_empty() || max_results == 0 { + let StringMatchOptions { + max_results, + cancel_flag, + case, + length_penalty, + } = options; + if candidates.is_empty() { return Vec::new(); } + let max_results = max_results.resolve(candidates.len()); let Some(query) = Query::build(query, case) else { return empty_query_results(candidates, max_results); @@ -185,19 +220,21 @@ where let config = nucleo::Config::DEFAULT; let mut matcher = matcher::get_matcher(config); - let mut results = Vec::with_capacity(max_results.min(candidates.len())); + let mut results = Vec::with_capacity(max_results); - match_string_helper( + let outcome = match_string_helper( candidates, &query, &mut matcher, length_penalty, &mut results, - &AtomicBool::new(false), - ) - .ok(); + cancel_flag, + ); matcher::return_matcher(matcher); + if outcome.is_err() || is_cancelled(cancel_flag, atomic::Ordering::Acquire) { + return Vec::new(); + } gpui_util::truncate_to_bottom_n_sorted_by(&mut results, max_results, &|a, b| b.cmp(a)); results } @@ -227,7 +264,7 @@ fn match_string_helper( matcher: &mut nucleo::Matcher, length_penalty: LengthPenalty, results: &mut Vec, - cancel_flag: &AtomicBool, + cancel_flag: Option<&AtomicBool>, ) -> Result<(), Cancelled> where T: Borrow, @@ -239,7 +276,7 @@ where for candidate in candidates { buf.clear(); matched_chars.clear(); - if cancel_flag.load(atomic::Ordering::Relaxed) { + if is_cancelled(cancel_flag, atomic::Ordering::Relaxed) { return Err(Cancelled); } @@ -294,6 +331,15 @@ mod tests { use super::*; use gpui::BackgroundExecutor; + fn options() -> StringMatchOptions<'static> { + StringMatchOptions { + max_results: MaxResults::All, + cancel_flag: None, + case: Case::Ignore, + length_penalty: LengthPenalty::Off, + } + } + fn candidates(strings: &[&str]) -> Vec { strings .iter() @@ -305,17 +351,7 @@ mod tests { #[gpui::test] async fn test_basic_match(executor: BackgroundExecutor) { let cs = candidates(&["hello", "world", "help"]); - let cancel = AtomicBool::new(false); - let results = match_strings_async( - &cs, - "hel", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor, - ) - .await; + let results = match_strings_async(&cs, "hel", options(), executor).await; let matched: Vec<&str> = results.iter().map(|m| m.string.as_ref()).collect(); assert!(matched.contains(&"hello")); assert!(matched.contains(&"help")); @@ -329,17 +365,7 @@ mod tests { "src/bin/main.rs", "tests/parser_test.rs", ]); - let cancel = AtomicBool::new(false); - let results = match_strings_async( - &cs, - "src parser", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor, - ) - .await; + let results = match_strings_async(&cs, "src parser", options(), executor).await; assert_eq!(results.len(), 1); assert_eq!(results[0].string, "src/lib/parser.rs"); } @@ -347,17 +373,7 @@ mod tests { #[gpui::test] async fn test_empty_query_returns_all(executor: BackgroundExecutor) { let cs = candidates(&["alpha", "beta", "gamma"]); - let cancel = AtomicBool::new(false); - let results = match_strings_async( - &cs, - "", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor, - ) - .await; + let results = match_strings_async(&cs, "", options(), executor).await; assert_eq!(results.len(), 3); assert!(results.iter().all(|m| m.score == 0.0)); } @@ -365,34 +381,14 @@ mod tests { #[gpui::test] async fn test_whitespace_only_query_returns_all(executor: BackgroundExecutor) { let cs = candidates(&["alpha", "beta", "gamma"]); - let cancel = AtomicBool::new(false); - let results = match_strings_async( - &cs, - " \t\n", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor, - ) - .await; + let results = match_strings_async(&cs, " \t\n", options(), executor).await; assert_eq!(results.len(), 3); } #[gpui::test] async fn test_empty_candidates(executor: BackgroundExecutor) { let cs: Vec = vec![]; - let cancel = AtomicBool::new(false); - let results = match_strings_async( - &cs, - "query", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor, - ) - .await; + let results = match_strings_async(&cs, "query", options(), executor).await; assert!(results.is_empty()); } @@ -403,10 +399,10 @@ mod tests { let results = match_strings_async( &cs, "hel", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, + StringMatchOptions { + cancel_flag: Some(&cancel), + ..options() + }, executor, ) .await; @@ -416,14 +412,13 @@ mod tests { #[gpui::test] async fn test_max_results_limit(executor: BackgroundExecutor) { let cs = candidates(&["ab", "abc", "abcd", "abcde"]); - let cancel = AtomicBool::new(false); let results = match_strings_async( &cs, "ab", - Case::Ignore, - LengthPenalty::Off, - 2, - &cancel, + StringMatchOptions { + max_results: MaxResults::limit::<2>(), + ..options() + }, executor, ) .await; @@ -437,17 +432,7 @@ mod tests { "fuzzy", "a_fuzzy_thing", ]); - let cancel = AtomicBool::new(false); - let results = match_strings_async( - &cs, - "fuzzy", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor.clone(), - ) - .await; + let results = match_strings_async(&cs, "fuzzy", options(), executor.clone()).await; let ordered = matches!( ( @@ -466,10 +451,10 @@ mod tests { let results_penalty = match_strings_async( &cs, "fuzzy", - Case::Ignore, - LengthPenalty::On, - 10, - &cancel, + StringMatchOptions { + length_penalty: LengthPenalty::On, + ..options() + }, executor, ) .await; @@ -480,17 +465,7 @@ mod tests { #[gpui::test] async fn test_utf8_positions(executor: BackgroundExecutor) { let cs = candidates(&["café"]); - let cancel = AtomicBool::new(false); - let results = match_strings_async( - &cs, - "caf", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor, - ) - .await; + let results = match_strings_async(&cs, "caf", options(), executor).await; assert_eq!(results.len(), 1); let m = &results[0]; assert_eq!(m.positions, vec![0, 1, 2]); @@ -502,27 +477,18 @@ mod tests { #[gpui::test] async fn test_smart_case(executor: BackgroundExecutor) { let cs = candidates(&["FooBar", "foobar", "FOOBAR"]); - let cancel = AtomicBool::new(false); - let case_insensitive = match_strings_async( - &cs, - "foobar", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor.clone(), - ) - .await; + let case_insensitive = + match_strings_async(&cs, "foobar", options(), executor.clone()).await; assert_eq!(case_insensitive.len(), 3); let smart = match_strings_async( &cs, "FooBar", - Case::Smart, - LengthPenalty::Off, - 10, - &cancel, + StringMatchOptions { + case: Case::Smart, + ..options() + }, executor, ) .await; @@ -545,14 +511,14 @@ mod tests { "aaaaaaaaaaaaaaaaaaaaaaaaaaaa_FooBar", "aaaaaaaaaaaaaaaaaaaaaaaaaaaa_foobar", ]); - let cancel = AtomicBool::new(false); let results = match_strings_async( &cs, "FooBar", - Case::Smart, - LengthPenalty::On, - 10, - &cancel, + StringMatchOptions { + case: Case::Smart, + length_penalty: LengthPenalty::On, + ..options() + }, executor, ) .await; @@ -575,17 +541,7 @@ mod tests { #[gpui::test] async fn test_char_bag_prefilter(executor: BackgroundExecutor) { let cs = candidates(&["abcdef", "abc", "def", "aabbcc"]); - let cancel = AtomicBool::new(false); - let results = match_strings_async( - &cs, - "abc", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor, - ) - .await; + let results = match_strings_async(&cs, "abc", options(), executor).await; let matched: Vec<&str> = results.iter().map(|m| m.string.as_ref()).collect(); assert!(matched.contains(&"abcdef")); assert!(matched.contains(&"abc")); @@ -596,7 +552,7 @@ mod tests { #[test] fn test_sync_basic_match() { let cs = candidates(&["hello", "world", "help"]); - let results = match_strings(&cs, "hel", Case::Ignore, LengthPenalty::Off, 10); + let results = match_strings(&cs, "hel", options()); let matched: Vec<&str> = results.iter().map(|m| m.string.as_ref()).collect(); assert!(matched.contains(&"hello")); assert!(matched.contains(&"help")); @@ -606,35 +562,86 @@ mod tests { #[test] fn test_sync_empty_query_returns_all() { let cs = candidates(&["alpha", "beta", "gamma"]); - let results = match_strings(&cs, "", Case::Ignore, LengthPenalty::Off, 10); + let results = match_strings(&cs, "", options()); assert_eq!(results.len(), 3); } #[test] fn test_sync_whitespace_only_query_returns_all() { let cs = candidates(&["alpha", "beta", "gamma"]); - let results = match_strings(&cs, " ", Case::Ignore, LengthPenalty::Off, 10); + let results = match_strings(&cs, " ", options()); assert_eq!(results.len(), 3); } #[test] fn test_sync_max_results() { let cs = candidates(&["ab", "abc", "abcd", "abcde"]); - let results = match_strings(&cs, "ab", Case::Ignore, LengthPenalty::Off, 2); + let results = match_strings( + &cs, + "ab", + StringMatchOptions { + max_results: MaxResults::limit::<2>(), + ..options() + }, + ); assert_eq!(results.len(), 2); } + #[test] + fn test_sync_cancellation() { + let cs = candidates(&["hello", "world"]); + let cancel = AtomicBool::new(true); + let results = match_strings( + &cs, + "hel", + StringMatchOptions { + cancel_flag: Some(&cancel), + ..options() + }, + ); + assert!(results.is_empty()); + } + + #[test] + fn test_sync_cancellation_during_last_candidate() { + struct CancellingCandidate<'a> { + candidate: StringMatchCandidate, + cancel: &'a AtomicBool, + } + + impl Borrow for CancellingCandidate<'_> { + fn borrow(&self) -> &StringMatchCandidate { + self.cancel.store(true, atomic::Ordering::Release); + &self.candidate + } + } + + let cancel = AtomicBool::new(false); + let cs = [CancellingCandidate { + candidate: StringMatchCandidate::new(0, "hello"), + cancel: &cancel, + }]; + let results = match_strings( + &cs, + "hel", + StringMatchOptions { + cancel_flag: Some(&cancel), + ..options() + }, + ); + assert!(results.is_empty()); + } + #[gpui::test] async fn test_empty_query_respects_max_results(executor: BackgroundExecutor) { let cs = candidates(&["alpha", "beta", "gamma", "delta"]); - let cancel = AtomicBool::new(false); let results = match_strings_async( &cs, "", - Case::Ignore, - LengthPenalty::Off, - 2, - &cancel, + StringMatchOptions { + max_results: MaxResults::limit::<2>(), + ..options() + }, executor, ) .await; @@ -644,17 +651,7 @@ mod tests { #[gpui::test] async fn test_multi_word_with_nonmatching_word(executor: BackgroundExecutor) { let cs = candidates(&["src/parser.rs", "src/main.rs"]); - let cancel = AtomicBool::new(false); - let results = match_strings_async( - &cs, - "src xyzzy", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor, - ) - .await; + let results = match_strings_async(&cs, "src xyzzy", options(), executor).await; assert!( results.is_empty(), "no candidate contains 'xyzzy', so nothing should match" @@ -665,17 +662,7 @@ mod tests { async fn test_segment_size_not_divisible_by_cpus(executor: BackgroundExecutor) { executor.set_num_cpus(4); let cs = candidates(&["alpha", "beta", "gamma", "delta", "epsilon"]); - let cancel = AtomicBool::new(false); - let results = match_strings_async( - &cs, - "a", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor, - ) - .await; + let results = match_strings_async(&cs, "a", options(), executor).await; let matched: Vec<&str> = results.iter().map(|m| m.string.as_ref()).collect(); assert!(matched.contains(&"alpha")); assert!(matched.contains(&"gamma")); @@ -686,17 +673,7 @@ mod tests { async fn test_segment_size_with_many_cpus_few_candidates(executor: BackgroundExecutor) { executor.set_num_cpus(16); let cs = candidates(&["one", "two", "three"]); - let cancel = AtomicBool::new(false); - let results = match_strings_async( - &cs, - "o", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor, - ) - .await; + let results = match_strings_async(&cs, "o", options(), executor).await; let matched: Vec<&str> = results.iter().map(|m| m.string.as_ref()).collect(); assert!(matched.contains(&"one")); assert!(matched.contains(&"two")); @@ -706,17 +683,7 @@ mod tests { async fn test_segment_size_single_candidate(executor: BackgroundExecutor) { executor.set_num_cpus(8); let cs = candidates(&["lonely"]); - let cancel = AtomicBool::new(false); - let results = match_strings_async( - &cs, - "lone", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor, - ) - .await; + let results = match_strings_async(&cs, "lone", options(), executor).await; assert_eq!(results.len(), 1); assert_eq!(results[0].string.as_ref(), "lonely"); } @@ -725,17 +692,7 @@ mod tests { async fn test_segment_size_candidates_equal_cpus(executor: BackgroundExecutor) { executor.set_num_cpus(4); let cs = candidates(&["aaa", "bbb", "ccc", "ddd"]); - let cancel = AtomicBool::new(false); - let results = match_strings_async( - &cs, - "a", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor, - ) - .await; + let results = match_strings_async(&cs, "a", options(), executor).await; assert_eq!(results.len(), 1); assert_eq!(results[0].string.as_ref(), "aaa"); } @@ -744,17 +701,7 @@ mod tests { async fn test_segment_size_candidates_one_more_than_cpus(executor: BackgroundExecutor) { executor.set_num_cpus(3); let cs = candidates(&["ant", "ape", "dog", "axe"]); - let cancel = AtomicBool::new(false); - let results = match_strings_async( - &cs, - "a", - Case::Ignore, - LengthPenalty::Off, - 10, - &cancel, - executor, - ) - .await; + let results = match_strings_async(&cs, "a", options(), executor).await; let matched: Vec<&str> = results.iter().map(|m| m.string.as_ref()).collect(); assert!(matched.contains(&"ant")); assert!(matched.contains(&"ape")); diff --git a/crates/git/src/git.rs b/crates/git/src/git.rs index 6749bbf0101..d12f0011aeb 100644 --- a/crates/git/src/git.rs +++ b/crates/git/src/git.rs @@ -162,6 +162,11 @@ pub struct RenameBranch { pub branch: Option, } +/// Trim. Then replace ` ` with `-`. +pub fn normalize_branch_name(query: &str) -> String { + query.trim().replace(' ', "-") +} + /// Restores a file to its last committed state, discarding local changes. #[derive(Clone, Debug, Default, PartialEq, Deserialize, JsonSchema, Action)] #[action(namespace = git, deprecated_aliases = ["editor::RevertFile"])] @@ -376,6 +381,13 @@ impl From for usize { mod tests { use super::*; + #[test] + fn test_normalize_branch_name() { + assert_eq!(normalize_branch_name(" branch-name "), "branch-name"); + assert_eq!(normalize_branch_name("branch name"), "branch-name"); + assert_eq!(normalize_branch_name(" branch name "), "branch--name"); + } + #[test] fn parses_short_sha1_oid_by_padding_trailing_nibbles() { let oid = "abc1234".parse::().expect("failed to parse oid"); diff --git a/crates/git/src/status.rs b/crates/git/src/status.rs index 7a993686011..31863a4b190 100644 --- a/crates/git/src/status.rs +++ b/crates/git/src/status.rs @@ -118,8 +118,8 @@ impl FileStatus { } .into(), [b'D', b'D'] => UnmergedStatus { - first_head: UnmergedStatusCode::Added, - second_head: UnmergedStatusCode::Added, + first_head: UnmergedStatusCode::Deleted, + second_head: UnmergedStatusCode::Deleted, } .into(), [x, b'U'] => UnmergedStatus { @@ -620,7 +620,9 @@ mod tests { use crate::{ repository::RepoPath, - status::{FileStatus, GitStatus, TreeDiff, TreeDiffStatus}, + status::{ + FileStatus, GitStatus, TreeDiff, TreeDiffStatus, UnmergedStatus, UnmergedStatusCode, + }, }; use super::{DiffStat, parse_numstat}; @@ -716,6 +718,34 @@ mod tests { ); } + #[test] + fn test_parse_unmerged_status_codes() { + use UnmergedStatusCode::{Added, Deleted, Updated}; + + let cases = [ + ("DD", Deleted, Deleted), + ("AU", Added, Updated), + ("UD", Updated, Deleted), + ("UA", Updated, Added), + ("DU", Deleted, Updated), + ("AA", Added, Added), + ("UU", Updated, Updated), + ]; + + for (code, first_head, second_head) in cases { + let status: GitStatus = format!("{code} conflicted.txt\0").parse().unwrap(); + assert_eq!(status.entries.len(), 1, "{code}"); + assert_eq!( + status.entries[0].1, + FileStatus::Unmerged(UnmergedStatus { + first_head, + second_head, + }), + "{code}" + ); + } + } + #[test] fn test_duplicate_untracked_entries() { // Regression test for ZED-2XA: git can produce duplicate untracked entries diff --git a/crates/git_ui/src/branch_picker.rs b/crates/git_ui/src/branch_picker.rs index 832e672300d..0780f9deefa 100644 --- a/crates/git_ui/src/branch_picker.rs +++ b/crates/git_ui/src/branch_picker.rs @@ -1,15 +1,14 @@ -use anyhow::Context as _; use editor::Editor; use fuzzy_nucleo::StringMatchCandidate; use collections::{HashMap, HashSet}; use git::repository::{Branch, delete_branch_flag}; -use git::{GitHostingProviderRegistry, parse_git_remote_url}; +use git::{GitHostingProviderRegistry, normalize_branch_name, parse_git_remote_url}; use gpui::http_client::Url; use gpui::{ Action, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, Global, InteractiveElement, IntoElement, Modifiers, ModifiersChangedEvent, ParentElement, PromptLevel, - Render, SharedString, Styled, Subscription, Task, TaskExt, WeakEntity, Window, actions, rems, + Render, SharedString, Styled, Subscription, Task, WeakEntity, Window, actions, rems, }; use picker::{Picker, PickerDelegate, PickerEditorPosition}; use project::git_store::{Repository, RepositoryEvent}; @@ -23,7 +22,7 @@ use ui::{ ListItemSpacing, ListSubHeader, PopoverMenu, PopoverMenuHandle, Severity, Tooltip, prelude::*, }; use ui_input::ErasedEditor; -use util::ResultExt; +use util::{ResultExt, maybe}; use workspace::notifications::DetachAndPromptErr; use workspace::{ModalView, Workspace}; @@ -211,6 +210,8 @@ pub struct BranchList { pub picker: Entity>, picker_focus_handle: FocusHandle, _subscriptions: Vec, + _load_default_branch: Option>, + _load_remote_provider_icons: Option>, embedded: bool, } @@ -369,45 +370,46 @@ impl BranchList { )); } - // Fetch default branch asynchronously since it requires a git operation - cx.spawn_in(window, async move |this, cx| { - let default_branch = default_branch_request - .context("No active repository")? + let load_default_branch = default_branch_request.map(|default_branch_request| { + cx.spawn(async move |this, cx| { + let default_branch = default_branch_request + .await + .ok() + .and_then(Result::ok) + .flatten(); + this.update(cx, |this, cx| { + this.picker.update(cx, |picker, _| { + picker.delegate.default_branch = default_branch; + }); + }) + .log_err(); + }) + }); + + let load_remote_provider_icons = remote_urls_request.map(|remote_urls_request| { + cx.spawn(async move |this, cx| { + maybe!(async move { + let remote_urls = remote_urls_request.await??; + let remote_provider_icons = + cx.update(|cx| remote_provider_icons(&remote_urls, cx)); + this.update(cx, |this, cx| { + this.picker.update(cx, |picker, cx| { + picker.delegate.remote_provider_icons = remote_provider_icons; + cx.notify(); + }); + }) + }) .await - .map(Result::ok) - .ok() - .flatten() - .flatten(); - - let _ = this.update_in(cx, |this, _window, cx| { - this.picker.update(cx, |picker, _cx| { - picker.delegate.default_branch = default_branch; - }); - }); - - anyhow::Ok(()) - }) - .detach_and_log_err(cx); - - cx.spawn(async move |this, cx| { - let remote_urls = remote_urls_request - .context("No active repository")? - .await??; - let remote_provider_icons = cx.update(|cx| remote_provider_icons(&remote_urls, cx)); - this.update(cx, |this, cx| { - this.picker.update(cx, |picker, cx| { - picker.delegate.remote_provider_icons = remote_provider_icons; - cx.notify(); - }); - })?; - anyhow::Ok(()) - }) - .detach_and_log_err(cx); + .log_err(); + }) + }); Self { picker, picker_focus_handle, _subscriptions: subscriptions, + _load_default_branch: load_default_branch, + _load_remote_provider_icons: load_remote_provider_icons, embedded, } } @@ -946,13 +948,6 @@ fn branch_matches_ref(branch: &Branch, branch_ref: &SharedString) -> bool { branch.ref_name.as_ref() == branch_ref.as_ref() || branch.name() == branch_ref.as_ref() } -// Git branch names can't contain whitespace, so we replace spaces with dashes, -// but we need to first trim because a branch name can't start or end with a -// dash. -fn normalize_branch_name(query: &str) -> String { - query.trim().replace(' ', "-") -} - fn branch_remote_name(branch: &Branch) -> Option<&str> { branch.remote_name().or_else(|| { branch @@ -1497,10 +1492,10 @@ impl PickerDelegate for BranchListDelegate { let mut matches: Vec = fuzzy_nucleo::match_strings_async( &candidates, &query, - fuzzy_nucleo::Case::Smart, - fuzzy_nucleo::LengthPenalty::On, - 10000, - &Default::default(), + fuzzy_nucleo::StringMatchOptions { + max_results: fuzzy_nucleo::MaxResults::limit::<10_000>(), + ..Default::default() + }, cx.background_executor().clone(), ) .await @@ -2390,6 +2385,8 @@ mod tests { picker, picker_focus_handle, _subscriptions: vec![_subscription], + _load_default_branch: None, + _load_remote_provider_icons: None, embedded: false, } }) @@ -3285,13 +3282,6 @@ mod tests { ); } - #[test] - fn test_normalize_branch_name() { - assert_eq!(normalize_branch_name(" branch-name "), "branch-name"); - assert_eq!(normalize_branch_name("branch name"), "branch-name"); - assert_eq!(normalize_branch_name(" branch name "), "branch--name"); - } - #[gpui::test] async fn test_remote_url_detection_https(cx: &mut TestAppContext) { init_test(cx); diff --git a/crates/git_ui/src/git_graph.rs b/crates/git_ui/src/git_graph.rs index a0950056c9d..5615de90d64 100644 --- a/crates/git_ui/src/git_graph.rs +++ b/crates/git_ui/src/git_graph.rs @@ -3631,7 +3631,7 @@ impl GitGraph { move |bounds: Bounds, _: (), window: &mut Window, cx: &mut App| { graph_canvas_bounds.set(Some(bounds)); - window.paint_layer(bounds, |window| { + window.paint_layer(|window| { let theme = cx.theme(); let accent_colors = theme.accents(); let background = theme.colors().editor_background; @@ -3670,6 +3670,48 @@ impl GitGraph { } } + // Commit nodes are painted before the lines, which are drawn + // over the nodes' halos to meet their rings. + for (row_idx, row) in rows.into_iter().enumerate() { + let absolute_row_idx = first_visible_row + row_idx; + let row_color = accent_colors.color_for_index(row.color_idx as u32); + let row_y_center = + bounds.origin.y + row_idx as f32 * row_height + row_height / 2.0 + - vertical_scroll_offset; + + let commit_x = lane_center_x(bounds, row.lane as f32); + + if paint_ref_connectors && !row.data.ref_names.is_empty() { + paint_dashed_connector( + bounds.origin.x, + commit_x - COMMIT_CIRCLE_RADIUS, + row_y_center, + row_color.opacity(0.5), + window, + ); + } + + // Match the node halo to the row's effective background so + // the ring blends seamlessly on hovered/selected rows. + let node_background = if selected_entry_idx == Some(absolute_row_idx) + || context_menu_target_index == Some(absolute_row_idx) + { + background.blend(selected_bg) + } else if hovered_entry_idx == Some(absolute_row_idx) { + background.blend(hover_bg) + } else { + background + }; + + draw_commit_circle( + commit_x, + row_y_center, + row_color, + node_background, + window, + ); + } + for line in commit_lines { let Some((start_segment_idx, start_column)) = line.get_first_visible_segment_idx(first_visible_row) @@ -3825,56 +3867,10 @@ impl GitGraph { for builder in builders { if let Ok(path) = builder.build() { - // we paint each color on it's own layer to stop overlapping lines - // of different colors changing the color of a line - window.paint_layer(bounds, |window| { - window.paint_path(path, line_color); - }); + window.paint_path(path, line_color); } } } - - // Commit nodes are painted last so they sit on top of the - // connector lines, keeping each commit a clear, distinct point. - for (row_idx, row) in rows.into_iter().enumerate() { - let absolute_row_idx = first_visible_row + row_idx; - let row_color = accent_colors.color_for_index(row.color_idx as u32); - let row_y_center = - bounds.origin.y + row_idx as f32 * row_height + row_height / 2.0 - - vertical_scroll_offset; - - let commit_x = lane_center_x(bounds, row.lane as f32); - - if paint_ref_connectors && !row.data.ref_names.is_empty() { - paint_dashed_connector( - bounds.origin.x, - commit_x - COMMIT_CIRCLE_RADIUS, - row_y_center, - row_color.opacity(0.5), - window, - ); - } - - // Match the node halo to the row's effective background so - // the ring blends seamlessly on hovered/selected rows. - let node_background = if selected_entry_idx == Some(absolute_row_idx) - || context_menu_target_index == Some(absolute_row_idx) - { - background.blend(selected_bg) - } else if hovered_entry_idx == Some(absolute_row_idx) { - background.blend(hover_bg) - } else { - background - }; - - draw_commit_circle( - commit_x, - row_y_center, - row_color, - node_background, - window, - ); - } }) }, ) diff --git a/crates/git_ui/src/git_panel.rs b/crates/git_ui/src/git_panel.rs index d00f20dcf64..84471ce3214 100644 --- a/crates/git_ui/src/git_panel.rs +++ b/crates/git_ui/src/git_panel.rs @@ -1278,6 +1278,26 @@ struct GitPanelContextMenu { _subscription: Subscription, } +/// The label for `repository`, disambiguated against every other repository in +/// the project. +fn repository_display_name( + repository: Option<&Entity>, + project: &Entity, + cx: &App, +) -> SharedString { + let Some(repository) = repository else { + return SharedString::default(); + }; + let id = repository.read(cx).id; + project + .read(cx) + .git_store() + .read(cx) + .display_names(cx) + .remove(&id) + .unwrap_or_else(|| repository.read(cx).display_name()) +} + pub struct GitPanel { pub(crate) active_repository: Option>, pub(crate) commit_editor: Entity, @@ -7312,12 +7332,7 @@ impl GitPanel { let head_commit = active_repository.read(cx).head_commit.clone(); let git_panel = cx.entity(); - let display_name = SharedString::from(Arc::from( - active_repository - .read(cx) - .display_name() - .trim_end_matches("/"), - )); + let display_name = repository_display_name(Some(&active_repository), &self.project, cx); let editor_is_long = self.commit_editor.update(cx, |editor, cx| { editor.max_point(cx).row().0 >= MAX_PANEL_EDITOR_LINES as u32 }); diff --git a/crates/git_ui/src/git_ui.rs b/crates/git_ui/src/git_ui.rs index f0b8469028a..b6cfa80bd34 100644 --- a/crates/git_ui/src/git_ui.rs +++ b/crates/git_ui/src/git_ui.rs @@ -8,7 +8,7 @@ mod blame_ui; pub mod clone; use git::{ - Oid, + Oid, normalize_branch_name, repository::{Branch, CommitDetails, Upstream, UpstreamTracking, UpstreamTrackingStatus}, status::{FileStatus, StatusCode, UnmergedStatus, UnmergedStatusCode}, }; @@ -453,6 +453,7 @@ struct RenameBranchModal { current_branch: SharedString, editor: Entity, repo: Entity, + _editor_subscription: Subscription, } impl RenameBranchModal { @@ -467,10 +468,16 @@ impl RenameBranchModal { editor.set_text(current_branch.clone(), window, cx); editor }); + let editor_subscription = cx.subscribe(&editor, |_, _, event, cx| { + if let editor::EditorEvent::BufferEdited = event { + cx.notify(); + } + }); Self { current_branch: current_branch.into(), editor, repo, + _editor_subscription: editor_subscription, } } @@ -479,7 +486,7 @@ impl RenameBranchModal { } fn confirm(&mut self, _: &Confirm, window: &mut Window, cx: &mut Context) { - let new_name = self.editor.read(cx).text(cx); + let new_name = normalize_branch_name(&self.editor.read(cx).text(cx)); if new_name.is_empty() || new_name == self.current_branch.as_ref() { cx.emit(DismissEvent); return; @@ -514,6 +521,7 @@ impl Focusable for RenameBranchModal { impl Render for RenameBranchModal { fn render(&mut self, _: &mut Window, cx: &mut Context) -> impl IntoElement { + let new_name = normalize_branch_name(&self.editor.read(cx).text(cx)); v_flex() .key_context("RenameBranchModal") .on_action(cx.listener(Self::cancel)) @@ -533,7 +541,21 @@ impl Render for RenameBranchModal { .size(HeadlineSize::XSmall), ), ) - .child(div().px_3().pb_3().w_full().child(self.editor.clone())) + .child( + v_flex() + .px_3() + .pb_3() + .w_full() + .gap_2() + .child(self.editor.clone()) + .child( + Label::new(new_name) + .size(LabelSize::Small) + .color(Color::Muted) + .single_line() + .truncate(), + ), + ) } } diff --git a/crates/git_ui/src/repository_selector.rs b/crates/git_ui/src/repository_selector.rs index 19c653cdaa0..5ddfda64115 100644 --- a/crates/git_ui/src/repository_selector.rs +++ b/crates/git_ui/src/repository_selector.rs @@ -1,8 +1,12 @@ use crate::git_status_icon; +use collections::HashMap; use git::status::{FileStatus, StatusCode, TrackedStatus, UnmergedStatus, UnmergedStatusCode}; use gpui::{App, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, Task, WeakEntity}; use picker::{Picker, PickerDelegate, PickerEditorPosition}; -use project::{Project, git_store::Repository}; +use project::{ + Project, + git_store::{Repository, RepositoryId}, +}; use std::sync::Arc; use ui::{ListItem, ListItemSpacing, prelude::*}; use workspace::{ModalView, Workspace}; @@ -35,17 +39,17 @@ impl RepositorySelector { cx: &mut Context, ) -> Self { let git_store = project_handle.read(cx).git_store().clone(); - let repository_entries = git_store.update(cx, |git_store, _cx| { - let mut repos: Vec<_> = git_store.repositories().values().cloned().collect(); - - repos.sort_by(|a, b| { - a.read(_cx) - .display_name() - .to_lowercase() - .cmp(&b.read(_cx).display_name().to_lowercase()) - }); - - repos + let display_names = git_store.read(cx).display_names(cx); + let mut repository_entries: Vec<_> = git_store + .read(cx) + .repositories() + .values() + .cloned() + .collect(); + repository_entries.sort_by(|a, b| { + display_name_of(&display_names, a, cx) + .to_lowercase() + .cmp(&display_name_of(&display_names, b, cx).to_lowercase()) }); let filtered_repositories = repository_entries.clone(); @@ -60,6 +64,7 @@ impl RepositorySelector { filtered_repositories, active_repository, selected_index, + display_names, }; let picker = cx.new(|cx| { @@ -127,6 +132,19 @@ pub struct RepositorySelectorDelegate { filtered_repositories: Vec>, active_repository: Option>, selected_index: usize, + display_names: HashMap, +} + +fn display_name_of( + display_names: &HashMap, + repository: &Entity, + cx: &App, +) -> SharedString { + let repository = repository.read(cx); + display_names + .get(&repository.id) + .cloned() + .unwrap_or_else(|| repository.display_name()) } impl RepositorySelectorDelegate { @@ -188,7 +206,12 @@ impl PickerDelegate for RepositorySelectorDelegate { let repo_names: Vec<(Entity, String)> = all_repositories .iter() - .map(|repo| (repo.clone(), repo.read(cx).display_name().to_lowercase())) + .map(|repo| { + ( + repo.clone(), + display_name_of(&self.display_names, repo, cx).to_lowercase(), + ) + }) .collect(); cx.spawn_in(window, async move |this, cx| { @@ -209,11 +232,11 @@ impl PickerDelegate for RepositorySelectorDelegate { this.update_in(cx, |this, window, cx| { let mut sorted_repositories = filtered_repositories; + let display_names = &this.delegate.display_names; sorted_repositories.sort_by(|a, b| { - a.read(cx) - .display_name() + display_name_of(display_names, a, cx) .to_lowercase() - .cmp(&b.read(cx).display_name().to_lowercase()) + .cmp(&display_name_of(display_names, b, cx).to_lowercase()) }); let selected_index = this .delegate @@ -253,8 +276,8 @@ impl PickerDelegate for RepositorySelectorDelegate { cx: &mut Context>, ) -> Option { let repo_info = self.filtered_repositories.get(ix)?; + let display_name = display_name_of(&self.display_names, repo_info, cx); let repo = repo_info.read(cx); - let display_name = repo.display_name(); let summary = repo.status_summary(); let is_active = self .active_repository @@ -267,8 +290,10 @@ impl PickerDelegate for RepositorySelectorDelegate { .toggle_state(selected) .child( h_flex() + .w_full() + .min_w_0() .gap_1() - .child(Label::new(display_name)) + .child(Label::new(display_name).single_line().truncate().flex_1()) .when(is_active, |this| { this.child( Icon::new(IconName::Check) diff --git a/crates/git_ui_core/src/worktree_service.rs b/crates/git_ui_core/src/worktree_service.rs index bb10e74bcf9..1a20d69e29b 100644 --- a/crates/git_ui_core/src/worktree_service.rs +++ b/crates/git_ui_core/src/worktree_service.rs @@ -629,26 +629,26 @@ pub async fn await_and_rollback_on_failure( /// Propagates worktree trust from the source workspace to the new workspace. /// If the source project's worktrees are all trusted, the new worktree paths /// will also be trusted automatically. -fn maybe_propagate_worktree_trust( +async fn maybe_propagate_worktree_trust( source_workspace: &WeakEntity, new_workspace: &Entity, paths: &[PathBuf], cx: &mut AsyncWindowContext, ) { - cx.update(|_, cx| { + let inherit_restriction = cx.update(|window, cx| { if ProjectSettings::get_global(cx).session.trust_all_worktrees { - return; + return None; } - let source_is_trusted = source_workspace - .upgrade() - .map(|workspace| { - let source_worktree_store = workspace.read(cx).project().read(cx).worktree_store(); - !TrustedWorktrees::has_restricted_worktrees(&source_worktree_store, cx) - }) - .unwrap_or(false); - - if !source_is_trusted { - return; + let source_workspace = source_workspace.upgrade()?; + let source_worktree_store = source_workspace + .read(cx) + .project() + .read(cx) + .worktree_store(); + if TrustedWorktrees::has_restricted_worktrees(&source_worktree_store, cx) { + return Some(new_workspace.update(cx, |new_workspace, cx| { + new_workspace.inherit_restricted_worktrees(&source_workspace, window, cx) + })); } let worktree_store = new_workspace.read(cx).project().read(cx).worktree_store(); @@ -667,8 +667,11 @@ fn maybe_propagate_worktree_trust( }); } } - }) - .ok(); + None + }); + if let Ok(Some(inherit_restriction)) = inherit_restriction { + inherit_restriction.await; + } // After trust propagation, refresh the security modal on the new workspace // so it dismisses itself if there are no more restricted worktrees. @@ -1258,7 +1261,7 @@ async fn open_worktree_workspace( }) .await; - maybe_propagate_worktree_trust(&workspace, &new_workspace, &all_paths, cx); + maybe_propagate_worktree_trust(&workspace, &new_workspace, &all_paths, cx).await; if transfer_state { window_handle.update(cx, |_multi_workspace, window, cx| { @@ -1709,6 +1712,100 @@ mod tests { ); } + #[gpui::test] + async fn test_linked_worktree_inherits_stay_in_restricted_mode(cx: &mut TestAppContext) { + init_test(cx); + cx.update(|cx| { + cx.set_global(db::AppDatabase::test_new()); + project::trusted_worktrees::init(collections::HashMap::default(), cx); + }); + + let fs = FakeFs::new(cx.background_executor.clone()); + cx.update(|cx| ::set_global(fs.clone(), cx)); + fs.insert_tree( + "/root", + json!({ + "project": { + ".git": {}, + "src": { + "main.rs": "fn main() {}", + }, + }, + }), + ) + .await; + let main_project_root = PathBuf::from(path!("/root/project")); + + for (worktree_name, stay_restricted_in_source) in [("undecided", false), ("declined", true)] + { + let project = + Project::test_with_worktree_trust(fs.clone(), [main_project_root.as_path()], cx) + .await; + project + .update(cx, |project, cx| project.git_scans_complete(cx)) + .await; + let (multi_workspace, window_cx) = cx.add_window_view(|window, cx| { + MultiWorkspace::test_new(project.clone(), window, cx) + }); + multi_workspace.update(window_cx, |multi_workspace, cx| { + multi_workspace.retain_active_workspace(cx); + }); + let main_workspace = multi_workspace.read_with(window_cx, |multi_workspace, _| { + multi_workspace.workspace().clone() + }); + + if stay_restricted_in_source { + main_workspace.update_in(window_cx, |workspace, window, cx| { + workspace.show_worktree_trust_security_modal(true, window, cx); + }); + window_cx.run_until_parked(); + window_cx.dispatch_action(workspace::ToggleWorktreeSecurity); + window_cx.run_until_parked(); + } + + main_workspace.update_in(window_cx, |workspace, window, cx| { + assert!( + workspace + .active_modal::(cx) + .is_none(), + "{worktree_name}" + ); + handle_create_worktree( + workspace, + &zed_actions::CreateWorktree { + worktree_name: Some(worktree_name.to_string()), + branch_target: NewWorktreeBranchTarget::CurrentBranch, + }, + window, + None, + cx, + ); + }); + window_cx.run_until_parked(); + + let new_workspace = multi_workspace.read_with(window_cx, |multi_workspace, _| { + multi_workspace.workspace().clone() + }); + assert_ne!(new_workspace, main_workspace, "{worktree_name}"); + new_workspace.read_with(window_cx, |workspace, cx| { + assert!( + project::trusted_worktrees::TrustedWorktrees::has_restricted_worktrees( + &workspace.project().read(cx).worktree_store(), + cx, + ), + "{worktree_name}" + ); + assert_eq!( + workspace + .active_modal::(cx) + .is_some(), + !stay_restricted_in_source, + "{worktree_name}" + ); + }); + } + } + #[test] fn test_remote_branch_name_parse() { assert_eq!( diff --git a/crates/gpui/Cargo.toml b/crates/gpui/Cargo.toml index f215c006fd6..3300a445059 100644 --- a/crates/gpui/Cargo.toml +++ b/crates/gpui/Cargo.toml @@ -119,9 +119,10 @@ unicode-segmentation.workspace = true gpui_util.workspace = true hdrhistogram = { workspace = true, optional = true } waker-fn = "1.2.0" -lyon = "1.0" +lyon_path = "1.0.19" pin-project = "1.1.10" spin.workspace = true +tiny-skia-path = "0.11" url.workspace = true uuid = { workspace = true, features = ["v4"] } web-time = { workspace = true, optional = true } @@ -181,7 +182,7 @@ postage = { workspace = true, features = ["blocking"] } web-time.workspace = true gpui_platform = { workspace = true, features = ["font-kit", "wayland", "x11"] } gpui_util.workspace = true -lyon = { version = "1.0", features = ["extra"] } +lyon_extra = "1.1.0" rand = { workspace = true, default-features = true } scheduler = { workspace = true, features = ["test-support"] } util_macros.workspace = true diff --git a/crates/gpui/examples/painting.rs b/crates/gpui/examples/painting.rs index 3d89b0ff522..63ec07d9aab 100644 --- a/crates/gpui/examples/painting.rs +++ b/crates/gpui/examples/painting.rs @@ -4,14 +4,14 @@ mod example_support; use gpui::{ - Background, Bounds, ColorSpace, Context, MouseDownEvent, Path, PathBuilder, PathStyle, Pixels, - Point, Render, StrokeOptions, Window, WindowOptions, canvas, div, linear_color_stop, - linear_gradient, point, prelude::*, px, quad, rgb, size, + Background, Bounds, ColorSpace, Context, LineJoin, MouseDownEvent, Path, PathBuilder, + PathStyle, Pixels, Point, Render, StrokeOptions, Window, WindowOptions, canvas, div, + linear_color_stop, linear_gradient, point, prelude::*, px, quad, rgb, size, }; use gpui_platform::application; struct PaintingViewer { - default_lines: Vec<(Path, Background)>, + default_lines: Vec<(Path, Background)>, background_quads: Vec<(Bounds, Background)>, lines: Vec>>, start: Point, @@ -154,8 +154,8 @@ impl PaintingViewer { lines.push((path, red2.into())); // draw a Rust logo - let mut builder = lyon::path::Path::svg_builder(); - lyon::extra::rust_logo::build_logo_path(&mut builder); + let mut builder = lyon_path::Path::svg_builder(); + lyon_extra::rust_logo::build_logo_path(&mut builder); // move down the Path let mut builder: PathBuilder = builder.into(); builder.translate(point(px(10.), px(200.))); @@ -273,9 +273,11 @@ impl PaintingViewer { } // draw a wave - let options = StrokeOptions::default() - .with_line_width(1.) - .with_line_join(lyon::path::LineJoin::Bevel); + let options = StrokeOptions { + line_width: 1., + line_join: LineJoin::Bevel, + ..Default::default() + }; let mut builder = PathBuilder::stroke(px(1.)).with_style(PathStyle::Stroke(options)); builder.move_to(point(px(40.), px(420.))); for i in 1..50 { @@ -301,6 +303,57 @@ impl PaintingViewer { self.lines.clear(); cx.notify(); } + + /// Fill the canvas with a deterministic scribble, for benchmarking. + fn stress_scribble(&mut self, cx: &mut Context) { + self.lines.clear(); + let mut state: u32 = 0x9E3779B9; + let mut random = move || { + state ^= state << 13; + state ^= state >> 17; + state ^= state << 5; + state as f32 / u32::MAX as f32 + }; + for _ in 0..30 { + let mut x = 40.0 + random() * 860.0; + let mut y = 80.0 + random() * 440.0; + let mut angle = random() * std::f32::consts::TAU; + let mut points = Vec::with_capacity(121); + points.push(point(px(x), px(y))); + for _ in 0..120 { + angle += (random() - 0.5) * 1.2; + x += angle.cos() * 12.0; + y += angle.sin() * 12.0; + if !(40.0..=900.0).contains(&x) { + angle = std::f32::consts::PI - angle; + x = x.clamp(40.0, 900.0); + } + if !(80.0..=520.0).contains(&y) { + angle = -angle; + y = y.clamp(80.0, 520.0); + } + points.push(point(px(x), px(y))); + } + self.lines.push(points); + } + cx.notify(); + } + + /// Fill the canvas with a grid of strokes, for benchmarking. + fn stress_grid(&mut self, cx: &mut Context) { + self.lines.clear(); + for i in 0..55 { + let y = 80.0 + i as f32 * 8.0; + self.lines + .push(vec![point(px(40.0), px(y)), point(px(900.0), px(y))]); + } + for i in 0..108 { + let x = 40.0 + i as f32 * 8.0; + self.lines + .push(vec![point(px(x), px(80.0)), point(px(x), px(520.0))]); + } + cx.notify(); + } } fn button( @@ -349,6 +402,8 @@ impl Render for PaintingViewer { cx, move |this, _| this.dashed = !dashed, )) + .child(button("Scribble", cx, |this, cx| this.stress_scribble(cx))) + .child(button("Grid", cx, |this, cx| this.stress_grid(cx))) .child(button("Clear", cx, |this, cx| this.clear(cx))), ), ) diff --git a/crates/gpui/examples/paths_bench.rs b/crates/gpui/examples/paths_bench.rs index 236e70e9fcc..6f931995604 100644 --- a/crates/gpui/examples/paths_bench.rs +++ b/crates/gpui/examples/paths_bench.rs @@ -14,7 +14,7 @@ const DEFAULT_WINDOW_WIDTH: Pixels = px(1024.0); const DEFAULT_WINDOW_HEIGHT: Pixels = px(768.0); struct PaintingViewer { - default_lines: Vec<(Path, Background)>, + default_lines: Vec<(Path, Background)>, _painting: bool, } diff --git a/crates/gpui/src/app.rs b/crates/gpui/src/app.rs index 75da2eb6e50..f102819ae5c 100644 --- a/crates/gpui/src/app.rs +++ b/crates/gpui/src/app.rs @@ -55,8 +55,8 @@ use crate::{ PromptButton, PromptHandle, PromptLevel, Render, RenderImage, RenderablePromptHandle, Reservation, ScreenCaptureSource, SharedString, SubscriberSet, Subscription, SvgRenderer, SystemNotification, SystemNotificationResponse, Task, TextRenderingMode, TextSystem, - ThermalState, Window, WindowAppearance, WindowButtonLayout, WindowHandle, WindowId, - WindowInvalidator, WindowingRequest, + ThermalState, Window, WindowAppearance, WindowBounds, WindowButtonLayout, WindowHandle, + WindowId, WindowInvalidator, WindowingRequest, colors::{Colors, GlobalColors}, hash, init_app_menus, }; @@ -971,7 +971,7 @@ pub struct App { pub(crate) name: Option<&'static str>, pub(crate) text_rendering_mode: Rc>, - pub(crate) window_update_stack: Vec, + pub(crate) window_update_stack: Vec, pub(crate) mode: GpuiMode, pub(crate) cursor_hide_mode: CursorHideMode, pub(crate) reduce_motion: bool, @@ -991,6 +991,13 @@ pub struct App { _ref_counts: Arc>, } +#[derive(Clone, Copy)] +pub(crate) struct WindowUpdateEntry { + window_id: WindowId, + bounds: WindowBounds, + display_id: Option, +} + impl App { #[allow(clippy::new_ret_no_self)] pub(crate) fn new_app( @@ -1599,6 +1606,40 @@ impl App { self.platform.active_window() } + /// Returns the display containing the window that is currently focused at the platform level. + pub fn active_display(&self) -> Option> { + let (display_id, _) = self.active_window_placement()?; + self.find_display(display_id?) + } + + pub(crate) fn active_window_placement(&self) -> Option<(Option, WindowBounds)> { + let window_id = self.active_window()?.window_id(); + + if let Some(state) = self + .window_update_stack + .iter() + .rev() + .find(|state| state.window_id == window_id) + { + return Some((state.display_id, state.bounds)); + } + + let window = self.windows.get(window_id)?.as_ref()?; + Some((window.display_id(), window.last_window_bounds())) + } + + pub(crate) fn sync_window_update_entry(&mut self, window: &Window) { + if let Some(state) = self + .window_update_stack + .iter_mut() + .rev() + .find(|state| state.window_id == window.handle.id) + { + state.bounds = window.last_window_bounds(); + state.display_id = window.display_id(); + } + } + /// Opens a new window with the given option and the root view returned by the given function. /// The function is invoked with a `Window`, which can be used to interact with window-specific /// functionality. @@ -1612,7 +1653,11 @@ impl App { let handle = WindowHandle::new(id); match Window::new(handle.into(), options, cx) { Ok(mut window) => { - cx.window_update_stack.push(id); + cx.window_update_stack.push(WindowUpdateEntry { + window_id: id, + bounds: window.last_window_bounds(), + display_id: window.display_id(), + }); let root_view = build_root_view(&mut window, cx); cx.window_update_stack.pop(); window.root.replace(root_view.into()); @@ -1687,6 +1732,66 @@ impl App { .cloned() } + /// Returns a diagnostic snapshot of app, display, and window state. + /// + /// This is for inspecting a running app that is misbehaving in a way that + /// is hard to reproduce. The layout is not stable and varies by platform; + /// do not parse it for program logic. A window that is being updated when + /// this is called is listed by ID only. + pub fn debug_state(&self) -> serde_json::Value { + let displays = self + .platform + .displays() + .into_iter() + .map(|display| { + serde_json::json!({ + "id": u64::from(display.id()), + "uuid": display.uuid().ok().map(|uuid| uuid.to_string()), + "bounds": display.bounds(), + "visible_bounds": display.visible_bounds(), + "refresh_interval_seconds": display + .refresh_interval() + .map(|interval| interval.as_secs_f64()), + }) + }) + .collect::>(); + let windows = self + .windows + .iter() + .map(|(window_id, window)| match window { + Some(window) => window.debug_state(), + None => serde_json::json!({ "id": window_id.as_u64(), "updating": true }), + }) + .collect::>(); + serde_json::json!({ + "compositor": self.platform.compositor_name(), + "thermal_state": format!("{:?}", self.platform.thermal_state()), + "power_mode": { + "cached": format!("{:?}", self.power_mode), + "platform": format!("{:?}", self.platform.power_mode()), + }, + "window_appearance": format!("{:?}", self.platform.window_appearance()), + "cursor_visible": self.platform.is_cursor_visible(), + "active_window_id": self + .platform + .active_window() + .map(|handle| handle.window_id().as_u64()), + "window_stack": self.platform.window_stack().map(|stack| { + stack + .into_iter() + .map(|handle| handle.window_id().as_u64()) + .collect::>() + }), + "primary_display_id": self + .platform + .primary_display() + .map(|display| u64::from(display.id())), + "displays": displays, + "windows": windows, + "platform": self.platform.debug_state(), + }) + } + /// Returns the current thermal state of the system. pub fn thermal_state(&self) -> ThermalState { self.platform.thermal_state() @@ -3264,7 +3369,11 @@ impl App { let root_view = window.root.clone().unwrap(); - cx.window_update_stack.push(window.handle.id); + cx.window_update_stack.push(WindowUpdateEntry { + window_id: window.handle.id, + bounds: window.last_window_bounds(), + display_id: window.display_id(), + }); update(Some((root_view, &mut window, cx))); fn trail(window_id: WindowId, window: Box, cx: &mut App) -> Option<()> { cx.window_update_stack.pop(); @@ -3349,7 +3458,7 @@ impl AppContext for App { cx.push_effect(Effect::EntityCreated { entity: handle.into_any(), tid: TypeId::of::(), - window: cx.window_update_stack.last().cloned(), + window: cx.window_update_stack.last().map(|state| state.window_id), }); cx.entities.insert(slot, entity) diff --git a/crates/gpui/src/app/test_context.rs b/crates/gpui/src/app/test_context.rs index d1797d5ff18..beff5ea7a8f 100644 --- a/crates/gpui/src/app/test_context.rs +++ b/crates/gpui/src/app/test_context.rs @@ -1,12 +1,13 @@ use crate::{ Action, AnyView, AnyWindowHandle, App, AppCell, AppContext, AsyncApp, AvailableSpace, - BackgroundExecutor, BorrowAppContext, Bounds, Capslock, ClipboardItem, DisplayId, DrawPhase, - Drawable, Element, Empty, EntityId, EventEmitter, ForegroundExecutor, Global, InputEvent, - Keystroke, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, MouseMoveEvent, - MouseUpEvent, Pixels, Platform, PlatformTextSystem, Point, Render, Result, SharedString, Size, - SystemNotification, SystemNotificationResponse, Task, TestDispatcher, TestPlatform, - TestScreenCaptureSource, TestWindow, TextSystem, VisualContext, Window, WindowBounds, - WindowHandle, WindowOptions, WindowVisibility, app::GpuiMode, window::ElementArenaScope, + BackgroundExecutor, BorrowAppContext, Bounds, Capslock, ClipboardItem, Decorations, DisplayId, + DrawPhase, Drawable, Element, Empty, EntityId, EventEmitter, ForegroundExecutor, Global, + InputEvent, Keystroke, Modifiers, ModifiersChangedEvent, MouseButton, MouseDownEvent, + MouseMoveEvent, MouseUpEvent, Pixels, Platform, PlatformTextSystem, Point, Render, Result, + SharedString, Size, SystemNotification, SystemNotificationResponse, Task, TestDispatcher, + TestPlatform, TestScreenCaptureSource, TestWindow, TextSystem, VisualContext, Window, + WindowBounds, WindowHandle, WindowOptions, WindowVisibility, app::GpuiMode, + window::ElementArenaScope, }; use anyhow::{anyhow, bail}; use futures::{Stream, StreamExt, channel::oneshot}; @@ -477,6 +478,16 @@ impl TestAppContext { .simulate_visibility_change(visibility); } + /// Simulates the platform changing how the window is decorated. + pub fn simulate_window_decorations_change( + &self, + window_handle: AnyWindowHandle, + decorations: Decorations, + ) { + self.test_window(window_handle) + .simulate_decorations_change(decorations); + } + /// Simulates connecting a display. pub fn simulate_display_added( &self, diff --git a/crates/gpui/src/bounds_tree.rs b/crates/gpui/src/bounds_tree.rs index e95e32477b9..a4a0ade5499 100644 --- a/crates/gpui/src/bounds_tree.rs +++ b/crates/gpui/src/bounds_tree.rs @@ -1,4 +1,4 @@ -use crate::{Bounds, Half}; +use crate::{Bounds, Half, scene::PrimitiveKind}; use std::{ cmp, fmt::Debug, @@ -13,10 +13,12 @@ const MAX_CHILDREN: usize = 12; /// A spatial tree optimized for finding maximum ordering among intersecting bounds. /// /// This is an R-tree variant specifically designed for the use case of assigning -/// z-order to overlapping UI elements. Key optimizations: -/// - Tracks the leaf with global max ordering for O(1) fast-path queries +/// z-order to overlapping UI elements. Each bounds has an ordering and a kind; +/// bounds sharing an ordering are drawn in the order of their kinds. Key +/// optimizations: +/// - Tracks the leaf with global max key for O(1) fast-path queries /// - Uses higher branching factor (4) for lower tree height -/// - Aggressive pruning during search based on max_order metadata +/// - Aggressive pruning during search based on max_key metadata #[derive(Debug)] pub(crate) struct BoundsTree where @@ -26,7 +28,7 @@ where nodes: Vec>, /// Index of the root node, if any. root: Option, - /// Index of the leaf with the highest ordering (for fast-path lookups). + /// Index of the leaf with the highest key (for fast-path lookups). max_leaf: Option, /// Reusable stack for tree traversal during insertion. insert_path: Vec, @@ -42,19 +44,24 @@ where { /// Bounding box containing this node and all descendants. bounds: Bounds, - /// Maximum ordering value in this subtree. - max_order: u32, + /// Maximum key in this subtree. + max_key: Key, /// Node-specific data. kind: NodeKind, } +/// The ordering of a bounds, then its kind, which orders the bounds that share +/// an ordering. +#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)] +struct Key { + ordering: u32, + kind: PrimitiveKind, +} + #[derive(Debug, Clone)] enum NodeKind { /// Leaf node containing actual bounds data. - Leaf { - /// The ordering assigned to this bounds. - order: u32, - }, + Leaf { key: Key }, /// Internal node with children. Internal { /// Indices of child nodes (2 to MAX_CHILDREN). @@ -65,7 +72,7 @@ enum NodeKind { /// Fixed-size array for child indices, avoiding heap allocation. #[derive(Debug, Clone)] struct NodeChildren { - // Keeps an invariant where the max order child is always at the end + // Keeps an invariant where the max key child is always at the end indices: [usize; MAX_CHILDREN], len: u8, } @@ -113,39 +120,48 @@ where self.search_stack.clear(); } - /// Inserts bounds into the tree and returns its assigned ordering. + /// Inserts bounds of the given kind into the tree and returns its assigned + /// ordering. /// - /// The ordering is one greater than the maximum ordering of any - /// existing bounds that intersect with the new bounds. - pub fn insert(&mut self, new_bounds: Bounds) -> u32 { - // Find maximum ordering among intersecting bounds - let max_intersecting = self.find_max_ordering(&new_bounds); - let ordering = max_intersecting + 1; + /// The ordering is one greater than the maximum ordering of any existing + /// bounds that intersect with the new bounds. The new bounds share that + /// maximum ordering instead if every intersecting bounds there has a kind + /// of at most `max_shared_kind`, since those are drawn first. + pub fn insert( + &mut self, + new_bounds: Bounds, + kind: PrimitiveKind, + max_shared_kind: PrimitiveKind, + ) -> u32 { + let ordering = match self.find_max_key(&new_bounds) { + None => 1, + Some(max_key) if max_key.kind <= max_shared_kind => max_key.ordering, + Some(max_key) => max_key.ordering + 1, + }; + let key = Key { ordering, kind }; // Insert the new leaf - let new_leaf_idx = self.insert_leaf(new_bounds, ordering); + let new_leaf_idx = self.insert_leaf(new_bounds, key); // Update max_leaf tracking self.max_leaf = match self.max_leaf { None => Some(new_leaf_idx), - Some(old_idx) if self.nodes[old_idx].max_order < ordering => Some(new_leaf_idx), + Some(old_idx) if self.nodes[old_idx].max_key < key => Some(new_leaf_idx), some => some, }; ordering } - /// Finds the maximum ordering among all bounds that intersect with the query. - fn find_max_ordering(&mut self, query: &Bounds) -> u32 { - let Some(root_idx) = self.root else { - return 0; - }; + /// Finds the maximum key among all bounds that intersect with the query. + fn find_max_key(&mut self, query: &Bounds) -> Option { + let root_idx = self.root?; - // Fast path: check if the max-ordering leaf intersects + // Fast path: check if the max-key leaf intersects if let Some(max_idx) = self.max_leaf { let max_node = &self.nodes[max_idx]; if query.intersects(&max_node.bounds) { - return max_node.max_order; + return Some(max_node.max_key); } } @@ -153,7 +169,8 @@ where self.search_stack.clear(); self.search_stack.push(NonNull::from(&self.nodes[root_idx])); - let mut max_found = 0u32; + // `None` compares below every key. + let mut max_found = None; while let Some(node) = self.search_stack.pop() { // SAFETY: `node` is guaranteed to be valid as the `nodes` stack is unmodified in this function @@ -161,7 +178,7 @@ where let node = unsafe { node.as_ref() }; // Pruning: skip if this subtree can't improve our result - if node.max_order <= max_found { + if Some(node.max_key) <= max_found { continue; } @@ -171,18 +188,18 @@ where } match &node.kind { - NodeKind::Leaf { order } => { - max_found = cmp::max(max_found, *order); + NodeKind::Leaf { key } => { + max_found = cmp::max(max_found, Some(*key)); } NodeKind::Internal { children } => { - // Children are maintained with highest max_order at the end. + // Children are maintained with highest max_key at the end. // Push in forward order to highest (last) is popped first. self.search_stack.extend( children .as_slice() .iter() .map(|&child_idx| &self.nodes[child_idx]) - .filter(|node| node.max_order > max_found) + .filter(|node| Some(node.max_key) > max_found) .map(NonNull::from), ); } @@ -192,14 +209,14 @@ where max_found } - /// Inserts a leaf node with the given bounds and ordering. + /// Inserts a leaf node with the given bounds and key. /// Returns the index of the new leaf. - fn insert_leaf(&mut self, bounds: Bounds, order: u32) -> usize { + fn insert_leaf(&mut self, bounds: Bounds, key: Key) -> usize { let new_leaf_idx = self.nodes.len(); self.nodes.push(Node { bounds: bounds.clone(), - max_order: order, - kind: NodeKind::Leaf { order }, + max_key: key, + kind: NodeKind::Leaf { key }, }); let Some(root_idx) = self.root else { @@ -211,11 +228,11 @@ where // If root is a leaf, create internal node with both if matches!(self.nodes[root_idx].kind, NodeKind::Leaf { .. }) { let root_bounds = self.nodes[root_idx].bounds.clone(); - let root_order = self.nodes[root_idx].max_order; + let root_key = self.nodes[root_idx].max_key; let mut children = NodeChildren::new(); // Max end invariant - if order > root_order { + if key > root_key { children.push(root_idx); children.push(new_leaf_idx); } else { @@ -226,7 +243,7 @@ where let new_root_idx = self.nodes.len(); self.nodes.push(Node { bounds: root_bounds.union(&bounds), - max_order: cmp::max(root_order, order), + max_key: cmp::max(root_key, key), kind: NodeKind::Internal { children }, }); self.root = Some(new_root_idx); @@ -270,24 +287,24 @@ where if let NodeKind::Internal { children } = &mut node.kind { children.push(new_leaf_idx); - // Swap new leaf only if it has the highest max_order - if order <= node.max_order { + // Swap new leaf only if it has the highest max_key + if key <= node.max_key { let last = children.len() - 1; children.indices.swap(last - 1, last); } } node.bounds = node.bounds.union(&bounds); - node.max_order = cmp::max(node.max_order, order); + node.max_key = cmp::max(node.max_key, key); break; } else { // Node is full, create new internal with [best_leaf, new_leaf] let sibling_bounds = self.nodes[best_child_idx].bounds.clone(); - let sibling_order = self.nodes[best_child_idx].max_order; + let sibling_key = self.nodes[best_child_idx].max_key; let mut new_children = NodeChildren::new(); // Max end invariant - if order > sibling_order { + if key > sibling_key { new_children.push(best_child_idx); new_children.push(new_leaf_idx); } else { @@ -296,10 +313,10 @@ where } let new_internal_idx = self.nodes.len(); - let new_internal_max = cmp::max(sibling_order, order); + let new_internal_max_key = cmp::max(sibling_key, key); self.nodes.push(Node { bounds: sibling_bounds.union(&bounds), - max_order: new_internal_max, + max_key: new_internal_max_key, kind: NodeKind::Internal { children: new_children, }, @@ -312,9 +329,9 @@ where children.indices[best_child_pos] = new_internal_idx; - // If new internal has highest max_order, swap it to the end + // If new internal has highest max_key, swap it to the end // to maintain sorting invariant - if new_internal_max > parent.max_order { + if new_internal_max_key > parent.max_key { children.indices.swap(best_child_pos, children_len - 1); } } @@ -326,14 +343,14 @@ where } } - // Propagate bounds and max_order updates up the tree + // Propagate bounds and max_key updates up the tree let mut updated_child_idx = None; for &node_idx in self.insert_path.iter().rev() { let node = &mut self.nodes[node_idx]; node.bounds = node.bounds.union(&bounds); - if node.max_order < order { - node.max_order = order; + if node.max_key < key { + node.max_key = key; // Swap updated child to end (skip first iteration since the invariant is already handled by previous cases) if let Some(child_idx) = updated_child_idx { @@ -380,6 +397,7 @@ mod tests { #[test] fn test_insert() { let mut tree = BoundsTree::::default(); + let (quad, shadow) = (PrimitiveKind::Quad, PrimitiveKind::Shadow); let bounds1 = Bounds { origin: Point { x: 0.0, y: 0.0 }, size: Size { @@ -403,9 +421,9 @@ mod tests { }; // Insert the bounds into the tree and verify the order is correct - assert_eq!(tree.insert(bounds1), 1); - assert_eq!(tree.insert(bounds2), 2); - assert_eq!(tree.insert(bounds3), 3); + assert_eq!(tree.insert(bounds1, quad, shadow), 1); + assert_eq!(tree.insert(bounds2, quad, shadow), 2); + assert_eq!(tree.insert(bounds3, quad, shadow), 3); // Insert non-overlapping bounds and verify they can reuse orders let bounds4 = Bounds { @@ -429,19 +447,24 @@ mod tests { height: 10.0, }, }; - assert_eq!(tree.insert(bounds4), 1); // bounds4 does not overlap with bounds1, bounds2, or bounds3 - assert_eq!(tree.insert(bounds5), 1); // bounds5 does not overlap with any other bounds - assert_eq!(tree.insert(bounds6), 2); // bounds6 overlaps with bounds4, so it should have a different order + assert_eq!(tree.insert(bounds4, quad, shadow), 1); // bounds4 does not overlap with bounds1, bounds2, or bounds3 + assert_eq!(tree.insert(bounds5, quad, shadow), 1); // bounds5 does not overlap with any other bounds + assert_eq!(tree.insert(bounds6, quad, shadow), 2); // bounds6 overlaps with bounds4, so it should have a different order } #[test] fn test_random_iterations() { let max_bounds = 100; for seed in 1..=1000 { - // let seed = 44; let mut tree = BoundsTree::default(); let mut rng = rand::rngs::StdRng::seed_from_u64(seed as u64); - let mut expected_quads: Vec<(Bounds, u32)> = Vec::new(); + let mut expected_quads: Vec<(Bounds, u32, PrimitiveKind)> = Vec::new(); + let kinds = [ + PrimitiveKind::Shadow, + PrimitiveKind::Quad, + PrimitiveKind::Path, + PrimitiveKind::Underline, + ]; // Insert a random number of random AABBs into the tree. let num_bounds = rng.random_range(1..=max_bounds); @@ -454,17 +477,22 @@ mod tests { origin: Point { x: min_x, y: min_y }, size: Size { width, height }, }; + let kind = kinds[rng.random_range(0..kinds.len())]; + let max_shared_kind = kinds[rng.random_range(0..kinds.len())]; - let expected_ordering = expected_quads + let max_intersecting = expected_quads .iter() - .filter_map(|quad| quad.0.intersects(&bounds).then_some(quad.1)) - .max() - .unwrap_or(0) - + 1; - expected_quads.push((bounds, expected_ordering)); + .filter(|quad| quad.0.intersects(&bounds)) + .map(|quad| (quad.1, quad.2)) + .max(); + let expected_ordering = match max_intersecting { + None => 1, + Some((ordering, max_kind)) if max_kind <= max_shared_kind => ordering, + Some((ordering, _)) => ordering + 1, + }; + expected_quads.push((bounds, expected_ordering, kind)); - // Insert the AABB into the tree and collect intersections. - let actual_ordering = tree.insert(bounds); + let actual_ordering = tree.insert(bounds, kind, max_shared_kind); assert_eq!(actual_ordering, expected_ordering); } } diff --git a/crates/gpui/src/geometry.rs b/crates/gpui/src/geometry.rs index 234299825c9..8d7c496c1ec 100644 --- a/crates/gpui/src/geometry.rs +++ b/crates/gpui/src/geometry.rs @@ -1187,6 +1187,37 @@ impl + Sub + Clone + Debug + Defa let bottom_right = self.bottom_right().max(&other.bottom_right()); Bounds::from_corners(top_left, bottom_right) } + + /// Computes the smallest `Bounds` that covers the area of both `Bounds`. + /// + /// Unlike [`Bounds::union`], an empty `Bounds` covers nothing, so joining with it returns + /// the other `Bounds` unchanged. + /// + /// # Examples + /// + /// ``` + /// # use gpui::{Bounds, Point, Size}; + /// let bounds = Bounds { + /// origin: Point { x: 5, y: 5 }, + /// size: Size { width: 10, height: 10 }, + /// }; + /// let empty = Bounds { + /// origin: Point { x: 0, y: 0 }, + /// size: Size { width: 0, height: 10 }, + /// }; + /// + /// assert_eq!(bounds.join(&empty), bounds); + /// assert_eq!(empty.join(&bounds), bounds); + /// ``` + pub fn join(&self, other: &Self) -> Self { + if self.is_empty() { + other.clone() + } else if other.is_empty() { + self.clone() + } else { + self.union(other) + } + } } impl Bounds @@ -3135,7 +3166,7 @@ impl From for DevicePixels { /// a single logical pixel may correspond to multiple physical pixels. By using `ScaledPixels`, /// dimensions and positions can be specified in a way that scales appropriately across different /// display resolutions. -#[derive(Clone, Copy, Default, Add, AddAssign, Sub, SubAssign, Div, DivAssign, PartialEq)] +#[derive(Clone, Copy, Default, Add, AddAssign, Sub, SubAssign, Neg, Div, DivAssign, PartialEq)] #[repr(transparent)] pub struct ScaledPixels(pub f32); @@ -3289,6 +3320,18 @@ impl MulAssign for ScaledPixels { } } +impl std::iter::Sum for ScaledPixels { + fn sum>(iter: I) -> Self { + iter.fold(Self::default(), |a, b| a + b) + } +} + +impl<'a> std::iter::Sum<&'a ScaledPixels> for ScaledPixels { + fn sum>(iter: I) -> Self { + iter.fold(Self::default(), |a, b| a + *b) + } +} + /// Represents a length in rems, a unit based on the font-size of the window, which can be assigned with [`Window::set_rem_size`][set_rem_size]. /// /// Rems are used for defining lengths that are scalable and consistent across different UI elements. @@ -4052,6 +4095,37 @@ mod tests { } } + #[test] + fn test_bounds_join() { + let bounds = Bounds { + origin: Point { x: 5.0, y: 5.0 }, + size: Size { + width: 5.0, + height: 5.0, + }, + }; + let other = Bounds { + origin: Point { x: 20.0, y: 0.0 }, + size: Size { + width: 5.0, + height: 5.0, + }, + }; + assert_eq!(bounds.join(&other), bounds.union(&other)); + + let empty = Bounds { + origin: Point { x: 0.0, y: 0.0 }, + size: Size { + width: 0.0, + height: 10.0, + }, + }; + assert_eq!(bounds.join(&empty), bounds); + assert_eq!(empty.join(&bounds), bounds); + assert_eq!(Bounds::default().join(&bounds), bounds); + assert_ne!(bounds.union(&empty), bounds); + } + #[test] fn test_bounds_intersects() { let bounds1 = Bounds { diff --git a/crates/gpui/src/gpui.rs b/crates/gpui/src/gpui.rs index 5b31a3557fb..abd966d750a 100644 --- a/crates/gpui/src/gpui.rs +++ b/crates/gpui/src/gpui.rs @@ -44,6 +44,7 @@ mod interactive; mod key_dispatch; mod keymap; mod path_builder; +mod path_winding; mod platform; mod platform_scheduler; mod scene; @@ -134,6 +135,7 @@ pub use inspector::*; pub use interactive::*; pub use keymap::*; pub use path_builder::*; +pub(crate) use path_winding::*; pub use platform::*; pub use profiler::*; pub use refineable::*; diff --git a/crates/gpui/src/path_builder.rs b/crates/gpui/src/path_builder.rs index 40a6e71e0a1..0e54d0bfd3d 100644 --- a/crates/gpui/src/path_builder.rs +++ b/crates/gpui/src/path_builder.rs @@ -1,17 +1,15 @@ -use anyhow::Error; +use anyhow::{Error, bail}; use etagere::euclid::{Point2D, Vector2D}; -use lyon::geom::Angle; -use lyon::math::{Vector, vector}; -use lyon::path::traits::SvgPathBuilder; -use lyon::path::{ArcFlags, Polygon}; -use lyon::tessellation::{ - BuffersBuilder, FillTessellator, FillVertex, StrokeTessellator, StrokeVertex, VertexBuffers, -}; +use lyon_path::geom::{Angle, CubicBezierSegment, QuadraticBezierSegment}; +use lyon_path::math::{Vector, vector}; +use lyon_path::traits::SvgPathBuilder; +use lyon_path::{ArcFlags, Event, Polygon}; -pub use lyon::math::Transform; -pub use lyon::tessellation::{FillOptions, FillRule, StrokeOptions}; +pub use lyon_path::math::Transform; +pub use lyon_path::{FillRule, LineCap, LineJoin}; -use crate::{Path, Pixels, Point, point, px}; +use crate::{PathCurve, PathTiles, Pixels, Point, point, px}; +use std::sync::Arc; /// Style of the PathBuilder pub enum PathStyle { @@ -21,17 +19,57 @@ pub enum PathStyle { Fill(FillOptions), } +/// How to stroke a path. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct StrokeOptions { + /// Width of the stroke. + pub line_width: f32, + /// Shape of the ends of open subpaths and dashes. + pub line_cap: LineCap, + /// Shape of corners. + pub line_join: LineJoin, + /// How long a miter join may get, as a multiple of the line width, + /// before it is beveled instead. + pub miter_limit: f32, +} + +impl Default for StrokeOptions { + fn default() -> Self { + Self { + line_width: 1.0, + line_cap: LineCap::Butt, + line_join: LineJoin::Miter, + miter_limit: 4.0, + } + } +} + +/// How to fill a path. +#[derive(Clone, Copy, Debug, PartialEq)] +pub struct FillOptions { + /// How overlapping contours combine into the filled region. + pub fill_rule: FillRule, +} + +impl Default for FillOptions { + fn default() -> Self { + Self { + fill_rule: FillRule::EvenOdd, + } + } +} + /// A [`Path`] builder. pub struct PathBuilder { - raw: lyon::path::builder::WithSvg, - transform: Option, + raw: lyon_path::builder::WithSvg, + transform: Option, /// PathStyle of the PathBuilder pub style: PathStyle, dash_array: Option>, } -impl From for PathBuilder { - fn from(builder: lyon::path::Builder) -> Self { +impl From for PathBuilder { + fn from(builder: lyon_path::Builder) -> Self { Self { raw: builder.with_svg(), ..Default::default() @@ -39,8 +77,8 @@ impl From for PathBuilder { } } -impl From> for PathBuilder { - fn from(raw: lyon::path::builder::WithSvg) -> Self { +impl From> for PathBuilder { + fn from(raw: lyon_path::builder::WithSvg) -> Self { Self { raw, ..Default::default() @@ -48,15 +86,15 @@ impl From> for PathBuilder } } -impl From for Point { - fn from(p: lyon::math::Point) -> Self { +impl From for Point { + fn from(p: lyon_path::math::Point) -> Self { point(px(p.x), px(p.y)) } } -impl From> for lyon::math::Point { +impl From> for lyon_path::math::Point { fn from(p: Point) -> Self { - lyon::math::point(p.x.0, p.y.0) + lyon_path::math::point(p.x.0, p.y.0) } } @@ -75,7 +113,7 @@ impl From> for Point2D { impl Default for PathBuilder { fn default() -> Self { Self { - raw: lyon::path::Path::builder().with_svg(), + raw: lyon_path::Path::builder().with_svg(), style: PathStyle::Fill(FillOptions::default()), transform: None, dash_array: None, @@ -87,7 +125,10 @@ impl PathBuilder { /// Creates a new [`PathBuilder`] to build a Stroke path. pub fn stroke(width: Pixels) -> Self { Self { - style: PathStyle::Stroke(StrokeOptions::default().with_line_width(width.0)), + style: PathStyle::Stroke(StrokeOptions { + line_width: width.0, + ..Default::default() + }), ..Self::default() } } @@ -102,7 +143,7 @@ impl PathBuilder { Self { style, ..self } } - /// Sets the dash array of the [`PathBuilder`]. + /// Sets the dash array of the [`PathBuilder`]. Fills ignore it. /// /// [MDN](https://developer.mozilla.org/en-US/docs/Web/SVG/Reference/Attribute/stroke-dasharray) pub fn dash_array(mut self, dash_array: &[Pixels]) -> Self { @@ -240,108 +281,297 @@ impl PathBuilder { } /// Builds into a [`Path`]. - #[inline] - pub fn build(self) -> Result, Error> { + pub fn build(self) -> Result { + let (curves, fill_rule) = self.outline()?; + Ok(Path::from_curves(curves, fill_rule)) + } + + /// The closed contours to fill, and the rule to fill them by. + pub(crate) fn outline(self) -> Result<(Vec, FillRule), Error> { let path = if let Some(transform) = self.transform { self.raw.build().transformed(&transform) } else { self.raw.build() }; - match self.style { - PathStyle::Stroke(options) => Self::tessellate_stroke(self.dash_array, &path, &options), - PathStyle::Fill(options) => Self::tessellate_fill(&path, &options), - } + Ok(match self.style { + PathStyle::Stroke(options) => ( + Self::stroke_outline(&path, &options, self.dash_array.as_deref())?, + FillRule::NonZero, + ), + PathStyle::Fill(options) => (Self::fill_outline(&path)?, options.fill_rule), + }) } - fn tessellate_fill( - path: &lyon::path::Path, - options: &FillOptions, - ) -> Result, Error> { - // Will contain the result of the tessellation. - let mut buf: VertexBuffers = VertexBuffers::new(); - let mut tessellator = FillTessellator::new(); - - // Compute the tessellation. - tessellator.tessellate_path( - path, - options, - &mut BuffersBuilder::new(&mut buf, |vertex: FillVertex| vertex.position()), - )?; - - Ok(Self::build_path(buf)) - } - - fn tessellate_stroke( - dash_array: Option>, - path: &lyon::path::Path, + fn stroke_outline( + path: &lyon_path::Path, options: &StrokeOptions, - ) -> Result, Error> { - let path = if let Some(dash_array) = dash_array { - let measurements = lyon::algorithms::measure::PathMeasurements::from_path(path, 0.01); - let mut sampler = measurements - .create_sampler(path, lyon::algorithms::measure::SampleType::Normalized); - let mut builder = lyon::path::Path::builder(); - - let total_length = sampler.length(); - let dash_array_len = dash_array.len(); - let mut pos = 0.; - let mut dash_index = 0; - while pos < total_length { - let dash_length = dash_array[dash_index % dash_array_len].0; - let next_pos = (pos + dash_length).min(total_length); - if dash_index % 2 == 0 { - let start = pos / total_length; - let end = next_pos / total_length; - sampler.split_range(start..end, &mut builder); + dash_array: Option<&[Pixels]>, + ) -> Result, Error> { + let outline = skia_path(path) + .map(|skia_path| match dash_array { + Some(dash_array) => { + let array = dash_array.iter().map(|length| length.0).collect(); + match tiny_skia_path::StrokeDash::new(array, 0.0) { + Some(dash) => skia_path + .dash(&dash, STROKE_RESOLUTION_SCALE) + .unwrap_or(skia_path), + // An invalid dash array strokes undashed, as in SVG. + None => skia_path, + } } - pos = next_pos; - dash_index += 1; - } - - &builder.build() - } else { - path + None => skia_path, + }) + .and_then(|skia_path| { + skia_path.stroke( + &tiny_skia_path::Stroke { + width: options.line_width, + miter_limit: options.miter_limit, + line_cap: match options.line_cap { + LineCap::Butt => tiny_skia_path::LineCap::Butt, + LineCap::Square => tiny_skia_path::LineCap::Square, + LineCap::Round => tiny_skia_path::LineCap::Round, + }, + line_join: match options.line_join { + LineJoin::Miter => tiny_skia_path::LineJoin::Miter, + LineJoin::MiterClip => tiny_skia_path::LineJoin::MiterClip, + LineJoin::Round => tiny_skia_path::LineJoin::Round, + LineJoin::Bevel => tiny_skia_path::LineJoin::Bevel, + }, + dash: None, + }, + STROKE_RESOLUTION_SCALE, + ) + }); + let Some(outline) = outline else { + return Ok(Vec::new()); }; - // Will contain the result of the tessellation. - let mut buf: VertexBuffers = VertexBuffers::new(); - let mut tessellator = StrokeTessellator::new(); - - // Compute the tessellation. - tessellator.tessellate_path( - path, - options, - &mut BuffersBuilder::new(&mut buf, |vertex: StrokeVertex| vertex.position()), - )?; - - Ok(Self::build_path(buf)) + let mut output = Outline::default(); + let at = |p: tiny_skia_path::Point| point(p.x, p.y); + for segment in outline.segments() { + match segment { + tiny_skia_path::PathSegment::MoveTo(p) => output.move_to(at(p)), + tiny_skia_path::PathSegment::LineTo(p) => output.line_to(at(p)), + tiny_skia_path::PathSegment::QuadTo(ctrl, p) => output.curve_to(at(p), at(ctrl)), + tiny_skia_path::PathSegment::CubicTo(ctrl1, ctrl2, p) => { + output.cubic_to(at(p), at(ctrl1), at(ctrl2)) + } + tiny_skia_path::PathSegment::Close => output.close(), + } + } + output.into_curves() } - /// Builds a [`Path`] from a [`lyon::tessellation::VertexBuffers`]. - pub fn build_path(buf: VertexBuffers) -> Path { - if buf.vertices.is_empty() { - return Path::new(Point::default()); + /// Convert a lyon path into a fill, closing every subpath. + fn fill_outline(path: &lyon_path::Path) -> Result, Error> { + let mut output = Outline::default(); + let at = |p: lyon_path::math::Point| point(p.x, p.y); + for event in path.iter() { + match event { + Event::Begin { at: p } => output.move_to(at(p)), + Event::Line { to, .. } => output.line_to(at(to)), + Event::Quadratic { ctrl, to, .. } => output.curve_to(at(to), at(ctrl)), + Event::Cubic { + ctrl1, ctrl2, to, .. + } => output.cubic_to(at(to), at(ctrl1), at(ctrl2)), + Event::End { .. } => output.close(), + } } - - let first_point = buf.vertices[0]; - - let mut path = Path::new(first_point.into()); - for i in 0..buf.indices.len() / 3 { - let i0 = buf.indices[i * 3] as usize; - let i1 = buf.indices[i * 3 + 1] as usize; - let i2 = buf.indices[i * 3 + 2] as usize; - - let v0 = buf.vertices[i0]; - let v1 = buf.vertices[i1]; - let v2 = buf.vertices[i2]; - - path.push_triangle( - (v0.into(), v1.into(), v2.into()), - (point(0., 1.), point(0., 1.), point(0., 1.)), - ); - } - - path + output.into_curves() } } + +/// A filled path, ready to paint. Build one with [`PathBuilder`]. +#[derive(Clone, Debug)] +pub struct Path { + /// Closed contours of monotone curves, in logical pixels. + curves: Arc<[PathCurve]>, + even_odd: bool, +} + +impl Path { + pub(crate) fn from_curves(curves: Vec, fill_rule: FillRule) -> Self { + Self { + curves: curves.into(), + even_odd: matches!(fill_rule, FillRule::EvenOdd), + } + } + + pub(crate) fn even_odd(&self) -> bool { + self.even_odd + } + + /// Bin the curves into tiles in device pixels, for painting at the given + /// display scale. + pub(crate) fn bin(&self, scale: f32) -> PathTiles { + crate::path_winding::bin(&self.curves, self.even_odd, scale) + } +} + +/// A path's contours as monotone curves, collected by [`PathBuilder`]. +#[derive(Default)] +pub(crate) struct Outline { + curves: Vec, + start: Point, + current: Point, + non_finite: bool, +} + +impl Outline { + /// Whether segments through these points can be added. + fn accepts(&mut self, points: &[Point]) -> bool { + self.non_finite |= !points + .iter() + .all(|point| point.x.is_finite() && point.y.is_finite()); + !self.non_finite + } + + /// Close the current contour and start a new one at the given point. + pub(crate) fn move_to(&mut self, to: Point) { + if !self.accepts(&[to]) { + return; + } + self.close(); + self.start = to; + self.current = to; + } + + pub(crate) fn line_to(&mut self, to: Point) { + if self.accepts(&[to]) && to != self.current { + self.curves.push(PathCurve::line(self.current, to)); + self.current = to; + } + } + + pub(crate) fn curve_to(&mut self, to: Point, ctrl: Point) { + if !self.accepts(&[to, ctrl]) || (to == self.current && ctrl == self.current) { + return; + } + PathCurve::push_monotone(&mut self.curves, self.current, ctrl, to); + self.current = to; + } + + pub(crate) fn cubic_to(&mut self, to: Point, ctrl1: Point, ctrl2: Point) { + /// Maximum error, in logical pixels. + const TOLERANCE: f32 = 0.25; + if !self.accepts(&[to, ctrl1, ctrl2]) { + return; + } + let lyon_point = |p: Point| lyon_path::math::point(p.x, p.y); + let cubic = CubicBezierSegment { + from: lyon_point(self.current), + ctrl1: lyon_point(ctrl1), + ctrl2: lyon_point(ctrl2), + to: lyon_point(to), + }; + cubic.for_each_quadratic_bezier(TOLERANCE, &mut |quadratic| { + self.curve_to( + point(quadratic.to.x, quadratic.to.y), + point(quadratic.ctrl.x, quadratic.ctrl.y), + ); + }); + } + + /// Close the current contour with a straight line back to its start. + pub(crate) fn close(&mut self) { + let start = self.start; + self.line_to(start); + } + + /// The curves, with every contour closed. + pub(crate) fn into_curves(mut self) -> Result, Error> { + if self.non_finite { + bail!("path has a non-finite point"); + } + self.close(); + Ok(self.curves) + } +} + +impl PathCurve { + fn new(p0: Point, ctrl: Point, p1: Point, sign: f32) -> Self { + Self { + p0, + p1, + a: point(p0.x - 2.0 * ctrl.x + p1.x, p0.y - 2.0 * ctrl.y + p1.y), + b: point(2.0 * (ctrl.x - p0.x), 2.0 * (ctrl.y - p0.y)), + sign, + pad: 0, + } + } + + /// A line, with exactly zero quadratic terms. + fn line(from: Point, to: Point) -> Self { + let (p0, p1, sign) = downward(from, to); + Self { + p0, + p1, + a: point(0.0, 0.0), + b: point(p1.x - p0.x, p1.y - p0.y), + sign, + pad: 0, + } + } + + /// Split a quadratic segment at its extrema into xy-monotone curves. + fn push_monotone(curves: &mut Vec, p0: Point, ctrl: Point, p1: Point) { + let curve = QuadraticBezierSegment { + from: lyon_path::math::point(p0.x, p0.y), + ctrl: lyon_path::math::point(ctrl.x, ctrl.y), + to: lyon_path::math::point(p1.x, p1.y), + }; + // Unlike `split_range`, this also clamps each piece's control point + // back into its endpoint box when rounding pushes it out. + curve.for_each_monotonic(&mut |monotone| { + let from = point(monotone.from.x, monotone.from.y); + let to = point(monotone.to.x, monotone.to.y); + if from == to { + return; + } + // Horizontal curves are kept: upward rays cross them. + let (p0, p1, sign) = downward(from, to); + let ctrl = point( + monotone.ctrl.x.clamp(p0.x.min(p1.x), p0.x.max(p1.x)), + monotone.ctrl.y.clamp(p0.y, p1.y), + ); + curves.push(Self::new(p0, ctrl, p1, sign)); + }); + } +} + +fn downward(from: Point, to: Point) -> (Point, Point, f32) { + if from.y > to.y { + (to, from, -1.0) + } else { + (from, to, 1.0) + } +} + +/// Strokes are expanded in logical pixels. tiny-skia keeps offset curves +/// within `0.25 / STROKE_RESOLUTION_SCALE` of exact, a quarter device pixel at +/// 2x, and flattens curves to within `0.5 / STROKE_RESOLUTION_SCALE` to measure +/// dashes. Round joins and caps ignore it: their arcs are approximated to 0.25 +/// logical pixels. +const STROKE_RESOLUTION_SCALE: f32 = 2.0; + +/// Returns [`None`] for empty geometry. +fn skia_path(path: &lyon_path::Path) -> Option { + let mut builder = tiny_skia_path::PathBuilder::new(); + for event in path.iter() { + match event { + Event::Begin { at } => builder.move_to(at.x, at.y), + Event::Line { to, .. } => builder.line_to(to.x, to.y), + Event::Quadratic { ctrl, to, .. } => builder.quad_to(ctrl.x, ctrl.y, to.x, to.y), + Event::Cubic { + ctrl1, ctrl2, to, .. + } => builder.cubic_to(ctrl1.x, ctrl1.y, ctrl2.x, ctrl2.y, to.x, to.y), + Event::End { close, .. } => { + if close { + builder.close(); + } + } + } + } + builder.finish() +} diff --git a/crates/gpui/src/path_winding.rs b/crates/gpui/src/path_winding.rs new file mode 100644 index 00000000000..5fe10dc197a --- /dev/null +++ b/crates/gpui/src/path_winding.rs @@ -0,0 +1,842 @@ +//! Path fills by per-pixel winding. +//! +//! [`PathBuilder`](crate::PathBuilder) turns contours into closed chains of +//! monotone quadratic curves. To paint the resulting [`Path`](crate::Path), we compute the +//! winding number at each pixel on the GPU, as in Eric Lengyel's Slug: we +//! cast rays leftward and upward from the pixel and count crossings with the +//! path's curves. Crossings within the pixel contribute partial winding to +//! approximate coverage across its area. Coverage is then determined by the +//! fill rule. +//! +//! To reduce the number of curves tested against each ray, we preprocess the +//! path on the CPU, binning its curves into square cells. Each cell lists the +//! curves intersecting or near it. The cell size is chosen per path to balance +//! the cost of binning against the cost of shading (see `cell_size`). +//! +//! Curves outside a cell's list cannot contribute partial winding, so the +//! binner sums their winding contributions along a leftward ray from the +//! cell's top-left corner into a *backdrop*. For each pixel, the shader starts +//! with this backdrop and adds the contributions of the listed curves. It also +//! corrects the backdrop to account for unlisted curves' contribution between the +//! corner and the pixel. +//! +//! Neighboring cells with the same curve list and backdrop are merged into +//! rectangular [`PathTile`]s, which are uploaded to and drawn by the GPU. For +//! example, a large rectangle can become nine tiles: four corners, four edges, +//! and an interior. + +use crate::{Bounds, PathCurve, PathTile, Point, ScaledPixels, point}; +use std::cell::RefCell; + +/// A tile lists every curve within this distance of its bounds. Any other curve +/// is more than half a pixel away from the tile, so it cannot contribute partial winding. +/// The extra 1/256 covers the rasterizer snapping tile edges to its subpixel grid. +const MARGIN: f32 = 0.5 + 1.0 / 256.0; + +/// `f32::min`, `max` and `clamp` without IEEE-compliant NaN handling, which costs a +/// compare and blend per call on x86-64's baseline target. +trait FastFloat { + fn fast_min(self, other: f32) -> f32; + fn fast_max(self, other: f32) -> f32; + fn fast_clamp(self, min: f32, max: f32) -> f32; +} + +impl FastFloat for f32 { + #[inline(always)] + fn fast_min(self, other: f32) -> f32 { + if self < other { self } else { other } + } + + #[inline(always)] + fn fast_max(self, other: f32) -> f32 { + if self > other { self } else { other } + } + + #[inline(always)] + fn fast_clamp(self, min: f32, max: f32) -> f32 { + self.fast_max(min).fast_min(max) + } +} + +/// A path's curves binned into tiles for one display scale. +#[derive(Debug, Default)] +pub(crate) struct PathTiles { + bounds: Bounds, + tiles: Vec, + /// Every tile's curve list, concatenated. + curves: Vec, +} + +impl PathTiles { + pub(crate) fn bounds(&self) -> Bounds { + self.bounds + } + + pub(crate) fn painted_bounds(&self) -> Bounds { + if self.tiles.is_empty() { + return self.bounds; + } + self.bounds.dilate(ScaledPixels(MARGIN)) + } + + pub(crate) fn tiles(&self) -> &[PathTile] { + &self.tiles + } + + pub(crate) fn curves(&self) -> &[PathCurve] { + &self.curves + } + + /// Drops the tiles that lie entirely outside `mask`. + pub(crate) fn retain_visible(&mut self, mask: Bounds) { + self.tiles.retain(|tile| { + tile.top_left.x < mask.right().0 + && tile.top_left.y < mask.bottom().0 + && tile.bottom_right.x > mask.origin.x.0 + && tile.bottom_right.y > mask.origin.y.0 + }); + } +} + +pub(crate) fn bin(curves: &[PathCurve], even_odd: bool, scale: f32) -> PathTiles { + debug_assert!(scale > 0.0 && scale.is_finite(), "invalid scale {scale}"); + if curves.is_empty() { + return PathTiles::default(); + } + BINNER.with_borrow_mut(|binner| { + let (min, max, length) = binner.scale(curves, scale); + let Some(grid) = Grid::covering(min, max, curves.len(), length) else { + log::warn!("path spanning {min:?} to {max:?} device pixels overflows; skipping"); + return PathTiles::default(); + }; + binner.find_spans(&grid); + binner.fill_cells(); + let (tiles, curves) = binner.merge_cells(&grid, even_odd); + let device = |p: Point| point(ScaledPixels(p.x), ScaledPixels(p.y)); + PathTiles { + bounds: Bounds::from_corners(device(min), device(max)), + tiles, + curves, + } + }) +} + +/// Picks the power-of-two cell size that minimizes the estimated time spent +/// binning and shading. Smaller cells list each curve in more cells, which +/// costs CPU time. Larger cells make the shader evaluate each listed curve at +/// more pixels, which costs GPU time. +/// +/// We estimate the binning and shading time by the following cost model, +/// expressed in terms of shader evaluations of one curve at one pixel: +/// +/// ```text +/// cost = listings * (LISTING_CPU_COST + area) + empty_cells * EMPTY_CELL_CPU_COST +/// ``` +fn cell_size(curves: f32, length: f32, size: Point) -> f32 { + // The CPU time of a listing and an empty cell, in shader evaluations, + // measured about 634 and 207 on a desktop (RX 6600) and 68 and 21 on an + // integrated GPU (HD 4600). Of the values in between, these lost the least + // on either machine, measuring CPU and GPU time on realistic paths. Walking + // a cell that lists curves has no cost: giving it one made dashed lines use + // larger cells, which cost far more GPU time than it saved on the CPU. + const LISTING_CPU_COST: f32 = 320.0; + const EMPTY_CELL_CPU_COST: f32 = 95.0; + // Smaller cells save GPU time, but on realistic paths they measured + // costing more CPU time than they saved, on both machines. + const MIN_CELL_SIZE: f32 = 16.0; + // Limits the grid's memory and walking time when the estimate undercounts + // empty cells, as when most curves crowd into a few cells of a large path. + const MAX_GRID_CELLS: f32 = 4096.0; + + let grid_cells = |cell_size: f32| { + ((size.x / cell_size).floor() + 1.0) * ((size.y / cell_size).floor() + 1.0) + }; + let extent = size.x.fast_max(size.y); + let mut cell_size = MIN_CELL_SIZE; + while grid_cells(cell_size) > MAX_GRID_CELLS { + cell_size *= 2.0; + } + let mut best = (f32::INFINITY, cell_size); + loop { + let listings = if cell_size >= extent { + curves + } else { + // Since curves are monotone, each crosses about `(w + h) / cell_size` grid lines. + curves + length / cell_size + }; + let area = cell_size.fast_min(size.x) * cell_size.fast_min(size.y) / 2.0; + let empty_cells = (grid_cells(cell_size) - listings).fast_max(0.0); + let cost = listings * (LISTING_CPU_COST + area) + empty_cells * EMPTY_CELL_CPU_COST; + if cost < best.0 { + best = (cost, cell_size); + } + if cell_size >= extent { + return best.1; + } + cell_size *= 2.0; + } +} + +fn fills(winding: i32, even_odd: bool) -> bool { + if even_odd { + winding % 2 != 0 + } else { + winding != 0 + } +} + +#[derive(Default)] +struct Binner { + /// The path's curves, scaled into device pixels. + input: Vec, + spans: Vec, + /// Per cell, where its list ends in `keys`. Reused while binning, as in a + /// counting sort: `find_spans` stores each cell's count here, and + /// `fill_cells` turns the counts into starts and advances them as it + /// fills each list. + cell_ends: Vec, + /// Per cell, the winding steps of curves crossing its row's top to its + /// left, other than those it lists. + steps: Vec, + /// Each cell's listings: a curve's leftmost x above its index. + keys: Vec, + /// The current row's runs. + runs: Vec, + /// The previous row's runs, whose tiles the current row can extend down. + above: Vec, +} + +thread_local! { + static BINNER: RefCell = Default::default(); +} + +/// A curve's run of consecutive cells within a row. +struct Span { + cell: usize, + count: usize, + key: u64, +} + +impl Binner { + fn scale(&mut self, curves: &[PathCurve], scale: f32) -> (Point, Point, f32) { + let mut min = point(f32::INFINITY, f32::INFINITY); + let mut max = point(f32::NEG_INFINITY, f32::NEG_INFINITY); + let mut length = 0.0; + self.input.clear(); + self.input.extend(curves.iter().map(|curve| { + let curve = curve.scaled(scale); + // The extents of a monotone curve can be computed from its endpoints. + min.x = min.x.fast_min(curve.min_x()); + max.x = max.x.fast_max(curve.max_x()); + min.y = min.y.fast_min(curve.p0.y); + max.y = max.y.fast_max(curve.p1.y); + length += curve.max_x() - curve.min_x() + curve.p1.y - curve.p0.y; + curve + })); + (min, max, length) + } + + fn find_spans(&mut self, grid: &Grid) { + let cells = grid.rows * grid.columns; + self.spans.clear(); + self.cell_ends.clear(); + self.cell_ends.resize(cells, 0); + self.steps.clear(); + self.steps.resize(cells, 0); + for (index, curve) in self.input.iter().enumerate() { + // This key sorts curves by leftmost x, which is used by the shader's early exit; + // then by index, so that curves are totally ordered. + let key = u64::from(ordered_bits(curve.min_x())) << 32 | index as u64; + for row in grid.row_of(curve.p0.y - MARGIN)..=grid.row_of(curve.p1.y + MARGIN) { + let row_top = grid.y(row); + let (low, high) = curve.x_range(row_top - MARGIN, grid.y(row + 1) + MARGIN); + let first = grid.column_of(low - MARGIN); + let last = grid.column_of(high + MARGIN); + let cell = row * grid.columns + first; + let count = last + 1 - first; + self.spans.push(Span { cell, count, key }); + for listings in self + .cell_ends + .get_mut(cell..cell + count) + .unwrap_or_default() + { + *listings += 1; + } + + // If this curve contributes to cell backdrops, record its contribution + // in the first cell to the right of its span. + if curve.crosses(row_top) + && last + 1 < grid.columns + && let Some(step) = self.steps.get_mut(cell + count) + { + *step += curve.step(); + } + } + } + } + + fn fill_cells(&mut self) { + let mut total = 0; + for end in self.cell_ends.iter_mut() { + let count = *end; + *end = total; + total += count; + } + self.keys.clear(); + self.keys.resize(total, 0); + for span in &self.spans { + for cursor in self + .cell_ends + .get_mut(span.cell..span.cell + span.count) + .unwrap_or_default() + { + if let Some(key) = self.keys.get_mut(*cursor) { + *key = span.key; + } + *cursor += 1; + } + } + let mut start = 0; + for &end in &self.cell_ends { + self.keys + .get_mut(start..end) + .unwrap_or_default() + .sort_unstable(); + start = end; + } + } + + fn merge_cells(&mut self, grid: &Grid, even_odd: bool) -> (Vec, Vec) { + let Binner { + input, + steps, + cell_ends, + keys, + runs, + above, + .. + } = self; + let mut tiles: Vec = Vec::new(); + // Each listing is copied at most once. + let mut curves = Vec::with_capacity(keys.len()); + above.clear(); + let mut cell_start = 0; + for row in 0..grid.rows { + runs.clear(); + let mut backdrop = 0; + for column in 0..grid.columns { + let index = row * grid.columns + column; + backdrop += steps.get(index).copied().unwrap_or(0); + let cell_end = cell_ends.get(index).copied().unwrap_or(cell_start); + let list = (cell_start, cell_end); + cell_start = cell_end; + + let cell = grid.cell(column, row); + let quad = if list.0 == list.1 { + fills(backdrop, even_odd).then(|| (cell.top_left(), cell.bottom_right())) + } else { + let mut measure = Measure::new(cell, backdrop); + for curve in listed(keys, input, list) { + measure.add(curve); + } + measure.quad(even_odd) + }; + let Some((top_left, bottom_right)) = quad else { + continue; + }; + let run = Run { + start: column, + end: column + 1, + backdrop, + list, + top_left, + bottom_right, + tile: 0, + }; + match runs.last_mut() { + Some(last) if last.end == run.start && last.shades_like(&run, keys) => { + last.end = run.end; + extend_quad(&mut last.top_left, &mut last.bottom_right, &run); + } + _ => runs.push(run), + } + } + + // Both rows' runs are in column order. + let mut above_runs = above.iter().peekable(); + for run in runs.iter_mut() { + while above_runs + .next_if(|other| other.start < run.start) + .is_some() + {} + let matching = above_runs.next_if(|other| { + other.start == run.start && other.end == run.end && other.shades_like(run, keys) + }); + run.tile = match matching { + Some(above_run) => { + if let Some(tile) = tiles.get_mut(above_run.tile) { + extend_quad(&mut tile.top_left, &mut tile.bottom_right, run); + } + above_run.tile + } + None => { + let curve_start = curves.len(); + // Tiles are trimmed to their curves' extents, so the path is known to be + // filled for pixels outside this box. + let mut curves_top_left = point(f32::INFINITY, f32::INFINITY); + let mut curves_bottom_right = point(f32::NEG_INFINITY, f32::NEG_INFINITY); + for curve in listed(keys, input, run.list) { + // The rasterizer snaps tile edges to its subpixel grid, so it can + // shade a pixel just outside a tile. Where the tile is trimmed, that + // pixel would also be outside the box, and be wrongly filled. Dilate + // the box by more than the largest snapping error to prevent this. + const BOX_MARGIN: f32 = MARGIN + 1.0 / 16.0; + + curves_top_left.x = + curves_top_left.x.fast_min(curve.min_x() - BOX_MARGIN); + curves_top_left.y = curves_top_left.y.fast_min(curve.p0.y - BOX_MARGIN); + curves_bottom_right.x = + curves_bottom_right.x.fast_max(curve.max_x() + BOX_MARGIN); + curves_bottom_right.y = + curves_bottom_right.y.fast_max(curve.p1.y + BOX_MARGIN); + curves.push(*curve); + } + tiles.push(PathTile { + paint: 0, + curve_start: curve_start as u32, + curve_count: (curves.len() - curve_start) as u32, + top_left: run.top_left, + bottom_right: run.bottom_right, + reference: grid.cell(run.start, row).top_left(), + backdrop: run.backdrop, + curves_top_left, + curves_bottom_right, + }); + tiles.len() - 1 + } + }; + } + std::mem::swap(above, runs); + } + (tiles, curves) + } +} + +/// Maps finite floats to integers in the same order. +fn ordered_bits(x: f32) -> u32 { + let bits = x.to_bits(); + if bits >> 31 == 1 { + !bits + } else { + bits | 1 << 31 + } +} + +/// Consecutive cells in a row, over columns `start..end`, that would be +/// shaded identically. +#[derive(Clone, Copy)] +struct Run { + start: usize, + end: usize, + backdrop: i32, + /// The cells' list, as a range of `keys`. + list: (usize, usize), + top_left: Point, + bottom_right: Point, + tile: usize, +} + +impl Run { + /// Whether the two have the same backdrop and list the same curves. + fn shades_like(&self, other: &Run, keys: &[u64]) -> bool { + self.backdrop == other.backdrop + && keys.get(self.list.0..self.list.1) == keys.get(other.list.0..other.list.1) + } +} + +/// Grows a quad to cover a run's quad. +fn extend_quad(top_left: &mut Point, bottom_right: &mut Point, run: &Run) { + top_left.x = top_left.x.fast_min(run.top_left.x); + top_left.y = top_left.y.fast_min(run.top_left.y); + bottom_right.x = bottom_right.x.fast_max(run.bottom_right.x); + bottom_right.y = bottom_right.y.fast_max(run.bottom_right.y); +} + +/// The curves in a range of `keys`. +fn listed<'a>( + keys: &'a [u64], + input: &'a [PathCurve], + list: (usize, usize), +) -> impl Iterator { + keys.get(list.0..list.1) + .unwrap_or_default() + .iter() + .filter_map(move |&key| input.get(key as u32 as usize)) +} + +struct Grid { + left: f32, + top: f32, + cell_size: f32, + columns: usize, + rows: usize, +} + +impl Grid { + fn covering(min: Point, max: Point, curves: usize, length: f32) -> Option { + let left = (min.x - MARGIN).floor(); + let top = (min.y - MARGIN).floor(); + let size = point(max.x + MARGIN - left, max.y + MARGIN - top); + if !(size.x.is_finite() && size.y.is_finite()) { + return None; + } + let cell_size = cell_size(curves as f32, length, size); + Some(Self { + left, + top, + cell_size, + columns: (size.x / cell_size) as usize + 1, + rows: (size.y / cell_size) as usize + 1, + }) + } + + fn column_of(&self, x: f32) -> usize { + let column = (x - self.left) / self.cell_size; + column.fast_clamp(0.0, (self.columns - 1) as f32) as u32 as usize + } + + fn row_of(&self, y: f32) -> usize { + let row = (y - self.top) / self.cell_size; + row.fast_clamp(0.0, (self.rows - 1) as f32) as u32 as usize + } + + fn x(&self, column: usize) -> f32 { + self.left + column as f32 * self.cell_size + } + + fn y(&self, row: usize) -> f32 { + self.top + row as f32 * self.cell_size + } + + fn cell(&self, column: usize, row: usize) -> Cell { + Cell { + left: self.x(column), + top: self.y(row), + right: self.x(column + 1), + bottom: self.y(row + 1), + } + } +} + +#[derive(Clone, Copy)] +struct Cell { + left: f32, + top: f32, + right: f32, + bottom: f32, +} + +impl Cell { + fn top_left(self) -> Point { + point(self.left, self.top) + } + + fn bottom_right(self) -> Point { + point(self.right, self.bottom) + } +} + +/// Accumulates the bounds and windings of a cell's curves, to trim its quad. +struct Measure { + cell: Cell, + backdrop: i32, + min: Point, + max: Point, + /// Left of and above every curve, no correction applies, so the winding + /// is the backdrop. Right of every curve, it is the backdrop plus the + /// curves crossing the cell's top; below every curve, the backdrop + /// corrected for the endpoints beside the cell's left edge. + right_winding: i32, + bottom_winding: i32, +} + +impl Measure { + fn new(cell: Cell, backdrop: i32) -> Self { + Self { + cell, + backdrop, + min: point(f32::INFINITY, f32::INFINITY), + max: point(f32::NEG_INFINITY, f32::NEG_INFINITY), + right_winding: backdrop, + bottom_winding: backdrop, + } + } + + #[inline(always)] + fn add(&mut self, curve: &PathCurve) { + let cell = self.cell; + self.min.x = self.min.x.fast_min(curve.min_x()); + self.max.x = self.max.x.fast_max(curve.max_x()); + self.min.y = self.min.y.fast_min(curve.p0.y); + self.max.y = self.max.y.fast_max(curve.p1.y); + if curve.crosses(cell.top) { + self.right_winding += curve.step(); + } + for (endpoint, step) in curve.endpoints() { + if endpoint.x <= cell.left && endpoint.y > cell.top { + self.bottom_winding -= step; + } + } + } + + /// The top-left and bottom-right corners of the quad to shade, if any: + /// the cell, trimmed to within `MARGIN` of the curves on each side where + /// the winding beyond them leaves pixels unfilled. + #[inline(always)] + fn quad(&self, even_odd: bool) -> Option<(Point, Point)> { + let cell = self.cell; + let clamp_x = |x: f32| x.fast_clamp(cell.left, cell.right); + let clamp_y = |y: f32| y.fast_clamp(cell.top, cell.bottom); + let unfilled = !fills(self.backdrop, even_odd); + let left = if unfilled { + clamp_x(self.min.x - MARGIN) + } else { + cell.left + }; + let top = if unfilled { + clamp_y(self.min.y - MARGIN) + } else { + cell.top + }; + let right = if fills(self.right_winding, even_odd) { + cell.right + } else { + clamp_x(self.max.x + MARGIN) + }; + let bottom = if fills(self.bottom_winding, even_odd) { + cell.bottom + } else { + clamp_y(self.max.y + MARGIN) + }; + (left < right && top < bottom).then(|| (point(left, top), point(right, bottom))) + } +} + +impl PathCurve { + fn scaled(&self, scale: f32) -> Self { + let scale_point = |p: Point| point(p.x * scale, p.y * scale); + Self { + p0: scale_point(self.p0), + p1: scale_point(self.p1), + a: scale_point(self.a), + b: scale_point(self.b), + sign: self.sign, + pad: 0, + } + } + + fn min_x(&self) -> f32 { + self.p0.x.fast_min(self.p1.x) + } + + fn max_x(&self) -> f32 { + self.p0.x.fast_max(self.p1.x) + } + + fn step(&self) -> i32 { + if self.sign < 0.0 { -1 } else { 1 } + } + + /// Whether the curve crosses the horizontal line at `y`. It's half-open, + /// so where two curves meet on the line, exactly one of them crosses it. + fn crosses(&self, y: f32) -> bool { + self.p0.y <= y && y < self.p1.y + } + + /// Each endpoint with the step the shader corrects for it. + fn endpoints(&self) -> [(Point, i32); 2] { + [(self.p0, self.step()), (self.p1, -self.step())] + } + + /// The curve's x extent between two heights. + fn x_range(&self, top: f32, bottom: f32) -> (f32, f32) { + let top = top.fast_max(self.p0.y); + let bottom = bottom.fast_min(self.p1.y); + let x_top = if top <= self.p0.y { + self.p0.x + } else { + self.x_at_y(top) + }; + let x_bottom = if bottom >= self.p1.y { + self.p1.x + } else { + self.x_at_y(bottom) + }; + // Clamped so rounding can't carry the range past the curve's extent. + ( + x_top.fast_min(x_bottom).fast_max(self.min_x()), + x_top.fast_max(x_bottom).fast_min(self.max_x()), + ) + } + + fn x_at_y(&self, y: f32) -> f32 { + if self.a.y == 0.0 { + if self.b.y == 0.0 { + return self.p0.x; + } + let t = ((y - self.p0.y) / self.b.y).fast_clamp(0.0, 1.0); + return (self.a.x * t + self.b.x) * t + self.p0.x; + } + let t = monotone_quadratic_root(self.a.y, self.b.y, self.p0.y - y, 1.0); + (self.a.x * t + self.b.x) * t + self.p0.x + } +} + +/// Solves a*t^2 + b*t + c = 0 for the root in [0, 1] on a monotone piece. +fn monotone_quadratic_root(a: f32, b: f32, c: f32, direction: f32) -> f32 { + let discriminant = (b * b - 4.0 * a * c).fast_max(0.0); + let denominator = b + direction * discriminant.sqrt(); + if denominator == 0.0 { + return 0.0; + } + (-2.0 * c / denominator).fast_clamp(0.0, 1.0) +} + +#[cfg(test)] +mod tests { + use super::*; + use crate::{ + ContentMask, Outline, PaintedPath, Path, PathBuilder, Pixels, Scene, black, px, size, + }; + + /// A rectangle spanning many cells is four edge strips, four corners and + /// one interior, however many cells it covers. + #[test] + fn rectangle_is_nine_tiles() { + let path = square(100., 40., 900., 600.); + assert_eq!(path.bin(1.25).tiles().len(), 9); + } + + /// A path far larger than the window is binned coarsely, and painting it + /// keeps only the tiles its clip shows. + #[test] + fn huge_path_paints_only_visible_tiles() { + let path = square(-20000., -20000., 20000., 20000.); + let tile_count = path.bin(1.5).tiles().len(); + assert!(tile_count < 10_000, "{tile_count} tiles"); + + let mask = Bounds { + origin: point(px(300.), px(200.)), + size: size(px(120.), px(90.)), + }; + let mut scene = Scene::default(); + scene.insert_primitive(PaintedPath::new( + path, + 1.5, + ContentMask { bounds: mask }, + black().into(), + )); + scene.finish(); + let painted: usize = scene.paths.iter().map(PaintedPath::tile_count).sum(); + assert!(painted > 0 && painted < 20, "{painted} tiles"); + } + + /// A path whose size overflows, at some scale or at any, is skipped. + #[test] + fn overflowing_paths_are_skipped() { + let radius = f32::MAX / 4.0; + let path = square(-radius, -radius, radius, radius); + assert!(!path.bin(1.0).tiles().is_empty()); + assert!(path.bin(4.0).tiles().is_empty()); + let radius = f32::MAX * 0.75; + let path = square(-radius, -radius, radius, radius); + assert!(path.bin(1.0).tiles().is_empty()); + } + + /// A non-finite point fails the whole path. Dropping only its segments + /// would leave its contour open. + #[test] + fn non_finite_point_fails_path() { + // Built directly, since lyon asserts its points are finite in debug + // builds. + let mut outline = Outline::default(); + outline.move_to(point(0., 0.)); + outline.line_to(point(10., 0.)); + outline.line_to(point(10., 10.)); + outline.move_to(point(20., 0.)); + outline.line_to(point(f32::NAN, 5.)); + outline.line_to(point(30., 10.)); + assert!(outline.into_curves().is_err()); + } + + /// The shader's backdrop corrections need curves that meet to share + /// bit-identical endpoints. A break shows up as streaks, not as a + /// failure, so check it directly. + #[test] + fn endpoints_balance() { + let mut curved_fill = PathBuilder::fill(); + curved_fill.move_to(point(px(450.3), px(280.7))); + curved_fill.curve_to(point(px(530.3), px(230.7)), point(px(450.3), px(230.7))); + curved_fill.arc_to( + point(px(30.), px(30.)), + px(0.), + false, + false, + point(px(590.3), px(230.7)), + ); + curved_fill.close(); + + let mut stroke = PathBuilder::stroke(px(2.)); + stroke.move_to(point(px(80.3), px(500.7))); + stroke.cubic_bezier_to( + point(px(900.), px(250.)), + point(px(300.), px(50.)), + point(px(700.), px(800.)), + ); + + let mut dashed = PathBuilder::stroke(px(3.)).dash_array(&[px(9.), px(4.)]); + dashed.move_to(point(px(50.3), px(10.7))); + dashed.arc_to( + point(px(40.), px(40.)), + px(0.), + false, + true, + point(px(90.3), px(50.7)), + ); + + for (name, builder) in [ + ("curved fill", curved_fill), + ("stroke", stroke), + ("dashed stroke", dashed), + ] { + let (curves, _) = builder.outline().unwrap(); + let mut balance = collections::HashMap::<(u32, u32), i32>::default(); + for curve in &curves { + for (endpoint, step) in curve.endpoints() { + *balance + .entry((endpoint.x.to_bits(), endpoint.y.to_bits())) + .or_default() += step; + } + } + assert!(!balance.is_empty(), "{name} produced no curves"); + for ((x, y), sum) in balance { + assert_eq!( + sum, + 0, + "{name}: endpoints at ({}, {}) do not balance", + f32::from_bits(x), + f32::from_bits(y), + ); + } + } + } + + fn square(left: f32, top: f32, right: f32, bottom: f32) -> Path { + let mut builder = PathBuilder::fill(); + let corners = [(left, top), (right, top), (right, bottom), (left, bottom)]; + let points: Vec> = + corners.iter().map(|&(x, y)| point(px(x), px(y))).collect(); + builder.add_polygon(&points, true); + builder.build().unwrap() + } +} diff --git a/crates/gpui/src/platform.rs b/crates/gpui/src/platform.rs index b84bcc5c092..1f344f2f46a 100644 --- a/crates/gpui/src/platform.rs +++ b/crates/gpui/src/platform.rs @@ -209,7 +209,7 @@ impl ActivityGuard { #[inline] pub fn guess_compositor() -> &'static str { if std::env::var_os("ZED_HEADLESS").is_some() { - return "Headless"; + return "headless"; } GraphicalEnvironment::detect().guess_compositor() } @@ -231,6 +231,11 @@ pub struct GraphicalEnvironment { pub x11_display: Option, /// `XDG_RUNTIME_DIR`: the directory containing Wayland sockets. pub xdg_runtime_dir: Option, + /// `XDG_CURRENT_DESKTOP`: the session's desktop environment, such as `ubuntu:GNOME`. + /// + /// Only reported by [`GraphicalEnvironment::desktop_environment`]; [`GraphicalEnvironment::apply_to`] + /// leaves it alone. + pub current_desktop: Option, /// `XDG_ACTIVATION_TOKEN`: lets the first window take focus on Wayland. /// /// A platform takes this process's token from its environment when it's created, and uses @@ -272,6 +277,11 @@ impl GraphicalEnvironment { /// Does nothing on this platform: programs inherit the session of the process that /// starts them. pub fn apply_to(&self, _command: &mut std::process::Command) {} + + /// Returns `None`: this platform has no desktop environments to tell apart. + pub fn desktop_environment(&self) -> Option { + None + } } /// The graphical session to connect to. Carries nothing yet on this platform. @@ -288,6 +298,11 @@ impl GraphicalEnvironment { /// Does nothing on this platform. pub fn apply_to(&self, _command: &mut std::process::Command) {} + + /// Returns `None`: this platform has no desktop environments to tell apart. + pub fn desktop_environment(&self) -> Option { + None + } } /// A display mode for [`App::request_windowing`] to switch to. @@ -310,6 +325,7 @@ impl GraphicalEnvironment { wayland_display: std::env::var_os("WAYLAND_DISPLAY"), x11_display: std::env::var_os("DISPLAY"), xdg_runtime_dir: std::env::var_os("XDG_RUNTIME_DIR"), + current_desktop: std::env::var_os("XDG_CURRENT_DESKTOP"), activation_token: None, } } @@ -330,6 +346,18 @@ impl GraphicalEnvironment { } } + /// Returns the session's desktop environment, if `XDG_CURRENT_DESKTOP` names one. + /// + /// The value is a colon-separated list ordered from most to least specific, + /// such as `ubuntu:GNOME`. + pub fn desktop_environment(&self) -> Option { + self.current_desktop + .as_ref() + .and_then(|desktop| desktop.to_str()) + .filter(|desktop| !desktop.is_empty()) + .map(str::to_owned) + } + /// Returns the compositor this environment selects: Wayland, then X11, then headless. /// /// Does not attempt to connect to the compositor. @@ -341,7 +369,7 @@ impl GraphicalEnvironment { } else if cfg!(feature = "x11") && is_set(&self.x11_display) { "X11" } else { - "Headless" + "headless" } } } @@ -510,6 +538,11 @@ pub trait Platform: 'static { fn on_will_open_app_menu(&self, callback: Box); fn on_validate_app_menu_command(&self, callback: Box bool>); + /// Platform-specific diagnostic state, for [`App::debug_state`]. + fn debug_state(&self) -> serde_json::Value { + serde_json::Value::Null + } + fn thermal_state(&self) -> ThermalState; fn on_thermal_state_change(&self, callback: Box); fn prevent_idle_sleep(&self, reason: &str) -> Task>; @@ -1304,6 +1337,10 @@ pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle { fn zoom(&self); fn toggle_fullscreen(&self); fn is_fullscreen(&self) -> bool; + /// Platform-specific diagnostic state, for [`App::debug_state`]. + fn debug_state(&self) -> serde_json::Value { + serde_json::Value::Null + } fn frame_waker(&self) -> Option> { None } @@ -1349,6 +1386,8 @@ pub trait PlatformWindow: HasWindowHandle + HasDisplayHandle { } #[cfg(target_os = "macos")] fn set_traffic_light_position(&self, _position: Point) {} + #[cfg(target_os = "macos")] + fn set_native_titlebar_visibility(&self, _visible: bool) {} fn show_character_palette(&self) {} fn titlebar_double_click(&self, _is_resizable: bool, _is_minimizable: bool) {} fn on_move_tab_to_new_window(&self, _callback: Box) {} @@ -2659,8 +2698,8 @@ pub struct WindowOptions { /// Whether the window should be minimized by the user pub is_minimizable: bool, - /// The display to create the window on, if this is None, - /// the window will be created on the main display + /// The display to create the window on. If neither this nor `window_bounds` is set, the window + /// is created on the active window's display. Otherwise, it falls back to the primary display. pub display_id: Option, /// The appearance of the window background. @@ -2783,9 +2822,10 @@ impl WindowBounds { } } - /// Creates a new window bounds that centers the window on the screen. - pub fn centered(size: Size, cx: &App) -> Self { - WindowBounds::Windowed(Bounds::centered(None, size, cx)) + /// Creates window bounds centered on the given display, or the primary display if none is + /// provided. + pub fn centered(display_id: Option, size: Size, cx: &App) -> Self { + WindowBounds::Windowed(Bounds::centered(display_id, size, cx)) } } @@ -3010,7 +3050,9 @@ impl From<&str> for PromptButton { } /// The style of the cursor (pointer) -#[derive(Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema)] +#[derive( + Copy, Clone, Default, Debug, PartialEq, Eq, Hash, Serialize, Deserialize, JsonSchema, EnumIter, +)] pub enum CursorStyle { /// The default cursor #[default] diff --git a/crates/gpui/src/platform/test/window.rs b/crates/gpui/src/platform/test/window.rs index 4a8ccc67ee4..ff1c4cd3805 100644 --- a/crates/gpui/src/platform/test/window.rs +++ b/crates/gpui/src/platform/test/window.rs @@ -1,10 +1,10 @@ use crate::{ - AnyWindowHandle, Bounds, DevicePixels, DispatchEventResult, DisplayId, GpuSpecs, HeadlessAtlas, - Pixels, PlatformAtlas, PlatformDisplay, PlatformHeadlessRenderer, PlatformInput, - PlatformInputHandler, PlatformWindow, Point, PromptButton, RequestFrameOptions, Scene, Size, - TestDisplay, TestPlatform, TextInputConfiguration, TextInputStateChange, WindowAppearance, - WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowInsets, WindowParams, - WindowVisibility, + AnyWindowHandle, Bounds, Decorations, DevicePixels, DispatchEventResult, DisplayId, GpuSpecs, + HeadlessAtlas, Pixels, Platform, PlatformAtlas, PlatformDisplay, PlatformHeadlessRenderer, + PlatformInput, PlatformInputHandler, PlatformWindow, Point, PromptButton, RequestFrameOptions, + Scene, Size, TestDisplay, TestPlatform, TextInputConfiguration, TextInputStateChange, + WindowAppearance, WindowBackgroundAppearance, WindowBounds, WindowControlArea, WindowInsets, + WindowParams, WindowVisibility, }; use gpui_util::ResultExt as _; #[cfg(any(test, feature = "test-support"))] @@ -57,6 +57,7 @@ pub(crate) struct TestWindowState { is_fullscreen: bool, scale_factor: f32, appearance: WindowAppearance, + decorations: Decorations, external_drag_files: Vec<(PathBuf, bool)>, start_external_drag_result: bool, } @@ -133,6 +134,7 @@ impl TestWindow { // Preserve the test platform's historical 2x default. scale_factor: 2.0, appearance: WindowAppearance::Light, + decorations: Decorations::default(), external_drag_files: Vec::new(), start_external_drag_result: false, }))) @@ -277,6 +279,17 @@ impl TestWindow { self.0.lock().appearance_change_callback = Some(callback); } + pub fn simulate_decorations_change(&self, decorations: Decorations) { + let mut lock = self.0.lock(); + lock.decorations = decorations; + let Some(mut callback) = lock.appearance_change_callback.take() else { + return; + }; + drop(lock); + callback(); + self.0.lock().appearance_change_callback = Some(callback); + } + /// Returns how many times this window's frame waker has been invoked. pub fn frame_wake_count(&self) -> usize { self.0.lock().frame_wake_count.get() @@ -478,8 +491,21 @@ impl PlatformWindow for TestWindow { } fn toggle_fullscreen(&self) { - let mut lock = self.0.lock(); - lock.is_fullscreen = !lock.is_fullscreen; + let platform = { + let mut lock = self.0.lock(); + lock.is_fullscreen = !lock.is_fullscreen; + lock.platform.upgrade() + }; + if let Some(platform) = platform { + let mut window = self.clone(); + platform + .foreground_executor() + .spawn(async move { + let size = window.0.lock().bounds.size; + window.simulate_resize(size); + }) + .detach(); + } } fn is_fullscreen(&self) -> bool { @@ -619,4 +645,8 @@ impl PlatformWindow for TestWindow { fn gpu_specs(&self) -> Option { None } + + fn window_decorations(&self) -> Decorations { + self.0.lock().decorations + } } diff --git a/crates/gpui/src/randomized_element_tree.rs b/crates/gpui/src/randomized_element_tree.rs index f8125c3183a..a34975a24cb 100644 --- a/crates/gpui/src/randomized_element_tree.rs +++ b/crates/gpui/src/randomized_element_tree.rs @@ -1713,8 +1713,8 @@ mod tests { #[derive(Debug, PartialEq)] struct SceneSnapshot { quads: Vec, - /// Every other primitive kind, formatted without the per-window atlas tile and - /// path IDs, which differ between two windows drawing the same scene. + /// Every other primitive kind, formatted without the per-window atlas tile + /// IDs, which differ between two windows drawing the same scene. other_primitives: Vec, element_ids: BTreeSet, } @@ -1732,12 +1732,7 @@ mod tests { .iter() .map(|underline| format!("{underline:?}")), ) - .chain(scene.paths.iter().map(|path| { - format!( - "path {} {:?} {:?} {:?} {:?}", - path.order, path.bounds, path.content_mask, path.color, path.vertices - ) - })) + .chain(scene.paths.iter().map(|path| format!("{path:?}"))) .chain(scene.monochrome_sprites.iter().map(|sprite| { format!( "monochrome {} {:?} {:?} {:?} {:?}", diff --git a/crates/gpui/src/scene.rs b/crates/gpui/src/scene.rs index a4116aa5251..b28e25b7881 100644 --- a/crates/gpui/src/scene.rs +++ b/crates/gpui/src/scene.rs @@ -5,19 +5,11 @@ use schemars::JsonSchema; use serde::{Deserialize, Serialize}; use crate::{ - AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, Edges, Hsla, Pixels, - Point, Radians, ScaledPixels, Size, bounds_tree::BoundsTree, point, + AtlasTextureId, AtlasTile, Background, Bounds, ContentMask, Corners, Edges, Hsla, Path, + PathTiles, Pixels, Point, Radians, ScaledPixels, Size, bounds_tree::BoundsTree, }; -use std::{ - fmt::Debug, - iter::Peekable, - ops::{Add, Range, Sub}, - slice, -}; - -#[allow(non_camel_case_types, unused)] -#[expect(missing_docs)] -pub type PathVertex_ScaledPixels = PathVertex; +use smallvec::SmallVec; +use std::{collections::VecDeque, fmt::Debug, iter::Peekable, ops::Range, rc::Rc, slice}; #[expect(missing_docs)] pub type DrawOrder = u32; @@ -36,15 +28,30 @@ impl From for PaddedBool32 { } } +impl PaddedBool32 { + /// The wrapped boolean. + pub fn as_bool(self) -> bool { + self.0 != 0 + } +} + +struct Layer { + primitives: SmallVec<[Range; 1]>, + bounds: Bounds, + max_kind: PrimitiveKind, + max_shared_kind: PrimitiveKind, +} + #[derive(Default)] #[expect(missing_docs)] pub struct Scene { pub(crate) paint_operations: Vec, primitive_bounds: BoundsTree, - layer_stack: Vec, + layer_stack: Vec, + layers: VecDeque, pub shadows: Vec, pub quads: Vec, - pub paths: Vec>, + pub paths: Vec, pub underlines: Vec, pub monochrome_sprites: Vec, pub subpixel_sprites: Vec, @@ -58,6 +65,7 @@ impl Scene { self.paint_operations.clear(); self.primitive_bounds.clear(); self.layer_stack.clear(); + self.layers.clear(); self.paths.clear(); self.shadows.clear(); self.quads.clear(); @@ -72,93 +80,124 @@ impl Scene { self.paint_operations.len() } - pub fn push_layer(&mut self, bounds: Bounds) { - let order = self.primitive_bounds.insert(bounds); - self.layer_stack.push(order); - self.paint_operations - .push(PaintOperation::StartLayer(bounds)); + pub fn push_layer(&mut self) { + self.layer_stack.push(self.layers.len()); + self.layers.push_back(Layer { + primitives: SmallVec::new(), + bounds: Bounds::default(), + max_kind: PrimitiveKind::Shadow, + max_shared_kind: PrimitiveKind::Surface, + }); + self.paint_operations.push(PaintOperation::StartLayer); } pub fn pop_layer(&mut self) { self.layer_stack.pop(); + if self.layer_stack.is_empty() { + while let Some(layer) = self.layers.pop_front() { + self.insert_layer(layer); + } + } self.paint_operations.push(PaintOperation::EndLayer); } - pub fn insert_primitive(&mut self, primitive: impl Into) { - let mut primitive = primitive.into(); - let clipped_bounds = primitive - .bounds() - .intersect(&primitive.content_mask().bounds); + fn insert_layer(&mut self, layer: Layer) { + if layer.primitives.is_empty() { + return; + } + let order = + self.primitive_bounds + .insert(layer.bounds, layer.max_kind, layer.max_shared_kind); + for index in layer.primitives.into_iter().flatten() { + if let PaintOperation::Primitive(primitive) = &self.paint_operations[index] { + let primitive = primitive.clone(); + self.push_primitive(primitive, order); + } + } + } + pub fn insert_primitive(&mut self, primitive: impl Into) { + let primitive = primitive.into(); + let clipped_bounds = primitive.clipped_bounds(); if clipped_bounds.is_empty() { return; } - let order = self - .layer_stack - .last() - .copied() - .unwrap_or_else(|| self.primitive_bounds.insert(clipped_bounds)); - match &mut primitive { - Primitive::Shadow(shadow) => { - shadow.order = order; - self.shadows.push(*shadow); - } - Primitive::Quad(quad) => { - quad.order = order; - self.quads.push(*quad); - } - Primitive::Path(path) => { - path.order = order; - path.id = PathId(self.paths.len()); - self.paths.push(path.clone()); - } - Primitive::Underline(underline) => { - underline.order = order; - self.underlines.push(*underline); - } - Primitive::MonochromeSprite(sprite) => { - sprite.order = order; - self.monochrome_sprites.push(*sprite); - } - Primitive::SubpixelSprite(sprite) => { - sprite.order = order; - self.subpixel_sprites.push(*sprite); - } - Primitive::PolychromeSprite(sprite) => { - sprite.order = order; - self.polychrome_sprites.push(*sprite); - } - Primitive::Surface(surface) => { - surface.order = order; - self.surfaces.push(surface.clone()); + let kind = primitive.kind(); + if let Some(&layer) = self.layer_stack.last() + && let Some(layer) = self.layers.get_mut(layer) + { + layer.bounds = layer.bounds.join(&clipped_bounds); + layer.max_kind = layer.max_kind.max(kind); + layer.max_shared_kind = layer.max_shared_kind.min(kind.max_shared_kind()); + let index = self.paint_operations.len(); + match layer.primitives.last_mut() { + Some(range) if range.end == index => range.end += 1, + _ => layer.primitives.push(index..index + 1), } + } else { + let order = self + .primitive_bounds + .insert(clipped_bounds, kind, kind.max_shared_kind()); + self.push_primitive(primitive.clone(), order); } self.paint_operations .push(PaintOperation::Primitive(primitive)); } + fn push_primitive(&mut self, primitive: Primitive, order: DrawOrder) { + match primitive { + Primitive::Shadow(shadow) => self.shadows.push(Shadow { order, ..shadow }), + Primitive::Quad(quad) => self.quads.push(Quad { order, ..quad }), + Primitive::Path(mut path) => { + path.order = order; + self.paths.push(path); + } + Primitive::Underline(underline) => { + self.underlines.push(Underline { order, ..underline }) + } + Primitive::MonochromeSprite(sprite) => self + .monochrome_sprites + .push(MonochromeSprite { order, ..sprite }), + Primitive::SubpixelSprite(sprite) => self + .subpixel_sprites + .push(SubpixelSprite { order, ..sprite }), + Primitive::PolychromeSprite(sprite) => self + .polychrome_sprites + .push(PolychromeSprite { order, ..sprite }), + Primitive::Surface(mut surface) => { + surface.order = order; + self.surfaces.push(surface); + } + } + } + pub fn replay(&mut self, range: Range, prev_scene: &Scene) { for operation in &prev_scene.paint_operations[range] { match operation { PaintOperation::Primitive(primitive) => self.insert_primitive(primitive.clone()), - PaintOperation::StartLayer(bounds) => self.push_layer(*bounds), + PaintOperation::StartLayer => self.push_layer(), PaintOperation::EndLayer => self.pop_layer(), } } } pub fn finish(&mut self) { - self.shadows.sort_by_key(|shadow| shadow.order); - self.quads.sort_by_key(|quad| quad.order); + debug_assert!(self.layer_stack.is_empty(), "unbalanced scene layers"); + let keys = &mut Vec::new(); + sort_in_place(&mut self.shadows, keys, |shadow| (shadow.order, 0)); + sort_in_place(&mut self.quads, keys, |quad| (quad.order, 0)); self.paths.sort_by_key(|path| path.order); - self.underlines.sort_by_key(|underline| underline.order); - self.monochrome_sprites - .sort_by_key(|sprite| (sprite.order, sprite.tile.texture_id.index)); - self.subpixel_sprites - .sort_by_key(|sprite| (sprite.order, sprite.tile.texture_id.index)); - self.polychrome_sprites - .sort_by_key(|sprite| (sprite.order, sprite.tile.texture_id.index)); + sort_in_place(&mut self.underlines, keys, |underline| (underline.order, 0)); + sort_in_place(&mut self.monochrome_sprites, keys, |sprite| { + (sprite.order, sprite.tile.texture_id.index) + }); + sort_in_place(&mut self.subpixel_sprites, keys, |sprite| { + (sprite.order, sprite.tile.texture_id.index) + }); + sort_in_place(&mut self.polychrome_sprites, keys, |sprite| { + (sprite.order, sprite.tile.texture_id.index) + }); self.surfaces.sort_by_key(|surface| surface.order); } @@ -191,6 +230,57 @@ impl Scene { } } +/// Sorts small `(key, index)` pairs instead of the primitives themselves, then moves each +/// primitive into place once. Primitives are large, so a comparison sort that shuffles them +/// directly spends most of its time copying. Ties keep insertion order, as `sort_by_key` +/// does, because the index is part of what is sorted. +fn sort_in_place( + primitives: &mut [T], + keys: &mut Vec<(u64, u32)>, + key: impl Fn(&T) -> (u32, u32), +) { + if primitives.is_sorted_by_key(&key) { + return; + } + keys.clear(); + keys.extend(primitives.iter().enumerate().map(|(index, primitive)| { + let (major, minor) = key(primitive); + ((major as u64) << 32 | minor as u64, index as u32) + })); + keys.sort_unstable(); + + // `keys[target].1` is the source index for `target`. Follow each cycle of that + // permutation, marking visited slots by pointing them at themselves. + for start in 0..primitives.len() { + if keys[start].1 as usize == start { + continue; + } + let displaced = primitives[start]; + let mut target = start; + loop { + let source = keys[target].1 as usize; + keys[target].1 = target as u32; + if source == start { + primitives[target] = displaced; + break; + } + primitives[target] = primitives[source]; + target = source; + } + } +} + +/// The depth step between consecutive quads in a frame with `quad_count` quads. +pub fn quad_depth_scale(quad_count: usize) -> f32 { + let denominator = (quad_count.min((1 << 24) - 1) + 1).next_power_of_two(); + 1.0 / denominator as f32 +} + +/// Maps a quad's index in [`Scene::quads`] to depth, with greater values closer. +pub fn quad_depth(quad_id: u32, scale: f32) -> f32 { + ((quad_id + 1) as f32 * scale).min(1.0) +} + #[derive(Clone, Copy, Debug, Eq, PartialEq, Ord, PartialOrd, Default)] #[cfg_attr( all( @@ -211,9 +301,26 @@ pub(crate) enum PrimitiveKind { Surface, } +impl PrimitiveKind { + /// We guarantee that overlapping primitives are drawn in paint order. + /// But, to improve GPU draw batching, the renderer sorts primitives that + /// share a draw order by kind, then by atlas texture, and only then in + /// paint order. So, a primitive can only share the draw order of the + /// topmost primitive it overlaps if that primitive's kind is at most the + /// one returned here. Otherwise, it needs a new draw order. + fn max_shared_kind(self) -> Self { + match self { + Self::MonochromeSprite => Self::Underline, + Self::SubpixelSprite => Self::MonochromeSprite, + Self::PolychromeSprite => Self::SubpixelSprite, + kind => kind, + } + } +} + pub(crate) enum PaintOperation { Primitive(Primitive), - StartLayer(Bounds), + StartLayer, EndLayer, } @@ -222,7 +329,7 @@ pub(crate) enum PaintOperation { pub enum Primitive { Shadow(Shadow), Quad(Quad), - Path(Path), + Path(PaintedPath), Underline(Underline), MonochromeSprite(MonochromeSprite), SubpixelSprite(SubpixelSprite), @@ -232,6 +339,19 @@ pub enum Primitive { #[expect(missing_docs)] impl Primitive { + pub(crate) fn kind(&self) -> PrimitiveKind { + match self { + Primitive::Shadow(_) => PrimitiveKind::Shadow, + Primitive::Quad(_) => PrimitiveKind::Quad, + Primitive::Path(_) => PrimitiveKind::Path, + Primitive::Underline(_) => PrimitiveKind::Underline, + Primitive::MonochromeSprite(_) => PrimitiveKind::MonochromeSprite, + Primitive::SubpixelSprite(_) => PrimitiveKind::SubpixelSprite, + Primitive::PolychromeSprite(_) => PrimitiveKind::PolychromeSprite, + Primitive::Surface(_) => PrimitiveKind::Surface, + } + } + pub fn bounds(&self) -> &Bounds { match self { Primitive::Shadow(shadow) => &shadow.bounds, @@ -245,11 +365,25 @@ impl Primitive { } } + fn transformation(&self) -> TransformationMatrix { + match self { + Primitive::MonochromeSprite(sprite) => sprite.transformation, + Primitive::SubpixelSprite(sprite) => sprite.transformation, + _ => TransformationMatrix::unit(), + } + } + + fn clipped_bounds(&self) -> Bounds { + self.transformation() + .transform_bounds(*self.bounds()) + .intersect(&self.content_mask().bounds) + } + pub fn content_mask(&self) -> &ContentMask { match self { Primitive::Shadow(shadow) => &shadow.content_mask, Primitive::Quad(quad) => &quad.content_mask, - Primitive::Path(path) => &path.content_mask, + Primitive::Path(path) => &path.paint.content_mask, Primitive::Underline(underline) => &underline.content_mask, Primitive::MonochromeSprite(sprite) => &sprite.content_mask, Primitive::SubpixelSprite(sprite) => &sprite.content_mask, @@ -272,7 +406,7 @@ struct BatchIterator<'a> { quads_start: usize, quads_iter: Peekable>, paths_start: usize, - paths_iter: Peekable>>, + paths_iter: Peekable>, underlines_start: usize, underlines_iter: Peekable>, monochrome_sprites_start: usize, @@ -295,7 +429,10 @@ impl<'a> Iterator for BatchIterator<'a> { PrimitiveKind::Shadow, ), (self.quads_iter.peek().map(|q| q.order), PrimitiveKind::Quad), - (self.paths_iter.peek().map(|q| q.order), PrimitiveKind::Path), + ( + self.paths_iter.peek().map(|path| path.order), + PrimitiveKind::Path, + ), ( self.underlines_iter.peek().map(|u| u.order), PrimitiveKind::Underline, @@ -578,10 +715,9 @@ pub struct Shadow { pub corner_radii: Corners, pub content_mask: ContentMask, pub color: Hsla, - pub element_bounds: Bounds, - pub element_corner_radii: Corners, - /// 0 = drop shadow (rendered outside the element), 1 = inset shadow (rendered inside). - pub inset: u32, + pub shape_bounds: Bounds, + pub shape_corner_radii: Corners, + pub inset: PaddedBool32, pub pad: u32, // align to 8 bytes } @@ -686,6 +822,31 @@ impl TransformationMatrix { } } + /// The smallest bounds that contain `bounds` once it is transformed. + pub(crate) fn transform_bounds(&self, bounds: Bounds) -> Bounds { + if *self == Self::unit() { + return bounds; + } + let [[xx, xy], [yx, yy]] = self.rotation_scale; + let [translate_x, translate_y] = self.translation; + let corners = [ + bounds.origin, + bounds.top_right(), + bounds.bottom_left(), + bounds.bottom_right(), + ] + .map(|corner| { + Point::new( + ScaledPixels(xx * corner.x.0 + xy * corner.y.0 + translate_x), + ScaledPixels(yx * corner.x.0 + yy * corner.y.0 + translate_y), + ) + }); + let [first, rest @ ..] = corners; + let top_left = rest.iter().fold(first, |min, corner| min.min(corner)); + let bottom_right = rest.iter().fold(first, |max, corner| max.max(corner)); + Bounds::from_corners(top_left, bottom_right) + } + /// Apply transformation to a point, mainly useful for debugging pub fn apply(&self, point: Point) -> Point { let input = [point.x.0, point.y.0]; @@ -779,171 +940,215 @@ impl From for Primitive { } } -#[derive(Copy, Clone, Debug, PartialEq, Eq, Hash)] +#[derive(Clone, Copy, Debug, PartialEq)] +#[repr(C)] #[expect(missing_docs)] -pub struct PathId(pub usize); +pub struct PathCurve { + pub p0: Point, + pub p1: Point, + pub a: Point, + pub b: Point, + pub sign: f32, + pub pad: u32, // align to 8 bytes +} + +#[derive(Clone, Copy, Debug)] +#[repr(C)] +#[expect(missing_docs)] +pub struct PathPaint { + /// The path's bounds, in device pixels. + pub bounds: Bounds, + pub content_mask: ContentMask, + pub color: Background, + pub even_odd: PaddedBool32, + pub pad: u32, // align to 8 bytes +} + +#[derive(Clone, Copy, Debug, PartialEq)] +#[repr(C)] +#[expect(missing_docs)] +pub struct PathTile { + pub paint: u32, + pub curve_start: u32, + pub curve_count: u32, + pub backdrop: i32, + pub top_left: Point, + pub bottom_right: Point, + pub reference: Point, + pub curves_top_left: Point, + pub curves_bottom_right: Point, +} -/// A line made up of a series of vertices and control points. #[derive(Clone, Debug)] #[expect(missing_docs)] -pub struct Path { - pub id: PathId, - pub order: DrawOrder, - pub bounds: Bounds

, - pub content_mask: ContentMask

, - pub vertices: Vec>, - pub color: Background, - start: Point

, - current: Point

, - contour_count: usize, +pub struct PaintedPath { + order: DrawOrder, + bounds: Bounds, + tiles: Rc, + paint: PathPaint, } -impl Path { - /// Create a new path with the given starting point. - pub fn new(start: Point) -> Self { +#[expect(missing_docs)] +impl PaintedPath { + /// Bins `path` into tiles, to be filled with `color` within `content_mask`. + pub fn new( + path: Path, + scale_factor: f32, + content_mask: ContentMask, + color: Background, + ) -> Self { + let content_mask = content_mask.scale(scale_factor); + let mut tiles = path.bin(scale_factor); + tiles.retain_visible(content_mask.bounds); + let paint = PathPaint { + bounds: tiles.bounds(), + content_mask, + color, + even_odd: path.even_odd().into(), + pad: 0, + }; Self { - id: PathId(0), - order: DrawOrder::default(), - vertices: Vec::new(), - start, - current: start, - bounds: Bounds { - origin: start, - size: Default::default(), - }, - content_mask: Default::default(), - color: Default::default(), - contour_count: 0, + order: 0, + bounds: tiles.painted_bounds(), + tiles: Rc::new(tiles), + paint, } } - /// Scale this path by the given factor. - pub fn scale(&self, factor: f32) -> Path { - Path { - id: self.id, - order: self.order, - bounds: self.bounds.scale(factor), - content_mask: self.content_mask.scale(factor), - vertices: self - .vertices - .iter() - .map(|vertex| vertex.scale(factor)) - .collect(), - start: self.start.map(|start| start.scale(factor)), - current: self.current.scale(factor), - contour_count: self.contour_count, - color: self.color, - } + pub fn tile_count(&self) -> usize { + self.tiles.tiles().len() } - /// Move the start, current point to the given point. - pub fn move_to(&mut self, to: Point) { - self.contour_count += 1; - self.start = to; - self.current = to; - } - - /// Draw a straight line from the current point to the given point. - pub fn line_to(&mut self, to: Point) { - self.contour_count += 1; - if self.contour_count > 1 { - self.push_triangle( - (self.start, self.current, to), - (point(0., 1.), point(0., 1.), point(0., 1.)), - ); - } - self.current = to; - } - - /// Draw a curve from the current point to the given point, using the given control point. - pub fn curve_to(&mut self, to: Point, ctrl: Point) { - self.contour_count += 1; - if self.contour_count > 1 { - self.push_triangle( - (self.start, self.current, to), - (point(0., 1.), point(0., 1.), point(0., 1.)), - ); - } - - self.push_triangle( - (self.current, ctrl, to), - (point(0., 0.), point(0.5, 0.), point(1., 1.)), - ); - self.current = to; - } - - /// Push a triangle to the Path. - pub fn push_triangle( - &mut self, - xy: (Point, Point, Point), - st: (Point, Point, Point), + pub fn append_to( + &self, + paints: &mut Vec, + curves: &mut Vec, + tiles: &mut Vec, ) { - self.bounds = self - .bounds - .union(&Bounds { - origin: xy.0, - size: Default::default(), - }) - .union(&Bounds { - origin: xy.1, - size: Default::default(), - }) - .union(&Bounds { - origin: xy.2, - size: Default::default(), - }); - - self.vertices.push(PathVertex { - xy_position: xy.0, - st_position: st.0, - content_mask: Default::default(), - }); - self.vertices.push(PathVertex { - xy_position: xy.1, - st_position: st.1, - content_mask: Default::default(), - }); - self.vertices.push(PathVertex { - xy_position: xy.2, - st_position: st.2, - content_mask: Default::default(), - }); + let paint_index = paints.len() as u32; + let curve_start = curves.len() as u32; + paints.push(self.paint); + curves.extend_from_slice(self.tiles.curves()); + tiles.extend(self.tiles.tiles().iter().map(|tile| PathTile { + paint: paint_index, + curve_start: curve_start + tile.curve_start, + ..*tile + })); } } -impl Path -where - T: Clone + Debug + Default + PartialEq + PartialOrd + Add + Sub, -{ - #[allow(unused)] - #[expect(missing_docs)] - pub fn clipped_bounds(&self) -> Bounds { - self.bounds.intersect(&self.content_mask.bounds) - } -} - -impl From> for Primitive { - fn from(path: Path) -> Self { +impl From for Primitive { + fn from(path: PaintedPath) -> Self { Primitive::Path(path) } } -#[derive(Clone, Debug)] -#[repr(C)] -#[expect(missing_docs)] -pub struct PathVertex { - pub xy_position: Point

, - pub st_position: Point, - pub content_mask: ContentMask

, -} +#[cfg(test)] +mod tests { + use super::*; + use crate::{point, size}; -#[expect(missing_docs)] -impl PathVertex { - pub fn scale(&self, factor: f32) -> PathVertex { - PathVertex { - xy_position: self.xy_position.scale(factor), - st_position: self.st_position, - content_mask: self.content_mask.scale(factor), + fn square(x: f32) -> Bounds { + Bounds { + origin: point(ScaledPixels(x), ScaledPixels(0.)), + size: size(ScaledPixels(10.), ScaledPixels(10.)), } } + + fn quad(x: f32) -> Quad { + Quad { + bounds: square(x), + content_mask: ContentMask { bounds: square(x) }, + ..Default::default() + } + } + + fn underline(x: f32) -> Underline { + Underline { + order: 0, + pad: 0, + bounds: square(x), + content_mask: ContentMask { bounds: square(x) }, + color: Hsla::default(), + thickness: ScaledPixels(1.), + wavy: false.into(), + } + } + + fn batch_labels(scene: &mut Scene) -> Vec { + scene.finish(); + scene.batches().map(|batch| batch.label()).collect() + } + + #[test] + fn layers_are_drawn_in_paint_order() { + // A quad painted after a layer goes above it. + let mut scene = Scene::default(); + scene.insert_primitive(quad(0.)); + scene.push_layer(); + scene.insert_primitive(underline(0.)); + scene.insert_primitive(underline(5.)); + scene.pop_layer(); + scene.insert_primitive(quad(5.)); + assert_eq!( + batch_labels(&mut scene), + ["quads (1)", "underlines (2)", "quads (1)"] + ); + + // A layer goes above the layer painted before it. + let mut scene = Scene::default(); + scene.push_layer(); + scene.insert_primitive(underline(0.)); + scene.pop_layer(); + scene.push_layer(); + scene.insert_primitive(quad(5.)); + scene.pop_layer(); + assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]); + } + + #[test] + fn nested_layers_are_drawn_above_their_parents() { + // A layer has one draw order, so what it paints after a nested layer + // still goes below that layer. + let mut scene = Scene::default(); + scene.push_layer(); + scene.insert_primitive(underline(0.)); + scene.push_layer(); + scene.insert_primitive(quad(5.)); + scene.pop_layer(); + scene.insert_primitive(underline(5.)); + scene.pop_layer(); + assert_eq!(batch_labels(&mut scene), ["underlines (2)", "quads (1)"]); + + // The same holds when the nested layer shares its parent's order. + let mut scene = Scene::default(); + scene.push_layer(); + scene.insert_primitive(quad(0.)); + scene.push_layer(); + scene.insert_primitive(quad(5.)); + scene.pop_layer(); + scene.insert_primitive(quad(8.)); + scene.pop_layer(); + assert_eq!(batch_labels(&mut scene), ["quads (3)"]); + assert_eq!( + scene + .quads + .iter() + .map(|quad| quad.bounds) + .collect::>(), + [square(0.), square(8.), square(5.)] + ); + + // A layer goes above the layers nested in the layer before it. + let mut scene = Scene::default(); + scene.push_layer(); + scene.push_layer(); + scene.insert_primitive(underline(0.)); + scene.pop_layer(); + scene.pop_layer(); + scene.push_layer(); + scene.insert_primitive(quad(5.)); + scene.pop_layer(); + assert_eq!(batch_labels(&mut scene), ["underlines (1)", "quads (1)"]); + } } diff --git a/crates/gpui/src/svg_renderer.rs b/crates/gpui/src/svg_renderer.rs index 49f77a170dc..ce0e2b076de 100644 --- a/crates/gpui/src/svg_renderer.rs +++ b/crates/gpui/src/svg_renderer.rs @@ -2,11 +2,14 @@ use crate::{ AssetSource, DevicePixels, IsZero, RenderImage, Result, SharedString, Size, swap_rgba_pa_to_bgra, }; +use collections::HashMap; use image::Frame; +use parking_lot::Mutex; use resvg::tiny_skia::Pixmap; use smallvec::SmallVec; use std::{ hash::Hash, + path::Path, sync::{Arc, LazyLock, OnceLock}, }; @@ -102,6 +105,19 @@ pub struct SvgRenderer { /// scales should retain this value to avoid re-paying the parse cost. pub struct ParsedSvg(usvg::Tree); +/// The font of an SVG `` element, as the values of its presentation attributes. +#[derive(Clone, Copy, Debug)] +pub struct SvgTextFont<'a> { + /// The `font-family` list. + pub family: &'a str, + /// The `font-size`, in pixels. + pub size: f32, + /// The `font-weight`. + pub weight: &'a str, + /// The `font-style`. + pub style: &'a str, +} + /// The size in which to rasterize the SVG. #[derive(Clone, Copy)] pub enum SvgSize { @@ -132,45 +148,64 @@ impl SvgRenderer { // eagerly at construction time. This avoids the expensive deep-clone // of the system font database for code paths that never render SVGs // (e.g. tests). - let enriched_fontdb: Arc>> = Arc::new(OnceLock::new()); + let enriched_fontdb = Arc::new(OnceLock::>::new()); let default_font_resolver = usvg::FontResolver::default_font_selector(); let font_resolver = Box::new({ let asset_source = asset_source.clone(); + let enriched_fontdb = enriched_fontdb.clone(); move |font: &usvg::Font, db: &mut Arc| { + let fontdb = enriched_fontdb.get_or_init(|| { + let mut db = (**SYSTEM_FONT_DB).clone(); + load_bundled_fonts(&*asset_source, &mut db); + fix_generic_font_families(&mut db); + Mutex::new(FontDatabase { + database: Arc::new(db), + owned_faces: HashMap::default(), + remaining_owned_bytes: MAX_OWNED_FONT_BYTES, + fallback_faces: HashMap::default(), + }) + }); if db.is_empty() { - let fontdb = enriched_fontdb.get_or_init(|| { - let mut db = (**SYSTEM_FONT_DB).clone(); - load_bundled_fonts(&*asset_source, &mut db); - fix_generic_font_families(&mut db); - Arc::new(db) - }); - *db = fontdb.clone(); + *db = fontdb.lock().database.clone(); } - if let Some(id) = default_font_resolver(font, db) { - return Some(id); - } - // fontdb doesn't recognize CSS system font keywords like "system-ui" - // or "ui-sans-serif", so fall back to sans-serif before any face. - let sans_query = usvg::fontdb::Query { - families: &[usvg::fontdb::Family::SansSerif], - ..Default::default() - }; - db.query(&sans_query) - .or_else(|| db.faces().next().map(|f| f.id)) + let id = default_font_resolver(font, db).or_else(|| { + // fontdb doesn't recognize CSS system font keywords like "system-ui" + // or "ui-sans-serif", so fall back to sans-serif before any face. + let sans_query = usvg::fontdb::Query { + families: &[usvg::fontdb::Family::SansSerif], + ..Default::default() + }; + db.query(&sans_query) + .or_else(|| db.faces().next().map(|f| f.id)) + })?; + Some(fontdb.lock().owned_face(db, id)) } }); let default_fallback_selection = usvg::FontResolver::default_fallback_selector(); let fallback_selection = Box::new( move |ch: char, fonts: &[usvg::fontdb::ID], db: &mut Arc| { - if is_emoji_presentation(ch) { - if let Some(id) = select_emoji_font(ch, fonts, db.as_ref(), EMOJI_FONT_FAMILIES) - { - return Some(id); + let mut select = |fonts: &[usvg::fontdb::ID]| { + if is_emoji_presentation(ch) { + if let Some(id) = + select_emoji_font(ch, fonts, db.as_ref(), EMOJI_FONT_FAMILIES) + { + return Some(id); + } } - } - default_fallback_selection(ch, fonts, db) + default_fallback_selection(ch, fonts, db) + }; + let Some(fontdb) = enriched_fontdb.get() else { + return select(fonts); + }; + let face = cached_fallback_face(fontdb, ch, fonts, select)?; + let owned_face = fontdb.lock().owned_face(db, face); + Some(if fonts.contains(&owned_face) { + face + } else { + owned_face + }) }, ); let options = usvg::Options { @@ -191,6 +226,29 @@ impl SvgRenderer { usvg::Tree::from_data(bytes, &self.usvg_options).map(ParsedSvg) } + /// Returns the advance of `text` drawn by this renderer as a single line of SVG ``. + pub fn measure_text_width( + &self, + text: &str, + font: &SvgTextFont<'_>, + ) -> Result { + let mut svg = String::from( + r#""#)); + push_xml_escaped(&mut svg, text); + svg.push_str(""); + + let tree = usvg::Tree::from_str(&svg, &self.usvg_options)?; + Ok(underline_width(tree.root())) + } + /// Rasterizes a previously parsed SVG into an image buffer. pub fn render_parsed( &self, @@ -306,6 +364,139 @@ fn rasterize_tree(tree: &usvg::Tree, size: SvgSize) -> Result, + owned_faces: HashMap, + remaining_owned_bytes: u64, + fallback_faces: HashMap<(usvg::fontdb::ID, char), Option>, +} + +impl FontDatabase { + fn owned_face( + &mut self, + db: &mut Arc, + id: usvg::fontdb::ID, + ) -> usvg::fontdb::ID { + let Some(usvg::fontdb::Source::File(path)) = db.face(id).map(|face| face.source.clone()) + else { + return id; + }; + if !self.owned_faces.contains_key(&id) { + self.own_font_file(&path); + } + *db = self.database.clone(); + self.owned_faces.get(&id).copied().unwrap_or(id) + } + + fn own_font_file(&mut self, path: &Path) { + let file_faces = self + .database + .faces() + .filter(|face| { + matches!(&face.source, usvg::fontdb::Source::File(face_path) if face_path == path) + }) + .map(|face| (face.id, face.index)) + .collect::>(); + let remaining_owned_bytes = self.remaining_owned_bytes; + let data = std::fs::metadata(path).and_then(|metadata| { + (metadata.len() <= remaining_owned_bytes) + .then(|| std::fs::read(path)) + .transpose() + }); + let owned_ids = match data { + Ok(Some(data)) if data.len() as u64 <= remaining_owned_bytes => { + let size = data.len() as u64; + let owned_ids = Arc::make_mut(&mut self.database) + .load_font_source(usvg::fontdb::Source::Binary(Arc::new(data))); + if !owned_ids.is_empty() { + self.remaining_owned_bytes -= size; + } + owned_ids + } + Ok(_) => Default::default(), + Err(error) => { + log::warn!("Failed to read font {path:?}: {error}"); + Default::default() + } + }; + for (id, index) in file_faces { + let owned_id = owned_ids + .iter() + .copied() + .find(|owned_id| { + self.database + .face(*owned_id) + .is_some_and(|face| face.index == index) + }) + .unwrap_or(id); + self.owned_faces.insert(id, owned_id); + } + } +} + +const MAX_CACHED_FALLBACK_FACES: usize = 16 * 1024; + +fn cached_fallback_face( + fontdb: &Mutex, + ch: char, + fonts: &[usvg::fontdb::ID], + mut select: impl FnMut(&[usvg::fontdb::ID]) -> Option, +) -> Option { + let Some(base) = fonts.first() else { + return select(fonts); + }; + let key = (*base, ch); + let cached_face = fontdb.lock().fallback_faces.get(&key).copied(); + let face = match cached_face { + Some(face) => face, + None => { + let face = select(&fonts[..1]); + let fallback_faces = &mut fontdb.lock().fallback_faces; + if fallback_faces.len() < MAX_CACHED_FALLBACK_FACES { + fallback_faces.insert(key, face); + } + face + } + }; + match face { + Some(face) if fonts.contains(&face) => select(fonts), + face => face, + } +} + +fn underline_width(group: &usvg::Group) -> f32 { + group.children().iter().fold(0., |width, node| { + width + + match node { + usvg::Node::Text(text) => text + .layouted() + .iter() + .filter_map(|span| span.underline.as_ref()) + .fold(0., |width, underline| { + width + underline.data().bounds().width() + }), + usvg::Node::Group(group) => underline_width(group), + usvg::Node::Path(_) | usvg::Node::Image(_) => 0., + } + }) +} + +fn push_xml_escaped(xml: &mut String, text: &str) { + for character in text.chars() { + match character { + '&' => xml.push_str("&"), + '<' => xml.push_str("<"), + '>' => xml.push_str(">"), + '"' => xml.push_str("""), + '\t' | '\n' | '\r' => xml.push(character), + '\u{0}'..='\u{1f}' | '\u{fffe}' | '\u{ffff}' => {} + _ => xml.push(character), + } + } +} + fn load_bundled_fonts(asset_source: &dyn AssetSource, db: &mut usvg::fontdb::Database) { let font_paths = [ "fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf", @@ -356,6 +547,7 @@ fn fix_generic_font_families(db: &mut usvg::fontdb::Database) { #[cfg(test)] mod tests { use super::*; + use std::{borrow::Cow, cell::Cell}; use usvg::fontdb::{Database, Family, Query}; const IBM_PLEX_REGULAR: &[u8] = @@ -390,6 +582,103 @@ mod tests { Ok(()) } + #[test] + fn measured_text_width_matches_rasterized_advance() -> Result<()> { + let renderer = SvgRenderer::new(Arc::new(BundledFonts)); + let font = SvgTextFont { + family: "IBM Plex Sans", + size: 40., + weight: "normal", + style: "normal", + }; + let frame_width = rasterized_text_width(&renderer, "MM")?; + assert!(frame_width > 0.); + + for text in ["MMMM", " ", " ", "\u{a0}", "\u{200b}", "M\u{200b}"] { + let measured = renderer.measure_text_width(text, &font)?; + let rasterized = rasterized_text_width(&renderer, &format!("M{text}M"))? - frame_width; + assert!( + (measured - rasterized).abs() <= 1., + "{text:?} measured {measured}px, rasterized {rasterized}px" + ); + } + assert_eq!( + renderer.measure_text_width("M\u{200b}", &font)?, + renderer.measure_text_width("M", &font)? + ); + assert!(renderer.measure_text_width("<&\"\u{1}>", &font)? > 0.); + Ok(()) + } + + #[test] + fn owns_font_bytes_within_budget() -> Result<()> { + let font_path = |name| { + std::env::temp_dir().join(format!( + "gpui-svg-renderer-{}-{name}.ttf", + std::process::id() + )) + }; + let (plex_path, lilex_path) = (font_path("plex"), font_path("lilex")); + std::fs::write(&plex_path, IBM_PLEX_REGULAR)?; + std::fs::write(&lilex_path, LILEX_REGULAR)?; + let mut database = Database::new(); + database.load_font_file(&plex_path)?; + database.load_font_file(&lilex_path)?; + let mut fonts = FontDatabase { + database: Arc::new(database), + owned_faces: HashMap::default(), + remaining_owned_bytes: IBM_PLEX_REGULAR.len() as u64, + fallback_faces: HashMap::default(), + }; + let mut db = fonts.database.clone(); + let face_ids = db.faces().map(|face| face.id).collect::>(); + let (plex_id, lilex_id) = (face_ids[0], face_ids[1]); + + let owned_plex_id = fonts.owned_face(&mut db, plex_id); + let owned_lilex_id = fonts.owned_face(&mut db, lilex_id); + std::fs::write(&plex_path, b"changed")?; + let data_len = |id| db.with_face_data(id, |data, _| data.len()); + let data_lens = (data_len(plex_id), data_len(owned_plex_id)); + std::fs::remove_file(&plex_path)?; + std::fs::remove_file(&lilex_path)?; + + assert_eq!(data_lens, (Some(7), Some(IBM_PLEX_REGULAR.len()))); + assert_eq!(owned_lilex_id, lilex_id); + assert_eq!(fonts.remaining_owned_bytes, 0); + assert_eq!(fonts.owned_face(&mut db, plex_id), owned_plex_id); + Ok(()) + } + + #[test] + fn fallback_faces_are_remembered_until_excluded() { + let database = db_with_bundled_fonts(); + let face_ids = database.faces().map(|face| face.id).collect::>(); + let (base, fallback) = (face_ids[0], face_ids[1]); + let fontdb = Mutex::new(FontDatabase { + database: Arc::new(database), + owned_faces: HashMap::default(), + remaining_owned_bytes: 0, + fallback_faces: HashMap::default(), + }); + let selections = Cell::new(0); + let fallback_face = |ch, fonts: &[usvg::fontdb::ID]| { + cached_fallback_face(&fontdb, ch, fonts, |excluded| { + selections.set(selections.get() + 1); + (!excluded.contains(&fallback)).then_some(fallback) + }) + }; + + assert_eq!(fallback_face('x', &[base]), Some(fallback)); + assert_eq!(fallback_face('x', &[base]), Some(fallback)); + assert_eq!(selections.get(), 1); + assert_eq!(fallback_face('x', &[base, fallback]), None); + assert_eq!(selections.get(), 2); + assert_eq!(fallback_face('y', &[base, fallback]), None); + assert_eq!(selections.get(), 4); + assert_eq!(fallback_face('y', &[base]), Some(fallback)); + assert_eq!(selections.get(), 4); + } + fn db_with_bundled_fonts() -> Database { let mut db = Database::new(); db.load_font_data(IBM_PLEX_REGULAR.to_vec()); @@ -522,4 +811,44 @@ mod tests { face.families ); } + + struct BundledFonts; + + impl AssetSource for BundledFonts { + fn load(&self, path: &str) -> Result>> { + Ok(match path { + "fonts/ibm-plex-sans/IBMPlexSans-Regular.ttf" => { + Some(Cow::Borrowed(IBM_PLEX_REGULAR)) + } + "fonts/lilex/Lilex-Regular.ttf" => Some(Cow::Borrowed(LILEX_REGULAR)), + _ => None, + }) + } + + fn list(&self, _path: &str) -> Result> { + Ok(Vec::new()) + } + } + + fn rasterized_text_width(renderer: &SvgRenderer, text: &str) -> Result { + let svg = format!( + r#"{text}"# + ); + let pixmap = renderer.render_pixmap(svg.as_bytes(), SvgSize::ScaleFactor(1.))?; + let width = pixmap.width() as usize; + let inked_columns = (0..width) + .filter(|column| { + pixmap + .pixels() + .iter() + .skip(*column) + .step_by(width) + .any(|pixel| pixel.alpha() > 0) + }) + .collect::>(); + Ok(match (inked_columns.first(), inked_columns.last()) { + (Some(first), Some(last)) => (last - first + 1) as f32, + _ => 0., + }) + } } diff --git a/crates/gpui/src/text_system/line.rs b/crates/gpui/src/text_system/line.rs index bbaa8f9cd73..e0eb71f5918 100644 --- a/crates/gpui/src/text_system/line.rs +++ b/crates/gpui/src/text_system/line.rs @@ -545,15 +545,7 @@ fn paint_line( &mut Window, ), ) -> Result<()> { - let line_bounds = line_paint_bounds( - origin, - layout, - line_height, - align, - align_width, - wrap_boundaries, - ); - window.paint_layer(line_bounds, |window| { + window.paint_layer(|window| { let padding_top = (line_height - layout.ascent - layout.descent) / 2.; let baseline_offset = point(px(0.), padding_top + layout.ascent); let underline_y_offset = underline_y_offset(line_height, layout.ascent, layout.descent); @@ -816,15 +808,7 @@ fn paint_line_background( window: &mut Window, cx: &mut App, ) -> Result<()> { - let line_bounds = line_paint_bounds( - origin, - layout, - line_height, - align, - align_width, - wrap_boundaries, - ); - window.paint_layer(line_bounds, |window| { + window.paint_layer(|window| { let mut decoration_runs = decoration_runs.iter(); let mut wraps = wrap_boundaries.iter().peekable(); let mut run_end = 0; @@ -955,51 +939,6 @@ fn paint_line_background( }) } -fn line_paint_bounds( - origin: Point, - layout: &LineLayout, - line_height: Pixels, - align: TextAlign, - align_width: Option, - wrap_boundaries: &[WrapBoundary], -) -> Bounds { - let mut bounds = Bounds::new( - origin, - size( - layout.width, - line_height * (wrap_boundaries.len() as f32 + 1.), - ), - ); - if align == TextAlign::Left || layout.len == 0 { - return bounds; - } - - let align_width = align_width.unwrap_or(layout.width); - let mut row_start = Pixels::ZERO; - let row_ends = wrap_boundaries - .iter() - .map(|boundary| { - layout.runs[boundary.run_ix].glyphs[boundary.glyph_ix] - .position - .x - }) - .chain([layout.width]); - for (row, row_end) in row_ends.enumerate() { - let width = row_end - row_start; - let offset = match align { - TextAlign::Left => Pixels::ZERO, - TextAlign::Center => (align_width - width) / 2., - TextAlign::Right => align_width - width, - }; - bounds = bounds.union(&Bounds::new( - point(origin.x + offset, origin.y + line_height * row as f32), - size(width, line_height), - )); - row_start = row_end; - } - bounds -} - fn aligned_origin_x( origin: Point, align_width: Pixels, @@ -1067,68 +1006,6 @@ mod tests { } } - #[test] - fn test_aligned_line_paint_bounds() { - let line = make_shaped_line("abcd", &[(0, 0.), (1, 10.), (2, 20.), (3, 30.)], 40., &[]); - let origin = point(px(10.), px(20.)); - let line_height = px(16.); - for (wrapped, align_width, expected_edges) in [ - (false, None, [(10., 50.), (10., 50.), (10., 50.)]), - (true, None, [(10., 50.), (10., 50.), (10., 50.)]), - (false, Some(40.), [(10., 50.), (10., 50.), (10., 50.)]), - (true, Some(40.), [(10., 50.), (10., 50.), (10., 50.)]), - (false, Some(100.), [(10., 50.), (10., 80.), (10., 110.)]), - (true, Some(100.), [(10., 50.), (10., 70.), (10., 110.)]), - (false, Some(10.), [(10., 50.), (-5., 50.), (-20., 50.)]), - (true, Some(10.), [(10., 50.), (5., 50.), (0., 50.)]), - (false, Some(0.), [(10., 50.), (-10., 50.), (-30., 50.)]), - (true, Some(0.), [(10., 50.), (0., 50.), (-10., 50.)]), - ] { - let boundaries = if wrapped { - vec![WrapBoundary { - run_ix: 0, - glyph_ix: 2, - }] - } else { - Vec::new() - }; - for (align, (left, right)) in [TextAlign::Left, TextAlign::Center, TextAlign::Right] - .into_iter() - .zip(expected_edges) - { - assert_eq!( - line_paint_bounds( - origin, - &line.layout, - line_height, - align, - align_width.map(px), - &boundaries, - ), - Bounds::new( - point(px(left), origin.y), - size(px(right - left), px(if wrapped { 32. } else { 16. })), - ), - "wrapped={wrapped}, align={align:?}, align_width={align_width:?}", - ); - } - } - let empty = make_shaped_line("", &[], 0., &[]); - for align in [TextAlign::Left, TextAlign::Center, TextAlign::Right] { - assert_eq!( - line_paint_bounds( - origin, - &empty.layout, - line_height, - align, - Some(px(100.)), - &[] - ), - Bounds::new(origin, size(Pixels::ZERO, line_height)), - ); - } - } - #[gpui::test] fn test_underline_handler_matches_default_paint(cx: &mut TestAppContext) { test_underline_handler_at_scales(cx, |window, cx| { diff --git a/crates/gpui/src/window.rs b/crates/gpui/src/window.rs index a7c6fb6a933..678313e2d38 100644 --- a/crates/gpui/src/window.rs +++ b/crates/gpui/src/window.rs @@ -14,9 +14,9 @@ use crate::{ EntityId, EventEmitter, FileDropEvent, FontId, Global, GlobalElementId, GlyphId, GpuSpecs, Hsla, InputHandler, InputPreference, IsZero, KeyBinding, KeyContext, KeyDownEvent, KeyEvent, Keystroke, KeystrokeEvent, LayoutId, LineLayoutIndex, Modifiers, ModifiersChangedEvent, - MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, Path, Pixels, - PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, Point, - PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, + MonochromeSprite, MouseButton, MouseEvent, MouseMoveEvent, MouseUpEvent, PaintedPath, Path, + Pixels, PlatformAtlas, PlatformDisplay, PlatformInput, PlatformInputHandler, PlatformWindow, + Point, PolychromeSprite, Priority, PromptButton, PromptLevel, Quad, Render, RenderGlyphParams, RenderImage, RenderImageParams, RenderSvgParams, Replay, ResizeEdge, SMOOTH_SVG_SCALE_FACTOR, SUBPIXEL_VARIANTS_X, SUBPIXEL_VARIANTS_Y, ScaledPixels, Scene, Shadow, SharedString, Size, StrikethroughStyle, Style, SubpixelSprite, Subscription, SystemWindowTab, @@ -633,6 +633,15 @@ impl FocusHandle { self.id.contains(other.id, window) } + /// Obtains whether the element associated with this handle is part of the most recently rendered frame. + pub fn is_rendered(&self, window: &Window) -> bool { + window + .rendered_frame + .dispatch_tree + .focusable_node_id(self.id) + .is_some() + } + /// Dispatch an action on the element that rendered this focus handle pub fn dispatch_action(&self, action: &dyn Action, window: &mut Window, cx: &mut App) { if let Some(node_id) = window @@ -1226,6 +1235,7 @@ pub struct Window { pub(crate) display_observers: SingleSubscriberSet, is_resizable: bool, is_minimizable: bool, + last_window_bounds: WindowBounds, sprite_atlas: Arc, text_system: Rc, text_rendering_mode: Rc>, @@ -1569,26 +1579,16 @@ pub(crate) struct ElementStateBox { pub(crate) type_name: &'static str, } -fn default_bounds(display_id: Option, cx: &mut App) -> WindowBounds { - // TODO, BUG: if you open a window with the currently active window - // on the stack, this will erroneously fallback to `None` - // - // TODO these should be the initial window bounds not considering maximized/fullscreen - let active_window_bounds = cx - .active_window() - .and_then(|w| w.update(cx, |_, window, _| window.window_bounds()).ok()); - +fn default_bounds( + active_window_bounds: Option, + display: Option<&dyn PlatformDisplay>, +) -> WindowBounds { const CASCADE_OFFSET: f32 = 25.0; - let display = display_id - .map(|id| cx.find_display(id)) - .unwrap_or_else(|| cx.primary_display()); - let default_placement = || Bounds::new(point(px(0.), px(0.)), DEFAULT_WINDOW_SIZE); // Use visible_bounds to exclude taskbar/dock areas let display_bounds = display - .as_ref() .map(|d| d.visible_bounds()) .unwrap_or_else(default_placement); @@ -1606,7 +1606,6 @@ fn default_bounds(display_id: Option, cx: &mut App) -> WindowBounds { }, None => ( display - .as_ref() .map(|d| d.default_bounds()) .unwrap_or_else(default_placement), WindowBounds::Windowed, @@ -1673,7 +1672,25 @@ impl Window { .as_ref() .and_then(|titlebar| titlebar.title.clone()); - let window_bounds = window_bounds.unwrap_or_else(|| default_bounds(display_id, cx)); + let active_window_placement = cx.active_window_placement(); + // Explicit bounds only make sense on the display they were computed for. + let target_display_id = display_id.or_else(|| { + active_window_placement + .filter(|_| window_bounds.is_none()) + .and_then(|(display_id, _)| display_id) + }); + let display = target_display_id + .and_then(|display_id| cx.find_display(display_id)) + .or_else(|| cx.primary_display()); + let display_id = display + .as_ref() + .map(|display| display.id()) + .or(target_display_id); + let active_window_bounds = active_window_placement + .filter(|(active_display_id, _)| *active_display_id == display_id) + .map(|(_, bounds)| bounds); + let window_bounds = window_bounds + .unwrap_or_else(|| default_bounds(active_window_bounds, display.as_deref())); let mut platform_window = cx.platform.open_window( handle, WindowParams { @@ -2357,6 +2374,7 @@ impl Window { display_observers: SingleSubscriberSet::new(), is_resizable, is_minimizable, + last_window_bounds: window_bounds, sprite_atlas, text_system, text_rendering_mode: cx.text_rendering_mode.clone(), @@ -2506,6 +2524,65 @@ impl Window { } } + /// This window's part of [`App::debug_state`]. + /// + /// Values GPUI caches are reported next to what the platform reports now, + /// so a stale cache shows up as a mismatch. + pub(crate) fn debug_state(&self) -> serde_json::Value { + let platform_window = &self.platform_window; + serde_json::json!({ + "id": self.handle.window_id().as_u64(), + "title": platform_window.get_title(), + "bounds": platform_window.bounds(), + "window_bounds": format!("{:?}", platform_window.window_bounds()), + "content_size": platform_window.content_size(), + "viewport_size": self.viewport_size, + "scale_factor": { + "cached": self.scale_factor, + "platform": platform_window.scale_factor(), + }, + "display_id": { + "cached": self.display_id.map(u64::from), + "platform": platform_window.display().map(|display| u64::from(display.id())), + }, + "active": { + "cached": self.active.get(), + "platform": platform_window.is_active(), + }, + "hovered": { + "cached": self.hovered.get(), + "platform": platform_window.is_hovered(), + }, + "visibility": { + "cached": format!("{:?}", self.visibility), + "platform": format!("{:?}", platform_window.visibility()), + }, + "appearance": { + "cached": format!("{:?}", self.appearance), + "platform": format!("{:?}", platform_window.appearance()), + }, + "is_fullscreen": platform_window.is_fullscreen(), + "is_maximized": platform_window.is_maximized(), + "mouse_position": { + "cached": self.mouse_position, + "platform": platform_window.mouse_position(), + }, + "modifiers": { + "cached": self.modifiers, + "platform": platform_window.modifiers(), + }, + "cursor_style": self.rendered_frame.cursor_style(self), + "frame": { + "dirty": self.invalidator.is_dirty(), + "needs_present": self.needs_present.get(), + "refreshing": self.refreshing, + "next_frame_callbacks": self.next_frame_callbacks.borrow().len(), + }, + "gpu": platform_window.gpu_specs(), + "platform": platform_window.debug_state(), + }) + } + /// Whether the platform is presenting this window's frames (see /// [`WindowVisibility`]). pub fn visibility(&self) -> WindowVisibility { @@ -2740,6 +2817,14 @@ impl Window { self.platform_window.window_bounds() } + pub(crate) fn last_window_bounds(&self) -> WindowBounds { + self.last_window_bounds + } + + pub(crate) fn display_id(&self) -> Option { + self.display_id + } + /// Return the `WindowBounds` excluding insets (Wayland and X11) pub fn inner_window_bounds(&self) -> WindowBounds { self.platform_window.inner_window_bounds() @@ -3003,6 +3088,8 @@ impl Window { pub fn bounds_changed(&mut self, cx: &mut App) { self.scale_factor = self.platform_window.scale_factor(); self.viewport_size = self.platform_window.content_size(); + self.last_window_bounds = self.platform_window.window_bounds(); + cx.sync_window_update_entry(self); self.mouse_position = self.platform_window.mouse_position(); self.refresh(); @@ -3286,6 +3373,12 @@ impl Window { self.platform_window.set_traffic_light_position(position); } + /// Shows or hides the native macOS titlebar, including the traffic light buttons. + #[cfg(target_os = "macos")] + pub fn set_native_titlebar_visibility(&self, visible: bool) { + self.platform_window.set_native_titlebar_visibility(visible); + } + /// Sets the application identifier. pub fn set_app_id(&mut self, app_id: &str) { self.platform_window.set_app_id(app_id); @@ -4775,28 +4868,20 @@ impl Window { }); } - /// Creates a new painting layer for the specified bounds. A "layer" is a batch - /// of geometry that are non-overlapping and have the same draw order. This is typically used + /// Creates a new painting layer. A "layer" is a batch of geometry that are + /// non-overlapping and have the same draw order. This is typically used /// for performance reasons. /// + /// Layers painted inside `f` are drawn above this layer, including above + /// what `f` paints after them. + /// /// This method should only be called as part of the paint phase of element drawing. - pub fn paint_layer(&mut self, bounds: Bounds, f: impl FnOnce(&mut Self) -> R) -> R { + pub fn paint_layer(&mut self, f: impl FnOnce(&mut Self) -> R) -> R { self.invalidator.debug_assert_paint(); - let content_mask = self.content_mask(); - let clipped_bounds = bounds.intersect(&content_mask.bounds); - if !clipped_bounds.is_empty() { - self.next_frame - .scene - .push_layer(self.cover_bounds(clipped_bounds)); - } - + self.next_frame.scene.push_layer(); let result = f(self); - - if !clipped_bounds.is_empty() { - self.next_frame.scene.pop_layer(); - } - + self.next_frame.scene.pop_layer(); result } @@ -4816,23 +4901,27 @@ impl Window { let scale_factor = self.scale_factor(); let content_mask = self.snapped_content_mask(); let opacity = self.element_opacity(); - let element_bounds = self.cover_bounds(bounds); - let element_corner_radii = corner_radii.scale(scale_factor); for shadow in shadows { if shadow.inset { continue; } - let shadow_bounds = (bounds + shadow.offset).dilate(shadow.spread_radius); + let shape_bounds = + self.cover_bounds((bounds + shadow.offset).dilate(shadow.spread_radius)); + if shape_bounds.is_empty() { + continue; + } + let blur_radius = shadow.blur_radius.scale(scale_factor); self.next_frame.scene.insert_primitive(Shadow { order: 0, - blur_radius: shadow.blur_radius.scale(scale_factor), - bounds: self.cover_bounds(shadow_bounds), + blur_radius, + // Leave room for the tail of the blur. + bounds: shape_bounds.dilate(blur_radius * 3.), content_mask, - corner_radii: corner_radii.scale(scale_factor), + corner_radii: Corners::default(), color: shadow.color.opacity(opacity), - element_bounds, - element_corner_radii, - inset: 0, + shape_bounds, + shape_corner_radii: corner_radii.scale(scale_factor), + inset: false.into(), pad: 0, }); } @@ -4871,55 +4960,58 @@ impl Window { self.next_frame.scene.insert_primitive(Shadow { order: 0, blur_radius: shadow.blur_radius.scale(scale_factor), - bounds: self.cover_bounds(hole), + bounds: element_bounds, content_mask, - corner_radii: hole_corner_radii.scale(scale_factor), + corner_radii: element_corner_radii, color: shadow.color.opacity(opacity), - element_bounds, - element_corner_radii, - inset: 1, + shape_bounds: self.cover_bounds(hole), + shape_corner_radii: hole_corner_radii.scale(scale_factor), + inset: true.into(), pad: 0, }); } } fn largest_border_interior(quad: &Quad) -> Bounds { - let radii = &quad.corner_radii; - let widths = &quad.border_widths; - let edge_radii = Edges { - top: radii.top_left.max(radii.top_right), - right: radii.top_right.max(radii.bottom_right), - bottom: radii.bottom_left.max(radii.bottom_right), - left: radii.top_left.max(radii.bottom_left), - }; + let size = quad.bounds.size; + let diagonal = (size.width.0 * size.width.0 + size.height.0 * size.height.0).sqrt(); + if diagonal == 0. { + return Bounds::default(); + } + // The interior's corners sit on the corner arcs. Taking the angle along + // the arc whose tangent is the quad's aspect ratio stays within 1% of + // the largest interior. + let cos = size.height.0 / diagonal; + let sin = size.width.0 / diagonal; - let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0)); - let inset_bounds = |top_left_inset, bottom_right_inset| { - Bounds::from_corners( - quad.bounds.origin + top_left_inset + antialias_inset, - quad.bounds.bottom_right() - bottom_right_inset - antialias_inset, + // A corner's inner border edge is a quarter ellipse around the + // corner's center, with the border widths taken off its radius. + let corner_inset = |radius: ScaledPixels, width_x: ScaledPixels, width_y: ScaledPixels| { + point( + width_x.max(radius - (radius - width_x) * cos), + width_y.max(radius - (radius - width_y) * sin), ) }; - // Rounded corners need only be excluded on one axis. Either candidate - // is empty of border pixels, so use the larger interior. - let horizontal_band = inset_bounds( - point(widths.left, widths.top.max(edge_radii.top)), - point(widths.right, widths.bottom.max(edge_radii.bottom)), - ); - let vertical_band = inset_bounds( - point(widths.left.max(edge_radii.left), widths.top), - point(widths.right.max(edge_radii.right), widths.bottom), - ); + let radii = &quad.corner_radii; + let widths = &quad.border_widths; + let top_left = corner_inset(radii.top_left, widths.left, widths.top); + let top_right = corner_inset(radii.top_right, widths.right, widths.top); + let bottom_right = corner_inset(radii.bottom_right, widths.right, widths.bottom); + let bottom_left = corner_inset(radii.bottom_left, widths.left, widths.bottom); - let area = |bounds: &Bounds| { - bounds.size.width.0.max(0.) * bounds.size.height.0.max(0.) - }; - if area(&horizontal_band) >= area(&vertical_band) { - horizontal_band - } else { - vertical_band - } + let antialias_inset = point(ScaledPixels(1.0), ScaledPixels(1.0)); + Bounds::from_corners( + quad.bounds.origin + + point(top_left.x.max(bottom_left.x), top_left.y.max(top_right.y)) + + antialias_inset, + quad.bounds.bottom_right() + - point( + top_right.x.max(bottom_right.x), + bottom_left.y.max(bottom_right.y), + ) + - antialias_inset, + ) } /// Paint one or more quads into the scene for the next frame at the current stacking context. @@ -4947,22 +5039,66 @@ impl Window { border_widths: snapped_border_widths, border_style: quad.border_style, }; + self.insert_quad(quad); + } - if !quad.background.is_transparent() { + fn insert_quad(&mut self, quad: Quad) { + let has_background = !quad.background.is_transparent(); + let has_border = + quad.border_widths != Edges::default() && !quad.border_color.is_transparent(); + if !has_background && !has_border { + return; + } + + let is_rectangle = + quad.border_widths == Edges::default() && quad.corner_radii == Corners::default(); + if has_background && is_rectangle { self.next_frame.scene.insert_primitive(quad); return; } - // Splitting a border-only quad around its empty interior avoids shading - // every transparent pixel inside large outlines. + let plain_border = quad.corner_radii == Corners::default() + && quad.border_style == BorderStyle::Solid + && (!has_background || quad.border_color.is_opaque()); + + // Splitting off the interior leaves only the strips around it for the + // border and corner shading. let outer_bounds = quad.bounds; - let inner_bounds = Self::largest_border_interior(&quad); + let inner_bounds = if plain_border { + quad.bounds.extend(quad.border_widths.map(|width| -*width)) + } else { + Self::largest_border_interior(&quad) + }; + + // A plain border's strips can be plain rectangles of the border color. + // Otherwise, each strip is the whole quad masked to the strip, so the + // border, corners and gradients are still shaded relative to the full quad. + let strip_quad = if plain_border { + Quad { + background: quad.border_color.into(), + border_widths: Edges::default(), + ..quad + } + } else { + quad + }; if inner_bounds.is_empty() { - self.next_frame.scene.insert_primitive(quad); + self.next_frame.scene.insert_primitive(strip_quad); return; } + if has_background { + self.next_frame.scene.insert_primitive(Quad { + content_mask: ContentMask { + bounds: quad.content_mask.bounds.intersect(&inner_bounds), + }, + border_widths: Edges::default(), + corner_radii: Corners::default(), + ..quad + }); + } + let strips = [ // Top Bounds::from_corners( @@ -4987,33 +5123,31 @@ impl Window { ]; for strip in strips { - let content_mask_bounds = quad.content_mask.bounds.intersect(&strip); - if !content_mask_bounds.is_empty() { - self.next_frame.scene.insert_primitive(Quad { - content_mask: ContentMask { - bounds: content_mask_bounds, - }, - ..quad - }); - } + self.next_frame.scene.insert_primitive(Quad { + content_mask: ContentMask { + bounds: quad.content_mask.bounds.intersect(&strip), + }, + ..strip_quad + }); } } /// Paint the given `Path` into the scene for the next frame at the current z-index. /// /// This method should only be called as part of the paint phase of element drawing. - pub fn paint_path(&mut self, mut path: Path, color: impl Into) { + pub fn paint_path(&mut self, path: Path, color: impl Into) { self.invalidator.debug_assert_paint(); let scale_factor = self.scale_factor(); let content_mask = self.content_mask(); let opacity = self.element_opacity(); - path.content_mask = content_mask; let color: Background = color.into(); - path.color = color.opacity(opacity); - self.next_frame - .scene - .insert_primitive(path.scale(scale_factor)); + self.next_frame.scene.insert_primitive(PaintedPath::new( + path, + scale_factor, + content_mask, + color.opacity(opacity), + )); } /// Paint an underline into the scene for the next frame at the current z-index. @@ -8530,6 +8664,34 @@ mod tests { } } + /// A stale cache is only visible if the snapshot reports GPUI's cached + /// value separately from what the platform reports now. + #[gpui::test] + fn test_debug_state_reports_cached_and_platform_values(cx: &mut TestAppContext) { + use crate::WindowVisibility; + + let window = cx.add_window(|_, _| EmptyView); + let window_id = window.window_id().as_u64(); + let window_state = |cx: &mut TestAppContext| { + let state = cx.update(|cx| cx.debug_state()); + state["windows"] + .as_array() + .and_then(|windows| windows.iter().find(|window| window["id"] == window_id)) + .cloned() + .expect("the open window is listed") + }; + + let state = window_state(cx); + assert_eq!(state["visibility"]["cached"], "Visible"); + assert_eq!(state["visibility"]["platform"], "Visible"); + + cx.test_window(window.into()) + .simulate_visibility_change(WindowVisibility::Hidden); + let state = window_state(cx); + assert_eq!(state["visibility"]["cached"], "Hidden"); + assert_eq!(state["visibility"]["platform"], "Hidden"); + } + /// Visibility transitions reach observers exactly once each, with the new /// state already stored on the window, and never wake the platform for a /// frame: the platform requests one itself when it resumes presenting. @@ -8688,6 +8850,48 @@ mod tests { } } + #[gpui::test] + fn test_window_opened_from_bounds_observer_uses_new_bounds(cx: &mut TestAppContext) { + use crate::Subscription; + + struct BoundsObserver { + _subscription: Subscription, + } + + impl Render for BoundsObserver { + fn render(&mut self, _: &mut Window, _: &mut Context) -> impl IntoElement { + Empty + } + } + + let opened_window = Rc::new(Cell::new(None)); + let window = cx.add_window({ + let opened_window = opened_window.clone(); + move |window, cx| BoundsObserver { + _subscription: cx.observe_window_bounds(window, move |_, _, cx| { + let handle = cx + .open_window(WindowOptions::default(), |_, cx| cx.new(|_| EmptyView)) + .unwrap(); + opened_window.set(Some(AnyWindowHandle::from(handle))); + }), + } + }); + window + .update(cx, |_, window, _| window.activate_window()) + .unwrap(); + + let new_size = size(px(400.), px(300.)); + cx.simulate_window_resize(window.into(), new_size); + + let opened_window = opened_window + .take() + .expect("bounds observer should have opened a window"); + let opened_size = opened_window + .update(cx, |_, window, _| window.bounds().size) + .unwrap(); + assert_eq!(opened_size, new_size); + } + #[gpui::test] fn test_fully_visible_bounds_preserve_layout_viewport(cx: &mut TestAppContext) { let window = cx.add_window(|_, _| EmptyView); @@ -9001,6 +9205,50 @@ mod tests { } } + #[gpui::test] + fn test_fullscreen_toggle_reports_current_bounds(cx: &mut TestAppContext) { + let window = cx.add_window(|_, _| EmptyView); + let handle = AnyWindowHandle::from(window); + let notifications = Rc::new(Cell::new(0)); + window + .update(cx, { + let notifications = notifications.clone(); + |_, window, cx| { + cx.observe_window_bounds(window, move |_, _, _| { + notifications.set(notifications.get() + 1) + }) + .detach(); + } + }) + .unwrap(); + let window_state = |cx: &mut TestAppContext| { + cx.update_window(handle, |_, window, _| { + ( + window.is_fullscreen(), + window.bounds().size, + window.viewport_size(), + ) + }) + .unwrap() + }; + let initial_size = window_state(cx).1; + + window + .update(cx, |_, window, _| window.toggle_fullscreen()) + .unwrap(); + cx.run_until_parked(); + assert_eq!(window_state(cx), (true, initial_size, initial_size)); + assert_eq!(notifications.get(), 1); + + let resized_size = size(px(800.), px(600.)); + window + .update(cx, |_, window, _| window.toggle_fullscreen()) + .unwrap(); + cx.simulate_window_resize(handle, resized_size); + cx.run_until_parked(); + assert_eq!(window_state(cx), (false, resized_size, resized_size)); + } + /// Platforms that stop requesting frames for idle windows (currently web) /// rely on the frame waker firing whenever frame demand arises; a demand /// source that skips the waker shows up there as a window that silently diff --git a/crates/gpui_apple/Cargo.toml b/crates/gpui_apple/Cargo.toml index 488d1dcab15..2503ed08bd5 100644 --- a/crates/gpui_apple/Cargo.toml +++ b/crates/gpui_apple/Cargo.toml @@ -56,6 +56,7 @@ objc2-metal = { version = "0.3.2", default-features = false, features = [ "MTLCommandBuffer", "MTLCommandEncoder", "MTLCommandQueue", + "MTLDepthStencil", "MTLDevice", "MTLDrawable", "MTLLibrary", diff --git a/crates/gpui_apple/build.rs b/crates/gpui_apple/build.rs index a29d01be664..47c0e41fb25 100644 --- a/crates/gpui_apple/build.rs +++ b/crates/gpui_apple/build.rs @@ -42,14 +42,15 @@ mod apple_build { "Edges".into(), "Size".into(), "Pixels".into(), - "PointF".into(), "Hsla".into(), "ContentMask".into(), "Uniforms".into(), "AtlasTile".into(), - "PathRasterizationInputIndex".into(), - "PathVertex_ScaledPixels".into(), - "PathRasterizationVertex".into(), + "GlobalInputIndex".into(), + "PathTileInputIndex".into(), + "PathTile".into(), + "PathCurve".into(), + "PathPaint".into(), "ShadowInputIndex".into(), "Shadow".into(), "QuadInputIndex".into(), @@ -60,7 +61,6 @@ mod apple_build { "SpriteInputIndex".into(), "MonochromeSprite".into(), "PolychromeSprite".into(), - "PathSprite".into(), "SurfaceInputIndex".into(), "SurfaceBounds".into(), "TransformationMatrix".into(), diff --git a/crates/gpui_apple/src/display_link.rs b/crates/gpui_apple/src/display_link.rs index 83d420594ec..8d1ede1168c 100644 --- a/crates/gpui_apple/src/display_link.rs +++ b/crates/gpui_apple/src/display_link.rs @@ -91,6 +91,10 @@ impl MetalFrameSource { pub fn set_paused(&self, paused: bool) { self.link.setPaused(paused); } + + pub fn is_paused(&self) -> bool { + self.link.isPaused() + } } impl Drop for MetalFrameSource { diff --git a/crates/gpui_apple/src/metal_renderer.rs b/crates/gpui_apple/src/metal_renderer.rs index 9b98a23a41f..86eff3d48b5 100644 --- a/crates/gpui_apple/src/metal_renderer.rs +++ b/crates/gpui_apple/src/metal_renderer.rs @@ -2,8 +2,8 @@ use crate::metal_atlas::MetalAtlas; use anyhow::{Context as _, Result}; use block2::RcBlock; use gpui::{ - AtlasTextureId, Background, Bounds, ContentMask, DevicePixels, PaintSurface, Path, Point, - PrimitiveBatch, ScaledPixels, Scene, Size, point, size, + AtlasTextureId, Bounds, ContentMask, DevicePixels, PaintSurface, PaintedPath, PrimitiveBatch, + ScaledPixels, Scene, Size, quad_depth, quad_depth_scale, size, }; #[cfg(any(test, feature = "bench-support", feature = "test-support"))] use image::RgbaImage; @@ -20,11 +20,12 @@ use objc2_foundation::{NSRange, NSString}; use objc2_metal::MTLCopyAllDevices; use objc2_metal::{ MTLBlendFactor, MTLBlendOperation, MTLBuffer, MTLClearColor, MTLCommandBuffer, - MTLCommandEncoder, MTLCommandQueue, MTLCreateSystemDefaultDevice, MTLDevice, MTLDrawable, - MTLGPUFamily, MTLLibrary, MTLLoadAction, MTLPixelFormat, MTLPrimitiveType, - MTLRenderCommandEncoder, MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, - MTLRenderPipelineState, MTLResourceOptions, MTLStorageMode, MTLStoreAction, MTLTexture, - MTLTextureDescriptor, MTLTextureType, MTLTextureUsage, MTLViewport, + MTLCommandEncoder, MTLCommandQueue, MTLCompareFunction, MTLCreateSystemDefaultDevice, + MTLDepthStencilDescriptor, MTLDepthStencilState, MTLDevice, MTLDrawable, MTLGPUFamily, + MTLLibrary, MTLLoadAction, MTLPixelFormat, MTLPrimitiveType, MTLRenderCommandEncoder, + MTLRenderPassDescriptor, MTLRenderPipelineDescriptor, MTLRenderPipelineState, + MTLResourceOptions, MTLStorageMode, MTLStoreAction, MTLTexture, MTLTextureDescriptor, + MTLTextureUsage, MTLViewport, }; #[cfg(any(test, feature = "bench-support", feature = "test-support"))] use objc2_metal::{MTLBlitCommandEncoder, MTLOrigin, MTLRegion, MTLSize}; @@ -33,16 +34,10 @@ use parking_lot::Mutex; use std::{cell::Cell, mem, mem::MaybeUninit, ops::Range, ptr, slice, sync::Arc}; -// Exported to metal -pub(crate) type PointF = gpui::Point; - #[cfg(not(feature = "runtime_shaders"))] const SHADERS_METALLIB: &[u8] = include_bytes!(concat!(env!("OUT_DIR"), "/shaders.metallib")); #[cfg(feature = "runtime_shaders")] const SHADERS_SOURCE_FILE: &str = include_str!(concat!(env!("OUT_DIR"), "/stitched_shaders.metal")); -// Use 4x MSAA, all devices support it. -// https://developer.apple.com/documentation/metal/mtldevice/1433355-supportstexturesamplecount -const PATH_SAMPLE_COUNT: u32 = 4; /// Metal requires the offset a buffer is bound at to be 256-byte aligned. const INSTANCE_BUFFER_ALIGNMENT: usize = 256; const MAX_INSTANCE_BUFFER_SIZE: usize = 256 * 1024 * 1024; @@ -135,35 +130,26 @@ pub struct MetalRenderer { /// For headless rendering, tracks whether output should be opaque opaque: bool, command_queue: Retained>, - paths_rasterization_pipeline_state: Retained>, - path_sprites_pipeline_state: Retained>, + path_tiles_pipeline_state: Retained>, shadows_pipeline_state: Retained>, quads_pipeline_state: Retained>, + opaque_quads_pipeline_state: Retained>, underlines_pipeline_state: Retained>, monochrome_sprites_pipeline_state: Retained>, polychrome_sprites_pipeline_state: Retained>, surfaces_pipeline_state: Retained>, - unit_vertices: Retained>, + depth_write_state: Retained>, + depth_test_state: Retained>, + depth_texture: Option>>, instance_buffer_pool: Arc>, sprite_atlas: Arc, core_video_texture_cache: CFRetained, - path_intermediate_texture: Option>>, - path_intermediate_msaa_texture: Option>>, - path_sample_count: u32, /// Offscreen render target reused across `render_scene` calls when /// rendering headlessly without reading pixels back. #[cfg(any(test, feature = "bench-support", feature = "test-support"))] headless_render_target: Option>>, } -#[repr(C)] -pub struct PathRasterizationVertex { - pub xy_position: Point, - pub st_position: Point, - pub color: Background, - pub bounds: Bounds, -} - impl MetalRenderer { /// Creates a new MetalRenderer with a CAMetalLayer for window-based rendering. pub fn new( @@ -287,63 +273,23 @@ impl MetalRenderer { )) .context("loading Metal library")?; - fn to_float2_bits(point: PointF) -> u64 { - let mut output = point.y.to_bits() as u64; - output <<= 32; - output |= point.x.to_bits() as u64; - output - } - // Shared memory can be used only if CPU and GPU share the same memory space. // https://developer.apple.com/documentation/metal/setting-resource-storage-modes // iOS does not support managed resources. Its simulator may report a // non-unified host GPU even though resources must still use shared storage. let is_unified_memory = cfg!(target_os = "ios") || device.hasUnifiedMemory(); - // Apple GPU families support memoryless textures, which can significantly reduce - // memory usage by keeping render targets in on-chip tile memory instead of - // allocating backing store in system memory. + // Only Apple GPUs can create shared-storage textures on macOS. // https://developer.apple.com/documentation/metal/mtlgpufamily let is_apple_gpu = device.supportsFamily(MTLGPUFamily::Apple1); - let unit_vertices = [ - to_float2_bits(point(0., 0.)), - to_float2_bits(point(1., 0.)), - to_float2_bits(point(0., 1.)), - to_float2_bits(point(0., 1.)), - to_float2_bits(point(1., 0.)), - to_float2_bits(point(1., 1.)), - ]; - // SAFETY: Metal copies the live array using its exact byte length. - let unit_vertices = unsafe { - device.newBufferWithBytes_length_options( - ptr::NonNull::from(&unit_vertices).cast(), - mem::size_of_val(&unit_vertices), - if is_unified_memory { - MTLResourceOptions::StorageModeShared - | MTLResourceOptions::CPUCacheModeWriteCombined - } else { - MTLResourceOptions::StorageModeManaged - }, - ) - } - .context("allocating unit vertex buffer")?; - - let paths_rasterization_pipeline_state = build_path_rasterization_pipeline_state( + let path_tiles_pipeline_state = build_pipeline_state( &device, &library, - "paths_rasterization", - "path_rasterization_vertex", - "path_rasterization_fragment", - MTLPixelFormat::BGRA8Unorm, - PATH_SAMPLE_COUNT, - )?; - let path_sprites_pipeline_state = build_path_sprite_pipeline_state( - &device, - &library, - "path_sprites", - "path_sprite_vertex", - "path_sprite_fragment", + "path_tiles", + "path_tile_vertex", + "path_tile_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let shadows_pipeline_state = build_pipeline_state( &device, @@ -352,6 +298,7 @@ impl MetalRenderer { "shadow_vertex", "shadow_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let quads_pipeline_state = build_pipeline_state( &device, @@ -360,6 +307,16 @@ impl MetalRenderer { "quad_vertex", "quad_fragment", MTLPixelFormat::BGRA8Unorm, + true, + )?; + let opaque_quads_pipeline_state = build_pipeline_state( + &device, + &library, + "opaque_quads", + "opaque_quad_vertex", + "opaque_quad_fragment", + MTLPixelFormat::BGRA8Unorm, + false, )?; let underlines_pipeline_state = build_pipeline_state( &device, @@ -368,6 +325,7 @@ impl MetalRenderer { "underline_vertex", "underline_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let monochrome_sprites_pipeline_state = build_pipeline_state( &device, @@ -376,6 +334,7 @@ impl MetalRenderer { "monochrome_sprite_vertex", "monochrome_sprite_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let polychrome_sprites_pipeline_state = build_pipeline_state( &device, @@ -384,6 +343,7 @@ impl MetalRenderer { "polychrome_sprite_vertex", "polychrome_sprite_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; let surfaces_pipeline_state = build_pipeline_state( &device, @@ -392,8 +352,12 @@ impl MetalRenderer { "surface_vertex", "surface_fragment", MTLPixelFormat::BGRA8Unorm, + true, )?; + let depth_write_state = build_depth_stencil_state(&device, true)?; + let depth_test_state = build_depth_stencil_state(&device, false)?; + let command_queue = device.newCommandQueue().context("creating command queue")?; let supports_shared_storage = cfg!(target_os = "ios") || is_apple_gpu; #[expect( @@ -423,21 +387,20 @@ impl MetalRenderer { is_unified_memory, opaque, command_queue, - paths_rasterization_pipeline_state, - path_sprites_pipeline_state, + path_tiles_pipeline_state, shadows_pipeline_state, quads_pipeline_state, + opaque_quads_pipeline_state, underlines_pipeline_state, monochrome_sprites_pipeline_state, polychrome_sprites_pipeline_state, surfaces_pipeline_state, - unit_vertices, + depth_write_state, + depth_test_state, + depth_texture: None, instance_buffer_pool, sprite_atlas, core_video_texture_cache, - path_intermediate_texture: None, - path_intermediate_msaa_texture: None, - path_sample_count: PATH_SAMPLE_COUNT, #[cfg(any(test, feature = "bench-support", feature = "test-support"))] headless_render_target: None, }) @@ -498,6 +461,14 @@ impl MetalRenderer { }; } + pub fn is_display_link_attached(&self) -> bool { + matches!(self.display_link_mode, DisplayLinkMode::Attached { .. }) + } + + pub fn presents_with_transaction(&self) -> bool { + self.presents_with_transaction + } + pub fn set_presents_with_transaction(&mut self, presents_with_transaction: bool) { self.presents_with_transaction = presents_with_transaction; if let Some(layer) = &self.layer { @@ -509,75 +480,6 @@ impl MetalRenderer { if let Some(layer) = &self.layer { layer.setDrawableSize(CGSize::new(size.width.0 as f64, size.height.0 as f64)); } - if let Err(error) = self.update_path_intermediate_textures(size) { - log::error!("failed to resize path textures: {error:#}"); - } - } - - fn update_path_intermediate_textures(&mut self, size: Size) -> Result<()> { - // We are uncertain when this happens, but sometimes size can be 0 here. Most likely before - // the layout pass on window creation. Zero-sized texture creation causes SIGABRT. - // https://github.com/zed-industries/zed/issues/36229 - if size.width.0 <= 0 || size.height.0 <= 0 { - self.path_intermediate_texture = None; - self.path_intermediate_msaa_texture = None; - return Ok(()); - } - - if self - .path_intermediate_texture - .as_ref() - .is_some_and(|texture| { - texture.width() == size.width.0 as usize - && texture.height() == size.height.0 as usize - }) - { - return Ok(()); - } - - self.path_intermediate_texture = None; - self.path_intermediate_msaa_texture = None; - let texture_descriptor = MTLTextureDescriptor::new(); - // SAFETY: The dimensions are positive and this descriptor creates a 2D texture. - unsafe { - texture_descriptor.setWidth(size.width.0 as usize); - texture_descriptor.setHeight(size.height.0 as usize); - } - texture_descriptor.setPixelFormat(MTLPixelFormat::BGRA8Unorm); - texture_descriptor.setStorageMode(MTLStorageMode::Private); - texture_descriptor.setUsage(MTLTextureUsage::RenderTarget | MTLTextureUsage::ShaderRead); - let intermediate_texture = self - .device - .newTextureWithDescriptor(&texture_descriptor) - .context("allocating path intermediate texture")?; - - let msaa_texture = if self.path_sample_count > 1 { - // https://developer.apple.com/documentation/metal/choosing-a-resource-storage-mode-for-apple-gpus - // Rendering MSAA textures are done in a single pass, so we can use memory-less storage on Apple Silicon - let storage_mode = if self.is_apple_gpu { - MTLStorageMode::Memoryless - } else { - MTLStorageMode::Private - }; - - let msaa_descriptor = texture_descriptor; - msaa_descriptor.setTextureType(MTLTextureType::Type2DMultisample); - msaa_descriptor.setStorageMode(storage_mode); - // SAFETY: The multisample texture uses the same sample count as its render pipeline. - unsafe { - msaa_descriptor.setSampleCount(self.path_sample_count as _); - } - Some( - self.device - .newTextureWithDescriptor(&msaa_descriptor) - .context("allocating multisample path texture")?, - ) - } else { - None - }; - self.path_intermediate_texture = Some(intermediate_texture); - self.path_intermediate_msaa_texture = msaa_texture; - Ok(()) } pub fn update_transparency(&mut self, transparent: bool) { @@ -652,9 +554,6 @@ impl MetalRenderer { texture: &ProtocolObject, viewport_size: Size, ) -> Result>> { - if self.path_intermediate_texture.is_none() { - self.update_path_intermediate_textures(viewport_size)?; - } let mut writer = InstanceBufferWriter::new( &self.device, &self.instance_buffer_pool, @@ -676,7 +575,6 @@ impl MetalRenderer { let command_buffer = self.draw_primitives_to_texture( scene, &instance_bindings, - &mut writer, texture, viewport_size, &mut surface_textures, @@ -737,10 +635,7 @@ impl MetalRenderer { // Headless callers do not have a Cocoa event-loop pool to release // autoreleased command buffers and render-pass descriptors. - objc2::rc::autoreleasepool(|_| { - self.update_path_intermediate_textures(size)?; - self.render_offscreen(scene, size) - }) + objc2::rc::autoreleasepool(|_| self.render_offscreen(scene, size)) } /// Renders a scene into a new offscreen texture of `size` and reads it @@ -805,8 +700,6 @@ impl MetalRenderer { } objc2::rc::autoreleasepool(|_| { - self.update_path_intermediate_textures(size)?; - let needs_new_target = self.headless_render_target.as_ref().is_none_or(|texture| { texture.width() != size.width.0 as usize || texture.height() != size.height.0 as usize @@ -845,7 +738,6 @@ impl MetalRenderer { &mut self, scene: &Scene, instance_bindings: &InstanceBindings, - writer: &mut InstanceBufferWriter, texture: &ProtocolObject, viewport_size: Size, surface_textures: &mut Vec>, @@ -855,66 +747,87 @@ impl MetalRenderer { .commandBuffer() .context("creating command buffer")?; let alpha = if self.opaque { 1. } else { 0. }; + let depth_texture = self.depth_texture_matching(texture)?; - let mut command_encoder = new_command_encoder_for_texture( + let command_encoder = new_command_encoder_for_texture( &command_buffer, texture, + &depth_texture, viewport_size, - Some(MTLClearColor { + MTLClearColor { red: 0., green: 0., blue: 0., alpha, - }), + }, )?; + let depth_scale = quad_depth_scale(scene.quads.len()); + // SAFETY: Metal copies both values, which match every vertex shader's + // `GlobalInputIndex_ViewportSize` and `GlobalInputIndex_DepthScale` arguments. + unsafe { + command_encoder.setVertexBytes_length_atIndex( + ptr::NonNull::from(&viewport_size).cast(), + mem::size_of_val(&viewport_size), + GlobalInputIndex::ViewportSize as usize, + ); + command_encoder.setVertexBytes_length_atIndex( + ptr::NonNull::from(&depth_scale).cast(), + mem::size_of_val(&depth_scale), + GlobalInputIndex::DepthScale as usize, + ); + } + self.draw_opaque_quads(scene.quads.len(), instance_bindings, &command_encoder); + command_encoder.setDepthStencilState(Some(&self.depth_test_state)); + + let mut quad_cursor: u32 = 0; + let mut path_tile_cursor = 0; for batch in scene.batches() { + // Quad shaders assign each quad its own depth. + // In every other batch type, the depth is fixed to the position of the quad cursor. + let (znear, zfar) = if matches!(&batch, PrimitiveBatch::Quads(_)) { + (0.0, 1.0) + } else { + let depth = quad_depth(quad_cursor, depth_scale) as f64; + (depth, depth) + }; + command_encoder.setViewport(MTLViewport { + originX: 0.0, + originY: 0.0, + width: i32::from(viewport_size.width) as f64, + height: i32::from(viewport_size.height) as f64, + znear, + zfar, + }); + match batch { PrimitiveBatch::Shadows(range) => { - self.draw_shadows(range, instance_bindings, viewport_size, &command_encoder) + self.draw_shadows(range, instance_bindings, &command_encoder) } PrimitiveBatch::Quads(range) => { - self.draw_quads(range, instance_bindings, viewport_size, &command_encoder) + quad_cursor += range.len() as u32; + self.draw_quads(range, instance_bindings, &command_encoder) } PrimitiveBatch::Paths(range) => { - let paths = &scene.paths[range]; - command_encoder.endEncoding(); - - let did_draw = self.draw_paths_to_intermediate( - paths, - writer, - viewport_size, - &command_buffer, - )?; - - command_encoder = new_command_encoder_for_texture( - &command_buffer, - texture, - viewport_size, - None, - )?; - - if did_draw { - if let Err(error) = self.draw_paths_from_intermediate( - paths, - writer, - viewport_size, - &command_encoder, - ) { - command_encoder.endEncoding(); - return Err(error); - } - } + let tiles_start = path_tile_cursor; + path_tile_cursor += scene.paths[range] + .iter() + .map(PaintedPath::tile_count) + .sum::(); + self.draw_path_tiles( + tiles_start..path_tile_cursor, + instance_bindings, + &command_encoder, + ) } PrimitiveBatch::Underlines(range) => { - self.draw_underlines(range, instance_bindings, viewport_size, &command_encoder) + self.draw_underlines(range, instance_bindings, &command_encoder) } PrimitiveBatch::MonochromeSprites { texture_id, range } => self .draw_monochrome_sprites( texture_id, range, instance_bindings, - viewport_size, &command_encoder, ), PrimitiveBatch::PolychromeSprites { texture_id, range } => self @@ -922,7 +835,6 @@ impl MetalRenderer { texture_id, range, instance_bindings, - viewport_size, &command_encoder, ), PrimitiveBatch::Surfaces(range) => { @@ -930,7 +842,6 @@ impl MetalRenderer { &scene.surfaces[range.clone()], range.start, instance_bindings, - viewport_size, &command_encoder, surface_textures, ) { @@ -947,95 +858,128 @@ impl MetalRenderer { Ok(command_buffer) } - fn draw_paths_to_intermediate( - &self, - paths: &[Path], - writer: &mut InstanceBufferWriter, - viewport_size: Size, - command_buffer: &ProtocolObject, - ) -> Result { - if paths.is_empty() { - return Ok(false); + fn depth_texture_matching( + &mut self, + target: &ProtocolObject, + ) -> Result>> { + if let Some(depth_texture) = &self.depth_texture + && depth_texture.width() == target.width() + && depth_texture.height() == target.height() + { + return Ok(depth_texture.clone()); } - let intermediate_texture = self - .path_intermediate_texture - .as_ref() - .context("missing path intermediate texture")?; - - let mut vertices = Vec::new(); - for path in paths { - vertices.extend(path.vertices.iter().map(|v| PathRasterizationVertex { - xy_position: v.xy_position, - st_position: v.st_position, - color: path.color, - bounds: path.bounds.intersect(&path.content_mask.bounds), - })); + let descriptor = MTLTextureDescriptor::new(); + // SAFETY: The size is the size of an existing render target, which the device supports. + unsafe { + descriptor.setWidth(target.width()); + descriptor.setHeight(target.height()); } - let vertex_instance_bindings = writer.write(&vertices)?; - - let render_pass_descriptor = MTLRenderPassDescriptor::new(); - // SAFETY: Index zero is within the render pass's color attachment array. - let color_attachment = unsafe { - render_pass_descriptor - .colorAttachments() - .objectAtIndexedSubscript(0) - }; - color_attachment.setLoadAction(MTLLoadAction::Clear); - color_attachment.setClearColor(MTLClearColor { - red: 0., - green: 0., - blue: 0., - alpha: 0., - }); - - if let Some(msaa_texture) = &self.path_intermediate_msaa_texture { - color_attachment.setTexture(Some(msaa_texture)); - color_attachment.setResolveTexture(Some(intermediate_texture)); - color_attachment.setStoreAction(MTLStoreAction::MultisampleResolve); + descriptor.setPixelFormat(MTLPixelFormat::Depth32Float); + descriptor.setUsage(MTLTextureUsage::RenderTarget); + // The depth buffer never leaves its render pass, so Apple GPUs can keep + // it in tile memory without allocating any backing store. + descriptor.setStorageMode(if self.is_apple_gpu { + MTLStorageMode::Memoryless } else { - color_attachment.setTexture(Some(intermediate_texture)); - color_attachment.setStoreAction(MTLStoreAction::Store); - } + MTLStorageMode::Private + }); + let depth_texture = self + .device + .newTextureWithDescriptor(&descriptor) + .context("allocating depth texture")?; + self.depth_texture = Some(depth_texture.clone()); + Ok(depth_texture) + } - let command_encoder = command_buffer - .renderCommandEncoderWithDescriptor(&render_pass_descriptor) - .context("creating path render command encoder")?; - command_encoder.setRenderPipelineState(&self.paths_rasterization_pipeline_state); - // SAFETY: The binding contains vertices.len() shader-compatible vertices at an aligned offset. - // Metal retains the buffer, and writer.finish publishes CPU writes before submission. - // The viewport bytes are copied from a live value into the matching shader slot. + fn draw_opaque_quads( + &self, + quad_count: usize, + instance_bindings: &InstanceBindings, + command_encoder: &ProtocolObject, + ) { + if quad_count == 0 { + return; + } + let quad_count_value = quad_count as u32; + + command_encoder.setRenderPipelineState(&self.opaque_quads_pipeline_state); + command_encoder.setDepthStencilState(Some(&self.depth_write_state)); + // SAFETY: The scene's quads and the copied count match the shader layouts and slots. + // Metal retains the buffer, and writer.finish publishes its writes. unsafe { command_encoder.setVertexBuffer_offset_atIndex( - Some(&vertex_instance_bindings.buffer), - vertex_instance_bindings.offset, - PathRasterizationInputIndex::Vertices as usize, + Some(&instance_bindings.quads.buffer), + instance_bindings.quads.offset, + QuadInputIndex::Quads as usize, ); command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - PathRasterizationInputIndex::ViewportSize as usize, + ptr::NonNull::from(&quad_count_value).cast(), + mem::size_of_val(&quad_count_value), + QuadInputIndex::QuadCount as usize, ); - command_encoder.setFragmentBuffer_offset_atIndex( - Some(&vertex_instance_bindings.buffer), - vertex_instance_bindings.offset, - PathRasterizationInputIndex::Vertices as usize, - ); - command_encoder.drawPrimitives_vertexStart_vertexCount( - MTLPrimitiveType::Triangle, + command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( + MTLPrimitiveType::TriangleStrip, + 0, + 4, + quad_count, 0, - vertices.len(), ); } + } - command_encoder.endEncoding(); - Ok(true) + fn draw_path_tiles( + &self, + tiles: Range, + instance_bindings: &InstanceBindings, + command_encoder: &ProtocolObject, + ) { + if tiles.is_empty() { + return; + } + + command_encoder.setRenderPipelineState(&self.path_tiles_pipeline_state); + // SAFETY: The scene's tile range and its curves and paints match the uploaded shader layouts and slots. + // Metal retains the buffers, and writer.finish publishes their writes. + unsafe { + command_encoder.setVertexBuffer_offset_atIndex( + Some(&instance_bindings.path_tiles.buffer), + instance_bindings.path_tiles.offset, + PathTileInputIndex::Tiles as usize, + ); + command_encoder.setVertexBuffer_offset_atIndex( + Some(&instance_bindings.path_paints.buffer), + instance_bindings.path_paints.offset, + PathTileInputIndex::Paints as usize, + ); + command_encoder.setFragmentBuffer_offset_atIndex( + Some(&instance_bindings.path_tiles.buffer), + instance_bindings.path_tiles.offset, + PathTileInputIndex::Tiles as usize, + ); + command_encoder.setFragmentBuffer_offset_atIndex( + Some(&instance_bindings.path_curves.buffer), + instance_bindings.path_curves.offset, + PathTileInputIndex::Curves as usize, + ); + command_encoder.setFragmentBuffer_offset_atIndex( + Some(&instance_bindings.path_paints.buffer), + instance_bindings.path_paints.offset, + PathTileInputIndex::Paints as usize, + ); + command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( + MTLPrimitiveType::TriangleStrip, + 0, + 4, + tiles.len(), + tiles.start, + ); + } } fn draw_shadows( &self, shadows: Range, instance_bindings: &InstanceBindings, - viewport_size: Size, command_encoder: &ProtocolObject, ) { if shadows.is_empty() { @@ -1043,14 +987,9 @@ impl MetalRenderer { } command_encoder.setRenderPipelineState(&self.shadows_pipeline_state); - // SAFETY: Six unit vertices and the scene's shadow range match the uploaded shader layouts and slots. - // Metal retains the buffers, writer.finish publishes their writes, and viewport bytes are copied. + // SAFETY: The scene's shadow range matches the uploaded shader layouts and slots. + // Metal retains the buffers, and writer.finish publishes their writes. unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&self.unit_vertices), - 0, - ShadowInputIndex::Vertices as usize, - ); command_encoder.setVertexBuffer_offset_atIndex( Some(&instance_bindings.shadows.buffer), instance_bindings.shadows.offset, @@ -1061,15 +1000,10 @@ impl MetalRenderer { instance_bindings.shadows.offset, ShadowInputIndex::Shadows as usize, ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - ShadowInputIndex::ViewportSize as usize, - ); command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( - MTLPrimitiveType::Triangle, + MTLPrimitiveType::TriangleStrip, 0, - 6, + 4, shadows.len(), shadows.start, ); @@ -1080,7 +1014,6 @@ impl MetalRenderer { &self, quads: Range, instance_bindings: &InstanceBindings, - viewport_size: Size, command_encoder: &ProtocolObject, ) { if quads.is_empty() { @@ -1088,14 +1021,9 @@ impl MetalRenderer { } command_encoder.setRenderPipelineState(&self.quads_pipeline_state); - // SAFETY: Six unit vertices and the scene's quad range match the uploaded shader layouts and slots. - // Metal retains the buffers, writer.finish publishes their writes, and viewport bytes are copied. + // SAFETY: The scene's quad range matches the uploaded shader layouts and slots. + // Metal retains the buffers, and writer.finish publishes their writes. unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&self.unit_vertices), - 0, - QuadInputIndex::Vertices as usize, - ); command_encoder.setVertexBuffer_offset_atIndex( Some(&instance_bindings.quads.buffer), instance_bindings.quads.offset, @@ -1106,103 +1034,20 @@ impl MetalRenderer { instance_bindings.quads.offset, QuadInputIndex::Quads as usize, ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - QuadInputIndex::ViewportSize as usize, - ); command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( - MTLPrimitiveType::Triangle, + MTLPrimitiveType::TriangleStrip, 0, - 6, + 4, quads.len(), quads.start, ); } } - fn draw_paths_from_intermediate( - &self, - paths: &[Path], - writer: &mut InstanceBufferWriter, - viewport_size: Size, - command_encoder: &ProtocolObject, - ) -> Result<()> { - let (Some(first_path), Some(last_path)) = (paths.first(), paths.last()) else { - return Ok(()); - }; - let intermediate_texture = self - .path_intermediate_texture - .as_ref() - .context("missing path intermediate texture")?; - - command_encoder.setRenderPipelineState(&self.path_sprites_pipeline_state); - // SAFETY: The shader slots match the unit vertices, copied viewport, and retained path texture. - // The preceding render pass writes this tracked texture before it is sampled. - unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&self.unit_vertices), - 0, - SpriteInputIndex::Vertices as usize, - ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - SpriteInputIndex::ViewportSize as usize, - ); - command_encoder.setFragmentTexture_atIndex( - Some(intermediate_texture), - SpriteInputIndex::AtlasTexture as usize, - ); - } - - // When copying paths from the intermediate texture to the drawable, - // each pixel must only be copied once, in case of transparent paths. - // - // If all paths have the same draw order, then their bounds are all - // disjoint, so we can copy each path's bounds individually. If this - // batch combines different draw orders, we perform a single copy - // for a minimal spanning rect. - let sprites; - if last_path.order == first_path.order { - sprites = paths - .iter() - .map(|path| PathSprite { - bounds: path.clipped_bounds(), - }) - .collect(); - } else { - let mut bounds = first_path.clipped_bounds(); - for path in paths.iter().skip(1) { - bounds = bounds.union(&path.clipped_bounds()); - } - sprites = vec![PathSprite { bounds }]; - } - - let sprite_instance_bindings = writer.write(&sprites)?; - // SAFETY: The draw uses six unit vertices and exactly the sprites written at this aligned binding. - // Metal retains the buffer, and writer.finish publishes CPU writes before submission. - unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&sprite_instance_bindings.buffer), - sprite_instance_bindings.offset, - SpriteInputIndex::Sprites as usize, - ); - command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount( - MTLPrimitiveType::Triangle, - 0, - 6, - sprites.len(), - ); - } - Ok(()) - } - fn draw_underlines( &self, underlines: Range, instance_bindings: &InstanceBindings, - viewport_size: Size, command_encoder: &ProtocolObject, ) { if underlines.is_empty() { @@ -1210,14 +1055,9 @@ impl MetalRenderer { } command_encoder.setRenderPipelineState(&self.underlines_pipeline_state); - // SAFETY: Six unit vertices and the scene's underline range match the uploaded shader layouts and slots. - // Metal retains the buffers, writer.finish publishes their writes, and viewport bytes are copied. + // SAFETY: The scene's underline range matches the uploaded shader layouts and slots. + // Metal retains the buffers, and writer.finish publishes their writes. unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&self.unit_vertices), - 0, - UnderlineInputIndex::Vertices as usize, - ); command_encoder.setVertexBuffer_offset_atIndex( Some(&instance_bindings.underlines.buffer), instance_bindings.underlines.offset, @@ -1228,15 +1068,10 @@ impl MetalRenderer { instance_bindings.underlines.offset, UnderlineInputIndex::Underlines as usize, ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - UnderlineInputIndex::ViewportSize as usize, - ); command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( - MTLPrimitiveType::Triangle, + MTLPrimitiveType::TriangleStrip, 0, - 6, + 4, underlines.len(), underlines.start, ); @@ -1248,7 +1083,6 @@ impl MetalRenderer { texture_id: AtlasTextureId, sprites: Range, instance_bindings: &InstanceBindings, - viewport_size: Size, command_encoder: &ProtocolObject, ) { if sprites.is_empty() { @@ -1263,24 +1097,14 @@ impl MetalRenderer { DevicePixels(texture.height() as i32), ); command_encoder.setRenderPipelineState(&self.monochrome_sprites_pipeline_state); - // SAFETY: The scene's sprite range, six unit vertices, and copied sizes match the shader layouts and slots. + // SAFETY: The scene's sprite range and copied sizes match the shader layouts and slots. // Metal retains the buffers and texture, and writer.finish publishes the instance writes. unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&self.unit_vertices), - 0, - SpriteInputIndex::Vertices as usize, - ); command_encoder.setVertexBuffer_offset_atIndex( Some(&instance_bindings.monochrome_sprites.buffer), instance_bindings.monochrome_sprites.offset, SpriteInputIndex::Sprites as usize, ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - SpriteInputIndex::ViewportSize as usize, - ); command_encoder.setVertexBytes_length_atIndex( ptr::NonNull::from(&texture_size).cast(), mem::size_of_val(&texture_size), @@ -1296,9 +1120,9 @@ impl MetalRenderer { SpriteInputIndex::AtlasTexture as usize, ); command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( - MTLPrimitiveType::Triangle, + MTLPrimitiveType::TriangleStrip, 0, - 6, + 4, sprites.len(), sprites.start, ); @@ -1310,7 +1134,6 @@ impl MetalRenderer { texture_id: AtlasTextureId, sprites: Range, instance_bindings: &InstanceBindings, - viewport_size: Size, command_encoder: &ProtocolObject, ) { if sprites.is_empty() { @@ -1325,24 +1148,14 @@ impl MetalRenderer { DevicePixels(texture.height() as i32), ); command_encoder.setRenderPipelineState(&self.polychrome_sprites_pipeline_state); - // SAFETY: The scene's sprite range, six unit vertices, and copied sizes match the shader layouts and slots. + // SAFETY: The scene's sprite range and copied sizes match the shader layouts and slots. // Metal retains the buffers and texture, and writer.finish publishes the instance writes. unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&self.unit_vertices), - 0, - SpriteInputIndex::Vertices as usize, - ); command_encoder.setVertexBuffer_offset_atIndex( Some(&instance_bindings.polychrome_sprites.buffer), instance_bindings.polychrome_sprites.offset, SpriteInputIndex::Sprites as usize, ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - SpriteInputIndex::ViewportSize as usize, - ); command_encoder.setVertexBytes_length_atIndex( ptr::NonNull::from(&texture_size).cast(), mem::size_of_val(&texture_size), @@ -1358,9 +1171,9 @@ impl MetalRenderer { SpriteInputIndex::AtlasTexture as usize, ); command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( - MTLPrimitiveType::Triangle, + MTLPrimitiveType::TriangleStrip, 0, - 6, + 4, sprites.len(), sprites.start, ); @@ -1372,7 +1185,6 @@ impl MetalRenderer { surfaces: &[PaintSurface], first_surface: usize, instance_bindings: &InstanceBindings, - viewport_size: Size, command_encoder: &ProtocolObject, surface_textures: &mut Vec>, ) -> Result<()> { @@ -1381,24 +1193,14 @@ impl MetalRenderer { } command_encoder.setRenderPipelineState(&self.surfaces_pipeline_state); - // SAFETY: The unit vertices, SurfaceBounds instances, and copied viewport match the shader layouts and slots. + // SAFETY: The SurfaceBounds instances match the shader layout and slot. // Metal retains the buffers, and writer.finish publishes CPU writes before submission. unsafe { - command_encoder.setVertexBuffer_offset_atIndex( - Some(&self.unit_vertices), - 0, - SurfaceInputIndex::Vertices as usize, - ); command_encoder.setVertexBuffer_offset_atIndex( Some(&instance_bindings.surfaces.buffer), instance_bindings.surfaces.offset, SurfaceInputIndex::Surfaces as usize, ); - command_encoder.setVertexBytes_length_atIndex( - ptr::NonNull::from(&viewport_size).cast(), - mem::size_of_val(&viewport_size), - SurfaceInputIndex::ViewportSize as usize, - ); } for (index, surface) in surfaces.iter().enumerate() { @@ -1467,12 +1269,12 @@ impl MetalRenderer { } surface_textures.extend([y_texture, cb_cr_texture]); - // SAFETY: Six unit vertices draw one instance within the uploaded scene's surface range. + // SAFETY: This draws one instance within the uploaded scene's surface range. unsafe { command_encoder.drawPrimitives_vertexStart_vertexCount_instanceCount_baseInstance( - MTLPrimitiveType::Triangle, + MTLPrimitiveType::TriangleStrip, 0, - 6, + 4, 1, first_surface + index, ); @@ -1485,8 +1287,9 @@ impl MetalRenderer { fn new_command_encoder_for_texture( command_buffer: &ProtocolObject, texture: &ProtocolObject, + depth_texture: &ProtocolObject, viewport_size: Size, - clear_color: Option, + clear_color: MTLClearColor, ) -> Result>> { let render_pass_descriptor = MTLRenderPassDescriptor::new(); // SAFETY: Index zero is within the render pass's color attachment array. @@ -1497,12 +1300,15 @@ fn new_command_encoder_for_texture( }; color_attachment.setTexture(Some(texture)); color_attachment.setStoreAction(MTLStoreAction::Store); - if let Some(clear_color) = clear_color { - color_attachment.setLoadAction(MTLLoadAction::Clear); - color_attachment.setClearColor(clear_color); - } else { - color_attachment.setLoadAction(MTLLoadAction::Load); - } + color_attachment.setLoadAction(MTLLoadAction::Clear); + color_attachment.setClearColor(clear_color); + + let depth_attachment = render_pass_descriptor.depthAttachment(); + depth_attachment.setTexture(Some(depth_texture)); + depth_attachment.setLoadAction(MTLLoadAction::Clear); + depth_attachment.setClearDepth(0.0); + // The depth buffer is only needed within this pass. + depth_attachment.setStoreAction(MTLStoreAction::DontCare); let command_encoder = command_buffer .renderCommandEncoderWithDescriptor(&render_pass_descriptor) @@ -1557,6 +1363,7 @@ fn build_pipeline_state( vertex_fn_name: &str, fragment_fn_name: &str, pixel_format: MTLPixelFormat, + blending: bool, ) -> Result>> { let vertex_fn = library .newFunctionWithName(&NSString::from_str(vertex_fn_name)) @@ -1572,92 +1379,30 @@ fn build_pipeline_state( // SAFETY: Index zero is within the pipeline's color attachment array. let color_attachment = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }; color_attachment.setPixelFormat(pixel_format); - color_attachment.setBlendingEnabled(true); + color_attachment.setBlendingEnabled(blending); color_attachment.setRgbBlendOperation(MTLBlendOperation::Add); color_attachment.setAlphaBlendOperation(MTLBlendOperation::Add); color_attachment.setSourceRGBBlendFactor(MTLBlendFactor::SourceAlpha); color_attachment.setSourceAlphaBlendFactor(MTLBlendFactor::One); color_attachment.setDestinationRGBBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); color_attachment.setDestinationAlphaBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); + descriptor.setDepthAttachmentPixelFormat(MTLPixelFormat::Depth32Float); device .newRenderPipelineStateWithDescriptor_error(&descriptor) .with_context(|| format!("creating {label} render pipeline")) } -fn build_path_sprite_pipeline_state( +fn build_depth_stencil_state( device: &ProtocolObject, - library: &ProtocolObject, - label: &str, - vertex_fn_name: &str, - fragment_fn_name: &str, - pixel_format: MTLPixelFormat, -) -> Result>> { - let vertex_fn = library - .newFunctionWithName(&NSString::from_str(vertex_fn_name)) - .with_context(|| format!("locating vertex function {vertex_fn_name}"))?; - let fragment_fn = library - .newFunctionWithName(&NSString::from_str(fragment_fn_name)) - .with_context(|| format!("locating fragment function {fragment_fn_name}"))?; - - let descriptor = MTLRenderPipelineDescriptor::new(); - descriptor.setLabel(Some(&NSString::from_str(label))); - descriptor.setVertexFunction(Some(vertex_fn.as_ref())); - descriptor.setFragmentFunction(Some(fragment_fn.as_ref())); - // SAFETY: Index zero is within the pipeline's color attachment array. - let color_attachment = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }; - color_attachment.setPixelFormat(pixel_format); - color_attachment.setBlendingEnabled(true); - color_attachment.setRgbBlendOperation(MTLBlendOperation::Add); - color_attachment.setAlphaBlendOperation(MTLBlendOperation::Add); - color_attachment.setSourceRGBBlendFactor(MTLBlendFactor::One); - color_attachment.setSourceAlphaBlendFactor(MTLBlendFactor::One); - color_attachment.setDestinationRGBBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); - color_attachment.setDestinationAlphaBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); - + write_depth: bool, +) -> Result>> { + let descriptor = MTLDepthStencilDescriptor::new(); + descriptor.setDepthCompareFunction(MTLCompareFunction::Greater); + descriptor.setDepthWriteEnabled(write_depth); device - .newRenderPipelineStateWithDescriptor_error(&descriptor) - .with_context(|| format!("creating {label} render pipeline")) -} - -fn build_path_rasterization_pipeline_state( - device: &ProtocolObject, - library: &ProtocolObject, - label: &str, - vertex_fn_name: &str, - fragment_fn_name: &str, - pixel_format: MTLPixelFormat, - path_sample_count: u32, -) -> Result>> { - let vertex_fn = library - .newFunctionWithName(&NSString::from_str(vertex_fn_name)) - .with_context(|| format!("locating vertex function {vertex_fn_name}"))?; - let fragment_fn = library - .newFunctionWithName(&NSString::from_str(fragment_fn_name)) - .with_context(|| format!("locating fragment function {fragment_fn_name}"))?; - - let descriptor = MTLRenderPipelineDescriptor::new(); - descriptor.setLabel(Some(&NSString::from_str(label))); - descriptor.setVertexFunction(Some(vertex_fn.as_ref())); - descriptor.setFragmentFunction(Some(fragment_fn.as_ref())); - if path_sample_count > 1 { - descriptor.setRasterSampleCount(path_sample_count as _); - descriptor.setAlphaToCoverageEnabled(false); - } - // SAFETY: Index zero is within the pipeline's color attachment array. - let color_attachment = unsafe { descriptor.colorAttachments().objectAtIndexedSubscript(0) }; - color_attachment.setPixelFormat(pixel_format); - color_attachment.setBlendingEnabled(true); - color_attachment.setRgbBlendOperation(MTLBlendOperation::Add); - color_attachment.setAlphaBlendOperation(MTLBlendOperation::Add); - color_attachment.setSourceRGBBlendFactor(MTLBlendFactor::One); - color_attachment.setSourceAlphaBlendFactor(MTLBlendFactor::One); - color_attachment.setDestinationRGBBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); - color_attachment.setDestinationAlphaBlendFactor(MTLBlendFactor::OneMinusSourceAlpha); - - device - .newRenderPipelineStateWithDescriptor_error(&descriptor) - .with_context(|| format!("creating {label} render pipeline")) + .newDepthStencilStateWithDescriptor(&descriptor) + .context("creating depth stencil state") } #[derive(Clone)] @@ -1668,6 +1413,9 @@ struct InstanceBinding { struct InstanceBindings { quads: InstanceBinding, + path_tiles: InstanceBinding, + path_curves: InstanceBinding, + path_paints: InstanceBinding, shadows: InstanceBinding, underlines: InstanceBinding, monochrome_sprites: InstanceBinding, @@ -1676,8 +1424,17 @@ struct InstanceBindings { } fn write_instances(scene: &Scene, writer: &mut InstanceBufferWriter) -> Result { + let mut path_paints = Vec::with_capacity(scene.paths.len()); + let mut path_curves = Vec::new(); + let mut path_tiles = Vec::new(); + for path in &scene.paths { + path.append_to(&mut path_paints, &mut path_curves, &mut path_tiles); + } Ok(InstanceBindings { quads: writer.write(&scene.quads)?, + path_tiles: writer.write(&path_tiles)?, + path_curves: writer.write(&path_curves)?, + path_paints: writer.write(&path_paints)?, shadows: writer.write(&scene.shadows)?, underlines: writer.write(&scene.underlines)?, monochrome_sprites: writer.write(&scene.monochrome_sprites)?, @@ -1826,56 +1583,50 @@ impl InstanceBufferWriter { } } +/// Vertex buffer slots bound once per render pass and shared by every +/// pipeline. Each primitive's own slots start after these. +#[repr(C)] +enum GlobalInputIndex { + ViewportSize = 0, + DepthScale = 1, +} + #[repr(C)] enum ShadowInputIndex { - Vertices = 0, - Shadows = 1, - ViewportSize = 2, + Shadows = 2, } #[repr(C)] enum QuadInputIndex { - Vertices = 0, - Quads = 1, - ViewportSize = 2, + Quads = 2, + QuadCount = 3, } #[repr(C)] enum UnderlineInputIndex { - Vertices = 0, - Underlines = 1, - ViewportSize = 2, + Underlines = 2, } #[repr(C)] enum SpriteInputIndex { - Vertices = 0, - Sprites = 1, - ViewportSize = 2, + Sprites = 2, AtlasTextureSize = 3, AtlasTexture = 4, } #[repr(C)] enum SurfaceInputIndex { - Vertices = 0, - Surfaces = 1, - ViewportSize = 2, + Surfaces = 2, TextureSize = 3, YTexture = 4, CbCrTexture = 5, } #[repr(C)] -enum PathRasterizationInputIndex { - Vertices = 0, - ViewportSize = 1, -} - -#[derive(Clone, Debug, Eq, PartialEq)] -#[repr(C)] -pub struct PathSprite { - pub bounds: Bounds, +enum PathTileInputIndex { + Tiles = 2, + Curves = 3, + Paints = 4, } #[derive(Clone, Debug, Eq, PartialEq)] @@ -1921,6 +1672,7 @@ impl gpui::PlatformHeadlessRenderer for MetalHeadlessRenderer { #[cfg(test)] mod tests { use super::*; + use gpui::Point; use objc2_core_foundation::{CFDictionary, CFType}; use objc2_core_video::{ CVPixelBufferCreate, CVPixelBufferGetBaseAddressOfPlane, @@ -1929,60 +1681,6 @@ mod tests { }; use objc2_metal::MTLCommandBufferStatus; - #[test] - fn path_intermediate_textures_are_reused_until_resize() -> Result<()> { - let mut renderer = MetalRenderer::new_headless(Default::default())?; - let initial_size = size(DevicePixels(64), DevicePixels(64)); - renderer.update_path_intermediate_textures(initial_size)?; - let initial_texture = renderer - .path_intermediate_texture - .clone() - .context("missing path intermediate texture")?; - let initial_msaa_texture = renderer.path_intermediate_msaa_texture.clone(); - - renderer.update_path_intermediate_textures(initial_size)?; - assert!(ptr::eq( - &*initial_texture, - renderer - .path_intermediate_texture - .as_deref() - .context("missing reused texture")?, - )); - assert_eq!( - initial_msaa_texture.as_ref().map(Retained::as_ptr), - renderer - .path_intermediate_msaa_texture - .as_ref() - .map(Retained::as_ptr), - ); - - renderer.update_path_intermediate_textures(size(DevicePixels(128), DevicePixels(64)))?; - let resized_texture = renderer - .path_intermediate_texture - .as_deref() - .context("missing resized texture")?; - assert_eq!( - (resized_texture.width(), resized_texture.height()), - (128, 64) - ); - assert!(!ptr::eq(&*initial_texture, resized_texture)); - if let Some(texture) = &renderer.path_intermediate_msaa_texture { - assert_eq!((texture.width(), texture.height()), (128, 64)); - } - - for (width, height) in [(0, 64), (64, 0), (-1, 64), (64, -1)] { - renderer.update_path_intermediate_textures(size( - DevicePixels(width), - DevicePixels(height), - ))?; - assert!(renderer.path_intermediate_texture.is_none()); - assert!(renderer.path_intermediate_msaa_texture.is_none()); - renderer.update_path_intermediate_textures(initial_size)?; - assert!(renderer.path_intermediate_texture.is_some()); - } - Ok(()) - } - #[test] fn render_to_image_rejects_zero_sized_layer() -> Result<()> { let mut renderer = MetalRenderer::new(Default::default(), false, false)?; diff --git a/crates/gpui_apple/src/shaders.metal b/crates/gpui_apple/src/shaders.metal index 2b52bb9ecc0..ef9163cdacb 100644 --- a/crates/gpui_apple/src/shaders.metal +++ b/crates/gpui_apple/src/shaders.metal @@ -3,11 +3,15 @@ using namespace metal; +constant uint SIMPLE_PRIMITIVE_FLAG = 1u << 31; + float4 hsla_to_rgba(Hsla hsla); float3 srgb_to_linear(float3 color); float3 linear_to_srgb(float3 color); float4 srgb_to_oklab(float4 color); float4 oklab_to_srgb(float4 color); +float4 to_device_position_impl(float2 position, + constant Size_DevicePixels *viewport_size); float4 to_device_position(float2 unit_vertex, Bounds_ScaledPixels bounds, constant Size_DevicePixels *viewport_size); float4 to_device_position_transformed(float2 unit_vertex, Bounds_ScaledPixels bounds, @@ -16,10 +20,17 @@ float4 to_device_position_transformed(float2 unit_vertex, Bounds_ScaledPixels bo float2 to_tile_position(float2 unit_vertex, AtlasTile tile, constant Size_DevicePixels *atlas_size); -float4 distance_from_clip_rect(float2 unit_vertex, Bounds_ScaledPixels bounds, - Bounds_ScaledPixels clip_bounds); float4 distance_from_clip_rect_transformed(float2 unit_vertex, Bounds_ScaledPixels bounds, Bounds_ScaledPixels clip_bounds, TransformationMatrix transformation); + +struct ClippedVertex { + float2 position; + // The corner as a fraction of the original bounds. + float2 unit_vertex; +}; + +ClippedVertex clip_to_mask(float2 unit_vertex, Bounds_ScaledPixels bounds, + Bounds_ScaledPixels mask); float corner_dash_velocity(float dv1, float dv2); float dash_alpha(float t, float period, float length, float dash_velocity, float antialias_threshold); @@ -28,96 +39,85 @@ float pick_corner_radius(float2 center_to_point, Corners_ScaledPixels corner_rad float quad_sdf(float2 point, Bounds_ScaledPixels bounds, Corners_ScaledPixels corner_radii); float quad_sdf_impl(float2 center_to_point, float corner_radius); -float gaussian(float x, float sigma); -float2 erf(float2 x); -float blur_along_x(float x, float y, float sigma, float corner, - float2 half_size); float4 over(float4 below, float4 above); float radians(float degrees); -float4 fill_color(Background background, float2 position, Bounds_ScaledPixels bounds, - float4 solid_color, float4 color0, float4 color1); -struct GradientColor { - float4 solid; - float4 color0; - float4 color1; +struct PreparedBackground { + float4 color0 [[flat]]; + float4 color1 [[flat]]; + uint tag [[flat]]; }; -GradientColor prepare_fill_color(uint tag, uint color_space, Hsla solid, Hsla color0, Hsla color1); -struct QuadVertexOutput { - uint quad_id [[flat]]; - float4 position [[position]]; - float4 border_color [[flat]]; - float4 background_solid [[flat]]; - float4 background_color0 [[flat]]; - float4 background_color1 [[flat]]; - float clip_distance [[clip_distance]][4]; -}; +PreparedBackground prepare_background(Background background); +float dither_offset(float2 position); +float4 background_color(PreparedBackground prepared, Background background, + Bounds_ScaledPixels bounds, float2 position); +bool has_rounded_corners(Corners_ScaledPixels corner_radii); +bool has_border(Edges_ScaledPixels border_widths); +bool is_shaped(Quad quad); struct QuadFragmentInput { uint quad_id [[flat]]; float4 position [[position]]; float4 border_color [[flat]]; - float4 background_solid [[flat]]; - float4 background_color0 [[flat]]; - float4 background_color1 [[flat]]; + PreparedBackground background; }; -vertex QuadVertexOutput quad_vertex(uint unit_vertex_id [[vertex_id]], - uint quad_id [[instance_id]], - constant float2 *unit_vertices - [[buffer(QuadInputIndex_Vertices)]], - constant Quad *quads - [[buffer(QuadInputIndex_Quads)]], - constant Size_DevicePixels *viewport_size - [[buffer(QuadInputIndex_ViewportSize)]]) { - float2 unit_vertex = unit_vertices[unit_vertex_id]; +constant float4 CULLED_POSITION = float4(0., 0., 0., 1.); + +float quad_depth(uint quad_id, float depth_scale) { + return saturate(float(quad_id + 1u) * depth_scale); +} + +// Opaque rectangles are drawn by the opaque pass instead of the quad pass. +bool is_opaque_rectangle(Quad quad) { + return quad.background.tag == 0u && quad.background.solid.a >= 1.0 && + !has_rounded_corners(quad.corner_radii) && + !has_border(quad.border_widths); +} + +vertex QuadFragmentInput quad_vertex( + uint vertex_id [[vertex_id]], uint quad_id [[instance_id]], + constant Quad *quads [[buffer(QuadInputIndex_Quads)]], + constant Size_DevicePixels *viewport_size + [[buffer(GlobalInputIndex_ViewportSize)]], + constant float *depth_scale [[buffer(GlobalInputIndex_DepthScale)]]) { Quad quad = quads[quad_id]; + if (is_opaque_rectangle(quad)) { + QuadFragmentInput culled = {}; + culled.position = CULLED_POSITION; + return culled; + } + + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + ClippedVertex clipped = + clip_to_mask(unit_vertex, quad.bounds, quad.content_mask.bounds); float4 device_position = - to_device_position(unit_vertex, quad.bounds, viewport_size); - float4 clip_distance = distance_from_clip_rect(unit_vertex, quad.bounds, - quad.content_mask.bounds); + to_device_position_impl(clipped.position, viewport_size); + device_position.z = quad_depth(quad_id, *depth_scale); float4 border_color = hsla_to_rgba(quad.border_color); + bool simple = !is_shaped(quad) && quad.background.tag == 0u; + PreparedBackground background = prepare_background(quad.background); - GradientColor gradient = prepare_fill_color( - quad.background.tag, - quad.background.color_space, - quad.background.solid, - quad.background.colors[0].color, - quad.background.colors[1].color - ); - - return QuadVertexOutput{ - quad_id, + return QuadFragmentInput{ + quad_id | (simple ? SIMPLE_PRIMITIVE_FLAG : 0u), device_position, border_color, - gradient.solid, - gradient.color0, - gradient.color1, - {clip_distance.x, clip_distance.y, clip_distance.z, clip_distance.w}}; + background}; } fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]], constant Quad *quads [[buffer(QuadInputIndex_Quads)]]) { - Quad quad = quads[input.quad_id]; - float4 background_color = fill_color(quad.background, input.position.xy, quad.bounds, - input.background_solid, input.background_color0, input.background_color1); - - bool unrounded = quad.corner_radii.top_left == 0.0 && - quad.corner_radii.bottom_left == 0.0 && - quad.corner_radii.top_right == 0.0 && - quad.corner_radii.bottom_right == 0.0; - - // Fast path when the quad is not rounded and doesn't have any border - if (quad.border_widths.top == 0.0 && - quad.border_widths.left == 0.0 && - quad.border_widths.right == 0.0 && - quad.border_widths.bottom == 0.0 && - unrounded) { - return background_color; + if ((input.quad_id & SIMPLE_PRIMITIVE_FLAG) != 0u) { + return input.background.color0; } + Quad quad = quads[input.quad_id]; + float4 background = background_color(input.background, quad.background, + quad.bounds, input.position.xy); + bool unrounded = !has_rounded_corners(quad.corner_radii); + float2 size = float2(quad.bounds.size.width, quad.bounds.size.height); float2 half_size = size / 2.0; float2 point = input.position.xy - float2(quad.bounds.origin.x, quad.bounds.origin.y); @@ -175,7 +175,7 @@ fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]], // Fast path for points that must be part of the background if (is_within_inner_straight_border && !is_near_rounded_corner) { - return background_color; + return background; } // Signed distance of the point to the outside edge of the quad's border @@ -208,7 +208,7 @@ fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]], // Negative when inside the border float border_sdf = max(inner_sdf, outer_sdf); - float4 color = background_color; + float4 color = background; if (border_sdf < antialias_threshold) { float4 border_color = input.border_color; @@ -388,8 +388,8 @@ fragment float4 quad_fragment(QuadFragmentInput input [[stage_in]], // Blend the border on top of the background and then linearly interpolate // between the two as we slide inside the background. - float4 blended_border = over(background_color, border_color); - color = mix(background_color, blended_border, + float4 blended_border = over(background, border_color); + color = mix(background, blended_border, saturate(antialias_threshold - inner_sdf)); } @@ -446,52 +446,139 @@ float quarter_ellipse_sdf(float2 point, float2 radii) { return unit_circle_sdf * (radii.x + radii.y) * -0.5; } -struct ShadowVertexOutput { +struct OpaqueQuadFragmentInput { float4 position [[position]]; float4 color [[flat]]; - uint shadow_id [[flat]]; - float clip_distance [[clip_distance]][4]; +}; + +vertex OpaqueQuadFragmentInput opaque_quad_vertex( + uint vertex_id [[vertex_id]], uint instance_id [[instance_id]], + constant Quad *quads [[buffer(QuadInputIndex_Quads)]], + constant uint *quad_count [[buffer(QuadInputIndex_QuadCount)]], + constant Size_DevicePixels *viewport_size + [[buffer(GlobalInputIndex_ViewportSize)]], + constant float *depth_scale [[buffer(GlobalInputIndex_DepthScale)]]) { + uint quad_id = *quad_count - 1u - instance_id; + Quad quad = quads[quad_id]; + if (!is_opaque_rectangle(quad)) { + return OpaqueQuadFragmentInput{CULLED_POSITION, float4(0.)}; + } + + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + ClippedVertex clipped = + clip_to_mask(unit_vertex, quad.bounds, quad.content_mask.bounds); + float4 device_position = + to_device_position_impl(clipped.position, viewport_size); + device_position.z = quad_depth(quad_id, *depth_scale); + return OpaqueQuadFragmentInput{device_position, + hsla_to_rgba(quad.background.solid)}; +} + +fragment float4 opaque_quad_fragment(OpaqueQuadFragmentInput input + [[stage_in]]) { + return input.color; +} + +struct PreparedBlurredRoundedRect { + float4 shape; + float4 r1; + float4 exponent; + float4 scale; }; struct ShadowFragmentInput { float4 position [[position]]; float4 color [[flat]]; uint shadow_id [[flat]]; + float4 blur_shape [[flat]]; + float4 blur_r1 [[flat]]; + float4 blur_exponent [[flat]]; + float4 blur_scale [[flat]]; }; -vertex ShadowVertexOutput shadow_vertex( - uint unit_vertex_id [[vertex_id]], uint shadow_id [[instance_id]], - constant float2 *unit_vertices [[buffer(ShadowInputIndex_Vertices)]], - constant Shadow *shadows [[buffer(ShadowInputIndex_Shadows)]], - constant Size_DevicePixels *viewport_size - [[buffer(ShadowInputIndex_ViewportSize)]]) { - float2 unit_vertex = unit_vertices[unit_vertex_id]; - Shadow shadow = shadows[shadow_id]; +float erf7(float x) { + x = clamp(x, -10., 10.) * (2. / sqrt(M_PI_F)); + float xx = x * x; + x = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx); + return x / sqrt(1. + x * x); +} - Bounds_ScaledPixels bounds; - if (shadow.inset != 0u) { - bounds = shadow.element_bounds; +// Raph Levien's blurred rounded rectangle approximation, whose blur s is sigma * sqrt(2): +// https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html +PreparedBlurredRoundedRect prepare_blurred_rounded_rect(float2 size, Corners_ScaledPixels corner_radii, float sigma) { + float s = max(sigma * sqrt(2.), 1e-6); + float s_inv = 1. / s; + float min_edge = min(size.x, size.y); + float r_max = 0.5 * min_edge; + float4 radii = float4(corner_radii.top_left, corner_radii.top_right, + corner_radii.bottom_right, corner_radii.bottom_left); + float4 r0 = min(sqrt(radii * radii + 1.15 * 1.15 * s * s), r_max); + float4 r1 = min(sqrt(radii * radii + 4. * s * s), r_max); + + float2 half_extent = 0.5 * s_inv * size; + float delta = 1.25 * s * (exp(-half_extent.x * half_extent.x) - exp(-half_extent.y * half_extent.y)); + float2 adjusted_size = float2(size.x + min(delta, 0.), size.y - max(delta, 0.)); + float4 peak = s_inv * 0.5 * (max(adjusted_size.x, adjusted_size.y) - 0.5 * radii); + + PreparedBlurredRoundedRect output; + output.shape = float4(0.5 * adjusted_size, s_inv, min_edge); + output.r1 = r1; + output.exponent = 2. * r1 / r0; + output.scale = 0.5 * float4(erf7(peak.x), erf7(peak.y), erf7(peak.z), erf7(peak.w)); + return output; +} + +float pick_corner(float2 center_to_point, float4 values) { + Corners_ScaledPixels corners = {values.x, values.y, values.z, values.w}; + return pick_corner_radius(center_to_point, corners); +} + +float blurred_rounded_rect(float2 center_to_point, PreparedBlurredRoundedRect prepared) { + float r1 = pick_corner(center_to_point, prepared.r1); + float exponent = pick_corner(center_to_point, prepared.exponent); + float scale = pick_corner(center_to_point, prepared.scale); + float s_inv = prepared.shape.z; + float min_edge = prepared.shape.w; + + float2 p0 = abs(center_to_point) - (prepared.shape.xy - r1); + float2 p1 = max(p0, 0.); + float d_pos; + if (p1.x > 0. && p1.y > 0.) { + d_pos = pow(pow(p1.x, exponent) + pow(p1.y, exponent), 1. / exponent); } else { - // Leave room for the gaussian tail outside the shadow rect. - float margin = 3. * shadow.blur_radius; - bounds = shadow.bounds; - bounds.origin.x -= margin; - bounds.origin.y -= margin; - bounds.size.width += 2. * margin; - bounds.size.height += 2. * margin; + d_pos = p1.x + p1.y; } - float4 device_position = - to_device_position(unit_vertex, bounds, viewport_size); - float4 clip_distance = - distance_from_clip_rect(unit_vertex, bounds, shadow.content_mask.bounds); - float4 color = hsla_to_rgba(shadow.color); + float d_neg = min(max(p0.x, p0.y), 0.); + float d = d_pos + d_neg - r1; + return scale * (erf7(s_inv * (min_edge + d)) - erf7(s_inv * d)); +} - return ShadowVertexOutput{ +vertex ShadowFragmentInput shadow_vertex( + uint vertex_id [[vertex_id]], uint shadow_id [[instance_id]], + constant Shadow *shadows [[buffer(ShadowInputIndex_Shadows)]], + constant Size_DevicePixels *viewport_size + [[buffer(GlobalInputIndex_ViewportSize)]]) { + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + Shadow shadow = shadows[shadow_id]; + + ClippedVertex clipped = + clip_to_mask(unit_vertex, shadow.bounds, shadow.content_mask.bounds); + float4 device_position = + to_device_position_impl(clipped.position, viewport_size); + float4 color = hsla_to_rgba(shadow.color); + PreparedBlurredRoundedRect blur = prepare_blurred_rounded_rect( + float2(shadow.shape_bounds.size.width, shadow.shape_bounds.size.height), + shadow.shape_corner_radii, shadow.blur_radius); + + return ShadowFragmentInput{ device_position, color, shadow_id, - {clip_distance.x, clip_distance.y, clip_distance.z, clip_distance.w}}; + blur.shape, + blur.r1, + blur.exponent, + blur.scale}; } fragment float4 shadow_fragment(ShadowFragmentInput input [[stage_in]], @@ -499,92 +586,54 @@ fragment float4 shadow_fragment(ShadowFragmentInput input [[stage_in]], [[buffer(ShadowInputIndex_Shadows)]]) { Shadow shadow = shadows[input.shadow_id]; - float2 origin = float2(shadow.bounds.origin.x, shadow.bounds.origin.y); - float2 size = float2(shadow.bounds.size.width, shadow.bounds.size.height); - float2 half_size = size / 2.; - float2 center = origin + half_size; - float2 point = input.position.xy - center; - float corner_radius; - if (point.x < 0.) { - if (point.y < 0.) { - corner_radius = shadow.corner_radii.top_left; - } else { - corner_radius = shadow.corner_radii.bottom_left; - } - } else { - if (point.y < 0.) { - corner_radius = shadow.corner_radii.top_right; - } else { - corner_radius = shadow.corner_radii.bottom_right; - } - } - float alpha; if (shadow.blur_radius == 0.) { - float distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii); + float distance = quad_sdf(input.position.xy, shadow.shape_bounds, + shadow.shape_corner_radii); alpha = saturate(0.5 - distance); } else { - // The signal is only non-zero in a limited range, so don't waste samples - float low = point.y - half_size.y; - float high = point.y + half_size.y; - float start = clamp(-3. * shadow.blur_radius, low, high); - float end = clamp(3. * shadow.blur_radius, low, high); - - // Accumulate samples (we can get away with surprisingly few samples) - float step = (end - start) / 4.; - float y = start + step * 0.5; - alpha = 0.; - for (int i = 0; i < 4; i++) { - alpha += blur_along_x(point.x, point.y - y, shadow.blur_radius, - corner_radius, half_size) * - gaussian(y, shadow.blur_radius) * step; - y += step; - } + float2 origin = float2(shadow.shape_bounds.origin.x, shadow.shape_bounds.origin.y); + float2 size = float2(shadow.shape_bounds.size.width, shadow.shape_bounds.size.height); + float2 center = origin + size / 2.; + PreparedBlurredRoundedRect blur = {input.blur_shape, input.blur_r1, + input.blur_exponent, input.blur_scale}; + alpha = blurred_rounded_rect(input.position.xy - center, blur); } if (shadow.inset != 0u) { // The inset shadow is the complement of the (blurred) hole rect, clipped to the element. // `saturate(0.5 - d)` gives a 1-pixel antialiased edge: d <= -0.5 -> 1, d >= 0.5 -> 0. alpha = 1. - alpha; - float element_distance = quad_sdf(input.position.xy, shadow.element_bounds, - shadow.element_corner_radii); + float element_distance = + quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii); alpha *= saturate(0.5 - element_distance); } return input.color * float4(1., 1., 1., alpha); } -struct UnderlineVertexOutput { - float4 position [[position]]; - float4 color [[flat]]; - uint underline_id [[flat]]; - float clip_distance [[clip_distance]][4]; -}; - struct UnderlineFragmentInput { float4 position [[position]]; float4 color [[flat]]; uint underline_id [[flat]]; }; -vertex UnderlineVertexOutput underline_vertex( - uint unit_vertex_id [[vertex_id]], uint underline_id [[instance_id]], - constant float2 *unit_vertices [[buffer(UnderlineInputIndex_Vertices)]], +vertex UnderlineFragmentInput underline_vertex( + uint vertex_id [[vertex_id]], uint underline_id [[instance_id]], constant Underline *underlines [[buffer(UnderlineInputIndex_Underlines)]], constant Size_DevicePixels *viewport_size - [[buffer(ShadowInputIndex_ViewportSize)]]) { - float2 unit_vertex = unit_vertices[unit_vertex_id]; + [[buffer(GlobalInputIndex_ViewportSize)]]) { + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); Underline underline = underlines[underline_id]; + ClippedVertex clipped = clip_to_mask(unit_vertex, underline.bounds, + underline.content_mask.bounds); float4 device_position = - to_device_position(unit_vertex, underline.bounds, viewport_size); - float4 clip_distance = distance_from_clip_rect(unit_vertex, underline.bounds, - underline.content_mask.bounds); + to_device_position_impl(clipped.position, viewport_size); float4 color = hsla_to_rgba(underline.color); - return UnderlineVertexOutput{ + return UnderlineFragmentInput{ device_position, color, - underline_id, - {clip_distance.x, clip_distance.y, clip_distance.z, clip_distance.w}}; + underline_id | (underline.wavy == 0u ? SIMPLE_PRIMITIVE_FLAG : 0u)}; } fragment float4 underline_fragment(UnderlineFragmentInput input [[stage_in]], @@ -593,37 +642,30 @@ fragment float4 underline_fragment(UnderlineFragmentInput input [[stage_in]], const float WAVE_FREQUENCY = 2.0; const float WAVE_HEIGHT_RATIO = 0.8; - Underline underline = underlines[input.underline_id]; - if (underline.wavy) { - float half_thickness = underline.thickness * 0.5; - float2 origin = - float2(underline.bounds.origin.x, underline.bounds.origin.y); - - float2 st = ((input.position.xy - origin) / underline.bounds.size.height) - - float2(0., 0.5); - float frequency = (M_PI_F * WAVE_FREQUENCY * underline.thickness) / underline.bounds.size.height; - float amplitude = (underline.thickness * WAVE_HEIGHT_RATIO) / underline.bounds.size.height; - - float sine = sin(st.x * frequency) * amplitude; - float dSine = cos(st.x * frequency) * amplitude * frequency; - float distance = (st.y - sine) / sqrt(1. + dSine * dSine); - float distance_in_pixels = distance * underline.bounds.size.height; - float distance_from_top_border = distance_in_pixels - half_thickness; - float distance_from_bottom_border = distance_in_pixels + half_thickness; - float alpha = saturate( - 0.5 - max(-distance_from_bottom_border, distance_from_top_border)); - return input.color * float4(1., 1., 1., alpha); - } else { + if ((input.underline_id & SIMPLE_PRIMITIVE_FLAG) != 0u) { return input.color; } -} -struct MonochromeSpriteVertexOutput { - float4 position [[position]]; - float2 tile_position; - float4 color [[flat]]; - float4 clip_distance; -}; + Underline underline = underlines[input.underline_id]; + float half_thickness = underline.thickness * 0.5; + float2 origin = + float2(underline.bounds.origin.x, underline.bounds.origin.y); + + float2 st = ((input.position.xy - origin) / underline.bounds.size.height) - + float2(0., 0.5); + float frequency = (M_PI_F * WAVE_FREQUENCY * underline.thickness) / underline.bounds.size.height; + float amplitude = (underline.thickness * WAVE_HEIGHT_RATIO) / underline.bounds.size.height; + + float sine = sin(st.x * frequency) * amplitude; + float dSine = cos(st.x * frequency) * amplitude * frequency; + float distance = (st.y - sine) / sqrt(1. + dSine * dSine); + float distance_in_pixels = distance * underline.bounds.size.height; + float distance_from_top_border = distance_in_pixels - half_thickness; + float distance_from_bottom_border = distance_in_pixels + half_thickness; + float alpha = saturate( + 0.5 - max(-distance_from_bottom_border, distance_from_top_border)); + return input.color * float4(1., 1., 1., alpha); +} struct MonochromeSpriteFragmentInput { float4 position [[position]]; @@ -632,15 +674,14 @@ struct MonochromeSpriteFragmentInput { float4 clip_distance; }; -vertex MonochromeSpriteVertexOutput monochrome_sprite_vertex( - uint unit_vertex_id [[vertex_id]], uint sprite_id [[instance_id]], - constant float2 *unit_vertices [[buffer(SpriteInputIndex_Vertices)]], +vertex MonochromeSpriteFragmentInput monochrome_sprite_vertex( + uint vertex_id [[vertex_id]], uint sprite_id [[instance_id]], constant MonochromeSprite *sprites [[buffer(SpriteInputIndex_Sprites)]], constant Size_DevicePixels *viewport_size - [[buffer(SpriteInputIndex_ViewportSize)]], + [[buffer(GlobalInputIndex_ViewportSize)]], constant Size_DevicePixels *atlas_size [[buffer(SpriteInputIndex_AtlasTextureSize)]]) { - float2 unit_vertex = unit_vertices[unit_vertex_id]; + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); MonochromeSprite sprite = sprites[sprite_id]; float4 device_position = to_device_position_transformed(unit_vertex, sprite.bounds, sprite.transformation, viewport_size); @@ -648,7 +689,7 @@ vertex MonochromeSpriteVertexOutput monochrome_sprite_vertex( sprite.content_mask.bounds, sprite.transformation); float2 tile_position = to_tile_position(unit_vertex, sprite.tile, atlas_size); float4 color = hsla_to_rgba(sprite.color); - return MonochromeSpriteVertexOutput{ + return MonochromeSpriteFragmentInput{ device_position, tile_position, color, @@ -672,185 +713,218 @@ fragment float4 monochrome_sprite_fragment( return color; } -struct PolychromeSpriteVertexOutput { - float4 position [[position]]; - float2 tile_position; - uint sprite_id [[flat]]; - float clip_distance [[clip_distance]][4]; -}; - struct PolychromeSpriteFragmentInput { float4 position [[position]]; float2 tile_position; uint sprite_id [[flat]]; + float opacity [[flat]]; }; -vertex PolychromeSpriteVertexOutput polychrome_sprite_vertex( - uint unit_vertex_id [[vertex_id]], uint sprite_id [[instance_id]], - constant float2 *unit_vertices [[buffer(SpriteInputIndex_Vertices)]], +vertex PolychromeSpriteFragmentInput polychrome_sprite_vertex( + uint vertex_id [[vertex_id]], uint sprite_id [[instance_id]], constant PolychromeSprite *sprites [[buffer(SpriteInputIndex_Sprites)]], constant Size_DevicePixels *viewport_size - [[buffer(SpriteInputIndex_ViewportSize)]], + [[buffer(GlobalInputIndex_ViewportSize)]], constant Size_DevicePixels *atlas_size [[buffer(SpriteInputIndex_AtlasTextureSize)]]) { - - float2 unit_vertex = unit_vertices[unit_vertex_id]; + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); PolychromeSprite sprite = sprites[sprite_id]; + ClippedVertex clipped = + clip_to_mask(unit_vertex, sprite.bounds, sprite.content_mask.bounds); float4 device_position = - to_device_position(unit_vertex, sprite.bounds, viewport_size); - float4 clip_distance = distance_from_clip_rect(unit_vertex, sprite.bounds, - sprite.content_mask.bounds); - float2 tile_position = to_tile_position(unit_vertex, sprite.tile, atlas_size); - return PolychromeSpriteVertexOutput{ + to_device_position_impl(clipped.position, viewport_size); + float2 tile_position = + to_tile_position(clipped.unit_vertex, sprite.tile, atlas_size); + bool simple = + !has_rounded_corners(sprite.corner_radii) && sprite.grayscale == 0u; + return PolychromeSpriteFragmentInput{ device_position, tile_position, - sprite_id, - {clip_distance.x, clip_distance.y, clip_distance.z, clip_distance.w}}; + sprite_id | (simple ? SIMPLE_PRIMITIVE_FLAG : 0u), + sprite.opacity}; } fragment float4 polychrome_sprite_fragment( PolychromeSpriteFragmentInput input [[stage_in]], constant PolychromeSprite *sprites [[buffer(SpriteInputIndex_Sprites)]], texture2d atlas_texture [[texture(SpriteInputIndex_AtlasTexture)]]) { - PolychromeSprite sprite = sprites[input.sprite_id]; constexpr sampler atlas_texture_sampler(mag_filter::linear, min_filter::linear); - float4 sample = + float4 color = atlas_texture.sample(atlas_texture_sampler, input.tile_position); - float distance = - quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii); + if ((input.sprite_id & SIMPLE_PRIMITIVE_FLAG) != 0u) { + return float4(color.rgb, color.a * input.opacity); + } - float4 color = sample; + PolychromeSprite sprite = sprites[input.sprite_id]; if (sprite.grayscale) { float grayscale = 0.2126 * color.r + 0.7152 * color.g + 0.0722 * color.b; color.r = grayscale; color.g = grayscale; color.b = grayscale; } - color.a *= sprite.opacity * saturate(0.5 - distance); + float distance = + quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii); + color.a *= input.opacity * saturate(0.5 - distance); return color; } -struct PathRasterizationVertexOutput { +struct PathTileFragmentInput { float4 position [[position]]; - float2 st_position; - uint vertex_id [[flat]]; - float clip_rect_distance [[clip_distance]][4]; + uint tile_id [[flat]]; + float4 curve_box [[flat]]; + PreparedBackground background; }; -struct PathRasterizationFragmentInput { - float4 position [[position]]; - float2 st_position; - uint vertex_id [[flat]]; -}; +vertex PathTileFragmentInput path_tile_vertex( + uint vertex_id [[vertex_id]], uint tile_id [[instance_id]], + constant PathTile *tiles [[buffer(PathTileInputIndex_Tiles)]], + constant PathPaint *paints [[buffer(PathTileInputIndex_Paints)]], + constant Size_DevicePixels *viewport_size + [[buffer(GlobalInputIndex_ViewportSize)]]) { + PathTile tile = tiles[tile_id]; + PathPaint paint = paints[tile.paint]; -vertex PathRasterizationVertexOutput path_rasterization_vertex( - uint vertex_id [[vertex_id]], - constant PathRasterizationVertex *vertices [[buffer(PathRasterizationInputIndex_Vertices)]], - constant Size_DevicePixels *atlas_size [[buffer(PathRasterizationInputIndex_ViewportSize)]] -) { - PathRasterizationVertex v = vertices[vertex_id]; - float2 vertex_position = float2(v.xy_position.x, v.xy_position.y); - float4 position = float4( - vertex_position * float2(2. / atlas_size->width, -2. / atlas_size->height) + float2(-1., 1.), - 0., - 1. - ); - return PathRasterizationVertexOutput{ - position, - float2(v.st_position.x, v.st_position.y), - vertex_id, - { - v.xy_position.x - v.bounds.origin.x, - v.bounds.origin.x + v.bounds.size.width - v.xy_position.x, - v.xy_position.y - v.bounds.origin.y, - v.bounds.origin.y + v.bounds.size.height - v.xy_position.y - } - }; + float2 mask_top_left = float2(paint.content_mask.bounds.origin.x, + paint.content_mask.bounds.origin.y); + float2 mask_bottom_right = + mask_top_left + float2(paint.content_mask.bounds.size.width, + paint.content_mask.bounds.size.height); + float2 top_left = clamp(float2(tile.top_left.x, tile.top_left.y), + mask_top_left, mask_bottom_right); + float2 bottom_right = clamp(float2(tile.bottom_right.x, tile.bottom_right.y), + top_left, mask_bottom_right); + float2 position = + float2((vertex_id & 1u) != 0u ? bottom_right.x : top_left.x, + (vertex_id & 2u) != 0u ? bottom_right.y : top_left.y); + + return PathTileFragmentInput{ + to_device_position_impl(position, viewport_size), + tile_id, + float4(tile.curves_top_left.x, tile.curves_top_left.y, + tile.curves_bottom_right.x, tile.curves_bottom_right.y), + prepare_background(paint.color)}; } -fragment float4 path_rasterization_fragment( - PathRasterizationFragmentInput input [[stage_in]], - constant PathRasterizationVertex *vertices [[buffer(PathRasterizationInputIndex_Vertices)]] -) { - float2 dx = dfdx(input.st_position); - float2 dy = dfdy(input.st_position); +// Solves a*t^2 + b*t + c = 0 for the root in [0, 1] on a monotone piece. +float monotone_quadratic_root(float a, float b, float c, float direction) { + float discriminant = max(b * b - 4.0 * a * c, 0.0); + float denominator = b + direction * sqrt(discriminant); + if (denominator == 0.0) { + return 0.0; + } + return saturate(-2.0 * c / denominator); +} - PathRasterizationVertex v = vertices[input.vertex_id]; - Background background = v.color; - Bounds_ScaledPixels path_bounds = v.bounds; - float alpha; - if (length(float2(dx.x, dy.x)) < 0.001) { - alpha = 1.0; - } else { - float2 gradient = float2( - (2. * input.st_position.x) * dx.x - dx.y, - (2. * input.st_position.x) * dy.x - dy.y - ); - float f = (input.st_position.x * input.st_position.x) - input.st_position.y; - float distance = f / length(gradient); - alpha = saturate(0.5 - distance); +// Coverage estimate adapted from https://github.com/EricLengyel/Slug/blob/be3c13eb7d63f9e8aa5c583e42d92c374cb91d98/SlugPixelShader.hlsl +// Copyright (c) 2017 Eric Lengyel. +// Licensed under the MIT license. + +// Accumulates the curve's winding along the pixel's leftward and upward rays. +// Like Slug, a crossing within half a pixel of the center counts fractionally. +void add_curve_winding(PathCurve curve, float2 center, thread float2 &winding, + thread float2 &weight) { + float2 p0 = float2(curve.p0.x, curve.p0.y); + float2 p1 = float2(curve.p1.x, curve.p1.y); + float2 a = float2(curve.a.x, curve.a.y); + float2 b = float2(curve.b.x, curve.b.y); + float min_x = min(p0.x, p1.x); + float max_x = max(p0.x, p1.x); + + if (p0.y <= center.y && center.y < p1.y) { + if (max_x <= center.x - 0.5) { + winding.x += curve.sign; + } else { + float t = monotone_quadratic_root(a.y, b.y, p0.y - center.y, 1.0); + float x = (a.x * t + b.x) * t + p0.x; + float distance = center.x - x; + winding.x += curve.sign * saturate(distance + 0.5); + weight.x = max(weight.x, saturate(1.0 - 2.0 * abs(distance))); + } } - GradientColor gradient_color = prepare_fill_color( - background.tag, - background.color_space, - background.solid, - background.colors[0].color, - background.colors[1].color - ); - - float4 color = fill_color( - background, - input.position.xy, - path_bounds, - gradient_color.solid, - gradient_color.color0, - gradient_color.color1 - ); - return float4(color.rgb * color.a * alpha, alpha * color.a); + if (min_x <= center.x && center.x < max_x) { + float direction = p1.x > p0.x ? 1.0 : -1.0; + if (p1.y <= center.y - 0.5) { + winding.y -= curve.sign * direction; + } else if (p0.y < center.y + 0.5) { + float t = monotone_quadratic_root(a.x, b.x, p0.x - center.x, direction); + float y = (a.y * t + b.y) * t + p0.y; + float distance = center.y - y; + winding.y -= curve.sign * direction * saturate(distance + 0.5); + weight.y = max(weight.y, saturate(1.0 - 2.0 * abs(distance))); + } + } } -struct PathSpriteVertexOutput { - float4 position [[position]]; - float2 texture_coords; -}; - -vertex PathSpriteVertexOutput path_sprite_vertex( - uint unit_vertex_id [[vertex_id]], - uint sprite_id [[instance_id]], - constant float2 *unit_vertices [[buffer(SpriteInputIndex_Vertices)]], - constant PathSprite *sprites [[buffer(SpriteInputIndex_Sprites)]], - constant Size_DevicePixels *viewport_size [[buffer(SpriteInputIndex_ViewportSize)]] -) { - float2 unit_vertex = unit_vertices[unit_vertex_id]; - PathSprite sprite = sprites[sprite_id]; - // Don't apply content mask because it was already accounted for when - // rasterizing the path. - float4 device_position = - to_device_position(unit_vertex, sprite.bounds, viewport_size); - - float2 screen_position = float2(sprite.bounds.origin.x, sprite.bounds.origin.y) + unit_vertex * float2(sprite.bounds.size.width, sprite.bounds.size.height); - float2 texture_coords = screen_position / float2(viewport_size->width, viewport_size->height); - - return PathSpriteVertexOutput{ - device_position, - texture_coords - }; +// The backdrop gives the unlisted curves' winding along a leftward ray from +// the tile's reference corner. We need it at the current pixel, along both +// leftward and upward rays. Because paths are closed, chains of unlisted +// curves can only begin or end where a listed curve does. So, we can compute +// the winding at the current pixel by correcting the backdrop for each listed +// endpoint between its ray and the pixel. +void correct_for_endpoint(float2 endpoint, float step, float2 reference, + float2 center, thread float2 &winding) { + if (endpoint.x <= reference.x) { + winding.x -= step * (float(endpoint.y <= center.y) - + float(endpoint.y <= reference.y)); + } + if (endpoint.y <= reference.y && endpoint.x <= center.x) { + winding.y += step; + } } -fragment float4 path_sprite_fragment( - PathSpriteVertexOutput input [[stage_in]], - texture2d intermediate_texture [[texture(SpriteInputIndex_AtlasTexture)]] -) { - constexpr sampler intermediate_texture_sampler(mag_filter::linear, min_filter::linear); - return intermediate_texture.sample(intermediate_texture_sampler, input.texture_coords); +fragment float4 path_tile_fragment( + PathTileFragmentInput input [[stage_in]], + constant PathTile *tiles [[buffer(PathTileInputIndex_Tiles)]], + constant PathCurve *curves [[buffer(PathTileInputIndex_Curves)]], + constant PathPaint *paints [[buffer(PathTileInputIndex_Paints)]]) { + float2 center = floor(input.position.xy) + 0.5; + if (input.background.tag == 0u && + (any(center < input.curve_box.xy) || any(center > input.curve_box.zw))) { + return input.background.color0; + } + PathTile tile = tiles[input.tile_id]; + PathPaint paint = paints[tile.paint]; + float2 reference = float2(tile.reference.x, tile.reference.y); + + float2 winding = float2(float(tile.backdrop)); + float2 weight = float2(0.0); + for (uint i = 0u; i < tile.curve_count; i++) { + PathCurve curve = curves[tile.curve_start + i]; + float2 p0 = float2(curve.p0.x, curve.p0.y); + float2 p1 = float2(curve.p1.x, curve.p1.y); + if (min(p0.x, p1.x) >= center.x + 0.5) { + break; + } + if (p0.y < center.y + 0.5) { + add_curve_winding(curve, center, winding, weight); + correct_for_endpoint(p0, curve.sign, reference, center, winding); + correct_for_endpoint(p1, -curve.sign, reference, center, winding); + } + } + + // Weight the winding computed by each ray by its nearest crossing's distance + // from the pixel center, using Slug's technique. + float coverage = + max(abs(dot(winding, weight)) / max(weight.x + weight.y, 1.0 / 65536.0), + min(abs(winding.x), abs(winding.y))); + coverage = paint.even_odd != 0u + ? 1.0 - abs(1.0 - fract(coverage * 0.5) * 2.0) + : saturate(coverage); + + if (coverage == 0.0) { + return float4(0.0); + } + + float4 color = background_color(input.background, paint.color, + paint.bounds, input.position.xy); + return float4(color.rgb, color.a * coverage); } struct SurfaceVertexOutput { float4 position [[position]]; float2 texture_position; - float clip_distance [[clip_distance]][4]; }; struct SurfaceFragmentInput { @@ -859,26 +933,24 @@ struct SurfaceFragmentInput { }; vertex SurfaceVertexOutput surface_vertex( - uint unit_vertex_id [[vertex_id]], uint surface_id [[instance_id]], - constant float2 *unit_vertices [[buffer(SurfaceInputIndex_Vertices)]], + uint vertex_id [[vertex_id]], uint surface_id [[instance_id]], constant SurfaceBounds *surfaces [[buffer(SurfaceInputIndex_Surfaces)]], constant Size_DevicePixels *viewport_size - [[buffer(SurfaceInputIndex_ViewportSize)]], + [[buffer(GlobalInputIndex_ViewportSize)]], constant Size_DevicePixels *texture_size [[buffer(SurfaceInputIndex_TextureSize)]]) { - float2 unit_vertex = unit_vertices[unit_vertex_id]; + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); SurfaceBounds surface = surfaces[surface_id]; + ClippedVertex clipped = + clip_to_mask(unit_vertex, surface.bounds, surface.content_mask.bounds); float4 device_position = - to_device_position(unit_vertex, surface.bounds, viewport_size); - float4 clip_distance = distance_from_clip_rect(unit_vertex, surface.bounds, - surface.content_mask.bounds); + to_device_position_impl(clipped.position, viewport_size); // We are going to copy the whole texture, so the texture position corresponds - // to the current vertex of the unit triangle. - float2 texture_position = unit_vertex; + // to the vertex's position within the unclipped surface bounds. + float2 texture_position = clipped.unit_vertex; return SurfaceVertexOutput{ device_position, - texture_position, - {clip_distance.x, clip_distance.y, clip_distance.z, clip_distance.w}}; + texture_position}; } fragment float4 surface_fragment(SurfaceFragmentInput input [[stage_in]], @@ -997,11 +1069,8 @@ float4 oklab_to_srgb(float4 color) { return float4(linear_to_srgb(linear_rgb), color.a); } -float4 to_device_position(float2 unit_vertex, Bounds_ScaledPixels bounds, - constant Size_DevicePixels *input_viewport_size) { - float2 position = - unit_vertex * float2(bounds.size.width, bounds.size.height) + - float2(bounds.origin.x, bounds.origin.y); +float4 to_device_position_impl(float2 position, + constant Size_DevicePixels *input_viewport_size) { float2 viewport_size = float2((float)input_viewport_size->width, (float)input_viewport_size->height); float2 device_position = @@ -1009,6 +1078,14 @@ float4 to_device_position(float2 unit_vertex, Bounds_ScaledPixels bounds, return float4(device_position, 0., 1.); } +float4 to_device_position(float2 unit_vertex, Bounds_ScaledPixels bounds, + constant Size_DevicePixels *input_viewport_size) { + float2 position = + unit_vertex * float2(bounds.size.width, bounds.size.height) + + float2(bounds.origin.x, bounds.origin.y); + return to_device_position_impl(position, input_viewport_size); +} + float4 to_device_position_transformed(float2 unit_vertex, Bounds_ScaledPixels bounds, TransformationMatrix transformation, constant Size_DevicePixels *input_viewport_size) { @@ -1089,39 +1166,20 @@ float quad_sdf_impl(float2 corner_center_to_point, float corner_radius) { } } -// A standard gaussian function, used for weighting samples -float gaussian(float x, float sigma) { - return exp(-(x * x) / (2. * sigma * sigma)) / (sqrt(2. * M_PI_F) * sigma); -} +ClippedVertex clip_to_mask(float2 unit_vertex, Bounds_ScaledPixels bounds, + Bounds_ScaledPixels mask) { + float2 bounds_origin = float2(bounds.origin.x, bounds.origin.y); + float2 bounds_size = float2(bounds.size.width, bounds.size.height); + float2 mask_origin = float2(mask.origin.x, mask.origin.y); + float2 mask_size = float2(mask.size.width, mask.size.height); + float2 origin = max(bounds_origin, mask_origin); + float2 corner = min(bounds_origin + bounds_size, mask_origin + mask_size); + float2 size = max(corner - origin, float2(0.)); -// This approximates the error function, needed for the gaussian integral -float2 erf(float2 x) { - float2 s = sign(x); - float2 a = abs(x); - float2 r1 = 1. + (0.278393 + (0.230389 + (0.000972 + 0.078108 * a) * a) * a) * a; - float2 r2 = r1 * r1; - return s - s / (r2 * r2); -} - -float blur_along_x(float x, float y, float sigma, float corner, - float2 half_size) { - float delta = min(half_size.y - corner - abs(y), 0.); - float curved = - half_size.x - corner + sqrt(max(0., corner * corner - delta * delta)); - float2 integral = - 0.5 + 0.5 * erf((x + float2(-curved, curved)) * (sqrt(0.5) / sigma)); - return integral.y - integral.x; -} - -float4 distance_from_clip_rect(float2 unit_vertex, Bounds_ScaledPixels bounds, - Bounds_ScaledPixels clip_bounds) { - float2 position = - unit_vertex * float2(bounds.size.width, bounds.size.height) + - float2(bounds.origin.x, bounds.origin.y); - return float4(position.x - clip_bounds.origin.x, - clip_bounds.origin.x + clip_bounds.size.width - position.x, - position.y - clip_bounds.origin.y, - clip_bounds.origin.y + clip_bounds.size.height - position.y); + ClippedVertex result; + result.position = origin + unit_vertex * size; + result.unit_vertex = (result.position - bounds_origin) / bounds_size; + return result; } float4 distance_from_clip_rect_transformed(float2 unit_vertex, Bounds_ScaledPixels bounds, @@ -1150,130 +1208,130 @@ float4 over(float4 below, float4 above) { return result; } -GradientColor prepare_fill_color(uint tag, uint color_space, Hsla solid, - Hsla color0, Hsla color1) { - GradientColor out; - if (tag == 0 || tag == 2 || tag == 3) { - out.solid = hsla_to_rgba(solid); - } else if (tag == 1) { - out.color0 = hsla_to_rgba(color0); - out.color1 = hsla_to_rgba(color1); +PreparedBackground prepare_background(Background background) { + PreparedBackground prepared; + prepared.tag = background.tag; + prepared.color1 = float4(0.0); - // Prepare color space in vertex for avoid conversion - // in fragment shader for performance reasons - if (color_space == 1) { - // Oklab - out.color0 = srgb_to_oklab(out.color0); - out.color1 = srgb_to_oklab(out.color1); + if (background.tag == 1u) { + prepared.color0 = hsla_to_rgba(background.colors[0].color); + prepared.color1 = hsla_to_rgba(background.colors[1].color); + // Interpolating in Oklab means converting the endpoints once rather + // than at every stop evaluation. + if (background.color_space == 1u) { + prepared.color0 = srgb_to_oklab(prepared.color0); + prepared.color1 = srgb_to_oklab(prepared.color1); } + } else { + prepared.color0 = hsla_to_rgba(background.solid); } - return out; + return prepared; } -float2x2 rotate2d(float angle) { - float s = sin(angle); - float c = cos(angle); - return float2x2(c, -s, s, c); +// Ordered (Bayer 4x4) dither threshold, remapped to [-1, +1]. +float dither_offset(float2 position) { + uint2 cell = uint2(position) & uint2(3u); + uint z = cell.x ^ cell.y; + uint threshold = ((z & 1u) << 3) | ((cell.y & 1u) << 2) | (z & 2u) | + ((cell.y & 2u) >> 1); + return (float(threshold) + 0.5) * (1.0 / 8.0) - 1.0; } -float4 fill_color(Background background, - float2 position, - Bounds_ScaledPixels bounds, - float4 solid_color, float4 color0, float4 color1) { - float4 color; +float4 background_color(PreparedBackground prepared, Background background, + Bounds_ScaledPixels bounds, float2 position) { + float4 color = prepared.color0; + if (prepared.tag == 0u) { + return color; + } - switch (background.tag) { - case 0: - color = solid_color; - break; + float2 origin = float2(bounds.origin.x, bounds.origin.y); + float2 size = float2(bounds.size.width, bounds.size.height); + + switch (prepared.tag) { case 1: { // -90 degrees to match the CSS gradient angle. - float gradient_angle = background.gradient_angle_or_pattern_height; - float radians = (fmod(gradient_angle, 360.0) - 90.0) * (M_PI_F / 180.0); + float radians = (fmod(background.gradient_angle_or_pattern_height, 360.0) - 90.0) * + (M_PI_F / 180.0); float2 direction = float2(cos(radians), sin(radians)); // Expand the short side to be the same as the long side - if (bounds.size.width > bounds.size.height) { - direction.y *= bounds.size.height / bounds.size.width; + if (size.x > size.y) { + direction.y *= size.y / size.x; } else { - direction.x *= bounds.size.width / bounds.size.height; + direction.x *= size.x / size.y; } - // Get the t value for the linear gradient with the color stop percentages. - float2 half_size = float2(bounds.size.width, bounds.size.height) / 2.; - float2 center = float2(bounds.origin.x, bounds.origin.y) + half_size; - float2 center_to_point = position - center; - float t = dot(center_to_point, direction) / length(direction); - // Check the direction to determine whether to use x or y - if (abs(direction.x) > abs(direction.y)) { - t = (t + half_size.x) / bounds.size.width; - } else { - t = (t + half_size.y) / bounds.size.height; - } + float extent = abs(direction.x) > abs(direction.y) ? size.x : size.y; + float direction_length = length(direction); + float span = background.colors[1].percentage - background.colors[0].percentage; + // The half-extent term is exactly half of `extent`, so the + // position-independent part reduces to this. + float offset = 0.5 - background.colors[0].percentage; - // Adjust t based on the stop percentages - t = (t - background.colors[0].percentage) - / (background.colors[1].percentage - - background.colors[0].percentage); - t = clamp(t, 0.0, 1.0); - - switch (background.color_space) { - case 0: - color = mix(color0, color1, t); - break; - case 1: { - float4 oklab_color = mix(color0, color1, t); - color = oklab_to_srgb(oklab_color); - break; + // t = dot(position - center, gradient.xy) + gradient.z + float3 gradient = float3(0.0); + if (direction_length != 0.0 && extent != 0.0) { + if (span == 0.0) { + const float STEP = 1e30; + gradient = float3(direction / (direction_length * extent) * STEP, offset * STEP); + } else { + gradient = float3(direction / (direction_length * extent * span), offset / span); } } + float2 center = origin + size * 0.5; + float t = saturate(dot(position - center, gradient.xy) + gradient.z); + color = mix(prepared.color0, prepared.color1, t); + if (background.color_space == 1u) { + color = oklab_to_srgb(color); + } // Dither to reduce banding in gradients (especially dark/alpha). - // Triangular-distributed noise breaks up 8-bit quantization steps. - // ±2/255 for RGB (enough for dark-on-dark compositing), - // ±3/255 for alpha (needs more because alpha × dark color = tiny steps). - { - float2 seed = position * 0.6180339887; // golden ratio spread - float r1 = fract(sin(dot(seed, float2(12.9898, 78.233))) * 43758.5453); - float r2 = fract(sin(dot(seed, float2(39.3460, 11.135))) * 24634.6345); - float tri = r1 + r2 - 1.0; // triangular PDF, range [-1, +1] - color.rgb += tri * 2.0 / 255.0; - color.a += tri * 3.0 / 255.0; - } - + float dither = dither_offset(position); + color.rgb += dither * 1.0 / 255.0; + color.a += dither * 1.5 / 255.0; break; } case 2: { - float gradient_angle_or_pattern_height = background.gradient_angle_or_pattern_height; - float pattern_width = (gradient_angle_or_pattern_height / 65535.0f) / 255.0f; - float pattern_interval = fmod(gradient_angle_or_pattern_height, 65535.0f) / 255.0f; - float pattern_height = pattern_width + pattern_interval; - float stripe_angle = M_PI_F / 4.0; - float pattern_period = pattern_height * sin(stripe_angle); - float2x2 rotation = rotate2d(stripe_angle); - float2 relative_position = position - float2(bounds.origin.x, bounds.origin.y); - float2 rotated_point = rotation * relative_position; - float pattern = fmod(rotated_point.x, pattern_period); - float distance = min(pattern, pattern_period - pattern) - pattern_period * (pattern_width / pattern_height) / 2.0f; - color = solid_color; - color.a *= saturate(0.5 - distance); - break; + float pattern_height_encoded = background.gradient_angle_or_pattern_height; + float pattern_width = (pattern_height_encoded / 65535.0) / 255.0; + float pattern_interval = fmod(pattern_height_encoded, 65535.0) / 255.0; + float pattern_height = pattern_width + pattern_interval; + // Only the rotated x coordinate is used, and multiplying by the + // rotation reduces it to dot(v, float2(cos a, sin a)). + float stripe_angle = M_PI_F / 4.0; + float2 stripe_direction = float2(cos(stripe_angle), sin(stripe_angle)); + float pattern_period = pattern_height * sin(stripe_angle); + float threshold = pattern_period * (pattern_width / pattern_height) / 2.0; + float pattern = fmod(dot(position - origin, stripe_direction), pattern_period); + float distance = min(pattern, pattern_period - pattern) - threshold; + color.a *= saturate(0.5 - distance); + break; } case 3: { - // checkerboard - float size = background.gradient_angle_or_pattern_height; - float2 relative_position = position - float2(bounds.origin.x, bounds.origin.y); - - float x_index = floor(relative_position.x / size); - float y_index = floor(relative_position.y / size); - float should_be_colored = fmod(x_index + y_index, 2.0); - - color = solid_color; - color.a *= saturate(should_be_colored); - break; + // checkerboard + float cell_size = background.gradient_angle_or_pattern_height; + float2 relative_position = position - origin; + float x_index = floor(relative_position.x / cell_size); + float y_index = floor(relative_position.y / cell_size); + color.a *= saturate(fmod(x_index + y_index, 2.0)); + break; } } return color; } + +bool has_rounded_corners(Corners_ScaledPixels corner_radii) { + return corner_radii.top_left != 0.0 || corner_radii.top_right != 0.0 || + corner_radii.bottom_right != 0.0 || corner_radii.bottom_left != 0.0; +} + +bool has_border(Edges_ScaledPixels border_widths) { + return border_widths.top != 0.0 || border_widths.right != 0.0 || + border_widths.bottom != 0.0 || border_widths.left != 0.0; +} + +bool is_shaped(Quad quad) { + return has_rounded_corners(quad.corner_radii) || has_border(quad.border_widths); +} diff --git a/crates/gpui_linux/src/linux/wayland/client.rs b/crates/gpui_linux/src/linux/wayland/client.rs index 625b1d51920..1cfb2e94786 100644 --- a/crates/gpui_linux/src/linux/wayland/client.rs +++ b/crates/gpui_linux/src/linux/wayland/client.rs @@ -1697,47 +1697,14 @@ impl Dispatch for WaylandClientStatePtr { }; drop(state); - if let wl_callback::Event::Done { callback_data } = event { - window.frame_callback_fired(PlatformFrameSignal::capture(|| { - frame_callback_signal_at(callback_data) - })); + // The callback's timestamp uses a clock the protocol leaves unspecified, + // so frame timing measures from receipt, as the other platforms do. + if let wl_callback::Event::Done { .. } = event { + window.frame_callback_fired(PlatformFrameSignal::capture(Instant::now)); } } } -fn frame_callback_signal_at(callback_data: u32) -> Instant { - let mut monotonic = libc::timespec { - tv_sec: 0, - tv_nsec: 0, - }; - // wl_surface.frame specifies an unspecified epoch. Mutter and Sway use - // CLOCK_MONOTONIC, but reject implausible ages for other compositor clocks. - let result = unsafe { libc::clock_gettime(libc::CLOCK_MONOTONIC, &mut monotonic) }; - let received_at = Instant::now(); - if result != 0 || monotonic.tv_sec < 0 || !(0..1_000_000_000).contains(&monotonic.tv_nsec) { - return received_at; - } - let monotonic_millis = - (monotonic.tv_sec as u64 * 1_000 + monotonic.tv_nsec as u64 / 1_000_000) as u32; - frame_callback_instant(callback_data, monotonic_millis, received_at) -} - -fn frame_callback_instant( - callback_data: u32, - monotonic_millis: u32, - received_at: Instant, -) -> Instant { - // The wire timestamp wraps every ~49 days. A future timestamp also wraps - // when subtracted, so the bound rejects it without guessing another epoch. - let age_millis = monotonic_millis.wrapping_sub(callback_data); - if age_millis > 60_000 { - return received_at; - } - received_at - .checked_sub(Duration::from_millis(u64::from(age_millis))) - .unwrap_or(received_at) -} - pub(crate) fn get_window( state: &mut RefMut, surface_id: &ObjectId, @@ -3226,43 +3193,6 @@ mod tests { assert_eq!(wl_output_version(2).expect("minimum output version"), 2); } - #[test] - fn frame_callback_timestamp_preserves_queue_delay() { - let received_at = Instant::now(); - assert_eq!( - frame_callback_instant(1_000, 1_025, received_at), - received_at - Duration::from_millis(25), - ); - assert_eq!( - frame_callback_instant(1_000, 1_000, received_at), - received_at, - ); - } - - #[test] - fn frame_callback_timestamp_wraps() { - let received_at = Instant::now(); - assert_eq!( - frame_callback_instant(u32::MAX - 9, 15, received_at), - received_at - Duration::from_millis(25), - ); - } - - #[test] - fn frame_callback_timestamp_rejects_implausible_clock() { - let received_at = Instant::now(); - for (callback_data, monotonic_millis) in [(1_001, 1_000), (0, 60_001), (0, u32::MAX)] { - assert_eq!( - frame_callback_instant(callback_data, monotonic_millis, received_at), - received_at, - ); - } - assert_eq!( - frame_callback_instant(0, 60_000, received_at), - received_at - Duration::from_secs(60), - ); - } - #[derive(Clone)] struct FakeDataOffer { name: &'static str, diff --git a/crates/gpui_linux/src/linux/wayland/window.rs b/crates/gpui_linux/src/linux/wayland/window.rs index 6647a8ef7f7..1f7d22d9a89 100644 --- a/crates/gpui_linux/src/linux/wayland/window.rs +++ b/crates/gpui_linux/src/linux/wayland/window.rs @@ -1114,6 +1114,8 @@ impl WaylandWindowStatePtr { if let Some(mut configure) = state.in_progress_configure.take() { let got_unmaximized = state.maximized && !configure.maximized; + let fullscreen_changed = state.fullscreen != configure.fullscreen; + let mode_changed = fullscreen_changed || state.maximized != configure.maximized; state.fullscreen = configure.fullscreen; state.maximized = configure.maximized; state.tiling = configure.tiling; @@ -1141,15 +1143,27 @@ impl WaylandWindowStatePtr { } } } + let resized = configure.size.is_some_and(|size| size != state.bounds.size); drop(state); if visibility_changed { self.report_visibility(configure.visibility); } + if !throttled && let Some(size) = configure.size { + self.resize(size); + } + if fullscreen_changed { + self.notify_resize(); + } if throttled { return; } - if let Some(size) = configure.size { - self.resize(size); + // Same-size mode changes skip the resize callback, so report them as a move. + if mode_changed && !resized && !fullscreen_changed { + let callback = self.callbacks.borrow_mut().moved.take(); + if let Some(mut fun) = callback { + fun(); + self.callbacks.borrow_mut().moved = Some(fun); + } } } } @@ -1548,6 +1562,18 @@ impl WaylandWindowStatePtr { update_window(state); } + fn notify_resize(&self) { + let (size, scale) = { + let state = self.state.borrow(); + (state.bounds.size, state.scale) + }; + let callback = self.callbacks.borrow_mut().resize.take(); + if let Some(mut fun) = callback { + fun(size, scale); + self.callbacks.borrow_mut().resize = Some(fun); + } + } + pub fn resize(&self, size: Size) { self.set_size_and_scale(Some(size), None); } diff --git a/crates/gpui_linux/src/linux/x11/window.rs b/crates/gpui_linux/src/linux/x11/window.rs index f6ee76ae8ca..33fac161705 100644 --- a/crates/gpui_linux/src/linux/x11/window.rs +++ b/crates/gpui_linux/src/linux/x11/window.rs @@ -305,6 +305,11 @@ impl X11WindowState { renderer.update_transparency(is_transparent); } } + + fn is_maximized(&self) -> bool { + // A maximized window that gets minimized will still retain its maximized state. + !self.hidden && self.maximized_vertical && self.maximized_horizontal + } } #[derive(Clone)] @@ -1063,7 +1068,11 @@ impl X11WindowStatePtr { pub fn property_notify(&self, event: xproto::PropertyNotifyEvent) -> anyhow::Result<()> { let state = self.state.borrow_mut(); if event.atom == state.atoms._NET_WM_STATE { + let was_fullscreen = state.fullscreen; self.set_wm_properties(state)?; + if self.state.borrow().fullscreen != was_fullscreen { + self.notify_resize(); + } } else if event.atom == state.atoms._GTK_EDGE_CONSTRAINTS { self.set_edge_constraints(state)?; } @@ -1121,6 +1130,7 @@ impl X11WindowStatePtr { .map(|chunk| u32::from_ne_bytes([chunk[0], chunk[1], chunk[2], chunk[3]])); let was_active = state.active; + let was_maximized = state.maximized_vertical && state.maximized_horizontal; state.active = false; state.fullscreen = false; state.maximized_vertical = false; @@ -1147,6 +1157,19 @@ impl X11WindowStatePtr { set_wm_hints_urgency(&self.xcb, self.x_window, false); } + // Maximized changes without a geometry change get no ConfigureNotify, so report them as a move. + // This ignores `hidden`, since minimizing shouldn't notify bounds observers. + let maximized_changed = + (state.maximized_vertical && state.maximized_horizontal) != was_maximized; + drop(state); + if maximized_changed { + let callback = self.callbacks.borrow_mut().moved.take(); + if let Some(mut fun) = callback { + fun(); + self.callbacks.borrow_mut().moved = Some(fun); + } + } + Ok(()) } @@ -1332,6 +1355,18 @@ impl X11WindowStatePtr { Ok(()) } + fn notify_resize(&self) { + let (content_size, scale_factor) = { + let state = self.state.borrow(); + (state.content_size(), state.scale_factor) + }; + let callback = self.callbacks.borrow_mut().resize.take(); + if let Some(mut fun) = callback { + fun(content_size, scale_factor); + self.callbacks.borrow_mut().resize = Some(fun); + } + } + pub fn set_active(&self, focus: bool) { let callback = self.callbacks.borrow_mut().active_status_change.take(); if let Some(mut fun) = callback { @@ -1390,10 +1425,7 @@ impl PlatformWindow for X11Window { } fn is_maximized(&self) -> bool { - let state = self.0.state.borrow(); - - // A maximized window that gets minimized will still retain its maximized state. - !state.hidden && state.maximized_vertical && state.maximized_horizontal + self.0.state.borrow().is_maximized() } fn window_bounds(&self) -> WindowBounds { diff --git a/crates/gpui_macos/Cargo.toml b/crates/gpui_macos/Cargo.toml index b4f9ddee9ce..c6362c40247 100644 --- a/crates/gpui_macos/Cargo.toml +++ b/crates/gpui_macos/Cargo.toml @@ -55,6 +55,7 @@ parking_lot.workspace = true raw-window-handle.workspace = true scheduler.workspace = true semver.workspace = true +serde_json.workspace = true smallvec.workspace = true strum.workspace = true uuid.workspace = true diff --git a/crates/gpui_macos/src/display_link.rs b/crates/gpui_macos/src/display_link.rs index 90a25979a1e..d6847185e68 100644 --- a/crates/gpui_macos/src/display_link.rs +++ b/crates/gpui_macos/src/display_link.rs @@ -331,6 +331,20 @@ impl MetalFrames { self.woken.set(false); } + pub fn debug_state(&self) -> serde_json::Value { + let paused = self + .source + .try_borrow() + .ok() + .and_then(|source| source.as_ref().map(MetalFrameSource::is_paused)); + serde_json::json!({ + "kind": "CAMetalDisplayLink", + "attached": self.is_attached(), + "paused": paused, + "woken": self.woken.get(), + }) + } + /// Ends an update, pausing the link if GPUI neither used its drawable nor /// asked for another frame while it ran. Returns whether it paused. pub fn end_frame(&self, used_drawable: bool) -> bool { @@ -382,6 +396,14 @@ impl WindowFrameSource { Ok(()) } + pub fn debug_state(&self) -> serde_json::Value { + serde_json::json!({ + "kind": "CVDisplayLink", + "attached": self.registration.is_some(), + "display_id": self.registration.map(|(display_id, _)| display_id), + }) + } + pub fn take_signal(&self) -> Option<(Instant, FrameRequestSource)> { self.signal.take() } diff --git a/crates/gpui_macos/src/gpui_macos.rs b/crates/gpui_macos/src/gpui_macos.rs index 8732badd321..7f1f124a682 100644 --- a/crates/gpui_macos/src/gpui_macos.rs +++ b/crates/gpui_macos/src/gpui_macos.rs @@ -17,7 +17,7 @@ mod screen_capture; use gpui_apple::metal_renderer as renderer; pub mod metal_renderer { - pub use gpui_apple::metal_renderer::{PathRasterizationVertex, PathSprite, SurfaceBounds}; + pub use gpui_apple::metal_renderer::SurfaceBounds; #[cfg(any(test, feature = "bench-support", feature = "test-support"))] pub use gpui_apple::metal_renderer::MetalHeadlessRenderer; diff --git a/crates/gpui_macos/src/platform.rs b/crates/gpui_macos/src/platform.rs index 7d02fcbcba6..d42ac63f2a9 100644 --- a/crates/gpui_macos/src/platform.rs +++ b/crates/gpui_macos/src/platform.rs @@ -32,9 +32,10 @@ use objc2::{ use objc2_app_kit::{ NSAppearance, NSAppearanceNameAqua, NSAppearanceNameDarkAqua, NSAppearanceNameVibrantDark, NSAppearanceNameVibrantLight, NSApplication, NSApplicationActivationPolicy, - NSControlStateValueOn, NSCursor, NSDocumentController, NSEventModifierFlags, NSMenu, - NSMenuItem, NSModalResponse, NSModalResponseOK, NSOpenPanel, NSSavePanel, NSScroller, - NSScrollerStyle, NSWorkspace, NSWorkspaceDidWakeNotification, NSWorkspaceWillSleepNotification, + NSApplicationOcclusionState, NSControlStateValueOn, NSCursor, NSDocumentController, + NSEventModifierFlags, NSMenu, NSMenuItem, NSModalResponse, NSModalResponseOK, NSOpenPanel, + NSSavePanel, NSScroller, NSScrollerStyle, NSWorkspace, NSWorkspaceDidWakeNotification, + NSWorkspaceWillSleepNotification, }; use objc2_foundation::{ NSActivityOptions, NSArray, NSBundle, NSError, NSInteger, NSProcessInfo, NSString, NSURL, @@ -55,6 +56,7 @@ use std::{ atomic::{AtomicBool, Ordering}, }, }; +use strum::IntoEnumIterator as _; const MAC_PLATFORM_IVAR: &CStr = c"platform"; static mut APP_CLASS: *const AnyClass = ptr::null(); @@ -1081,6 +1083,34 @@ impl Platform for MacPlatform { self.ensure_system_power_observers(); } + fn debug_state(&self) -> serde_json::Value { + let app = NSApplication::sharedApplication(self.1); + let key_window: *mut AnyObject = unsafe { msg_send![&*app, keyWindow] }; + let main_window: *mut AnyObject = unsafe { msg_send![&*app, mainWindow] }; + let window_number = |window: *mut AnyObject| -> Option { + (!window.is_null()).then(|| unsafe { msg_send![window, windowNumber] }) + }; + // AppKit's cursor for this app, mapped back to the style GPUI would + // have set it from. `None` when it is not one GPUI sets. + let current_cursor = Retained::as_ptr(&NSCursor::currentCursor()).cast::(); + let current_cursor_style = CursorStyle::iter().find(|style| { + // SAFETY: The platform is only used on the main thread. + let cursor = unsafe { crate::window::native_cursor(*style) }; + ptr::eq(cursor, current_cursor) + }); + serde_json::json!({ + "current_cursor_style": current_cursor_style, + "app_is_active": app.isActive(), + "app_is_hidden": app.isHidden(), + "app_occlusion_state_visible": app + .occlusionState() + .contains(NSApplicationOcclusionState::Visible), + "key_window_number": window_number(key_window), + "main_window_number": window_number(main_window), + "low_power_mode": NSProcessInfo::processInfo().isLowPowerModeEnabled(), + }) + } + fn thermal_state(&self) -> ThermalState { process_info::thermal_state() } diff --git a/crates/gpui_macos/src/window.rs b/crates/gpui_macos/src/window.rs index 32a6a540092..b3492c084c1 100644 --- a/crates/gpui_macos/src/window.rs +++ b/crates/gpui_macos/src/window.rs @@ -434,6 +434,10 @@ unsafe fn build_window_class(name: &CStr, superclass: &AnyClass) -> *const AnyCl sel!(windowWillEnterFullScreen:), window_will_enter_fullscreen as extern "C" fn(_, Sel, *mut AnyObject), ); + decl.add_method( + sel!(windowDidFailToEnterFullScreen:), + window_did_fail_to_enter_fullscreen as extern "C" fn(_, Sel, *mut AnyObject), + ); decl.add_method( sel!(windowWillExitFullScreen:), window_will_exit_fullscreen as extern "C" fn(_, Sel, *mut AnyObject), @@ -677,6 +681,7 @@ struct MacWindowState { last_left_mouse_down_event: Option>, synthetic_drag_counter: usize, traffic_light_position: Option>, + native_titlebar_visible: bool, traffic_light_frames: Option, pre_fullscreen_traffic_light_frames: Option, transparent_titlebar: bool, @@ -708,6 +713,10 @@ struct MacWindowState { impl MacWindowState { fn move_traffic_light(&mut self) { + if !self.native_titlebar_visible { + self.update_native_titlebar_visibility(); + } + if let Some(traffic_light_position) = self.traffic_light_position { if self.is_fullscreen() && !self.is_exiting_fullscreen { self.restore_traffic_light(); @@ -767,6 +776,46 @@ impl MacWindowState { } } + fn update_native_titlebar_visibility(&self) { + let Some(close_button) = self + .native_window() + .standardWindowButton(NSWindowButton::CloseButton) + else { + return; + }; + if let Some(titlebar_container) = Self::titlebar_container(&close_button) { + titlebar_container.setHidden(!self.native_titlebar_visible); + } + } + + fn apply_fullscreen_titlebar_opacity(&self) { + let min_version = NSOperatingSystemVersion { + majorVersion: 15, + minorVersion: 3, + patchVersion: 0, + }; + + if is_macos_version_at_least(min_version) { + unsafe { + let _: () = msg_send![self.native_window, setTitlebarAppearsTransparent: Bool::NO]; + } + } + } + + fn restore_windowed_titlebar_transparency(&self) { + let min_version = NSOperatingSystemVersion { + majorVersion: 15, + minorVersion: 3, + patchVersion: 0, + }; + + if is_macos_version_at_least(min_version) && self.transparent_titlebar { + unsafe { + let _: () = msg_send![self.native_window, setTitlebarAppearsTransparent: Bool::YES]; + } + } + } + fn capture_traffic_light_frames(&self) -> Option { let buttons = self.traffic_light_buttons()?; let titlebar_container = Self::titlebar_container(&buttons.close)?; @@ -1142,6 +1191,7 @@ impl MacWindow { traffic_light_position: titlebar .as_ref() .and_then(|titlebar| titlebar.traffic_light_position), + native_titlebar_visible: true, traffic_light_frames: None, pre_fullscreen_traffic_light_frames: None, transparent_titlebar: titlebar @@ -1659,6 +1709,12 @@ impl PlatformWindow for MacWindow { } } + fn set_native_titlebar_visibility(&self, visible: bool) { + let mut state = self.0.lock(); + state.native_titlebar_visible = visible; + state.update_native_titlebar_visibility(); + } + fn set_traffic_light_position(&self, position: Point) { let mut state = self.0.lock(); state.traffic_light_position = Some(position); @@ -2173,6 +2229,56 @@ impl PlatformWindow for MacWindow { None } + fn debug_state(&self) -> serde_json::Value { + let state = self.0.lock(); + let window = state.native_window(); + let screen: *mut AnyObject = unsafe { msg_send![state.native_window, screen] }; + let frame = window.frame(); + let layer = state.renderer.layer().map(|layer| { + let drawable_size = layer.drawableSize(); + serde_json::json!({ + "drawable_size": [drawable_size.width, drawable_size.height], + "contents_scale": layer.contentsScale(), + }) + }); + serde_json::json!({ + "window_number": window.windowNumber(), + "occlusion_state_visible": window + .occlusionState() + .contains(NSWindowOcclusionState::Visible), + "is_visible": window.isVisible(), + "is_key_window": window.isKeyWindow(), + "is_main_window": window.isMainWindow(), + "is_miniaturized": window.isMiniaturized(), + "is_on_active_space": window.isOnActiveSpace(), + "screen_display_id": display_id_for_screen(screen), + "frame": [frame.origin.x, frame.origin.y, frame.size.width, frame.size.height], + "backing_scale_factor": window.backingScaleFactor(), + "frame_source": match &state.frame_source { + FrameSource::Metal(metal_frames) => metal_frames.debug_state(), + FrameSource::DisplayLink(Some(frame_source)) => frame_source.debug_state(), + FrameSource::DisplayLink(None) => serde_json::json!({ + "kind": "CVDisplayLink", + "attached": false, + }), + }, + "renderer": { + "display_link_attached": state.renderer.is_display_link_attached(), + "presents_with_transaction": state.renderer.presents_with_transaction(), + "layer": layer, + }, + "request_frame_callback_installed": state.request_frame_callback.is_some(), + "last_reported_visibility": state + .last_visibility + .map(|visibility| format!("{visibility:?}")), + "activated_at_least_once": state.activated_least_once, + "cursor": { + "cached_style": state.cursor_style, + "cached_visible": state.cursor_visible.load(Ordering::Relaxed), + }, + }) + } + fn update_ime_position(&self, _bounds: Bounds) { let executor = self.0.lock().foreground_executor.clone(); executor @@ -2565,17 +2671,13 @@ fn add_mouse_tracking_area(native_view: &NSView) { native_view.addTrackingArea(&tracking_area); } -extern "C" fn reset_cursor_rects(this: &AnyObject, _: Sel) { - // SAFETY: AppKit invokes cursor-rect updates on the main thread for GPUIView instances, - // whose WINDOW_STATE_IVAR is initialized when the view is created. The cursor registered - // below is a valid NSCursor. +/// # Safety +/// +/// Must be called on the AppKit main thread. +pub(crate) unsafe fn native_cursor(style: CursorStyle) -> *mut AnyObject { + // SAFETY: Each selector is an `NSCursor` class method returning a cursor. unsafe { - let _: () = msg_send![super(this, class!(NSView)), resetCursorRects]; - - let window_state = get_window_state(this); - let cursor_style = window_state.lock().cursor_style; - - let cursor: *mut AnyObject = match cursor_style { + match style { CursorStyle::Arrow => msg_send![class!(NSCursor), arrowCursor], CursorStyle::IBeam => msg_send![class!(NSCursor), IBeamCursor], CursorStyle::Crosshair => msg_send![class!(NSCursor), crosshairCursor], @@ -2609,7 +2711,21 @@ extern "C" fn reset_cursor_rects(this: &AnyObject, _: Sel) { CursorStyle::DragLink => msg_send![class!(NSCursor), dragLinkCursor], CursorStyle::DragCopy => msg_send![class!(NSCursor), dragCopyCursor], CursorStyle::ContextualMenu => msg_send![class!(NSCursor), contextualMenuCursor], - }; + } + } +} + +extern "C" fn reset_cursor_rects(this: &AnyObject, _: Sel) { + // SAFETY: AppKit invokes cursor-rect updates on the main thread for GPUIView instances, + // whose WINDOW_STATE_IVAR is initialized when the view is created. The cursor registered + // below is a valid NSCursor. + unsafe { + let _: () = msg_send![super(this, class!(NSView)), resetCursorRects]; + + let window_state = get_window_state(this); + let cursor_style = window_state.lock().cursor_style; + + let cursor = native_cursor(cursor_style); let bounds: NSRect = msg_send![this, bounds]; let _: () = msg_send![this, addCursorRect: bounds, cursor: cursor]; @@ -3083,37 +3199,22 @@ extern "C" fn window_will_enter_fullscreen(this: &AnyObject, _: Sel, _: *mut Any lock.is_exiting_fullscreen = false; lock.pre_fullscreen_traffic_light_frames = lock.traffic_light_frames; lock.restore_traffic_light(); + lock.apply_fullscreen_titlebar_opacity(); +} - let min_version = NSOperatingSystemVersion { - majorVersion: 15, - minorVersion: 3, - patchVersion: 0, - }; - - if is_macos_version_at_least(min_version) { - unsafe { - let _: () = msg_send![lock.native_window, setTitlebarAppearsTransparent: Bool::NO]; - } - } +extern "C" fn window_did_fail_to_enter_fullscreen(this: &AnyObject, _: Sel, _: *mut AnyObject) { + let window_state = unsafe { get_window_state(this) }; + let mut lock = window_state.as_ref().lock(); + lock.restore_windowed_titlebar_transparency(); + lock.traffic_light_frames = lock.pre_fullscreen_traffic_light_frames.take(); + lock.move_traffic_light(); } extern "C" fn window_will_exit_fullscreen(this: &AnyObject, _: Sel, _: *mut AnyObject) { let window_state = unsafe { get_window_state(this) }; let mut lock = window_state.as_ref().lock(); lock.is_exiting_fullscreen = true; - - let min_version = NSOperatingSystemVersion { - majorVersion: 15, - minorVersion: 3, - patchVersion: 0, - }; - - if is_macos_version_at_least(min_version) && lock.transparent_titlebar { - unsafe { - let _: () = msg_send![lock.native_window, setTitlebarAppearsTransparent: Bool::YES]; - } - } - + lock.restore_windowed_titlebar_transparency(); lock.move_traffic_light(); } @@ -3121,6 +3222,9 @@ extern "C" fn window_did_fail_to_exit_fullscreen(this: &AnyObject, _: Sel, _: *m let window_state = unsafe { get_window_state(this) }; let mut lock = window_state.as_ref().lock(); lock.is_exiting_fullscreen = false; + if lock.is_fullscreen() { + lock.apply_fullscreen_titlebar_opacity(); + } lock.restore_traffic_light(); } diff --git a/crates/gpui_platform/benches/primitives.rs b/crates/gpui_platform/benches/primitives.rs index 4b19618675f..f86866dd5f6 100644 --- a/crates/gpui_platform/benches/primitives.rs +++ b/crates/gpui_platform/benches/primitives.rs @@ -12,9 +12,9 @@ use std::{fmt, rc::Rc, time::Duration}; use gpui::{ App, AtlasTextureId, AtlasTextureKind, AtlasTile, Background, BenchAppContext, Bounds, - BoxShadow, Context, Corners, DevicePixels, Hsla, IntoElement, Path, PathBuilder, Pixels, - Render, Scene, SharedString, Styled, TextAlign, TextRun, TileId, TransformationMatrix, - UnderlineStyle, Window, canvas, fill, hsla, point, + BoxShadow, ContentMask, Context, Corners, DevicePixels, Hsla, IntoElement, PaintedPath, Path, + PathBuilder, Pixels, Render, Scene, SharedString, Styled, TextAlign, TextRun, TileId, + TransformationMatrix, UnderlineStyle, Window, canvas, fill, hsla, point, private::rand::{Rng as _, SeedableRng as _, rngs::StdRng}, px, size, }; @@ -80,9 +80,12 @@ enum Kind { Quad, Shadow, Underline, - /// Tessellated before timing: path tessellation is measured by the tree benchmarks, - /// and would otherwise dominate what these cases are for. - Path(Path), + /// Built and binned before timing, since binning would otherwise dominate what these + /// cases are for. The window paints `path`, and the scene takes a copy of `painted`. + Path { + path: Path, + painted: PaintedPath, + }, Text(SharedString), } @@ -113,7 +116,10 @@ fn random_rectangles(seed: u64, count: usize, extent: f32) -> Rc<[Rectangle]> { 0..9 => Kind::Quad, 9..11 => Kind::Shadow, 11..13 => Kind::Underline, - 13..16 => triangle(bounds).map_or(Kind::Quad, Kind::Path), + 13..16 => triangle(bounds).map_or(Kind::Quad, |path| Kind::Path { + painted: PaintedPath::new(path.clone(), 1., scene_content_mask(), color.into()), + path, + }), _ => { let length = rng.random_range(1..12); Kind::Text("Ag3 Wq7 fixture"[..length].to_string().into()) @@ -130,7 +136,7 @@ fn random_rectangles(seed: u64, count: usize, extent: f32) -> Rc<[Rectangle]> { .into() } -fn triangle(bounds: Bounds) -> Option> { +fn triangle(bounds: Bounds) -> Option { let mut path = PathBuilder::fill(); path.move_to(bounds.origin); path.line_to(bounds.top_right()); @@ -236,7 +242,7 @@ fn paint(rectangle: &Rectangle, window: &mut Window, cx: &mut App) { wavy: false, }, ), - Kind::Path(path) => window.paint_path(path.clone(), rectangle.color), + Kind::Path { path, .. } => window.paint_path(path.clone(), rectangle.color), // Shaped every frame, as the text element does; the line layout cache makes // repeated shaping a lookup. Kind::Text(text) => { @@ -283,11 +289,20 @@ fn glyph_tile(index: usize) -> AtlasTile { } } +fn scene_content_mask() -> ContentMask { + ContentMask { + bounds: Bounds::new(point(px(0.), px(0.)), size(px(1_024.), px(1_024.))), + } +} + fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) { + insert_primitives(scene, rectangles); + scene.finish(); +} + +fn insert_primitives(scene: &mut Scene, rectangles: &[Rectangle]) { scene.clear(); - let content_mask = gpui::ContentMask { - bounds: Bounds::new(point(px(0.), px(0.)), size(px(1_024.), px(1_024.))).scale(1.), - }; + let content_mask = scene_content_mask().scale(1.); for (index, rectangle) in rectangles.iter().enumerate() { let bounds = rectangle.bounds.scale(1.); match &rectangle.kind { @@ -304,13 +319,13 @@ fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) { Kind::Shadow => scene.insert_primitive(gpui::Shadow { order: 0, blur_radius: gpui::ScaledPixels(6.), - bounds, - corner_radii: Corners::all(gpui::ScaledPixels(4.)), + bounds: bounds.dilate(gpui::ScaledPixels(18.)), + corner_radii: Corners::default(), content_mask, color: rectangle.color, - element_bounds: bounds, - element_corner_radii: Corners::all(gpui::ScaledPixels(4.)), - inset: 0, + shape_bounds: bounds, + shape_corner_radii: Corners::all(gpui::ScaledPixels(4.)), + inset: false.into(), pad: 0, }), Kind::Underline => scene.insert_primitive(gpui::Underline { @@ -322,12 +337,7 @@ fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) { thickness: bounds.size.height.min(gpui::ScaledPixels(4.)), wavy: Default::default(), }), - Kind::Path(path) => { - let mut path = path.scale(1.); - path.content_mask = content_mask; - path.color = rectangle.background; - scene.insert_primitive(path); - } + Kind::Path { painted, .. } => scene.insert_primitive(painted.clone()), Kind::Text(text) => { let glyph_size = bounds.size.height.min(gpui::ScaledPixels(32.)); for glyph in 0..text.len() { @@ -346,7 +356,26 @@ fn build_scene(scene: &mut Scene, rectangles: &[Rectangle]) { } } } - scene.finish(); +} + +fn scene_finish(criterion: &mut criterion::Criterion) { + let mut group = criterion.benchmark_group("Primitives/finish"); + for case in cases() { + let mut fixture = None; + group.bench_function(case.to_string(), |bencher| { + let rectangles = fixture.get_or_insert_with(|| rectangles(&case, 512.)); + bencher.iter_batched_ref( + || { + let mut scene = Scene::default(); + insert_primitives(&mut scene, rectangles); + scene + }, + |scene| scene.finish(), + criterion::BatchSize::LargeInput, + ); + }); + } + group.finish(); } fn scene_ordering(criterion: &mut criterion::Criterion) { @@ -409,6 +438,6 @@ gpui::bench_group!( .warm_up_time(Duration::from_millis(500)) .measurement_time(Duration::from_secs(1)) .sample_size(20); - targets = paint_rectangles, scene_ordering + targets = paint_rectangles, scene_ordering, scene_finish ); gpui::bench_main!(benches); diff --git a/crates/gpui_wgpu/Cargo.toml b/crates/gpui_wgpu/Cargo.toml index 600d0083d86..777b3e1420c 100644 --- a/crates/gpui_wgpu/Cargo.toml +++ b/crates/gpui_wgpu/Cargo.toml @@ -48,6 +48,7 @@ wgpu = { workspace = true, features = ["std", "metal", "gles", "vulkan", "wgsl", wgpu = { workspace = true, default-features = true } [target.'cfg(target_family = "wasm")'.dependencies] +js-sys.workspace = true web-sys = { workspace = true, features = ["HtmlCanvasElement"] } wgpu = { workspace = true, features = ["webgl"] } diff --git a/crates/gpui_wgpu/src/cosmic_text_system.rs b/crates/gpui_wgpu/src/cosmic_text_system.rs index 775067518c6..7d738affa57 100644 --- a/crates/gpui_wgpu/src/cosmic_text_system.rs +++ b/crates/gpui_wgpu/src/cosmic_text_system.rs @@ -816,7 +816,10 @@ impl CosmicTextSystemState { let shaped_glyph = ShapedGlyph { id: GlyphId(glyph.glyph_id as u32), - position: point(glyph.x.into(), glyph.y.into()), + position: point( + (glyph.x + glyph.x_offset * f32::from(font_size)).into(), + (glyph.y - glyph.y_offset * f32::from(font_size)).into(), + ), index: glyph.start, is_emoji, }; @@ -1369,6 +1372,29 @@ mod tests { Ok(text_system.layout_line(text, gpui::px(14.0), &runs)) } + #[test] + fn combining_marks_are_positioned_over_their_base() -> Result<()> { + let text_system = text_system()?; + let layout = layout_text(&text_system, "v\u{0304}v")?; + let glyphs = layout + .runs + .iter() + .flat_map(|run| run.glyphs.iter()) + .collect::>(); + assert_eq!(glyphs.len(), 3); + let base = glyphs[0].position; + let mark = glyphs[1].position; + let next = glyphs[2].position; + assert!(mark.x > base.x); + assert!( + mark.x < next.x, + "combining mark positioned after its base: mark.x={:?}, next.x={:?}", + mark.x, + next.x + ); + Ok(()) + } + /// Mirrors the original crash: mixed-direction text reaching the shaper /// through `shape_text`, which only splits lines on `\n`. #[test] diff --git a/crates/gpui_wgpu/src/shaders.wgsl b/crates/gpui_wgpu/src/shaders.wgsl index 9be210bf225..69a5338d3c5 100644 --- a/crates/gpui_wgpu/src/shaders.wgsl +++ b/crates/gpui_wgpu/src/shaders.wgsl @@ -79,10 +79,15 @@ fn apply_contrast_and_gamma_correction3(sample: vec3, color: vec3, enh struct GlobalParams { viewport_size: vec2, - premultiplied_alpha: u32, - pad: u32, + path_paint_base: u32, + path_curve_base: u32, + depth_scale: f32, + quad_count: u32, + pad: vec2, } +override PREMULTIPLIED_ALPHA: bool = false; + struct GammaParams { gamma_ratios: vec4, grayscale_enhanced_contrast: f32, @@ -99,6 +104,8 @@ struct GammaParams { const M_PI_F: f32 = 3.1415926; const GRAYSCALE_FACTORS: vec3 = vec3(0.2126, 0.7152, 0.0722); +const SIMPLE_PRIMITIVE_FLAG: u32 = 0x80000000u; + struct Bounds { origin: vec2, size: vec2, @@ -136,7 +143,7 @@ struct Background { // 2u is PatternSlash // 3u is Checkerboard tag: u32, - // 0u is sRGB linear color + // 0u is sRGB color // 1u is Oklab color color_space: u32, solid: Hsla, @@ -195,17 +202,29 @@ fn distance_from_clip_rect_impl(position: vec2, clip_bounds: Bounds) -> vec return vec4(tl.x, br.x, tl.y, br.y); } -fn distance_from_clip_rect(unit_vertex: vec2, bounds: Bounds, clip_bounds: Bounds) -> vec4 { - let position = unit_vertex * vec2(bounds.size) + bounds.origin; - return distance_from_clip_rect_impl(position, clip_bounds); -} - fn distance_from_clip_rect_transformed(unit_vertex: vec2, bounds: Bounds, clip_bounds: Bounds, transform: TransformationMatrix) -> vec4 { let position = unit_vertex * vec2(bounds.size) + bounds.origin; let transformed = transpose(transform.rotation_scale) * position + transform.translation; return distance_from_clip_rect_impl(transformed, clip_bounds); } +struct ClippedVertex { + position: vec2, + // The corner as a fraction of the original bounds. + unit_vertex: vec2, +} + +fn clip_to_mask(unit_vertex: vec2, bounds: Bounds, mask: Bounds) -> ClippedVertex { + let origin = max(bounds.origin, mask.origin); + let corner = min(bounds.origin + bounds.size, mask.origin + mask.size); + let size = max(corner - origin, vec2(0.0)); + + var result: ClippedVertex; + result.position = origin + unit_vertex * size; + result.unit_vertex = (result.position - bounds.origin) / bounds.size; + return result; +} + // https://gamedev.stackexchange.com/questions/92015/optimized-linear-to-srgb-glsl fn srgb_to_linear(srgb: vec3) -> vec3 { let cutoff = srgb < vec3(0.04045); @@ -316,27 +335,6 @@ fn over(below: vec4, above: vec4) -> vec4 { return vec4(color, alpha); } -// A standard gaussian function, used for weighting samples -fn gaussian(x: f32, sigma: f32) -> f32{ - return exp(-(x * x) / (2.0 * sigma * sigma)) / (sqrt(2.0 * M_PI_F) * sigma); -} - -// This approximates the error function, needed for the gaussian integral -fn erf(v: vec2) -> vec2 { - let s = sign(v); - let a = abs(v); - let r1 = 1.0 + (0.278393 + (0.230389 + (0.000972 + 0.078108 * a) * a) * a) * a; - let r2 = r1 * r1; - return s - s / (r2 * r2); -} - -fn blur_along_x(x: f32, y: f32, sigma: f32, corner: f32, half_size: vec2) -> f32 { - let delta = min(half_size.y - corner - abs(y), 0.0); - let curved = half_size.x - corner + sqrt(max(0.0, corner * corner - delta * delta)); - let integral = 0.5 + 0.5 * erf((x + vec2(-curved, curved)) * (sqrt(0.5) / sigma)); - return integral.y - integral.x; -} - // Selects corner radius based on quadrant. fn pick_corner_radius(center_to_point: vec2, radii: Corners) -> f32 { if (center_to_point.x < 0.0) { @@ -390,60 +388,65 @@ fn quad_sdf_impl(corner_center_to_point: vec2, corner_radius: f32) -> f32 { // target alpha compositing mode. fn blend_color(color: vec4, alpha_factor: f32) -> vec4 { let alpha = color.a * alpha_factor; - let multiplier = select(1.0, alpha, globals.premultiplied_alpha != 0u); + let multiplier = select(1.0, alpha, PREMULTIPLIED_ALPHA); return vec4(color.rgb * multiplier, alpha); } -struct GradientColor { - solid: vec4, +struct PreparedBackground { color0: vec4, color1: vec4, + tag: u32, } -fn prepare_gradient_color(tag: u32, color_space: u32, - solid: Hsla, colors: array) -> GradientColor { - var result = GradientColor(); +fn prepare_background(background: Background) -> PreparedBackground { + var result: PreparedBackground; + result.tag = background.tag; + result.color1 = vec4(0.0); - if (tag == 0u || tag == 2u || tag == 3u) { - result.solid = hsla_to_rgba(solid); - } else if (tag == 1u) { - // The hsla_to_rgba is returns a linear sRGB color - result.color0 = hsla_to_rgba(colors[0].color); - result.color1 = hsla_to_rgba(colors[1].color); - - // Prepare color space in vertex for avoid conversion - // in fragment shader for performance reasons - if (color_space == 0u) { - // sRGB + if (background.tag == 1u) { + // `hsla_to_rgba` returns linear sRGB. Converting the endpoints to the + // interpolation space once avoids converting at every stop evaluation. + result.color0 = hsla_to_rgba(background.colors[0].color); + result.color1 = hsla_to_rgba(background.colors[1].color); + if (background.color_space == 0u) { result.color0 = linear_to_srgba(result.color0); result.color1 = linear_to_srgba(result.color1); - } else if (color_space == 1u) { - // Oklab + } else if (background.color_space == 1u) { result.color0 = linear_srgb_to_oklab(result.color0); result.color1 = linear_srgb_to_oklab(result.color1); } + } else { + result.color0 = hsla_to_rgba(background.solid); } return result; } -fn gradient_color(background: Background, position: vec2, bounds: Bounds, - solid_color: vec4, color0: vec4, color1: vec4) -> vec4 { - var background_color = vec4(0.0); +// Ordered (Bayer 4x4) dither threshold, remapped to [-1, +1]. +fn dither_offset(position: vec2) -> f32 { + let cell = vec2(position) & vec2(3u); + let z = cell.x ^ cell.y; + let threshold = ((z & 1u) << 3u) + | ((cell.y & 1u) << 2u) + | (z & 2u) + | ((cell.y & 2u) >> 1u); + return (f32(threshold) + 0.5) * (1.0 / 8.0) - 1.0; +} - switch (background.tag) { - default: { - return solid_color; - } +fn background_color(prepared: PreparedBackground, background: Background, bounds: Bounds, + position: vec2) -> vec4 { + var color = prepared.color0; + if (prepared.tag == 0u) { + return color; + } + + switch (prepared.tag) { case 1u: { - // Linear gradient background. // -90 degrees to match the CSS gradient angle. - let angle = background.gradient_angle_or_pattern_height; - let radians = (angle % 360.0 - 90.0) * M_PI_F / 180.0; + let radians = (background.gradient_angle_or_pattern_height % 360.0 - 90.0) + * M_PI_F / 180.0; var direction = vec2(cos(radians), sin(radians)); - let stop0_percentage = background.colors[0].percentage; - let stop1_percentage = background.colors[1].percentage; // Expand the short side to be the same as the long side if (bounds.size.x > bounds.size.y) { @@ -452,66 +455,64 @@ fn gradient_color(background: Background, position: vec2, bounds: Bounds, direction.x *= bounds.size.x / bounds.size.y; } - // Get the t value for the linear gradient with the color stop percentages. - let half_size = bounds.size / 2.0; - let center = bounds.origin + half_size; - let center_to_point = position - center; - var t = dot(center_to_point, direction) / length(direction); - // Check the direct to determine the use x or y - if (abs(direction.x) > abs(direction.y)) { - t = (t + half_size.x) / bounds.size.x; + let extent = select(bounds.size.y, bounds.size.x, abs(direction.x) > abs(direction.y)); + let direction_length = length(direction); + let span = background.colors[1].percentage - background.colors[0].percentage; + // The half-extent term is exactly half of `extent`, so the + // position-independent part reduces to this. + let offset = 0.5 - background.colors[0].percentage; + + // t = dot(position - center, gradient.xy) + gradient.z + var gradient = vec3(0.0); + if (direction_length != 0.0 && extent != 0.0) { + if (span == 0.0) { + const STEP: f32 = 1e30; + gradient = vec3(direction / (direction_length * extent) * STEP, offset * STEP); + } else { + gradient = vec3(direction / (direction_length * extent * span), offset / span); + } + } + let center = bounds.origin + bounds.size * 0.5; + let t = saturate(dot(position - center, gradient.xy) + gradient.z); + color = mix(prepared.color0, prepared.color1, t); + if (background.color_space == 1u) { + color = oklab_to_linear_srgb(color); } else { - t = (t + half_size.y) / bounds.size.y; + color = srgba_to_linear(color); } - // Adjust t based on the stop percentages - t = (t - stop0_percentage) / (stop1_percentage - stop0_percentage); - t = clamp(t, 0.0, 1.0); - - switch (background.color_space) { - default: { - background_color = srgba_to_linear(mix(color0, color1, t)); - } - case 1u: { - let oklab_color = mix(color0, color1, t); - background_color = oklab_to_linear_srgb(oklab_color); - } - } + // Dither to reduce banding in gradients (especially dark/alpha). + let dither = dither_offset(position); + color = vec4(color.rgb + dither * 1.0 / 255.0, color.a + dither * 1.5 / 255.0); } case 2u: { // pattern slash - let gradient_angle_or_pattern_height = background.gradient_angle_or_pattern_height; - let pattern_width = (gradient_angle_or_pattern_height / 65535.0f) / 255.0f; - let pattern_interval = (gradient_angle_or_pattern_height % 65535.0f) / 255.0f; + let pattern_height_encoded = background.gradient_angle_or_pattern_height; + let pattern_width = (pattern_height_encoded / 65535.0) / 255.0; + let pattern_interval = (pattern_height_encoded % 65535.0) / 255.0; let pattern_height = pattern_width + pattern_interval; + // Only the rotated x coordinate is used, and multiplying by the + // rotation reduces it to dot(v, vec2(cos a, sin a)). let stripe_angle = M_PI_F / 4.0; + let stripe_direction = vec2(cos(stripe_angle), sin(stripe_angle)); let pattern_period = pattern_height * sin(stripe_angle); - let rotation = mat2x2( - cos(stripe_angle), -sin(stripe_angle), - sin(stripe_angle), cos(stripe_angle) - ); - let relative_position = position - bounds.origin; - let rotated_point = rotation * relative_position; - let pattern = rotated_point.x % pattern_period; - let distance = min(pattern, pattern_period - pattern) - pattern_period * (pattern_width / pattern_height) / 2.0f; - background_color = solid_color; - background_color.a *= saturate(0.5 - distance); + let threshold = pattern_period * (pattern_width / pattern_height) / 2.0; + let pattern = dot(position - bounds.origin, stripe_direction) % pattern_period; + let distance = min(pattern, pattern_period - pattern) - threshold; + color.a *= saturate(0.5 - distance); } case 3u: { // checkerboard - let size = background.gradient_angle_or_pattern_height; + let cell_size = background.gradient_angle_or_pattern_height; let relative_position = position - bounds.origin; - - let x_index = floor(relative_position.x / size); - let y_index = floor(relative_position.y / size); - let should_be_colored = (x_index + y_index) % 2.0; - - background_color = solid_color; - background_color.a *= saturate(should_be_colored); + let x_index = floor(relative_position.x / cell_size); + let y_index = floor(relative_position.y / cell_size); + color.a *= saturate((x_index + y_index) % 2.0); } + default: {} } - return background_color; + return color; } // --- quads --- // @@ -527,65 +528,84 @@ struct Quad { border_widths: Edges, } +fn has_rounded_corners(corner_radii: Corners) -> bool { + return corner_radii.top_left != 0.0 + || corner_radii.top_right != 0.0 + || corner_radii.bottom_right != 0.0 + || corner_radii.bottom_left != 0.0; +} + +fn has_border(border_widths: Edges) -> bool { + return border_widths.top != 0.0 + || border_widths.right != 0.0 + || border_widths.bottom != 0.0 + || border_widths.left != 0.0; +} + +fn is_shaped(quad: Quad) -> bool { + return has_rounded_corners(quad.corner_radii) || has_border(quad.border_widths); +} + +const CULLED_POSITION: vec4 = vec4(0.0, 0.0, 0.0, 1.0); + +fn quad_depth(quad_id: u32) -> f32 { + return saturate(f32(quad_id + 1u) * globals.depth_scale); +} + +// Opaque rectangles are drawn by the opaque pass instead of the quad pass. +fn is_opaque_rectangle(quad: Quad) -> bool { + return quad.background.tag == 0u + && quad.background.solid.a >= 1.0 + && !has_rounded_corners(quad.corner_radii) + && !has_border(quad.border_widths); +} + struct QuadVarying { @builtin(position) position: vec4, @location(0) @interpolate(flat) border_color: vec4, @location(1) @interpolate(flat) quad_id: u32, - // TODO: use `clip_distance` once Naga supports it - @location(2) clip_distances: vec4, - @location(3) @interpolate(flat) background_solid: vec4, - @location(4) @interpolate(flat) background_color0: vec4, - @location(5) @interpolate(flat) background_color1: vec4, + // Inter-stage values can't be structs, so `PreparedBackground` is flattened. + @location(2) @interpolate(flat) background_color0: vec4, + @location(3) @interpolate(flat) background_color1: vec4, + @location(4) @interpolate(flat) background_tag: u32, } @vertex fn vs_quad(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> QuadVarying { - let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); let quad = load_quad(instance_id); var out = QuadVarying(); - out.position = to_device_position(unit_vertex, quad.bounds); + if (is_opaque_rectangle(quad)) { + out.position = CULLED_POSITION; + return out; + } + + let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); + let clipped = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask); + out.position = to_device_position_impl(clipped.position); + out.position.z = quad_depth(instance_id); - let gradient = prepare_gradient_color( - quad.background.tag, - quad.background.color_space, - quad.background.solid, - quad.background.colors - ); - out.background_solid = gradient.solid; - out.background_color0 = gradient.color0; - out.background_color1 = gradient.color1; out.border_color = hsla_to_rgba(quad.border_color); - out.quad_id = instance_id; - out.clip_distances = distance_from_clip_rect(unit_vertex, quad.bounds, quad.content_mask); + let simple = !is_shaped(quad) && quad.background.tag == 0u; + out.quad_id = instance_id | select(0u, SIMPLE_PRIMITIVE_FLAG, simple); + let background = prepare_background(quad.background); + out.background_color0 = background.color0; + out.background_color1 = background.color1; + out.background_tag = background.tag; return out; } @fragment fn fs_quad(input: QuadVarying) -> @location(0) vec4 { - // Alpha clip first, since we don't have `clip_distance`. - if (any(input.clip_distances < vec4(0.0))) { - return vec4(0.0); + if ((input.quad_id & SIMPLE_PRIMITIVE_FLAG) != 0u) { + return blend_color(input.background_color0, 1.0); } let quad = load_quad(input.quad_id); - - let background_color = gradient_color(quad.background, input.position.xy, quad.bounds, - input.background_solid, input.background_color0, input.background_color1); - - let unrounded = quad.corner_radii.top_left == 0.0 && - quad.corner_radii.bottom_left == 0.0 && - quad.corner_radii.top_right == 0.0 && - quad.corner_radii.bottom_right == 0.0; - - // Fast path when the quad is not rounded and doesn't have any border - if (quad.border_widths.top == 0.0 && - quad.border_widths.left == 0.0 && - quad.border_widths.right == 0.0 && - quad.border_widths.bottom == 0.0 && - unrounded) { - return blend_color(background_color, 1.0); - } + let prepared = PreparedBackground(input.background_color0, input.background_color1, + input.background_tag); + let background = background_color(prepared, quad.background, quad.bounds, input.position.xy); + let unrounded = !has_rounded_corners(quad.corner_radii); let size = quad.bounds.size; let half_size = size / 2.0; @@ -650,7 +670,7 @@ fn fs_quad(input: QuadVarying) -> @location(0) vec4 { // However, that might negatively impact performance in the case of // reasonable sizes for rounded corners. if (is_within_inner_straight_border && !is_near_rounded_corner) { - return blend_color(background_color, 1.0); + return blend_color(background, 1.0); } // Signed distance of the point to the outside edge of the quad's border. It @@ -684,7 +704,7 @@ fn fs_quad(input: QuadVarying) -> @location(0) vec4 { // Negative when inside the border let border_sdf = max(inner_sdf, outer_sdf); - var color = background_color; + var color = background; if (border_sdf < antialias_threshold) { var border_color = input.border_color; @@ -884,8 +904,8 @@ fn fs_quad(input: QuadVarying) -> @location(0) vec4 { // Blend the border on top of the background and then linearly interpolate // between the two as we slide inside the background. - let blended_border = over(background_color, border_color); - color = mix(background_color, blended_border, + let blended_border = over(background, border_color); + color = mix(background, blended_border, saturate(antialias_threshold - inner_sdf)); } @@ -945,20 +965,52 @@ fn fmod(a: f32, b: f32) -> f32 { return a - b * trunc(a / b); } +// --- opaque quads --- // + +struct OpaqueQuadVarying { + @builtin(position) position: vec4, + @location(0) @interpolate(flat) color: vec4, +} + +@vertex +fn vs_opaque_quad(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> OpaqueQuadVarying { + let quad_id = globals.quad_count - 1u - instance_id; + let quad = load_quad(quad_id); + + var out = OpaqueQuadVarying(); + if (!is_opaque_rectangle(quad)) { + out.position = CULLED_POSITION; + return out; + } + + let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); + let clipped = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask); + out.position = to_device_position_impl(clipped.position); + out.position.z = quad_depth(quad_id); + out.color = blend_color(hsla_to_rgba(quad.background.solid), 1.0); + return out; +} + +@fragment +fn fs_opaque_quad(input: OpaqueQuadVarying) -> @location(0) vec4 { + return input.color; +} + // --- shadows --- // struct Shadow { order: u32, blur_radius: f32, - // The shadow rect for drop shadows; the "hole" rect for inset shadows. + // The area the shadow paints: the blurred extent of a drop shadow, or the element + // that an inset shadow is clipped to. bounds: Bounds, corner_radii: Corners, content_mask: Bounds, color: Hsla, - // Only consulted when `inset == 1u`: the element's own bounds, used as a rounded-rect - // clip so the shadow never escapes the element. - element_bounds: Bounds, - element_corner_radii: Corners, + // The shape that is blurred: the silhouette of a drop shadow, or the hole of an + // inset shadow. + shape_bounds: Bounds, + shape_corner_radii: Corners, // 0 = drop shadow, 1 = inset shadow. inset: u32, pad: u32, // align to 8 bytes @@ -968,8 +1020,74 @@ struct ShadowVarying { @builtin(position) position: vec4, @location(0) @interpolate(flat) color: vec4, @location(1) @interpolate(flat) shadow_id: u32, - //TODO: use `clip_distance` once Naga supports it - @location(3) clip_distances: vec4, + @location(2) @interpolate(flat) blur_shape: vec4, + @location(3) @interpolate(flat) blur_r1: vec4, + @location(4) @interpolate(flat) blur_exponent: vec4, + @location(5) @interpolate(flat) blur_scale: vec4, +} + +struct PreparedBlurredRoundedRect { + shape: vec4, + r1: vec4, + exponent: vec4, + scale: vec4, +} + +fn erf7(input: f32) -> f32 { + let x = clamp(input, -10.0, 10.0) * (2.0 / sqrt(M_PI_F)); + let xx = x * x; + let y = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx); + return y / sqrt(1.0 + y * y); +} + +// Raph Levien's blurred rounded rectangle approximation, whose blur s is sigma * sqrt(2): +// https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html +fn prepare_blurred_rounded_rect(size: vec2, corner_radii: Corners, sigma: f32) -> PreparedBlurredRoundedRect { + let s = max(sigma * sqrt(2.0), 1e-6); + let s_inv = 1.0 / s; + let min_edge = min(size.x, size.y); + let r_max = 0.5 * min_edge; + let radii = vec4(corner_radii.top_left, corner_radii.top_right, + corner_radii.bottom_right, corner_radii.bottom_left); + let r0 = min(sqrt(radii * radii + 1.15 * 1.15 * s * s), vec4(r_max)); + let r1 = min(sqrt(radii * radii + 4.0 * s * s), vec4(r_max)); + + let half_extent = 0.5 * s_inv * size; + let delta = 1.25 * s * (exp(-half_extent.x * half_extent.x) - exp(-half_extent.y * half_extent.y)); + let adjusted_size = vec2(size.x + min(delta, 0.0), size.y - max(delta, 0.0)); + let peak = s_inv * 0.5 * (max(adjusted_size.x, adjusted_size.y) - 0.5 * radii); + + var output: PreparedBlurredRoundedRect; + output.shape = vec4(0.5 * adjusted_size, s_inv, min_edge); + output.r1 = r1; + output.exponent = 2.0 * r1 / r0; + output.scale = 0.5 * vec4(erf7(peak.x), erf7(peak.y), erf7(peak.z), erf7(peak.w)); + return output; +} + +fn pick_corner(center_to_point: vec2, values: vec4) -> f32 { + return pick_corner_radius(center_to_point, Corners(values.x, values.y, values.z, values.w)); +} + +fn blurred_rounded_rect(center_to_point: vec2, prepared: PreparedBlurredRoundedRect) -> f32 { + let r1 = pick_corner(center_to_point, prepared.r1); + let exponent = pick_corner(center_to_point, prepared.exponent); + let scale = pick_corner(center_to_point, prepared.scale); + let s_inv = prepared.shape.z; + let min_edge = prepared.shape.w; + + let p0 = abs(center_to_point) - (prepared.shape.xy - r1); + let p1 = max(p0, vec2(0.0)); + var d_pos: f32; + if (p1.x > 0.0 && p1.y > 0.0) { + d_pos = pow(pow(p1.x, exponent) + pow(p1.y, exponent), 1.0 / exponent); + } else { + d_pos = p1.x + p1.y; + } + + let d_neg = min(max(p0.x, p0.y), 0.0); + let d = d_pos + d_neg - r1; + return scale * (erf7(s_inv * (min_edge + d)) - erf7(s_inv * d)); } @vertex @@ -977,171 +1095,217 @@ fn vs_shadow(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) ins let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); var shadow = load_shadow(instance_id); - var geometry: Bounds; - if (shadow.inset != 0u) { - geometry = shadow.element_bounds; - } else { - // Leave room for the gaussian tail outside the shadow rect. - let margin = 3.0 * shadow.blur_radius; - geometry = shadow.bounds; - geometry.origin -= vec2(margin); - geometry.size += 2.0 * vec2(margin); - } - var out = ShadowVarying(); - out.position = to_device_position(unit_vertex, geometry); + let clipped = clip_to_mask(unit_vertex, shadow.bounds, shadow.content_mask); + out.position = to_device_position_impl(clipped.position); out.color = hsla_to_rgba(shadow.color); out.shadow_id = instance_id; - out.clip_distances = distance_from_clip_rect(unit_vertex, geometry, shadow.content_mask); + let blur = prepare_blurred_rounded_rect(shadow.shape_bounds.size, shadow.shape_corner_radii, + shadow.blur_radius); + out.blur_shape = blur.shape; + out.blur_r1 = blur.r1; + out.blur_exponent = blur.exponent; + out.blur_scale = blur.scale; return out; } @fragment fn fs_shadow(input: ShadowVarying) -> @location(0) vec4 { - // Alpha clip first, since we don't have `clip_distance`. - if (any(input.clip_distances < vec4(0.0))) { - return vec4(0.0); - } - let shadow = load_shadow(input.shadow_id); - let half_size = shadow.bounds.size / 2.0; - let center = shadow.bounds.origin + half_size; - let center_to_point = input.position.xy - center; - - let corner_radius = pick_corner_radius(center_to_point, shadow.corner_radii); var alpha: f32; if (shadow.blur_radius == 0.0) { - let distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii); + let distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii); alpha = saturate(0.5 - distance); } else { - // The signal is only non-zero in a limited range, so don't waste samples - let low = center_to_point.y - half_size.y; - let high = center_to_point.y + half_size.y; - let start = clamp(-3.0 * shadow.blur_radius, low, high); - let end = clamp(3.0 * shadow.blur_radius, low, high); - - // Accumulate samples (we can get away with surprisingly few samples) - let step = (end - start) / 4.0; - var y = start + step * 0.5; - alpha = 0.0; - for (var i = 0; i < 4; i += 1) { - let blur = blur_along_x(center_to_point.x, center_to_point.y - y, - shadow.blur_radius, corner_radius, half_size); - alpha += blur * gaussian(y, shadow.blur_radius) * step; - y += step; - } + let center = shadow.shape_bounds.origin + shadow.shape_bounds.size / 2.0; + let blur = PreparedBlurredRoundedRect(input.blur_shape, input.blur_r1, + input.blur_exponent, input.blur_scale); + alpha = blurred_rounded_rect(input.position.xy - center, blur); } if (shadow.inset != 0u) { // The inset shadow is the complement of the (blurred) hole rect, clipped to the element. // `saturate(0.5 - d)` gives a 1-pixel antialiased edge: d <= -0.5 -> 1, d >= 0.5 -> 0. alpha = 1.0 - alpha; - let element_distance = quad_sdf(input.position.xy, shadow.element_bounds, - shadow.element_corner_radii); + let element_distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii); alpha *= saturate(0.5 - element_distance); } return blend_color(input.color, alpha); } -// --- path rasterization --- // +// --- path tiles --- // -struct PathRasterizationVertex { - xy_position: vec2, - st_position: vec2, - color: Background, - bounds: Bounds, +struct PathTile { + paint: u32, + curve_start: u32, + curve_count: u32, + backdrop: i32, + top_left: vec2, + bottom_right: vec2, + reference: vec2, + curves_top_left: vec2, + curves_bottom_right: vec2, } +struct PathCurve { + p0: vec2, + p1: vec2, + a: vec2, + b: vec2, + sign: f32, + pad: u32, +} +struct PathPaint { + bounds: Bounds, + content_mask: Bounds, + color: Background, + even_odd: u32, + pad: u32, +} -struct PathRasterizationVarying { +struct PathTileVarying { @builtin(position) position: vec4, - @location(0) st_position: vec2, - @location(1) @interpolate(flat) vertex_id: u32, - //TODO: use `clip_distance` once Naga supports it - @location(3) clip_distances: vec4, + @location(0) @interpolate(flat) tile_id: u32, + // Inter-stage values can't be structs, so `PreparedBackground` is flattened. + @location(1) @interpolate(flat) background_color0: vec4, + @location(2) @interpolate(flat) background_color1: vec4, + @location(3) @interpolate(flat) background_tag: u32, + @location(4) @interpolate(flat) curve_box: vec4, } @vertex -fn vs_path_rasterization(@builtin(vertex_index) vertex_id: u32) -> PathRasterizationVarying { - let v = load_path_vertex(vertex_id); +fn vs_path_tile(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PathTileVarying { + let tile = load_path_tile(instance_id); + let paint = load_path_paint(tile.paint); - var out = PathRasterizationVarying(); - out.position = to_device_position_impl(v.xy_position); - out.st_position = v.st_position; - out.vertex_id = vertex_id; - out.clip_distances = distance_from_clip_rect_impl(v.xy_position, v.bounds); + let mask_top_left = paint.content_mask.origin; + let mask_bottom_right = paint.content_mask.origin + paint.content_mask.size; + let top_left = clamp(tile.top_left, mask_top_left, mask_bottom_right); + let bottom_right = clamp(tile.bottom_right, top_left, mask_bottom_right); + let position = vec2( + select(top_left.x, bottom_right.x, (vertex_id & 1u) != 0u), + select(top_left.y, bottom_right.y, (vertex_id & 2u) != 0u), + ); + + var out = PathTileVarying(); + out.position = to_device_position_impl(position); + out.tile_id = instance_id; + out.curve_box = vec4(tile.curves_top_left, tile.curves_bottom_right); + let background = prepare_background(paint.color); + out.background_color0 = background.color0; + out.background_color1 = background.color1; + out.background_tag = background.tag; return out; } +// Solves a*t^2 + b*t + c = 0 for the root in [0, 1] on a monotone piece. +fn monotone_quadratic_root(a: f32, b: f32, c: f32, direction: f32) -> f32 { + let discriminant = max(b * b - 4.0 * a * c, 0.0); + let denominator = b + direction * sqrt(discriminant); + if (denominator == 0.0) { + return 0.0; + } + return saturate(-2.0 * c / denominator); +} + +// Coverage estimate adapted from https://github.com/EricLengyel/Slug/blob/be3c13eb7d63f9e8aa5c583e42d92c374cb91d98/SlugPixelShader.hlsl +// Copyright (c) 2017 Eric Lengyel. +// Licensed under the MIT license. + +// Accumulates the curve's winding along the pixel's leftward and upward rays. Like Slug, a crossing +// within half a pixel of the center counts fractionally. +fn add_curve_winding(curve: PathCurve, center: vec2, winding: ptr>, + weight: ptr>) { + let min_x = min(curve.p0.x, curve.p1.x); + let max_x = max(curve.p0.x, curve.p1.x); + + if (curve.p0.y <= center.y && center.y < curve.p1.y) { + if (max_x <= center.x - 0.5) { + (*winding).x += curve.sign; + } else { + let t = monotone_quadratic_root(curve.a.y, curve.b.y, curve.p0.y - center.y, 1.0); + let x = (curve.a.x * t + curve.b.x) * t + curve.p0.x; + let distance = center.x - x; + (*winding).x += curve.sign * saturate(distance + 0.5); + (*weight).x = max((*weight).x, saturate(1.0 - 2.0 * abs(distance))); + } + } + + if (min_x <= center.x && center.x < max_x) { + let direction = select(-1.0, 1.0, curve.p1.x > curve.p0.x); + if (curve.p1.y <= center.y - 0.5) { + (*winding).y -= curve.sign * direction; + } else if (curve.p0.y < center.y + 0.5) { + let t = monotone_quadratic_root(curve.a.x, curve.b.x, curve.p0.x - center.x, direction); + let y = (curve.a.y * t + curve.b.y) * t + curve.p0.y; + let distance = center.y - y; + (*winding).y -= curve.sign * direction * saturate(distance + 0.5); + (*weight).y = max((*weight).y, saturate(1.0 - 2.0 * abs(distance))); + } + } +} + +// The backdrop gives the unlisted curves' winding along a leftward ray from the tile's reference +// corner. We need it at the current pixel, along both leftward and upward rays. Because paths are +// closed, chains of unlisted curves can only begin or end where a listed curve does. So, we can +// compute the winding at the current pixel by correcting the backdrop for each listed endpoint +// between its ray and the pixel. +fn correct_for_endpoint(endpoint: vec2, step: f32, reference: vec2, center: vec2, + winding: ptr>) { + if (endpoint.x <= reference.x) { + (*winding).x -= step * (f32(endpoint.y <= center.y) - f32(endpoint.y <= reference.y)); + } + if (endpoint.y <= reference.y && endpoint.x <= center.x) { + (*winding).y += step; + } +} + @fragment -fn fs_path_rasterization(input: PathRasterizationVarying) -> @location(0) vec4 { - let dx = dpdx(input.st_position); - let dy = dpdy(input.st_position); - if (any(input.clip_distances < vec4(0.0))) { +fn fs_path_tile(input: PathTileVarying) -> @location(0) vec4 { + let center = floor(input.position.xy) + 0.5; + if (input.background_tag == 0u + && (any(center < input.curve_box.xy) || any(center > input.curve_box.zw))) { + return blend_color(input.background_color0, 1.0); + } + let tile = load_path_tile(input.tile_id); + let paint = load_path_paint(tile.paint); + + var winding = vec2(f32(tile.backdrop)); + var weight = vec2(0.0); + for (var i = 0u; i < tile.curve_count; i++) { + let curve = load_path_curve(tile.curve_start + i); + if (min(curve.p0.x, curve.p1.x) >= center.x + 0.5) { + break; + } + if (curve.p0.y < center.y + 0.5) { + add_curve_winding(curve, center, &winding, &weight); + correct_for_endpoint(curve.p0, curve.sign, tile.reference, center, &winding); + correct_for_endpoint(curve.p1, -curve.sign, tile.reference, center, &winding); + } + } + + // Weight the winding computed by each ray by its nearest crossing's distance from the pixel center, + // using Slug's technique. + var coverage = max( + abs(dot(winding, weight)) / max(weight.x + weight.y, 1.0 / 65536.0), + min(abs(winding.x), abs(winding.y))); + if (paint.even_odd != 0u) { + coverage = 1.0 - abs(1.0 - fract(coverage * 0.5) * 2.0); + } else { + coverage = saturate(coverage); + } + + if (coverage == 0.0) { return vec4(0.0); } - let v = load_path_vertex(input.vertex_id); - let background = v.color; - let bounds = v.bounds; - - var alpha: f32; - if (length(vec2(dx.x, dy.x)) < 0.001) { - // If the gradient is too small, return a solid color. - alpha = 1.0; - } else { - let gradient = 2.0 * input.st_position.xx * vec2(dx.x, dy.x) - vec2(dx.y, dy.y); - let f = input.st_position.x * input.st_position.x - input.st_position.y; - let distance = f / length(gradient); - alpha = saturate(0.5 - distance); - } - let prepared_gradient = prepare_gradient_color( - background.tag, - background.color_space, - background.solid, - background.colors, - ); - let color = gradient_color(background, input.position.xy, bounds, - prepared_gradient.solid, prepared_gradient.color0, prepared_gradient.color1); - return vec4(color.rgb * color.a * alpha, color.a * alpha); -} - -// --- paths --- // - -struct PathSprite { - bounds: Bounds, -} - - -struct PathVarying { - @builtin(position) position: vec4, - @location(0) texture_coords: vec2, -} - -@vertex -fn vs_path(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) instance_id: u32) -> PathVarying { - let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); - let sprite = load_path_sprite(instance_id); - // Don't apply content mask because it was already accounted for when rasterizing the path. - let device_position = to_device_position(unit_vertex, sprite.bounds); - // For screen-space intermediate texture, convert screen position to texture coordinates - let screen_position = sprite.bounds.origin + unit_vertex * sprite.bounds.size; - let texture_coords = screen_position / globals.viewport_size; - - var out = PathVarying(); - out.position = device_position; - out.texture_coords = texture_coords; - - return out; -} - -@fragment -fn fs_path(input: PathVarying) -> @location(0) vec4 { - let sample = textureSample(t_sprite, s_sprite, input.texture_coords); - return sample; + let prepared = PreparedBackground(input.background_color0, input.background_color1, + input.background_tag); + let color = background_color(prepared, paint.color, paint.bounds, input.position.xy); + return blend_color(color, coverage); } // --- underlines --- // @@ -1161,8 +1325,6 @@ struct UnderlineVarying { @builtin(position) position: vec4, @location(0) @interpolate(flat) color: vec4, @location(1) @interpolate(flat) underline_id: u32, - //TODO: use `clip_distance` once Naga supports it - @location(3) clip_distances: vec4, } @vertex @@ -1171,10 +1333,10 @@ fn vs_underline(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index) let underline = load_underline(instance_id); var out = UnderlineVarying(); - out.position = to_device_position(unit_vertex, underline.bounds); + let clipped = clip_to_mask(unit_vertex, underline.bounds, underline.content_mask); + out.position = to_device_position_impl(clipped.position); out.color = hsla_to_rgba(underline.color); - out.underline_id = instance_id; - out.clip_distances = distance_from_clip_rect(unit_vertex, underline.bounds, underline.content_mask); + out.underline_id = instance_id | select(0u, SIMPLE_PRIMITIVE_FLAG, underline.wavy == 0u); return out; } @@ -1183,17 +1345,11 @@ fn fs_underline(input: UnderlineVarying) -> @location(0) vec4 { const WAVE_FREQUENCY: f32 = 2.0; const WAVE_HEIGHT_RATIO: f32 = 0.8; - // Alpha clip first, since we don't have `clip_distance`. - if (any(input.clip_distances < vec4(0.0))) { - return vec4(0.0); - } - - let underline = load_underline(input.underline_id); - if (underline.wavy == 0u) - { + if ((input.underline_id & SIMPLE_PRIMITIVE_FLAG) != 0u) { return blend_color(input.color, input.color.a); } + let underline = load_underline(input.underline_id); let half_thickness = underline.thickness * 0.5; let st = (input.position.xy - underline.bounds.origin) / underline.bounds.size.y - vec2(0.0, 0.5); @@ -1275,7 +1431,7 @@ struct PolySpriteVarying { @builtin(position) position: vec4, @location(0) tile_position: vec2, @location(1) @interpolate(flat) sprite_id: u32, - @location(3) clip_distances: vec4, + @location(2) @interpolate(flat) opacity: f32, } @vertex @@ -1284,30 +1440,28 @@ fn vs_poly_sprite(@builtin(vertex_index) vertex_id: u32, @builtin(instance_index let sprite = load_poly_sprite(instance_id); var out = PolySpriteVarying(); - out.position = to_device_position(unit_vertex, sprite.bounds); - out.tile_position = to_tile_position(unit_vertex, sprite.tile); - out.sprite_id = instance_id; - out.clip_distances = distance_from_clip_rect(unit_vertex, sprite.bounds, sprite.content_mask); + let clipped = clip_to_mask(unit_vertex, sprite.bounds, sprite.content_mask); + out.position = to_device_position_impl(clipped.position); + out.tile_position = to_tile_position(clipped.unit_vertex, sprite.tile); + let simple = !has_rounded_corners(sprite.corner_radii) && sprite.grayscale == 0u; + out.sprite_id = instance_id | select(0u, SIMPLE_PRIMITIVE_FLAG, simple); + out.opacity = sprite.opacity; return out; } @fragment fn fs_poly_sprite(input: PolySpriteVarying) -> @location(0) vec4 { - let sample = textureSample(t_sprite, s_sprite, input.tile_position); - // Alpha clip after using the derivatives. - if (any(input.clip_distances < vec4(0.0))) { - return vec4(0.0); + var color = textureSample(t_sprite, s_sprite, input.tile_position); + if ((input.sprite_id & SIMPLE_PRIMITIVE_FLAG) != 0u) { + return blend_color(color, input.opacity); } let sprite = load_poly_sprite(input.sprite_id); - let distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii); - - var color = sample; if (sprite.grayscale != 0u) { - let grayscale = dot(color.rgb, GRAYSCALE_FACTORS); - color = vec4(vec3(grayscale), sample.a); + color = vec4(vec3(dot(color.rgb, GRAYSCALE_FACTORS)), color.a); } - return blend_color(color, sprite.opacity * saturate(0.5 - distance)); + let distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii); + return blend_color(color, input.opacity * saturate(0.5 - distance)); } // --- surfaces --- // @@ -1332,7 +1486,6 @@ const ycbcr_to_RGB = mat4x4( struct SurfaceVarying { @builtin(position) position: vec4, @location(0) texture_position: vec2, - @location(3) clip_distances: vec4, } @vertex @@ -1340,19 +1493,15 @@ fn vs_surface(@builtin(vertex_index) vertex_id: u32) -> SurfaceVarying { let unit_vertex = vec2(f32(vertex_id & 1u), 0.5 * f32(vertex_id & 2u)); var out = SurfaceVarying(); - out.position = to_device_position(unit_vertex, surface_locals.bounds); - out.texture_position = unit_vertex; - out.clip_distances = distance_from_clip_rect(unit_vertex, surface_locals.bounds, surface_locals.content_mask); + let clipped = clip_to_mask(unit_vertex, surface_locals.bounds, surface_locals.content_mask); + out.position = to_device_position_impl(clipped.position); + // The whole texture is copied, so sample at the vertex's position within the unclipped bounds. + out.texture_position = clipped.unit_vertex; return out; } @fragment fn fs_surface(input: SurfaceVarying) -> @location(0) vec4 { - // Alpha clip after using the derivatives. - if (any(input.clip_distances < vec4(0.0))) { - return vec4(0.0); - } - let y_cb_cr = vec4( textureSampleLevel(t_y, s_surface, input.texture_position, 0.0).r, textureSampleLevel(t_cb_cr, s_surface, input.texture_position, 0.0).rg, diff --git a/crates/gpui_wgpu/src/shaders_storage.wgsl b/crates/gpui_wgpu/src/shaders_storage.wgsl index 55b80802e6c..08d31698157 100644 --- a/crates/gpui_wgpu/src/shaders_storage.wgsl +++ b/crates/gpui_wgpu/src/shaders_storage.wgsl @@ -7,8 +7,6 @@ @group(1) @binding(0) var b_quads: array; @group(1) @binding(0) var b_shadows: array; -@group(1) @binding(0) var b_path_vertices: array; -@group(1) @binding(0) var b_path_sprites: array; @group(1) @binding(0) var b_underlines: array; @group(1) @binding(0) var b_mono_sprites: array; @group(1) @binding(0) var b_poly_sprites: array; @@ -21,12 +19,20 @@ fn load_shadow(instance_id: u32) -> Shadow { return b_shadows[instance_id]; } -fn load_path_vertex(vertex_id: u32) -> PathRasterizationVertex { - return b_path_vertices[vertex_id]; +@group(1) @binding(0) var b_path_tiles: array; +@group(1) @binding(1) var b_path_curves: array; +@group(1) @binding(2) var b_path_paints: array; + +fn load_path_tile(instance_id: u32) -> PathTile { + return b_path_tiles[instance_id]; } -fn load_path_sprite(instance_id: u32) -> PathSprite { - return b_path_sprites[instance_id]; +fn load_path_curve(index: u32) -> PathCurve { + return b_path_curves[index]; +} + +fn load_path_paint(index: u32) -> PathPaint { + return b_path_paints[index]; } fn load_underline(instance_id: u32) -> Underline { diff --git a/crates/gpui_wgpu/src/shaders_webgl.wgsl b/crates/gpui_wgpu/src/shaders_webgl.wgsl index e28a56568c6..66f95950772 100644 --- a/crates/gpui_wgpu/src/shaders_webgl.wgsl +++ b/crates/gpui_wgpu/src/shaders_webgl.wgsl @@ -206,19 +206,43 @@ fn load_shadow(instance_id: u32) -> Shadow { ); } -fn load_path_vertex(vertex_id: u32) -> PathRasterizationVertex { - var cursor = instance_cursor(vertex_id * 26u); - return PathRasterizationVertex( +fn load_path_tile(instance_id: u32) -> PathTile { + var cursor = instance_cursor(instance_id * 14u); + return PathTile( + read_word(&cursor), + read_word(&cursor), + read_word(&cursor), + read_i32(&cursor), + read_vec2_f32(&cursor), + read_vec2_f32(&cursor), + read_vec2_f32(&cursor), read_vec2_f32(&cursor), read_vec2_f32(&cursor), - read_background(&cursor), - read_bounds(&cursor), ); } -fn load_path_sprite(instance_id: u32) -> PathSprite { - var cursor = instance_cursor(instance_id * 4u); - return PathSprite(read_bounds(&cursor)); +// Tiles index this frame's paint and curve arrays, which start at the bases in `globals`. +fn load_path_curve(index: u32) -> PathCurve { + var cursor = instance_cursor((globals.path_curve_base + index) * 10u); + return PathCurve( + read_vec2_f32(&cursor), + read_vec2_f32(&cursor), + read_vec2_f32(&cursor), + read_vec2_f32(&cursor), + read_f32(&cursor), + read_word(&cursor), + ); +} + +fn load_path_paint(index: u32) -> PathPaint { + var cursor = instance_cursor((globals.path_paint_base + index) * 28u); + return PathPaint( + read_bounds(&cursor), + read_bounds(&cursor), + read_background(&cursor), + read_word(&cursor), + read_word(&cursor), + ); } fn load_underline(instance_id: u32) -> Underline { diff --git a/crates/gpui_wgpu/src/wgpu_context.rs b/crates/gpui_wgpu/src/wgpu_context.rs index 5563a761d33..37e9a0aab45 100644 --- a/crates/gpui_wgpu/src/wgpu_context.rs +++ b/crates/gpui_wgpu/src/wgpu_context.rs @@ -338,6 +338,18 @@ impl WgpuContext { } } + pub fn supports_transient_attachments(&self) -> bool { + #[cfg(target_family = "wasm")] + if self.backend == WgpuBackend::BrowserWebGpu { + // wgpu passes usage bits straight to the browser without knowing + // whether it recognizes this one. + return js_sys::Reflect::get(&js_sys::global(), &"GPUTextureUsage".into()) + .and_then(|usage| js_sys::Reflect::has(&usage, &"TRANSIENT_ATTACHMENT".into())) + .unwrap_or(false); + } + true + } + #[cfg(target_family = "wasm")] pub async fn new_web( canvas: &web_sys::HtmlCanvasElement, diff --git a/crates/gpui_wgpu/src/wgpu_renderer.rs b/crates/gpui_wgpu/src/wgpu_renderer.rs index 46f9ffdb989..9cb06b0d2f5 100644 --- a/crates/gpui_wgpu/src/wgpu_renderer.rs +++ b/crates/gpui_wgpu/src/wgpu_renderer.rs @@ -3,8 +3,8 @@ use anyhow::{Context as _, Result}; use bytemuck::{Pod, Zeroable}; use collections::FxHashMap; use gpui::{ - AtlasTextureId, Background, Bounds, DevicePixels, GpuSpecs, Path, Point, PrimitiveBatch, - ScaledPixels, Scene, Size, get_gamma_correction_ratios, + AtlasTextureId, Bounds, DevicePixels, GpuSpecs, PaintedPath, PrimitiveBatch, ScaledPixels, + Scene, Size, get_gamma_correction_ratios, quad_depth, quad_depth_scale, }; use log::warn; #[cfg(not(target_family = "wasm"))] @@ -59,8 +59,18 @@ fn least_common_multiple(left: u64, right: u64) -> u64 { #[derive(Clone, Copy, Pod, Zeroable)] struct GlobalParams { viewport_size: [f32; 2], - premultiplied_alpha: u32, - pad: u32, + path_paint_base: u32, + path_curve_base: u32, + depth_scale: f32, + quad_count: u32, + pad: [u32; 2], +} + +const DEPTH_FORMAT: wgpu::TextureFormat = wgpu::TextureFormat::Depth32Float; + +struct DepthTexture { + texture: wgpu::Texture, + view: wgpu::TextureView, } #[repr(C)] @@ -96,21 +106,6 @@ struct GammaParams { _pad: u32, } -#[derive(Clone, Debug)] -#[repr(C)] -struct PathSprite { - bounds: Bounds, -} - -#[derive(Clone, Debug)] -#[repr(C)] -struct PathRasterizationVertex { - xy_position: Point, - st_position: Point, - color: Background, - bounds: Bounds, -} - pub struct WgpuSurfaceConfig { pub size: Size, pub transparent: bool, @@ -125,9 +120,9 @@ pub struct WgpuSurfaceConfig { struct WgpuPipelines { quads: wgpu::RenderPipeline, + opaque_quads: wgpu::RenderPipeline, shadows: wgpu::RenderPipeline, - path_rasterization: wgpu::RenderPipeline, - paths: wgpu::RenderPipeline, + path_tiles: wgpu::RenderPipeline, underlines: wgpu::RenderPipeline, mono_sprites: wgpu::RenderPipeline, subpixel_sprites: Option, @@ -147,9 +142,23 @@ struct InstanceBinding { first_instance: u32, } +struct PathTileBinding { + tiles: InstanceBinding, + paint_base: u32, + curve_base: u32, +} + +/// Where one array of instance data was written this frame. +struct InstanceAllocation { + offset: u64, + size: u64, + first_instance: u32, +} + struct InstanceBindings { quads: InstanceBinding, shadows: InstanceBinding, + path_tiles: PathTileBinding, underlines: InstanceBinding, monochrome_sprites: InstanceBinding, subpixel_sprites: InstanceBinding, @@ -159,6 +168,7 @@ struct InstanceBindings { struct WgpuBindGroupLayouts { globals: wgpu::BindGroupLayout, instances: wgpu::BindGroupLayout, + path_tiles: wgpu::BindGroupLayout, texture: wgpu::BindGroupLayout, surfaces: wgpu::BindGroupLayout, } @@ -188,12 +198,7 @@ struct WgpuResources { atlas_texture_bind_groups: FxHashMap, globals_buffer: wgpu::Buffer, globals_bind_group: wgpu::BindGroup, - path_globals_bind_group: wgpu::BindGroup, instance_data: InstanceData, - path_intermediate_texture: Option, - path_intermediate_view: Option, - path_msaa_texture: Option, - path_msaa_view: Option, } struct CachedTextureBindGroup { @@ -201,19 +206,9 @@ struct CachedTextureBindGroup { bind_group: wgpu::BindGroup, } -impl WgpuResources { - fn invalidate_intermediate_textures(&mut self) { - self.path_intermediate_texture = None; - self.path_intermediate_view = None; - self.path_msaa_texture = None; - self.path_msaa_view = None; - } -} - struct WgpuRendererCore { resources: WgpuResources, atlas: Arc, - path_globals_offset: u64, gamma_offset: u64, instance_data_capacity: u64, max_instance_data_size: u64, @@ -222,7 +217,14 @@ struct WgpuRendererCore { rendering_params: RenderingParameters, is_bgr: bool, dual_source_blending: bool, + transient_attachments: bool, adapter_info: wgpu::AdapterInfo, + depth_texture: Option, + /// Read by the headless renderer to create its render target. + #[cfg(all( + not(target_family = "wasm"), + any(test, feature = "bench-support", feature = "test-support") + ))] target_format: wgpu::TextureFormat, max_texture_size: u32, } @@ -579,6 +581,30 @@ impl WgpuRendererCore { entries: &[instance_data_entry], }); + // Path tiles read their curves and paints too. The texture transport + // reads all three from the one instance texture. + let path_tiles = if uses_webgl_instance_data { + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("path_tiles_layout"), + entries: &[instance_data_entry], + }) + } else { + device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { + label: Some("path_tiles_layout"), + entries: &[ + instance_data_entry, + wgpu::BindGroupLayoutEntry { + binding: 1, + ..instance_data_entry + }, + wgpu::BindGroupLayoutEntry { + binding: 2, + ..instance_data_entry + }, + ], + }) + }; + let texture = device.create_bind_group_layout(&wgpu::BindGroupLayoutDescriptor { label: Some("texture_layout"), entries: &[ @@ -648,6 +674,7 @@ impl WgpuRendererCore { WgpuBindGroupLayouts { globals, instances, + path_tiles, texture, surfaces, } @@ -696,7 +723,6 @@ impl WgpuRendererCore { layouts: &WgpuBindGroupLayouts, surface_format: wgpu::TextureFormat, alpha_mode: wgpu::CompositeAlphaMode, - path_sample_count: u32, dual_source_blending: bool, uses_webgl_instance_data: bool, ) -> WgpuPipelines { @@ -742,11 +768,15 @@ impl WgpuRendererCore { None }; - let blend_mode = match alpha_mode { - wgpu::CompositeAlphaMode::PreMultiplied => { - wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING - } - _ => wgpu::BlendState::ALPHA_BLENDING, + let premultiplied_alpha = alpha_mode == wgpu::CompositeAlphaMode::PreMultiplied; + let blend_mode = if premultiplied_alpha { + wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING + } else { + wgpu::BlendState::ALPHA_BLENDING + }; + let compilation_options = wgpu::PipelineCompilationOptions { + constants: &[("PREMULTIPLIED_ALPHA", f64::from(premultiplied_alpha as u8))], + ..Default::default() }; let color_target = wgpu::ColorTargetState { @@ -763,7 +793,7 @@ impl WgpuRendererCore { texture_layout: Option<&wgpu::BindGroupLayout>, topology: wgpu::PrimitiveTopology, color_targets: &[Option], - sample_count: u32, + depth_write_enabled: bool, module: &wgpu::ShaderModule| { let mut bind_group_layouts = vec![Some(globals_layout), Some(data_layout)]; bind_group_layouts.extend(texture_layout.map(Some)); @@ -780,13 +810,13 @@ impl WgpuRendererCore { module, entry_point: Some(vs_entry), buffers: &[], - compilation_options: wgpu::PipelineCompilationOptions::default(), + compilation_options: compilation_options.clone(), }, fragment: Some(wgpu::FragmentState { module, entry_point: Some(fs_entry), targets: color_targets, - compilation_options: wgpu::PipelineCompilationOptions::default(), + compilation_options: compilation_options.clone(), }), primitive: wgpu::PrimitiveState { topology, @@ -797,12 +827,14 @@ impl WgpuRendererCore { unclipped_depth: false, conservative: false, }, - depth_stencil: None, - multisample: wgpu::MultisampleState { - count: sample_count, - mask: !0, - alpha_to_coverage_enabled: false, - }, + depth_stencil: Some(wgpu::DepthStencilState { + format: DEPTH_FORMAT, + depth_write_enabled: Some(depth_write_enabled), + depth_compare: Some(wgpu::CompareFunction::Greater), + stencil: wgpu::StencilState::default(), + bias: wgpu::DepthBiasState::default(), + }), + multisample: wgpu::MultisampleState::default(), multiview_mask: None, cache: None, }) @@ -817,7 +849,24 @@ impl WgpuRendererCore { None, wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, + &shader_module, + ); + + let opaque_quads = create_pipeline( + "opaque_quads", + "vs_opaque_quad", + "fs_opaque_quad", + &layouts.globals, + &layouts.instances, + None, + wgpu::PrimitiveTopology::TriangleStrip, + &[Some(wgpu::ColorTargetState { + format: surface_format, + blend: None, + write_mask: wgpu::ColorWrites::ALL, + })], + true, &shader_module, ); @@ -830,41 +879,20 @@ impl WgpuRendererCore { None, wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); - let path_rasterization = create_pipeline( - "path_rasterization", - "vs_path_rasterization", - "fs_path_rasterization", + let path_tiles = create_pipeline( + "path_tiles", + "vs_path_tile", + "fs_path_tile", &layouts.globals, - &layouts.instances, + &layouts.path_tiles, None, - wgpu::PrimitiveTopology::TriangleList, - &[Some(wgpu::ColorTargetState { - format: surface_format, - blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), - write_mask: wgpu::ColorWrites::ALL, - })], - path_sample_count, - &shader_module, - ); - - let paths = create_pipeline( - "paths", - "vs_path", - "fs_path", - &layouts.globals, - &layouts.instances, - Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, - &[Some(wgpu::ColorTargetState { - format: surface_format, - blend: Some(wgpu::BlendState::PREMULTIPLIED_ALPHA_BLENDING), - write_mask: wgpu::ColorWrites::ALL, - })], - 1, + &[Some(color_target.clone())], + false, &shader_module, ); @@ -877,7 +905,7 @@ impl WgpuRendererCore { None, wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); @@ -890,7 +918,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); @@ -921,7 +949,7 @@ impl WgpuRendererCore { blend: Some(subpixel_blend), write_mask: wgpu::ColorWrites::COLOR, })], - 1, + false, subpixel_module, )) } else { @@ -937,7 +965,7 @@ impl WgpuRendererCore { Some(&layouts.texture), wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target.clone())], - 1, + false, &shader_module, ); @@ -950,15 +978,15 @@ impl WgpuRendererCore { None, wgpu::PrimitiveTopology::TriangleStrip, &[Some(color_target)], - 1, + false, &shader_module, ); WgpuPipelines { quads, + opaque_quads, shadows, - path_rasterization, - paths, + path_tiles, underlines, mono_sprites, subpixel_sprites, @@ -966,58 +994,6 @@ impl WgpuRendererCore { surfaces, } } - - fn create_path_intermediate( - device: &wgpu::Device, - format: wgpu::TextureFormat, - width: u32, - height: u32, - ) -> (wgpu::Texture, wgpu::TextureView) { - let texture = device.create_texture(&wgpu::TextureDescriptor { - label: Some("path_intermediate"), - size: wgpu::Extent3d { - width: width.max(1), - height: height.max(1), - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count: 1, - dimension: wgpu::TextureDimension::D2, - format, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TEXTURE_BINDING, - view_formats: &[], - }); - let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); - (texture, view) - } - - fn create_msaa_if_needed( - device: &wgpu::Device, - format: wgpu::TextureFormat, - width: u32, - height: u32, - sample_count: u32, - ) -> Option<(wgpu::Texture, wgpu::TextureView)> { - if sample_count <= 1 { - return None; - } - let texture = device.create_texture(&wgpu::TextureDescriptor { - label: Some("path_msaa"), - size: wgpu::Extent3d { - width: width.max(1), - height: height.max(1), - depth_or_array_layers: 1, - }, - mip_level_count: 1, - sample_count, - dimension: wgpu::TextureDimension::D2, - format, - usage: wgpu::TextureUsages::RENDER_ATTACHMENT, - view_formats: &[], - }); - let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); - Some((texture, view)) - } } impl WgpuRenderer { @@ -1043,32 +1019,6 @@ impl WgpuRenderer { self.surface_config.width = clamped_width.max(1); self.surface_config.height = clamped_height.max(1); - let Some(core) = self.core_mut() else { - return; - }; - let resources = &mut core.resources; - - // Wait for any in-flight GPU work to complete before destroying textures - if let Err(e) = resources.device.poll(wgpu::PollType::Wait { - submission_index: None, - timeout: None, - }) { - warn!("Failed to poll device during resize: {e:?}"); - } - - // Destroy old textures before allocating new ones to avoid GPU memory spikes - if let Some(ref texture) = resources.path_intermediate_texture { - texture.destroy(); - } - if let Some(ref texture) = resources.path_msaa_texture { - texture.destroy(); - } - - // Invalidate intermediate textures - they will be lazily recreated - // in draw() after we confirm the surface is healthy. This avoids - // panics when the device/surface is in an invalid state during resize. - resources.invalidate_intermediate_textures(); - if let RendererState::Ready { surface, core } = &self.state { surface.configure(&core.resources.device, &self.surface_config); } @@ -1096,16 +1046,7 @@ impl WgpuRenderer { let Some(core) = self.core_mut() else { return; }; - let resources = &mut core.resources; - resources.pipelines = WgpuRendererCore::create_pipelines( - &resources.device, - &resources.bind_group_layouts, - format, - new_alpha_mode, - core.rendering_params.path_sample_count, - core.dual_source_blending, - core.uses_webgl_instance_data, - ); + core.rebuild_pipelines(format, new_alpha_mode); if let RendererState::Ready { surface, core } = &self.state { surface.configure(&core.resources.device, &self.surface_config); @@ -1178,7 +1119,6 @@ impl WgpuRenderer { if self.failed_frame_count > 10 { panic!("Too many consecutive GPU errors. Last error: {error}"); } else if self.failed_frame_count > 5 { - core.resources.invalidate_intermediate_textures(); self.atlas.clear(); self.needs_redraw = true; self.failed_frame_count = 0; @@ -1218,15 +1158,7 @@ impl WgpuRenderer { let frame_view = frame .texture .create_view(&wgpu::TextureViewDescriptor::default()); - let premultiplied_alpha = - self.surface_config.alpha_mode == wgpu::CompositeAlphaMode::PreMultiplied; - if let Err(error) = core.render_frame( - scene, - &frame_view, - size, - premultiplied_alpha, - wgpu::Color::TRANSPARENT, - ) { + if let Err(error) = core.render_frame(scene, &frame_view, size, wgpu::Color::TRANSPARENT) { log::error!("{error:#}"); return false; } @@ -1245,7 +1177,7 @@ impl WgpuRendererCore { ) -> Self { let device = Arc::clone(&context.device); let queue = Arc::clone(&context.queue); - let rendering_params = RenderingParameters::new(&context.adapter, target_format); + let rendering_params = RenderingParameters::new(); let uses_webgl_instance_data = context.uses_webgl_instance_data(); let dual_source_blending = context.supports_dual_source_blending() && !uses_webgl_instance_data; @@ -1255,7 +1187,6 @@ impl WgpuRendererCore { &bind_group_layouts, target_format, alpha_mode, - rendering_params.path_sample_count, dual_source_blending, uses_webgl_instance_data, ); @@ -1268,8 +1199,7 @@ impl WgpuRendererCore { let uniform_alignment = device.limits().min_uniform_buffer_offset_alignment as u64; let globals_size = std::mem::size_of::() as u64; let gamma_size = std::mem::size_of::() as u64; - let path_globals_offset = globals_size.next_multiple_of(uniform_alignment); - let gamma_offset = (path_globals_offset + globals_size).next_multiple_of(uniform_alignment); + let gamma_offset = globals_size.next_multiple_of(uniform_alignment); let globals_buffer = device.create_buffer(&wgpu::BufferDescriptor { label: Some("globals_buffer"), size: gamma_offset + gamma_size, @@ -1337,28 +1267,6 @@ impl WgpuRendererCore { }, ], }); - let path_globals_bind_group = device.create_bind_group(&wgpu::BindGroupDescriptor { - label: Some("path_globals_bind_group"), - layout: &bind_group_layouts.globals, - entries: &[ - wgpu::BindGroupEntry { - binding: 0, - resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { - buffer: &globals_buffer, - offset: path_globals_offset, - size: NonZeroU64::new(globals_size), - }), - }, - wgpu::BindGroupEntry { - binding: 1, - resource: wgpu::BindingResource::Buffer(wgpu::BufferBinding { - buffer: &globals_buffer, - offset: gamma_offset, - size: NonZeroU64::new(gamma_size), - }), - }, - ], - }); let max_texture_size = device.limits().max_texture_dimension_2d; Self { @@ -1371,15 +1279,9 @@ impl WgpuRendererCore { atlas_texture_bind_groups: FxHashMap::default(), globals_buffer, globals_bind_group, - path_globals_bind_group, instance_data, - path_intermediate_texture: None, - path_intermediate_view: None, - path_msaa_texture: None, - path_msaa_view: None, }, atlas, - path_globals_offset, gamma_offset, instance_data_capacity, max_instance_data_size, @@ -1388,7 +1290,13 @@ impl WgpuRendererCore { rendering_params, is_bgr: false, dual_source_blending, + transient_attachments: context.supports_transient_attachments(), adapter_info: context.adapter.get_info(), + depth_texture: None, + #[cfg(all( + not(target_family = "wasm"), + any(test, feature = "bench-support", feature = "test-support") + ))] target_format, max_texture_size, } @@ -1398,44 +1306,23 @@ impl WgpuRendererCore { &self.resources } - fn resources_mut(&mut self) -> &mut WgpuResources { - &mut self.resources + fn rebuild_pipelines( + &mut self, + surface_format: wgpu::TextureFormat, + alpha_mode: wgpu::CompositeAlphaMode, + ) { + self.resources.pipelines = Self::create_pipelines( + &self.resources.device, + &self.resources.bind_group_layouts, + surface_format, + alpha_mode, + self.dual_source_blending, + self.uses_webgl_instance_data, + ); } - /// Path rendering goes through an intermediate texture that must match the frame - /// target's dimensions, so the textures are keyed by size and rebuilt on mismatch. - fn ensure_intermediate_textures(&mut self, size: Size) { - let width = size.width.0 as u32; - let height = size.height.0 as u32; - if self - .resources - .path_intermediate_texture - .as_ref() - .is_some_and(|texture| texture.width() == width && texture.height() == height) - { - return; - } - - let format = self.target_format; - let path_sample_count = self.rendering_params.path_sample_count; - let resources = &mut self.resources; - - let (texture, view) = - Self::create_path_intermediate(&resources.device, format, width, height); - resources.path_intermediate_texture = Some(texture); - resources.path_intermediate_view = Some(view); - - let (path_msaa_texture, path_msaa_view) = Self::create_msaa_if_needed( - &resources.device, - format, - width, - height, - path_sample_count, - ) - .map(|(texture, view)| (Some(texture), Some(view))) - .unwrap_or((None, None)); - resources.path_msaa_texture = path_msaa_texture; - resources.path_msaa_view = path_msaa_view; + fn resources_mut(&mut self) -> &mut WgpuResources { + &mut self.resources } fn render_frame( @@ -1443,7 +1330,6 @@ impl WgpuRendererCore { scene: &Scene, target_view: &wgpu::TextureView, size: Size, - premultiplied_alpha: bool, clear_color: wgpu::Color, ) -> Result { anyhow::ensure!( @@ -1458,7 +1344,6 @@ impl WgpuRendererCore { ); self.atlas.before_frame(); - self.ensure_intermediate_textures(size); let gamma_params = GammaParams { gamma_ratios: self.rendering_params.gamma_ratios, @@ -1467,32 +1352,13 @@ impl WgpuRendererCore { is_bgr: self.is_bgr as u32, _pad: 0, }; - let globals = GlobalParams { - viewport_size: [size.width.0 as f32, size.height.0 as f32], - premultiplied_alpha: premultiplied_alpha as u32, - pad: 0, - }; - let path_globals = GlobalParams { - premultiplied_alpha: 0, - ..globals - }; - self.resources.queue.write_buffer( - &self.resources.globals_buffer, - 0, - bytemuck::bytes_of(&globals), - ); - self.resources.queue.write_buffer( - &self.resources.globals_buffer, - self.path_globals_offset, - bytemuck::bytes_of(&path_globals), - ); self.resources.queue.write_buffer( &self.resources.globals_buffer, self.gamma_offset, bytemuck::bytes_of(&gamma_params), ); - self.record_frame(scene, target_view, clear_color) + self.record_frame(scene, target_view, size, clear_color) .inspect_err(|_| { // Queue writes are staged before encoding; flush them even if the frame fails. self.resources.queue.submit(std::iter::empty()); @@ -1503,6 +1369,7 @@ impl WgpuRendererCore { &mut self, scene: &Scene, frame_view: &wgpu::TextureView, + size: Size, clear_color: wgpu::Color, ) -> Result { let mut instance_offset = 0; @@ -1520,7 +1387,31 @@ impl WgpuRendererCore { scene.polychrome_sprites.len(), ) })?; + let depth_scale = quad_depth_scale(scene.quads.len()); + let globals = GlobalParams { + viewport_size: [size.width.0 as f32, size.height.0 as f32], + path_paint_base: instance_bindings.path_tiles.paint_base, + path_curve_base: instance_bindings.path_tiles.curve_base, + depth_scale, + quad_count: scene.quads.len() as u32, + pad: [0; 2], + }; + self.resources().queue.write_buffer( + &self.resources().globals_buffer, + 0, + bytemuck::bytes_of(&globals), + ); self.prepare_texture_bind_groups(scene); + self.ensure_depth_texture(size); + let depth_view = &self + .depth_texture + .as_ref() + .context("depth texture missing")? + .view; + // Quads are written first, so their instance indices are their + // indices in `scene.quads` on both transports, which the quad depths + // rely on. + debug_assert_eq!(instance_bindings.quads.first_instance, 0); let mut encoder = self.resources() @@ -1541,18 +1432,57 @@ impl WgpuRendererCore { }, depth_slice: None, })], - depth_stencil_attachment: None, + depth_stencil_attachment: Some(wgpu::RenderPassDepthStencilAttachment { + view: depth_view, + depth_ops: Some(wgpu::Operations { + load: wgpu::LoadOp::Clear(0.0), + store: wgpu::StoreOp::Discard, + }), + stencil_ops: None, + }), ..Default::default() }); + pass.set_bind_group(0, &self.resources().globals_bind_group, &[]); + self.draw_instances( + &instance_bindings.quads, + &self.resources().pipelines.opaque_quads, + instance_range(0..scene.quads.len()), + &mut pass, + ); + + let viewport_width = size.width.0 as f32; + let viewport_height = size.height.0 as f32; + let mut quad_cursor: u32 = 0; + let mut path_tile_cursor = 0; for batch in scene.batches() { + // Quad shaders assign each quad its own depth. + // In every other batch type, the depth is fixed to the position of the quad cursor. + let (minimum_depth, maximum_depth) = if matches!(&batch, PrimitiveBatch::Quads(_)) { + (0.0, 1.0) + } else { + let depth = quad_depth(quad_cursor, depth_scale); + (depth, depth) + }; + pass.set_viewport( + 0.0, + 0.0, + viewport_width, + viewport_height, + minimum_depth, + maximum_depth, + ); + match batch { - PrimitiveBatch::Quads(range) => self.draw_instances( - &instance_bindings.quads, - &self.resources().pipelines.quads, - instance_range(range), - &mut pass, - ), + PrimitiveBatch::Quads(range) => { + quad_cursor += range.len() as u32; + self.draw_instances( + &instance_bindings.quads, + &self.resources().pipelines.quads, + instance_range(range), + &mut pass, + ) + } PrimitiveBatch::Shadows(range) => self.draw_instances( &instance_bindings.shadows, &self.resources().pipelines.shadows, @@ -1560,40 +1490,17 @@ impl WgpuRendererCore { &mut pass, ), PrimitiveBatch::Paths(range) => { - let paths = &scene.paths[range]; - if paths.is_empty() { - continue; - } - - drop(pass); - let rasterized = self.draw_paths_to_intermediate( - &mut encoder, - paths, - &mut instance_offset, - )?; - - pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("main_pass_continued"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: frame_view, - resolve_target: None, - ops: wgpu::Operations { - load: wgpu::LoadOp::Load, - store: wgpu::StoreOp::Store, - }, - depth_slice: None, - })], - depth_stencil_attachment: None, - ..Default::default() - }); - - if rasterized { - self.draw_paths_from_intermediate( - paths, - &mut instance_offset, - &mut pass, - )?; - } + let tiles_start = path_tile_cursor; + path_tile_cursor += scene.paths[range] + .iter() + .map(PaintedPath::tile_count) + .sum::(); + self.draw_instances( + &instance_bindings.path_tiles.tiles, + &self.resources().pipelines.path_tiles, + instance_range(tiles_start..path_tile_cursor), + &mut pass, + ) } PrimitiveBatch::Underlines(range) => self.draw_instances( &instance_bindings.underlines, @@ -1647,6 +1554,41 @@ impl WgpuRendererCore { Ok(submission) } + fn ensure_depth_texture(&mut self, size: Size) { + let width = size.width.0 as u32; + let height = size.height.0 as u32; + if let Some(depth_texture) = &self.depth_texture + && depth_texture.texture.width() == width + && depth_texture.texture.height() == height + { + return; + } + let usage = if self.transient_attachments { + wgpu::TextureUsages::RENDER_ATTACHMENT | wgpu::TextureUsages::TRANSIENT_ATTACHMENT + } else { + wgpu::TextureUsages::RENDER_ATTACHMENT + }; + let texture = self + .resources() + .device + .create_texture(&wgpu::TextureDescriptor { + label: Some("depth_texture"), + size: wgpu::Extent3d { + width, + height, + depth_or_array_layers: 1, + }, + mip_level_count: 1, + sample_count: 1, + dimension: wgpu::TextureDimension::D2, + format: DEPTH_FORMAT, + usage, + view_formats: &[], + }); + let view = texture.create_view(&wgpu::TextureViewDescriptor::default()); + self.depth_texture = Some(DepthTexture { texture, view }); + } + fn write_instances( &mut self, scene: &Scene, @@ -1663,6 +1605,7 @@ impl WgpuRendererCore { instance_offset, &scene.shadows, )?, + path_tiles: self.write_path_tiles(scene, instance_offset)?, underlines: self.write_instance_binding( "underlines_bind_group", instance_offset, @@ -1767,7 +1710,6 @@ impl WgpuRendererCore { return; } pass.set_pipeline(pipeline); - pass.set_bind_group(0, &self.resources().globals_bind_group, &[]); pass.set_bind_group(1, &instances.bind_group, &[]); pass.draw( 0..4, @@ -1793,7 +1735,6 @@ impl WgpuRendererCore { return Ok(()); }; pass.set_pipeline(pipeline); - pass.set_bind_group(0, &resources.globals_bind_group, &[]); pass.set_bind_group(1, &sprite_instances.bind_group, &[]); pass.set_bind_group(2, &texture.bind_group, &[]); pass.draw( @@ -1813,132 +1754,13 @@ impl WgpuRendererCore { } } - fn draw_paths_from_intermediate( - &mut self, - paths: &[Path], - instance_offset: &mut u64, - pass: &mut wgpu::RenderPass<'_>, - ) -> Result<()> { - let first_path = &paths[0]; - let sprites: Vec = if paths.last().map(|p| &p.order) == Some(&first_path.order) - { - paths - .iter() - .map(|p| PathSprite { - bounds: p.clipped_bounds(), - }) - .collect() - } else { - let mut bounds = first_path.clipped_bounds(); - for path in paths.iter().skip(1) { - bounds = bounds.union(&path.clipped_bounds()); - } - vec![PathSprite { bounds }] - }; - - let Some(path_intermediate_view) = self.resources().path_intermediate_view.clone() else { - return Ok(()); - }; - let instances = - self.write_instance_binding("path_sprites_bind_group", instance_offset, &sprites)?; - let texture = self.create_texture_bind_group( - "path_intermediate_texture_bind_group", - &path_intermediate_view, - ); - let resources = self.resources(); - pass.set_pipeline(&resources.pipelines.paths); - pass.set_bind_group(0, &resources.globals_bind_group, &[]); - pass.set_bind_group(1, &instances.bind_group, &[]); - pass.set_bind_group(2, &texture, &[]); - pass.draw( - 0..4, - instances.first_instance..instances.first_instance + sprites.len() as u32, - ); - Ok(()) - } - - fn draw_paths_to_intermediate( - &mut self, - encoder: &mut wgpu::CommandEncoder, - paths: &[Path], - instance_offset: &mut u64, - ) -> Result { - let mut vertices = Vec::new(); - for path in paths { - let bounds = path.clipped_bounds(); - vertices.extend(path.vertices.iter().map(|v| PathRasterizationVertex { - xy_position: v.xy_position, - st_position: v.st_position, - color: path.color, - bounds, - })); - } - - if vertices.is_empty() { - return Ok(false); - } - - let vertex_binding = self.write_instance_binding( - "path_rasterization_bind_group", - instance_offset, - &vertices, - )?; - - let resources = self.resources(); - let Some(path_intermediate_view) = resources.path_intermediate_view.as_ref() else { - return Ok(false); - }; - - let (target_view, resolve_target) = if let Some(ref msaa_view) = resources.path_msaa_view { - (msaa_view, Some(path_intermediate_view)) - } else { - (path_intermediate_view, None) - }; - - { - let mut pass = encoder.begin_render_pass(&wgpu::RenderPassDescriptor { - label: Some("path_rasterization_pass"), - color_attachments: &[Some(wgpu::RenderPassColorAttachment { - view: target_view, - resolve_target, - ops: wgpu::Operations { - load: wgpu::LoadOp::Clear(wgpu::Color::TRANSPARENT), - store: wgpu::StoreOp::Store, - }, - depth_slice: None, - })], - depth_stencil_attachment: None, - ..Default::default() - }); - - pass.set_pipeline(&resources.pipelines.path_rasterization); - pass.set_bind_group(0, &resources.path_globals_bind_group, &[]); - pass.set_bind_group(1, &vertex_binding.bind_group, &[]); - // The path rasterization shader loads records by vertex index - // rather than instance index, so the allocation's base shifts the - // vertex range here. - pass.draw( - vertex_binding.first_instance - ..vertex_binding.first_instance + vertices.len() as u32, - 0..1, - ); - } - - Ok(true) - } - - fn write_instance_binding( - &mut self, - label: &str, - instance_offset: &mut u64, - instances: &[T], - ) -> Result { - let data = unsafe { Self::instance_bytes(instances) }; + /// The alignment of an allocation of `byte_len` bytes of `stride`-sized + /// records, and the bytes it takes up from that aligned offset. + fn instance_allocation_layout(&self, stride: u64, byte_len: u64) -> (u64, u64) { // wgpu rejects zero-sized bindings, so empty primitive arrays still // reserve the 16-byte minimum. - let size = (data.len() as u64).max(16); - let stride = (std::mem::size_of::() as u64).max(1); - let (alignment, allocation_size) = if self.uses_webgl_instance_data { + let size = byte_len.max(16); + if self.uses_webgl_instance_data { // The texture transport has no binding offset: the shader indexes // the instance texture absolutely, so each allocation must start on // a whole instance (a stride multiple) and a whole texel, and must @@ -1950,7 +1772,36 @@ impl WgpuRendererCore { ) } else { (self.instance_data_alignment.max(1), size) - }; + } + } + + /// The most space `instances` can take up, including alignment padding. + fn instance_allocation_bound(&self, instances: &[T]) -> u64 { + let stride = (std::mem::size_of::() as u64).max(1); + let (alignment, allocation_size) = + self.instance_allocation_layout(stride, std::mem::size_of_val(instances) as u64); + alignment + allocation_size + } + + /// Grows the instance data up front if `size` more bytes won't fit, so the + /// allocations that follow land in the same buffer or texture. + fn reserve_instance_data(&mut self, instance_offset: &mut u64, size: u64) -> Result<()> { + if *instance_offset + size > self.instance_data_capacity { + self.grow_instance_data(size)?; + *instance_offset = 0; + } + Ok(()) + } + + fn write_instance_data( + &mut self, + instance_offset: &mut u64, + instances: &[T], + ) -> Result { + let data = unsafe { Self::instance_bytes(instances) }; + let stride = (std::mem::size_of::() as u64).max(1); + let (alignment, allocation_size) = + self.instance_allocation_layout(stride, data.len() as u64); let mut offset = (*instance_offset).next_multiple_of(alignment); if offset + allocation_size > self.instance_data_capacity { self.grow_instance_data(allocation_size)?; @@ -1973,6 +1824,35 @@ impl WgpuRendererCore { } } } + Ok(InstanceAllocation { + offset, + size: (data.len() as u64).max(16), + first_instance, + }) + } + + fn instance_binding_resource( + &self, + allocation: &InstanceAllocation, + ) -> wgpu::BindingResource<'_> { + match &self.resources().instance_data { + InstanceData::Storage(buffer) => wgpu::BindingResource::Buffer(wgpu::BufferBinding { + buffer, + offset: allocation.offset, + size: NonZeroU64::new(allocation.size), + }), + InstanceData::Texture { view, .. } => wgpu::BindingResource::TextureView(view), + } + } + + fn write_instance_binding( + &mut self, + label: &str, + instance_offset: &mut u64, + instances: &[T], + ) -> Result { + let allocation = self.write_instance_data(instance_offset, instances)?; + let resources = self.resources(); let bind_group = resources .device .create_bind_group(&wgpu::BindGroupDescriptor { @@ -1980,23 +1860,79 @@ impl WgpuRendererCore { layout: &resources.bind_group_layouts.instances, entries: &[wgpu::BindGroupEntry { binding: 0, - resource: match &resources.instance_data { - InstanceData::Storage(buffer) => { - wgpu::BindingResource::Buffer(wgpu::BufferBinding { - buffer, - offset, - size: NonZeroU64::new(size), - }) - } - InstanceData::Texture { view, .. } => { - wgpu::BindingResource::TextureView(view) - } - }, + resource: self.instance_binding_resource(&allocation), }], }); Ok(InstanceBinding { bind_group, - first_instance, + first_instance: allocation.first_instance, + }) + } + + fn write_path_tiles( + &mut self, + scene: &Scene, + instance_offset: &mut u64, + ) -> Result { + let mut paint_data = Vec::with_capacity(scene.paths.len()); + let mut curve_data = Vec::new(); + let mut tile_data = Vec::new(); + for path in &scene.paths { + path.append_to(&mut paint_data, &mut curve_data, &mut tile_data); + } + + // All three arrays are bound together, so they must not be split by a + // grow partway through. + let reserved = self.instance_allocation_bound(&paint_data) + + self.instance_allocation_bound(&curve_data) + + self.instance_allocation_bound(&tile_data); + self.reserve_instance_data(instance_offset, reserved)?; + + let paints = self.write_instance_data(instance_offset, &paint_data)?; + let curves = self.write_instance_data(instance_offset, &curve_data)?; + let tiles = self.write_instance_data(instance_offset, &tile_data)?; + + let resources = self.resources(); + let bind_group = if self.uses_webgl_instance_data { + resources + .device + .create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("path_tiles_bind_group"), + layout: &resources.bind_group_layouts.path_tiles, + entries: &[wgpu::BindGroupEntry { + binding: 0, + resource: self.instance_binding_resource(&tiles), + }], + }) + } else { + resources + .device + .create_bind_group(&wgpu::BindGroupDescriptor { + label: Some("path_tiles_bind_group"), + layout: &resources.bind_group_layouts.path_tiles, + entries: &[ + wgpu::BindGroupEntry { + binding: 0, + resource: self.instance_binding_resource(&tiles), + }, + wgpu::BindGroupEntry { + binding: 1, + resource: self.instance_binding_resource(&curves), + }, + wgpu::BindGroupEntry { + binding: 2, + resource: self.instance_binding_resource(&paints), + }, + ], + }) + }; + Ok(PathTileBinding { + tiles: InstanceBinding { + bind_group, + first_instance: tiles.first_instance, + }, + paint_base: paints.first_instance, + curve_base: curves.first_instance, }) } @@ -2144,10 +2080,6 @@ impl WgpuRenderer { } state @ (RendererState::Unconfigured { .. } | RendererState::Released) => state, }; - // Drop intermediate textures since they reference the old surface size. - if let Some(core) = self.core_mut() { - core.resources.invalidate_intermediate_textures(); - } } /// Replace the wgpu surface with a new one (e.g. after Android destroys @@ -2179,6 +2111,7 @@ impl WgpuRenderer { } else { self.opaque_alpha_mode }; + let alpha_mode_changed = alpha_mode != self.surface_config.alpha_mode; self.surface_config.width = width; self.surface_config.height = height; @@ -2200,8 +2133,10 @@ impl WgpuRenderer { anyhow::bail!("Cannot replace the surface: GPU resources have been released") } }; + if alpha_mode_changed { + core.rebuild_pipelines(self.surface_config.format, alpha_mode); + } surface.configure(&core.resources.device, &self.surface_config); - core.resources.invalidate_intermediate_textures(); self.state = RendererState::Ready { surface, core }; Ok(()) @@ -2436,7 +2371,7 @@ impl WgpuHeadlessRenderer { .view .clone(); self.core - .render_frame(scene, &view, size, false, wgpu::Color::BLACK)?; + .render_frame(scene, &view, size, wgpu::Color::BLACK)?; Ok(()) } @@ -2596,22 +2531,15 @@ fn create_surface( } struct RenderingParameters { - path_sample_count: u32, gamma_ratios: [f32; 4], grayscale_enhanced_contrast: f32, subpixel_enhanced_contrast: f32, } impl RenderingParameters { - fn new(adapter: &wgpu::Adapter, surface_format: wgpu::TextureFormat) -> Self { + fn new() -> Self { use std::env; - let format_features = adapter.get_texture_format_features(surface_format); - let path_sample_count = [4, 2, 1] - .into_iter() - .find(|&n| format_features.flags.sample_count_supported(n)) - .unwrap_or(1); - let gamma = env::var("ZED_FONTS_GAMMA") .ok() .and_then(|v| v.parse().ok()) @@ -2632,7 +2560,6 @@ impl RenderingParameters { .max(0.0); Self { - path_sample_count, gamma_ratios, grayscale_enhanced_contrast, subpixel_enhanced_contrast, @@ -2644,9 +2571,9 @@ impl RenderingParameters { mod tests { use super::*; use gpui::{ - BorderStyle, ColorSpace, ContentMask, Corners, Edges, Hsla, MonochromeSprite, - PolychromeSprite, Quad, Shadow, Size, SubpixelSprite, Underline, linear_color_stop, - linear_gradient, + BorderStyle, ColorSpace, ContentMask, Corners, Edges, Hsla, MonochromeSprite, PathCurve, + PathPaint, PathTile, Point, PolychromeSprite, Quad, Shadow, Size, SubpixelSprite, + Underline, linear_color_stop, linear_gradient, }; #[cfg(target_os = "linux")] use gpui::{DevicePixels, PlatformHeadlessRenderer, Scene}; @@ -2831,8 +2758,9 @@ mod tests { fn webgl_record_sizes_match_shader_word_strides() { assert_eq!(std::mem::size_of::(), 40 * 4); assert_eq!(std::mem::size_of::(), 28 * 4); - assert_eq!(std::mem::size_of::(), 26 * 4); - assert_eq!(std::mem::size_of::(), 4 * 4); + assert_eq!(std::mem::size_of::(), 14 * 4); + assert_eq!(std::mem::size_of::(), 10 * 4); + assert_eq!(std::mem::size_of::(), 28 * 4); assert_eq!(std::mem::size_of::(), 16 * 4); assert_eq!(std::mem::size_of::(), 28 * 4); assert_eq!(std::mem::size_of::(), 28 * 4); diff --git a/crates/gpui_windows/build.rs b/crates/gpui_windows/build.rs index a544f6cf904..4b5c3d66d76 100644 --- a/crates/gpui_windows/build.rs +++ b/crates/gpui_windows/build.rs @@ -33,9 +33,9 @@ mod shader_compilation { // Define all modules let modules = [ "quad", + "opaque_quad", "shadow", - "path_rasterization", - "path_sprite", + "path_tile", "underline", "monochrome_sprite", "subpixel_sprite", diff --git a/crates/gpui_windows/src/directx_renderer.rs b/crates/gpui_windows/src/directx_renderer.rs index 4cce3e06cdc..8573fe40309 100644 --- a/crates/gpui_windows/src/directx_renderer.rs +++ b/crates/gpui_windows/src/directx_renderer.rs @@ -1,4 +1,5 @@ use std::{ + ops::Range, slice, sync::{Arc, OnceLock}, }; @@ -25,8 +26,6 @@ use gpui::*; pub(crate) const DISABLE_DIRECT_COMPOSITION: &str = "GPUI_DISABLE_DIRECT_COMPOSITION"; const RENDER_TARGET_FORMAT: DXGI_FORMAT = DXGI_FORMAT_B8G8R8A8_UNORM; -// This configuration is used for MSAA rendering on paths only, and it's guaranteed to be supported by DirectX 11. -const PATH_MULTISAMPLE_COUNT: u32 = 4; const MAX_INSTANCE_BUFFER_SIZE: usize = 256 * 1024 * 1024; pub(crate) struct FontInfo { @@ -63,6 +62,7 @@ pub(crate) struct DirectXRendererDevices { pub(crate) dxgi_factory: IDXGIFactory6, pub(crate) device: ID3D11Device, pub(crate) device_context: ID3D11DeviceContext, + device_context1: Option, dxgi_device: Option, annotation: Option, } @@ -72,12 +72,8 @@ struct DirectXResources { swap_chain: IDXGISwapChain1, render_target: Option, render_target_view: Option, - - // Path intermediate textures (with MSAA) - path_intermediate_texture: ID3D11Texture2D, - path_intermediate_srv: Option, - path_intermediate_msaa_texture: ID3D11Texture2D, - path_intermediate_msaa_view: Option, + depth_stencil_texture: ID3D11Texture2D, + depth_stencil_view: Option, // Cached viewport viewport: D3D11_VIEWPORT, @@ -86,8 +82,10 @@ struct DirectXResources { struct DirectXRenderPipelines { shadow_pipeline: PipelineState, quad_pipeline: PipelineState, - path_rasterization_pipeline: PipelineState, - path_sprite_pipeline: PipelineState, + opaque_quad_pipeline: OpaqueQuadPipeline, + path_tile_pipeline: PipelineState, + path_curves: StructuredBuffer, + path_paints: StructuredBuffer, underline_pipeline: PipelineState, mono_sprites: PipelineState, subpixel_sprites: PipelineState, @@ -138,12 +136,14 @@ impl DirectXRendererDevices { Some(device.cast().context("Creating DXGI device")?) }; let annotation = device_context.cast().ok(); + let device_context1 = device_context.cast().ok(); Ok(Self { adapter: adapter.clone(), dxgi_factory: dxgi_factory.clone(), device: device.clone(), device_context: device_context.clone(), + device_context1, dxgi_device, annotation, }) @@ -201,7 +201,7 @@ impl DirectXRenderer { self.atlas.clone() } - fn pre_draw(&self, clear_color: &[f32; 4]) -> Result<()> { + fn pre_draw(&self, clear_color: &[f32; 4], depth_scale: f32) -> Result<()> { let resources = self.resources.as_ref().expect("resources missing"); let device_context = &self .devices @@ -217,7 +217,8 @@ impl DirectXRenderer { grayscale_enhanced_contrast: self.font_info.grayscale_enhanced_contrast, subpixel_enhanced_contrast: self.font_info.subpixel_enhanced_contrast, is_bgr: self.font_info.is_bgr as u32, - _pad: [0; 3], + depth_scale, + _pad: [0; 2], }], )?; unsafe { @@ -228,8 +229,19 @@ impl DirectXRenderer { .context("missing render target view")?, clear_color, ); - device_context - .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None); + device_context.ClearDepthStencilView( + resources + .depth_stencil_view + .as_ref() + .context("missing depth stencil view")?, + D3D11_CLEAR_DEPTH.0, + 0.0, + 0, + ); + device_context.OMSetRenderTargets( + Some(slice::from_ref(&resources.render_target_view)), + resources.depth_stencil_view.as_ref(), + ); device_context.RSSetViewports(Some(slice::from_ref(&resources.viewport))); device_context .VSSetConstantBuffers(0, Some(slice::from_ref(&self.globals.global_params_buffer))); @@ -241,6 +253,13 @@ impl DirectXRenderer { Ok(()) } + fn discard_depth_buffer(&self) -> Option<()> { + let context1 = self.devices.as_ref()?.device_context1.as_ref()?; + let depth_stencil_view = self.resources.as_ref()?.depth_stencil_view.as_ref()?; + unsafe { context1.DiscardView(depth_stencil_view) }; + Some(()) + } + #[inline] fn present(&mut self) -> Result<()> { let result = unsafe { @@ -314,9 +333,10 @@ impl DirectXRenderer { .handle_device_lost(&devices.device, &devices.device_context); unsafe { - devices - .device_context - .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None); + devices.device_context.OMSetRenderTargets( + Some(slice::from_ref(&resources.render_target_view)), + resources.depth_stencil_view.as_ref(), + ); } self.devices = Some(devices); self.resources = Some(resources); @@ -351,10 +371,14 @@ impl DirectXRenderer { scene: &Scene, background_appearance: WindowBackgroundAppearance, ) -> Result<()> { - self.pre_draw(&match background_appearance { - WindowBackgroundAppearance::Opaque => [1.0f32; 4], - _ => [0.0f32; 4], - })?; + let depth_scale = quad_depth_scale(scene.quads.len()); + self.pre_draw( + &match background_appearance { + WindowBackgroundAppearance::Opaque => [1.0f32; 4], + _ => [0.0f32; 4], + }, + depth_scale, + )?; self.upload_scene_buffers(scene)?; let annotation = self @@ -362,17 +386,46 @@ impl DirectXRenderer { .as_ref() .and_then(|devices| devices.annotation.clone()) .filter(|annotation| unsafe { annotation.GetStatus().as_bool() }); + + if !scene.quads.is_empty() { + let _annotation = annotation.as_ref().map(|annotation| { + Annotation::new( + annotation, + HSTRING::from(format!("opaque quads ({})", scene.quads.len())), + ) + }); + self.draw_opaque_quads(scene.quads.len())?; + } + + let mut quad_cursor: u32 = 0; + let mut path_tile_cursor = 0; for batch in scene.batches() { let _annotation = annotation .as_ref() .map(|annotation| Annotation::new(annotation, HSTRING::from(batch.label()))); + + // Quad shaders assign each quad its own depth. + // In every other batch type, the depth is fixed to the position of the quad cursor. + if matches!(&batch, PrimitiveBatch::Quads(_)) { + self.set_viewport_depth_range(0.0, 1.0)?; + } else { + let depth = quad_depth(quad_cursor, depth_scale); + self.set_viewport_depth_range(depth, depth)?; + } + match batch { PrimitiveBatch::Shadows(range) => self.draw_shadows(range.start, range.len()), - PrimitiveBatch::Quads(range) => self.draw_quads(range.start, range.len()), + PrimitiveBatch::Quads(range) => { + quad_cursor += range.len() as u32; + self.draw_quads(range.start, range.len()) + } PrimitiveBatch::Paths(range) => { - let paths = &scene.paths[range]; - self.draw_paths_to_intermediate(paths)?; - self.draw_paths_from_intermediate(paths) + let tiles_start = path_tile_cursor; + path_tile_cursor += scene.paths[range] + .iter() + .map(PaintedPath::tile_count) + .sum::(); + self.draw_paths(tiles_start..path_tile_cursor) } PrimitiveBatch::Underlines(range) => self.draw_underlines(range.start, range.len()), PrimitiveBatch::MonochromeSprites { texture_id, range } => { @@ -401,6 +454,7 @@ impl DirectXRenderer { ) })?; } + self.discard_depth_buffer(); Ok(()) } @@ -482,6 +536,36 @@ impl DirectXRenderer { .context("Failed to build RgbaImage from staging readback") } + fn set_viewport_depth_range(&self, minimum_depth: f32, maximum_depth: f32) -> Result<()> { + let devices = self.devices.as_ref().context("devices missing")?; + let resources = self.resources.as_ref().context("resources missing")?; + // Equal endpoints collapse every shader depth to the same value. + let viewport = D3D11_VIEWPORT { + MinDepth: minimum_depth, + MaxDepth: maximum_depth, + ..resources.viewport + }; + unsafe { + devices + .device_context + .RSSetViewports(Some(slice::from_ref(&viewport))) + }; + Ok(()) + } + + fn draw_opaque_quads(&self, quad_count: usize) -> Result<()> { + let devices = self.devices.as_ref().context("devices missing")?; + self.pipelines.opaque_quad_pipeline.draw( + &devices.device_context, + &self.pipelines.quad_pipeline, + self.globals + .batch_params_buffer + .as_ref() + .context("batch params buffer missing")?, + quad_count as u32, + ) + } + pub(crate) fn resize(&mut self, new_size: Size) -> Result<()> { let width = new_size.width.0.max(1) as u32; let height = new_size.height.0.max(1) as u32; @@ -518,9 +602,10 @@ impl DirectXRenderer { resources.recreate_resources(devices, width, height)?; unsafe { - devices - .device_context - .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None); + devices.device_context.OMSetRenderTargets( + Some(slice::from_ref(&resources.render_target_view)), + resources.depth_stencil_view.as_ref(), + ); } Ok(()) @@ -545,6 +630,39 @@ impl DirectXRenderer { )?; } + if !scene.paths.is_empty() { + let mut paints = Vec::with_capacity(scene.paths.len()); + let mut curves = Vec::new(); + let mut tiles = Vec::new(); + for path in &scene.paths { + path.append_to(&mut paints, &mut curves, &mut tiles); + } + + self.pipelines.path_tile_pipeline.update_buffer( + &devices.device, + &devices.device_context, + &tiles, + )?; + self.pipelines + .path_curves + .write(&devices.device, &devices.device_context, &curves)?; + self.pipelines + .path_paints + .write(&devices.device, &devices.device_context, &paints)?; + let buffers = [ + self.pipelines.path_curves.view.clone(), + self.pipelines.path_paints.view.clone(), + ]; + unsafe { + devices + .device_context + .VSSetShaderResources(2, Some(&buffers)); + devices + .device_context + .PSSetShaderResources(2, Some(&buffers)); + } + } + if !scene.underlines.is_empty() { self.pipelines.underline_pipeline.update_buffer( &devices.device, @@ -612,110 +730,19 @@ impl DirectXRenderer { ) } - fn draw_paths_to_intermediate(&mut self, paths: &[Path]) -> Result<()> { - if paths.is_empty() { + fn draw_paths(&mut self, tile_range: Range) -> Result<()> { + if tile_range.is_empty() { return Ok(()); } - let devices = self.devices.as_ref().context("devices missing")?; - let resources = self.resources.as_ref().context("resources missing")?; - // Clear intermediate MSAA texture - unsafe { - devices.device_context.ClearRenderTargetView( - resources.path_intermediate_msaa_view.as_ref().unwrap(), - &[0.0; 4], - ); - // Set intermediate MSAA texture as render target - devices.device_context.OMSetRenderTargets( - Some(slice::from_ref(&resources.path_intermediate_msaa_view)), - None, - ); - } - - // Collect all vertices and sprites for a single draw call - let mut vertices = Vec::new(); - - for path in paths { - vertices.extend(path.vertices.iter().map(|v| PathRasterizationSprite { - xy_position: v.xy_position, - st_position: v.st_position, - color: path.color, - bounds: path.clipped_bounds(), - })); - } - - self.pipelines.path_rasterization_pipeline.update_buffer( - &devices.device, + self.pipelines.path_tile_pipeline.draw_range( &devices.device_context, - &vertices, - )?; - - self.pipelines.path_rasterization_pipeline.draw( - &devices.device_context, - D3D_PRIMITIVE_TOPOLOGY_TRIANGLELIST, - vertices.len() as u32, - 1, - )?; - - // Resolve MSAA to non-MSAA intermediate texture - unsafe { - devices.device_context.ResolveSubresource( - &resources.path_intermediate_texture, - 0, - &resources.path_intermediate_msaa_texture, - 0, - RENDER_TARGET_FORMAT, - ); - // Restore main render target - devices - .device_context - .OMSetRenderTargets(Some(slice::from_ref(&resources.render_target_view)), None); - } - - Ok(()) - } - - fn draw_paths_from_intermediate(&mut self, paths: &[Path]) -> Result<()> { - let Some(first_path) = paths.first() else { - return Ok(()); - }; - - // When copying paths from the intermediate texture to the drawable, - // each pixel must only be copied once, in case of transparent paths. - // - // If all paths have the same draw order, then their bounds are all - // disjoint, so we can copy each path's bounds individually. If this - // batch combines different draw orders, we perform a single copy - // for a minimal spanning rect. - let sprites = if paths.last().unwrap().order == first_path.order { - paths - .iter() - .map(|path| PathSprite { - bounds: path.clipped_bounds(), - }) - .collect::>() - } else { - let mut bounds = first_path.clipped_bounds(); - for path in paths.iter().skip(1) { - bounds = bounds.union(&path.clipped_bounds()); - } - vec![PathSprite { bounds }] - }; - - let devices = self.devices.as_ref().context("devices missing")?; - let resources = self.resources.as_ref().context("resources missing")?; - self.pipelines.path_sprite_pipeline.update_buffer( - &devices.device, - &devices.device_context, - &sprites, - )?; - - // Draw the sprites with the path texture - self.pipelines.path_sprite_pipeline.draw_with_texture( - &devices.device_context, - slice::from_ref(&resources.path_intermediate_srv), - slice::from_ref(&self.globals.sampler), - sprites.len() as u32, + self.globals + .batch_params_buffer + .as_ref() + .context("batch params buffer missing")?, + tile_range.start as u32, + tile_range.len() as u32, ) } @@ -892,10 +919,8 @@ impl DirectXResources { let ( render_target, render_target_view, - path_intermediate_texture, - path_intermediate_srv, - path_intermediate_msaa_texture, - path_intermediate_msaa_view, + depth_stencil_texture, + depth_stencil_view, viewport, ) = create_resources(devices, &swap_chain, width, height)?; set_rasterizer_state(&devices.device, &devices.device_context)?; @@ -904,10 +929,8 @@ impl DirectXResources { swap_chain, render_target: Some(render_target), render_target_view, - path_intermediate_texture, - path_intermediate_msaa_texture, - path_intermediate_msaa_view, - path_intermediate_srv, + depth_stencil_texture, + depth_stencil_view, viewport, }) } @@ -922,18 +945,14 @@ impl DirectXResources { let ( render_target, render_target_view, - path_intermediate_texture, - path_intermediate_srv, - path_intermediate_msaa_texture, - path_intermediate_msaa_view, + depth_stencil_texture, + depth_stencil_view, viewport, ) = create_resources(devices, &self.swap_chain, width, height)?; self.render_target = Some(render_target); self.render_target_view = render_target_view; - self.path_intermediate_texture = path_intermediate_texture; - self.path_intermediate_msaa_texture = path_intermediate_msaa_texture; - self.path_intermediate_msaa_view = path_intermediate_msaa_view; - self.path_intermediate_srv = path_intermediate_srv; + self.depth_stencil_texture = depth_stencil_texture; + self.depth_stencil_view = depth_stencil_view; self.viewport = viewport; Ok(()) } @@ -955,20 +974,15 @@ impl DirectXRenderPipelines { 64, create_blend_state(device)?, )?; - let path_rasterization_pipeline = PipelineState::new( + let path_tile_pipeline = PipelineState::new( device, - "path_rasterization_pipeline", - ShaderModule::PathRasterization, - 32, - create_blend_state_for_path_rasterization(device)?, - )?; - let path_sprite_pipeline = PipelineState::new( - device, - "path_sprite_pipeline", - ShaderModule::PathSprite, - 4, - create_blend_state_for_path_sprite(device)?, + "path_tile_pipeline", + ShaderModule::PathTile, + 64, + create_blend_state(device)?, )?; + let path_curves = StructuredBuffer::new(device, "path_curves", 256)?; + let path_paints = StructuredBuffer::new(device, "path_paints", 64)?; let underline_pipeline = PipelineState::new( device, "underline_pipeline", @@ -997,12 +1011,15 @@ impl DirectXRenderPipelines { 16, create_blend_state(device)?, )?; + let opaque_quad_pipeline = OpaqueQuadPipeline::new(device)?; Ok(Self { shadow_pipeline, quad_pipeline, - path_rasterization_pipeline, - path_sprite_pipeline, + opaque_quad_pipeline, + path_tile_pipeline, + path_curves, + path_paints, underline_pipeline, mono_sprites, subpixel_sprites, @@ -1073,7 +1090,8 @@ struct GlobalParams { grayscale_enhanced_contrast: f32, subpixel_enhanced_contrast: f32, is_bgr: u32, - _pad: [u32; 3], + depth_scale: f32, + _pad: [u32; 2], } #[derive(Clone, Copy, Debug, Default)] @@ -1083,17 +1101,71 @@ struct BatchParams { _padding: [u32; 3], } -const _: () = assert!(std::mem::size_of::() == 16); +struct StructuredBuffer { + label: &'static str, + buffer: ID3D11Buffer, + capacity: usize, + view: Option, + _marker: std::marker::PhantomData, +} + +impl StructuredBuffer { + fn new(device: &ID3D11Device, label: &'static str, capacity: usize) -> Result { + let buffer = create_buffer(device, std::mem::size_of::(), capacity)?; + let view = create_buffer_view(device, &buffer)?; + Ok(StructuredBuffer { + label, + buffer, + capacity, + view, + _marker: std::marker::PhantomData, + }) + } + + fn write( + &mut self, + device: &ID3D11Device, + device_context: &ID3D11DeviceContext, + data: &[T], + ) -> Result<()> { + self.ensure_capacity(device, data.len())?; + update_buffer(device_context, &self.buffer, data) + } + + fn ensure_capacity(&mut self, device: &ID3D11Device, len: usize) -> Result<()> { + if self.capacity < len { + let element_size = std::mem::size_of::().max(1); + let required_size = len.checked_mul(element_size); + anyhow::ensure!( + required_size.is_some_and(|size| size <= MAX_INSTANCE_BUFFER_SIZE), + "{} buffer needs {len} elements of {element_size} bytes, above the maximum of {MAX_INSTANCE_BUFFER_SIZE} bytes", + self.label + ); + let new_capacity = len + .next_power_of_two() + .min(MAX_INSTANCE_BUFFER_SIZE / element_size); + log::debug!( + "Updating {} buffer size from {} to {}", + self.label, + self.capacity, + new_capacity + ); + let buffer = create_buffer(device, std::mem::size_of::(), new_capacity)?; + let view = create_buffer_view(device, &buffer)?; + self.buffer = buffer; + self.view = view; + self.capacity = new_capacity; + } + Ok(()) + } +} struct PipelineState { - label: &'static str, vertex: ID3D11VertexShader, fragment: ID3D11PixelShader, - buffer: ID3D11Buffer, - buffer_size: usize, - view: Option, + instances: StructuredBuffer, blend_state: ID3D11BlendState, - _marker: std::marker::PhantomData, + depth_stencil_state: ID3D11DepthStencilState, } impl PipelineState { @@ -1112,18 +1184,13 @@ impl PipelineState { let raw_shader = RawShaderBytes::new(shader_module, ShaderTarget::Fragment)?; create_fragment_shader(device, raw_shader.as_bytes())? }; - let buffer = create_buffer(device, std::mem::size_of::(), buffer_size)?; - let view = create_buffer_view(device, &buffer)?; Ok(PipelineState { - label, vertex, fragment, - buffer, - buffer_size, - view, + instances: StructuredBuffer::new(device, label, buffer_size)?, blend_state, - _marker: std::marker::PhantomData, + depth_stencil_state: create_depth_stencil_state(device, D3D11_DEPTH_WRITE_MASK_ZERO)?, }) } @@ -1133,77 +1200,7 @@ impl PipelineState { device_context: &ID3D11DeviceContext, data: &[T], ) -> Result<()> { - if self.buffer_size < data.len() { - let element_size = std::mem::size_of::(); - let required_size = std::mem::size_of_val(data); - anyhow::ensure!( - required_size <= MAX_INSTANCE_BUFFER_SIZE, - "{} buffer needs {required_size} bytes, above the maximum of {MAX_INSTANCE_BUFFER_SIZE}", - self.label - ); - let new_buffer_size = data - .len() - .next_power_of_two() - .min(MAX_INSTANCE_BUFFER_SIZE / element_size); - log::debug!( - "Updating {} buffer size from {} to {}", - self.label, - self.buffer_size, - new_buffer_size - ); - let buffer = create_buffer(device, std::mem::size_of::(), new_buffer_size)?; - let view = create_buffer_view(device, &buffer)?; - self.buffer = buffer; - self.view = view; - self.buffer_size = new_buffer_size; - } - update_buffer(device_context, &self.buffer, data) - } - - fn draw( - &self, - device_context: &ID3D11DeviceContext, - topology: D3D_PRIMITIVE_TOPOLOGY, - vertex_count: u32, - instance_count: u32, - ) -> Result<()> { - set_pipeline_state( - device_context, - slice::from_ref(&self.view), - topology, - &self.vertex, - &self.fragment, - &self.blend_state, - ); - unsafe { - device_context.DrawInstanced(vertex_count, instance_count, 0, 0); - } - Ok(()) - } - - fn draw_with_texture( - &self, - device_context: &ID3D11DeviceContext, - texture: &[Option], - sampler: &[Option], - instance_count: u32, - ) -> Result<()> { - set_pipeline_state( - device_context, - slice::from_ref(&self.view), - D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, - &self.vertex, - &self.fragment, - &self.blend_state, - ); - unsafe { - device_context.PSSetSamplers(0, Some(sampler)); - device_context.VSSetShaderResources(0, Some(texture)); - device_context.PSSetShaderResources(0, Some(texture)); - - device_context.DrawInstanced(4, instance_count, 0, 0); - } - Ok(()) + self.instances.write(device, device_context, data) } fn draw_range( @@ -1213,19 +1210,16 @@ impl PipelineState { first_instance: u32, instance_count: u32, ) -> Result<()> { - anyhow::ensure!( - first_instance as usize + instance_count as usize <= self.buffer_size, - "DirectX instance range exceeds the {} buffer", - self.label - ); + self.ensure_range(first_instance, instance_count)?; update_batch_start(device_context, batch_params_buffer, first_instance)?; set_pipeline_state( device_context, - slice::from_ref(&self.view), + slice::from_ref(&self.instances.view), D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, &self.vertex, &self.fragment, &self.blend_state, + &self.depth_stencil_state, ); unsafe { device_context.DrawInstanced(4, instance_count, 0, 0); @@ -1242,19 +1236,16 @@ impl PipelineState { first_instance: u32, instance_count: u32, ) -> Result<()> { - anyhow::ensure!( - first_instance as usize + instance_count as usize <= self.buffer_size, - "DirectX instance range exceeds the {} buffer", - self.label - ); + self.ensure_range(first_instance, instance_count)?; update_batch_start(device_context, batch_params_buffer, first_instance)?; set_pipeline_state( device_context, - slice::from_ref(&self.view), + slice::from_ref(&self.instances.view), D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, &self.vertex, &self.fragment, &self.blend_state, + &self.depth_stencil_state, ); unsafe { device_context.PSSetSamplers(0, Some(sampler)); @@ -1264,21 +1255,72 @@ impl PipelineState { } Ok(()) } + + fn ensure_range(&self, first_instance: u32, instance_count: u32) -> Result<()> { + anyhow::ensure!( + first_instance as usize + instance_count as usize <= self.instances.capacity, + "DirectX instance range exceeds the {} buffer", + self.instances.label + ); + Ok(()) + } } -#[derive(Clone, Copy)] -#[repr(C)] -struct PathRasterizationSprite { - xy_position: Point, - st_position: Point, - color: Background, - bounds: Bounds, +/// Draws opaque rectangles ahead of everything else, writing depth so that +/// later passes skip the pixels they cover. +struct OpaqueQuadPipeline { + vertex: ID3D11VertexShader, + fragment: ID3D11PixelShader, + blend_state: ID3D11BlendState, + depth_stencil_state: ID3D11DepthStencilState, } -#[derive(Clone, Copy)] -#[repr(C)] -struct PathSprite { - bounds: Bounds, +impl OpaqueQuadPipeline { + fn new(device: &ID3D11Device) -> Result { + let vertex = { + let raw_shader = RawShaderBytes::new(ShaderModule::OpaqueQuad, ShaderTarget::Vertex)?; + create_vertex_shader(device, raw_shader.as_bytes())? + }; + let fragment = { + let raw_shader = RawShaderBytes::new(ShaderModule::OpaqueQuad, ShaderTarget::Fragment)?; + create_fragment_shader(device, raw_shader.as_bytes())? + }; + Ok(OpaqueQuadPipeline { + vertex, + fragment, + blend_state: create_opaque_blend_state(device)?, + depth_stencil_state: create_depth_stencil_state(device, D3D11_DEPTH_WRITE_MASK_ALL)?, + }) + } + + /// Draws every quad, last first. The vertex shader drops all but opaque + /// rectangles. + fn draw( + &self, + device_context: &ID3D11DeviceContext, + quad_pipeline: &PipelineState, + batch_params_buffer: &ID3D11Buffer, + quad_count: u32, + ) -> Result<()> { + if quad_count == 0 { + return Ok(()); + } + quad_pipeline.ensure_range(0, quad_count)?; + // Drawing front to back lets the depth test skip pixels that a later + // quad already covers. + update_batch_start(device_context, batch_params_buffer, quad_count - 1)?; + set_pipeline_state( + device_context, + slice::from_ref(&quad_pipeline.instances.view), + D3D_PRIMITIVE_TOPOLOGY_TRIANGLESTRIP, + &self.vertex, + &self.fragment, + &self.blend_state, + &self.depth_stencil_state, + ); + unsafe { device_context.DrawInstanced(4, quad_count, 0, 0) }; + Ok(()) + } } impl Drop for DirectXRenderer { @@ -1362,32 +1404,19 @@ fn create_resources( ID3D11Texture2D, Option, ID3D11Texture2D, - Option, - ID3D11Texture2D, - Option, + Option, D3D11_VIEWPORT, )> { let (render_target, render_target_view) = create_render_target_and_its_view(swap_chain, &devices.device)?; - let (path_intermediate_texture, path_intermediate_srv) = - create_path_intermediate_texture(&devices.device, width, height)?; - let (path_intermediate_msaa_texture, path_intermediate_msaa_view) = - create_path_intermediate_msaa_texture_and_view(&devices.device, width, height)?; - let viewport = D3D11_VIEWPORT { - TopLeftX: 0.0, - TopLeftY: 0.0, - Width: width as f32, - Height: height as f32, - MinDepth: 0.0, - MaxDepth: 1.0, - }; + let (depth_stencil_texture, depth_stencil_view) = + create_depth_stencil_texture_and_view(&devices.device, width, height)?; + let viewport = set_viewport(&devices.device_context, width as f32, height as f32); Ok(( render_target, render_target_view, - path_intermediate_texture, - path_intermediate_srv, - path_intermediate_msaa_texture, - path_intermediate_msaa_view, + depth_stencil_texture, + depth_stencil_view, viewport, )) } @@ -1404,11 +1433,25 @@ fn create_render_target_and_its_view( } #[inline] -fn create_path_intermediate_texture( +fn set_viewport(device_context: &ID3D11DeviceContext, width: f32, height: f32) -> D3D11_VIEWPORT { + let viewport = [D3D11_VIEWPORT { + TopLeftX: 0.0, + TopLeftY: 0.0, + Width: width, + Height: height, + MinDepth: 0.0, + MaxDepth: 1.0, + }]; + unsafe { device_context.RSSetViewports(Some(&viewport)) }; + viewport[0] +} + +#[inline] +fn create_depth_stencil_texture_and_view( device: &ID3D11Device, width: u32, height: u32, -) -> Result<(ID3D11Texture2D, Option)> { +) -> Result<(ID3D11Texture2D, Option)> { let texture = unsafe { let mut output = None; let desc = D3D11_TEXTURE2D_DESC { @@ -1416,55 +1459,22 @@ fn create_path_intermediate_texture( Height: height, MipLevels: 1, ArraySize: 1, - Format: RENDER_TARGET_FORMAT, + Format: DXGI_FORMAT_D32_FLOAT, SampleDesc: DXGI_SAMPLE_DESC { Count: 1, Quality: 0, }, Usage: D3D11_USAGE_DEFAULT, - BindFlags: (D3D11_BIND_RENDER_TARGET.0 | D3D11_BIND_SHADER_RESOURCE.0) as u32, + BindFlags: D3D11_BIND_DEPTH_STENCIL.0 as u32, CPUAccessFlags: 0, MiscFlags: 0, }; device.CreateTexture2D(&desc, None, Some(&mut output))?; output.unwrap() }; - - let mut shader_resource_view = None; - unsafe { device.CreateShaderResourceView(&texture, None, Some(&mut shader_resource_view))? }; - - Ok((texture, Some(shader_resource_view.unwrap()))) -} - -#[inline] -fn create_path_intermediate_msaa_texture_and_view( - device: &ID3D11Device, - width: u32, - height: u32, -) -> Result<(ID3D11Texture2D, Option)> { - let msaa_texture = unsafe { - let mut output = None; - let desc = D3D11_TEXTURE2D_DESC { - Width: width, - Height: height, - MipLevels: 1, - ArraySize: 1, - Format: RENDER_TARGET_FORMAT, - SampleDesc: DXGI_SAMPLE_DESC { - Count: PATH_MULTISAMPLE_COUNT, - Quality: D3D11_STANDARD_MULTISAMPLE_PATTERN.0 as u32, - }, - Usage: D3D11_USAGE_DEFAULT, - BindFlags: D3D11_BIND_RENDER_TARGET.0 as u32, - CPUAccessFlags: 0, - MiscFlags: 0, - }; - device.CreateTexture2D(&desc, None, Some(&mut output))?; - output.unwrap() - }; - let mut msaa_view = None; - unsafe { device.CreateRenderTargetView(&msaa_texture, None, Some(&mut msaa_view))? }; - Ok((msaa_texture, Some(msaa_view.unwrap()))) + let mut view = None; + unsafe { device.CreateDepthStencilView(&texture, None, Some(&mut view))? }; + Ok((texture, view)) } #[inline] @@ -1509,6 +1519,52 @@ fn create_blend_state(device: &ID3D11Device) -> Result { } } +#[inline] +fn create_opaque_blend_state(device: &ID3D11Device) -> Result { + let mut desc = D3D11_BLEND_DESC::default(); + desc.RenderTarget[0].BlendEnable = false.into(); + desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; + desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; + desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; + desc.RenderTarget[0].DestBlend = D3D11_BLEND_ZERO; + desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_ZERO; + desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8; + unsafe { + let mut state = None; + device.CreateBlendState(&desc, Some(&mut state))?; + Ok(state.unwrap()) + } +} + +#[inline] +fn create_depth_stencil_state( + device: &ID3D11Device, + write_mask: D3D11_DEPTH_WRITE_MASK, +) -> Result { + let stencil_op = D3D11_DEPTH_STENCILOP_DESC { + StencilFailOp: D3D11_STENCIL_OP_KEEP, + StencilDepthFailOp: D3D11_STENCIL_OP_KEEP, + StencilPassOp: D3D11_STENCIL_OP_KEEP, + StencilFunc: D3D11_COMPARISON_ALWAYS, + }; + let desc = D3D11_DEPTH_STENCIL_DESC { + DepthEnable: true.into(), + DepthWriteMask: write_mask, + DepthFunc: D3D11_COMPARISON_GREATER, + StencilEnable: false.into(), + StencilReadMask: D3D11_DEFAULT_STENCIL_READ_MASK as u8, + StencilWriteMask: D3D11_DEFAULT_STENCIL_WRITE_MASK as u8, + FrontFace: stencil_op, + BackFace: stencil_op, + }; + unsafe { + let mut state = None; + device.CreateDepthStencilState(&desc, Some(&mut state))?; + Ok(state.unwrap()) + } +} + #[inline] fn create_blend_state_for_subpixel_rendering(device: &ID3D11Device) -> Result { let mut desc = D3D11_BLEND_DESC::default(); @@ -1530,46 +1586,6 @@ fn create_blend_state_for_subpixel_rendering(device: &ID3D11Device) -> Result Result { - // If the feature level is set to greater than D3D_FEATURE_LEVEL_9_3, the display - // device performs the blend in linear space, which is ideal. - let mut desc = D3D11_BLEND_DESC::default(); - desc.RenderTarget[0].BlendEnable = true.into(); - desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; - desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; - desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; - desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; - desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; - desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; - desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8; - unsafe { - let mut state = None; - device.CreateBlendState(&desc, Some(&mut state))?; - Ok(state.unwrap()) - } -} - -#[inline] -fn create_blend_state_for_path_sprite(device: &ID3D11Device) -> Result { - // If the feature level is set to greater than D3D_FEATURE_LEVEL_9_3, the display - // device performs the blend in linear space, which is ideal. - let mut desc = D3D11_BLEND_DESC::default(); - desc.RenderTarget[0].BlendEnable = true.into(); - desc.RenderTarget[0].BlendOp = D3D11_BLEND_OP_ADD; - desc.RenderTarget[0].BlendOpAlpha = D3D11_BLEND_OP_ADD; - desc.RenderTarget[0].SrcBlend = D3D11_BLEND_ONE; - desc.RenderTarget[0].SrcBlendAlpha = D3D11_BLEND_ONE; - desc.RenderTarget[0].DestBlend = D3D11_BLEND_INV_SRC_ALPHA; - desc.RenderTarget[0].DestBlendAlpha = D3D11_BLEND_INV_SRC_ALPHA; - desc.RenderTarget[0].RenderTargetWriteMask = D3D11_COLOR_WRITE_ENABLE_ALL.0 as u8; - unsafe { - let mut state = None; - device.CreateBlendState(&desc, Some(&mut state))?; - Ok(state.unwrap()) - } -} - #[inline] fn create_vertex_shader(device: &ID3D11Device, bytes: &[u8]) -> Result { unsafe { @@ -1610,13 +1626,18 @@ fn create_buffer( element_size: usize, buffer_size: usize, ) -> Result { + let byte_width = element_size + .checked_mul(buffer_size) + .and_then(|size| u32::try_from(size).ok()) + .context("structured buffer size overflows u32")?; let desc = D3D11_BUFFER_DESC { - ByteWidth: (element_size * buffer_size) as u32, + ByteWidth: byte_width, Usage: D3D11_USAGE_DYNAMIC, BindFlags: D3D11_BIND_SHADER_RESOURCE.0 as u32, CPUAccessFlags: D3D11_CPU_ACCESS_WRITE.0 as u32, MiscFlags: D3D11_RESOURCE_MISC_BUFFER_STRUCTURED.0 as u32, - StructureByteStride: element_size as u32, + StructureByteStride: u32::try_from(element_size) + .context("structured buffer stride overflows u32")?, }; let mut buffer = None; unsafe { device.CreateBuffer(&desc, None, Some(&mut buffer)) }?; @@ -1672,6 +1693,7 @@ fn set_pipeline_state( vertex_shader: &ID3D11VertexShader, fragment_shader: &ID3D11PixelShader, blend_state: &ID3D11BlendState, + depth_stencil_state: &ID3D11DepthStencilState, ) { unsafe { device_context.VSSetShaderResources(1, Some(buffer_view)); @@ -1680,6 +1702,7 @@ fn set_pipeline_state( device_context.VSSetShader(vertex_shader, None); device_context.PSSetShader(fragment_shader, None); device_context.OMSetBlendState(blend_state, None, 0xFFFFFFFF); + device_context.OMSetDepthStencilState(depth_stencil_state, 0); } } @@ -1709,10 +1732,10 @@ pub(crate) mod shader_resources { #[derive(Copy, Clone, Debug, Eq, PartialEq)] pub(crate) enum ShaderModule { Quad, + OpaqueQuad, Shadow, Underline, - PathRasterization, - PathSprite, + PathTile, MonochromeSprite, SubpixelSprite, PolychromeSprite, @@ -1761,6 +1784,10 @@ pub(crate) mod shader_resources { ShaderTarget::Vertex => QUAD_VERTEX_BYTES, ShaderTarget::Fragment => QUAD_FRAGMENT_BYTES, }, + ShaderModule::OpaqueQuad => match target { + ShaderTarget::Vertex => OPAQUE_QUAD_VERTEX_BYTES, + ShaderTarget::Fragment => OPAQUE_QUAD_FRAGMENT_BYTES, + }, ShaderModule::Shadow => match target { ShaderTarget::Vertex => SHADOW_VERTEX_BYTES, ShaderTarget::Fragment => SHADOW_FRAGMENT_BYTES, @@ -1769,13 +1796,9 @@ pub(crate) mod shader_resources { ShaderTarget::Vertex => UNDERLINE_VERTEX_BYTES, ShaderTarget::Fragment => UNDERLINE_FRAGMENT_BYTES, }, - ShaderModule::PathRasterization => match target { - ShaderTarget::Vertex => PATH_RASTERIZATION_VERTEX_BYTES, - ShaderTarget::Fragment => PATH_RASTERIZATION_FRAGMENT_BYTES, - }, - ShaderModule::PathSprite => match target { - ShaderTarget::Vertex => PATH_SPRITE_VERTEX_BYTES, - ShaderTarget::Fragment => PATH_SPRITE_FRAGMENT_BYTES, + ShaderModule::PathTile => match target { + ShaderTarget::Vertex => PATH_TILE_VERTEX_BYTES, + ShaderTarget::Fragment => PATH_TILE_FRAGMENT_BYTES, }, ShaderModule::MonochromeSprite => match target { ShaderTarget::Vertex => MONOCHROME_SPRITE_VERTEX_BYTES, @@ -1862,10 +1885,10 @@ pub(crate) mod shader_resources { pub fn as_str(self) -> &'static str { match self { ShaderModule::Quad => "quad", + ShaderModule::OpaqueQuad => "opaque_quad", ShaderModule::Shadow => "shadow", ShaderModule::Underline => "underline", - ShaderModule::PathRasterization => "path_rasterization", - ShaderModule::PathSprite => "path_sprite", + ShaderModule::PathTile => "path_tile", ShaderModule::MonochromeSprite => "monochrome_sprite", ShaderModule::SubpixelSprite => "subpixel_sprite", ShaderModule::PolychromeSprite => "polychrome_sprite", diff --git a/crates/gpui_windows/src/events.rs b/crates/gpui_windows/src/events.rs index 4dd0c38c030..d308bfa4e58 100644 --- a/crates/gpui_windows/src/events.rs +++ b/crates/gpui_windows/src/events.rs @@ -169,7 +169,7 @@ impl WindowsWindowInner { } } - fn handle_move_msg(&self, handle: HWND, lparam: LPARAM) -> Option { + fn handle_move_msg(self: &Rc, handle: HWND, lparam: LPARAM) -> Option { let origin = logical_point( lparam.signed_loword() as f32, lparam.signed_hiword() as f32, @@ -944,7 +944,7 @@ impl WindowsWindowInner { Some(0) } - fn handle_display_change_msg(&self, handle: HWND) -> Option { + fn handle_display_change_msg(self: &Rc, handle: HWND) -> Option { let new_monitor = unsafe { MonitorFromWindow(handle, MONITOR_DEFAULTTONULL) }; if new_monitor.is_invalid() { log::error!("No monitor detected!"); @@ -955,12 +955,20 @@ impl WindowsWindowInner { Some(0) } - fn set_display(&self, display: WindowsDisplay) { + // Windows can deliver `WM_DISPLAYCHANGE` and `WM_MOVE` while GPUI is + // updating a window (e.g. a clipboard read during a draw pumps sent + // messages), so report the change after that update completes. + fn set_display(self: &Rc, display: WindowsDisplay) { self.state.display.set(display); - if let Some(mut callback) = self.state.callbacks.display_changed.take() { - callback(); - self.state.callbacks.display_changed.set(Some(callback)); - } + let this = self.clone(); + self.executor + .spawn(async move { + if let Some(mut callback) = this.state.callbacks.display_changed.take() { + callback(); + this.state.callbacks.display_changed.set(Some(callback)); + } + }) + .detach(); } fn handle_hit_test_msg(&self, handle: HWND, lparam: LPARAM) -> Option { diff --git a/crates/gpui_windows/src/shaders.hlsl b/crates/gpui_windows/src/shaders.hlsl index 2f9a00c4186..87882544fca 100644 --- a/crates/gpui_windows/src/shaders.hlsl +++ b/crates/gpui_windows/src/shaders.hlsl @@ -6,7 +6,8 @@ cbuffer GlobalParams: register(b0) { float grayscale_enhanced_contrast; float subpixel_enhanced_contrast; uint is_bgr; - uint3 global_pad; + float depth_scale; + uint2 global_pad; }; cbuffer BatchParams: register(b1) { @@ -58,7 +59,7 @@ struct Background { // 1u is LinearGradient // 2u is PatternSlash uint tag; - // 0u is sRGB linear color + // 0u is sRGB color // 1u is Oklab color uint color_space; Hsla solid; @@ -67,10 +68,10 @@ struct Background { uint pad; }; -struct GradientColor { - float4 solid; - float4 color0; - float4 color1; +struct PreparedBackground { + nointerpolation float4 color0: COLOR1; + nointerpolation float4 color1: COLOR2; + nointerpolation uint tag: TEXCOORD2; }; struct AtlasTextureId { @@ -98,6 +99,8 @@ struct TransformationMatrix { static const float M_PI_F = 3.141592653f; static const float3 GRAYSCALE_FACTORS = float3(0.2126f, 0.7152f, 0.0722f); +static const uint SIMPLE_PRIMITIVE_FLAG = 1u << 31; + float4 to_device_position_impl(float2 position) { float2 device_position = position / global_viewport_size * float2(2.0, -2.0) + float2(-1.0, 1.0); return float4(device_position, 0., 1.); @@ -108,23 +111,41 @@ float4 to_device_position(float2 unit_vertex, Bounds bounds) { return to_device_position_impl(position); } +float quad_depth(uint quad_id) { + return saturate(float(quad_id + 1u) * depth_scale); +} + +static const float4 CULLED_POSITION = float4(0.0, 0.0, 0.0, 1.0); + float4 distance_from_clip_rect_impl(float2 position, Bounds clip_bounds) { float2 tl = position - clip_bounds.origin; float2 br = clip_bounds.origin + clip_bounds.size - position; return float4(tl.x, br.x, tl.y, br.y); } -float4 distance_from_clip_rect(float2 unit_vertex, Bounds bounds, Bounds clip_bounds) { - float2 position = unit_vertex * bounds.size + bounds.origin; - return distance_from_clip_rect_impl(position, clip_bounds); -} - float4 distance_from_clip_rect_transformed(float2 unit_vertex, Bounds bounds, Bounds clip_bounds, TransformationMatrix transformation) { float2 position = unit_vertex * bounds.size + bounds.origin; float2 transformed = mul(position, transformation.rotation_scale) + transformation.translation; return distance_from_clip_rect_impl(transformed, clip_bounds); } +struct ClippedVertex { + float2 position; + // The corner as a fraction of the original bounds. + float2 unit_vertex; +}; + +ClippedVertex clip_to_mask(float2 unit_vertex, Bounds bounds, Bounds mask) { + float2 origin = max(bounds.origin, mask.origin); + float2 corner = min(bounds.origin + bounds.size, mask.origin + mask.size); + float2 size = max(corner - origin, float2(0.0, 0.0)); + + ClippedVertex result; + result.position = origin + unit_vertex * size; + result.unit_vertex = (result.position - bounds.origin) / bounds.size; + return result; +} + // Convert linear RGB to sRGB float3 linear_to_srgb(float3 color) { return pow(color, float3(1.0 / 2.2, 1.0 / 2.2, 1.0 / 2.2)); @@ -135,7 +156,7 @@ float3 srgb_to_linear(float3 color) { return pow(color, float3(2.2, 2.2, 2.2)); } -/// Hsla to linear RGBA conversion. +/// Hsla to sRGB conversion. float4 hsla_to_rgba(Hsla hsla) { float h = hsla.h * 6.0; // Now, it's an angle but scaled in [0, 6) range float s = hsla.s; @@ -226,27 +247,6 @@ float4 oklab_to_srgb(float4 color) { return float4(linear_to_srgb(linear_rgb), color.a); } -// This approximates the error function, needed for the gaussian integral -float2 erf(float2 x) { - float2 s = sign(x); - float2 a = abs(x); - x = 1. + (0.278393 + (0.230389 + 0.078108 * (a * a)) * a) * a; - x *= x; - return s - s / (x * x); -} - -float blur_along_x(float x, float y, float sigma, float corner, float2 half_size) { - float delta = min(half_size.y - corner - abs(y), 0.); - float curved = half_size.x - corner + sqrt(max(0., corner * corner - delta * delta)); - float2 integral = 0.5 + 0.5 * erf((x + float2(-curved, curved)) * (sqrt(0.5) / sigma)); - return integral.y - integral.x; -} - -// A standard gaussian function, used for weighting samples -float gaussian(float x, float sigma) { - return exp(-(x * x) / (2. * sigma * sigma)) / (sqrt(2. * M_PI_F) * sigma); -} - float4 over(float4 below, float4 above) { float4 result; float alpha = above.a + below.a * (1.0 - above.a); @@ -314,126 +314,114 @@ float quad_sdf(float2 pt, Bounds bounds, Corners corner_radii) { return quad_sdf_impl(corner_center_to_point, corner_radius); } -GradientColor prepare_gradient_color(uint tag, uint color_space, Hsla solid, LinearColorStop colors[2]) { - GradientColor output; - if (tag == 0 || tag == 2 || tag == 3) { - output.solid = hsla_to_rgba(solid); - } else if (tag == 1) { - output.color0 = hsla_to_rgba(colors[0].color); - output.color1 = hsla_to_rgba(colors[1].color); +PreparedBackground prepare_background(Background background) { + PreparedBackground output; + output.tag = background.tag; + output.color1 = float4(0.0, 0.0, 0.0, 0.0); - // Prepare color space in vertex for avoid conversion - // in fragment shader for performance reasons - if (color_space == 1) { - // Oklab + if (background.tag == 1) { + output.color0 = hsla_to_rgba(background.colors[0].color); + output.color1 = hsla_to_rgba(background.colors[1].color); + // Interpolating in Oklab means converting the endpoints once rather + // than at every stop evaluation. + if (background.color_space == 1) { output.color0 = srgb_to_oklab(output.color0); output.color1 = srgb_to_oklab(output.color1); } + } else { + output.color0 = hsla_to_rgba(background.solid); } return output; } -float2x2 rotate2d(float angle) { - float s = sin(angle); - float c = cos(angle); - return float2x2(c, -s, s, c); +// Ordered (Bayer 4x4) dither threshold, remapped to [-1, +1]. +float dither_offset(float2 position) { + uint2 cell = uint2(position) & 3u; + uint z = cell.x ^ cell.y; + uint threshold = ((z & 1u) << 3) + | ((cell.y & 1u) << 2) + | (z & 2u) + | ((cell.y & 2u) >> 1); + return (float(threshold) + 0.5) * (1.0 / 8.0) - 1.0; } -float4 gradient_color(Background background, - float2 position, - Bounds bounds, - float4 solid_color, float4 color0, float4 color1) { - float4 color; +float4 background_color(PreparedBackground prepared, Background background, Bounds bounds, + float2 position) { + float4 color = prepared.color0; + if (prepared.tag == 0u) { + return color; + } - switch (background.tag) { - case 0: - color = solid_color; - break; + switch (prepared.tag) { case 1: { // -90 degrees to match the CSS gradient angle. - float gradient_angle = background.gradient_angle_or_pattern_height; - float radians = (fmod(gradient_angle, 360.0) - 90.0) * (M_PI_F / 180.0); + float radians = (fmod(background.gradient_angle_or_pattern_height, 360.0) - 90.0) + * (M_PI_F / 180.0); float2 direction = float2(cos(radians), sin(radians)); // Expand the short side to be the same as the long side if (bounds.size.x > bounds.size.y) { direction.y *= bounds.size.y / bounds.size.x; } else { - direction.x *= bounds.size.x / bounds.size.y; + direction.x *= bounds.size.x / bounds.size.y; } - // Get the t value for the linear gradient with the color stop percentages. - float2 half_size = bounds.size * 0.5; - float2 center = bounds.origin + half_size; - float2 center_to_point = position - center; - float t = dot(center_to_point, direction) / length(direction); - // Check the direct to determine the use x or y - if (abs(direction.x) > abs(direction.y)) { - t = (t + half_size.x) / bounds.size.x; - } else { - t = (t + half_size.y) / bounds.size.y; - } + float extent = abs(direction.x) > abs(direction.y) + ? bounds.size.x + : bounds.size.y; + float direction_length = length(direction); + float span = background.colors[1].percentage - background.colors[0].percentage; + // The half-extent term is exactly half of `extent`, so the + // position-independent part reduces to this. + float offset = 0.5 - background.colors[0].percentage; - // Adjust t based on the stop percentages - t = (t - background.colors[0].percentage) - / (background.colors[1].percentage - - background.colors[0].percentage); - t = clamp(t, 0.0, 1.0); - - switch (background.color_space) { - case 0: - color = lerp(color0, color1, t); - break; - case 1: { - float4 oklab_color = lerp(color0, color1, t); - color = oklab_to_srgb(oklab_color); - break; + // t = dot(position - center, gradient.xy) + gradient.z + float3 gradient = float3(0.0, 0.0, 0.0); + if (direction_length != 0.0 && extent != 0.0) { + if (span == 0.0) { + const float STEP = 1e30; + gradient = float3(direction / (direction_length * extent) * STEP, offset * STEP); + } else { + gradient = float3(direction / (direction_length * extent * span), offset / span); } } + float2 center = bounds.origin + bounds.size * 0.5; + float t = saturate(dot(position - center, gradient.xy) + gradient.z); + color = lerp(prepared.color0, prepared.color1, t); + if (background.color_space == 1) { + color = oklab_to_srgb(color); + } // Dither to reduce banding in gradients (especially dark/alpha). - // Triangular-distributed noise breaks up 8-bit quantization steps. - // ±2/255 for RGB (enough for dark-on-dark compositing), - // ±3/255 for alpha (needs more because alpha × dark color = tiny steps). - { - float2 seed = position * 0.6180339887; // golden ratio spread - float r1 = frac(sin(dot(seed, float2(12.9898, 78.233))) * 43758.5453); - float r2 = frac(sin(dot(seed, float2(39.3460, 11.135))) * 24634.6345); - float tri = r1 + r2 - 1.0; // triangular PDF, range [-1, +1] - color.rgb += tri * 2.0 / 255.0; - color.a += tri * 3.0 / 255.0; - } - + float dither = dither_offset(position); + color.rgb += dither * 1.0 / 255.0; + color.a += dither * 1.5 / 255.0; break; } case 2: { - float gradient_angle_or_pattern_height = background.gradient_angle_or_pattern_height; - float pattern_width = (gradient_angle_or_pattern_height / 65535.0f) / 255.0f; - float pattern_interval = fmod(gradient_angle_or_pattern_height, 65535.0f) / 255.0f; + float pattern_height_encoded = background.gradient_angle_or_pattern_height; + float pattern_width = (pattern_height_encoded / 65535.0) / 255.0; + float pattern_interval = fmod(pattern_height_encoded, 65535.0) / 255.0; float pattern_height = pattern_width + pattern_interval; + // Only the rotated x coordinate is used, and a row-vector multiply + // by the rotation reduces it to dot(v, float2(cos a, sin a)). float stripe_angle = M_PI_F / 4.0; + float2 stripe_direction = float2(cos(stripe_angle), sin(stripe_angle)); float pattern_period = pattern_height * sin(stripe_angle); - float2x2 rotation = rotate2d(stripe_angle); - float2 relative_position = position - bounds.origin; - float2 rotated_point = mul(relative_position, rotation); - float pattern = fmod(rotated_point.x, pattern_period); - float distance = min(pattern, pattern_period - pattern) - pattern_period * (pattern_width / pattern_height) / 2.0f; - color = solid_color; + float threshold = pattern_period * (pattern_width / pattern_height) / 2.0; + float pattern = fmod(dot(position - bounds.origin, stripe_direction), pattern_period); + float distance = min(pattern, pattern_period - pattern) - threshold; color.a *= saturate(0.5 - distance); break; } case 3: { // checkerboard - float size = background.gradient_angle_or_pattern_height; + float cell_size = background.gradient_angle_or_pattern_height; float2 relative_position = position - bounds.origin; - - float x_index = floor(relative_position.x / size); - float y_index = floor(relative_position.y / size); - float should_be_colored = (x_index + y_index) % 2.0; - - color = solid_color; - color.a *= saturate(should_be_colored); + float x_index = floor(relative_position.x / cell_size); + float y_index = floor(relative_position.y / cell_size); + color.a *= saturate((x_index + y_index) % 2.0); break; } } @@ -509,72 +497,77 @@ struct Quad { Edges border_widths; }; -struct QuadVertexOutput { - nointerpolation uint quad_id: TEXCOORD0; - float4 position: SV_Position; - nointerpolation float4 border_color: COLOR0; - nointerpolation float4 background_solid: COLOR1; - nointerpolation float4 background_color0: COLOR2; - nointerpolation float4 background_color1: COLOR3; - float4 clip_distance: SV_ClipDistance; -}; +bool has_rounded_corners(Corners corner_radii) { + return corner_radii.top_left != 0.0 + || corner_radii.top_right != 0.0 + || corner_radii.bottom_right != 0.0 + || corner_radii.bottom_left != 0.0; +} + +bool has_border(Edges border_widths) { + return border_widths.top != 0.0 + || border_widths.right != 0.0 + || border_widths.bottom != 0.0 + || border_widths.left != 0.0; +} + +bool is_shaped(Quad quad) { + return has_rounded_corners(quad.corner_radii) || has_border(quad.border_widths); +} struct QuadFragmentInput { nointerpolation uint quad_id: TEXCOORD0; float4 position: SV_Position; nointerpolation float4 border_color: COLOR0; - nointerpolation float4 background_solid: COLOR1; - nointerpolation float4 background_color0: COLOR2; - nointerpolation float4 background_color1: COLOR3; + PreparedBackground background; }; +// Opaque rectangles are drawn by the opaque pass instead of the quad pass. +bool is_opaque_rectangle(Quad quad) { + return quad.background.tag == 0u + && quad.background.solid.a >= 1.0 + && !has_rounded_corners(quad.corner_radii) + && !has_border(quad.border_widths); +} + StructuredBuffer quads: register(t1); -QuadVertexOutput quad_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { - float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); +QuadFragmentInput quad_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { uint quad_id = batch_start_index + instance_id; Quad quad = quads[quad_id]; - float4 device_position = to_device_position(unit_vertex, quad.bounds); - GradientColor gradient = prepare_gradient_color( - quad.background.tag, - quad.background.color_space, - quad.background.solid, - quad.background.colors - ); - float4 clip_distance = distance_from_clip_rect(unit_vertex, quad.bounds, quad.content_mask); + if (is_opaque_rectangle(quad)) { + QuadFragmentInput culled = (QuadFragmentInput)0; + culled.position = CULLED_POSITION; + return culled; + } + + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + ClippedVertex vertex = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask); + float4 device_position = to_device_position_impl(vertex.position); + float4 border_color = hsla_to_rgba(quad.border_color); - QuadVertexOutput output; + QuadFragmentInput output; output.position = device_position; + output.position.z = quad_depth(quad_id); output.border_color = border_color; - output.quad_id = quad_id; - output.background_solid = gradient.solid; - output.background_color0 = gradient.color0; - output.background_color1 = gradient.color1; - output.clip_distance = clip_distance; + bool simple = !is_shaped(quad) && quad.background.tag == 0u; + output.quad_id = quad_id | (simple ? SIMPLE_PRIMITIVE_FLAG : 0u); + output.background = prepare_background(quad.background); return output; } float4 quad_fragment(QuadFragmentInput input): SV_Target { - Quad quad = quads[input.quad_id]; - float4 background_color = gradient_color(quad.background, input.position.xy, quad.bounds, - input.background_solid, input.background_color0, input.background_color1); - - bool unrounded = quad.corner_radii.top_left == 0.0 && - quad.corner_radii.top_right == 0.0 && - quad.corner_radii.bottom_left == 0.0 && - quad.corner_radii.bottom_right == 0.0; - - // Fast path when the quad is not rounded and doesn't have any border - if (quad.border_widths.top == 0.0 && - quad.border_widths.left == 0.0 && - quad.border_widths.right == 0.0 && - quad.border_widths.bottom == 0.0 && - unrounded) { - return background_color; + if ((input.quad_id & SIMPLE_PRIMITIVE_FLAG) != 0u) { + return input.background.color0; } + Quad quad = quads[input.quad_id]; + float4 background = + background_color(input.background, quad.background, quad.bounds, input.position.xy); + bool unrounded = !has_rounded_corners(quad.corner_radii); + float2 size = quad.bounds.size; float2 half_size = size / 2.; float2 the_point = input.position.xy - quad.bounds.origin; @@ -631,7 +624,7 @@ float4 quad_fragment(QuadFragmentInput input): SV_Target { // Fast path for points that must be part of the background if (is_within_inner_straight_border && !is_near_rounded_corner) { - return background_color; + return background; } // Signed distance of the point to the outside edge of the quad's border @@ -664,7 +657,7 @@ float4 quad_fragment(QuadFragmentInput input): SV_Target { // Negative when inside the border float border_sdf = max(inner_sdf, outer_sdf); - float4 color = background_color; + float4 color = background; if (border_sdf < antialias_threshold) { float4 border_color = input.border_color; // Dashed border logic when border_style == 1 @@ -839,14 +832,49 @@ float4 quad_fragment(QuadFragmentInput input): SV_Target { // Blend the border on top of the background and then linearly interpolate // between the two as we slide inside the background. - float4 blended_border = over(background_color, border_color); - color = lerp(background_color, blended_border, + float4 blended_border = over(background, border_color); + color = lerp(background, blended_border, saturate(antialias_threshold - inner_sdf)); } return color * float4(1.0, 1.0, 1.0, saturate(antialias_threshold - outer_sdf)); } +/* +** +** Opaque quads +** +*/ + +struct OpaqueQuadFragmentInput { + float4 position: SV_Position; + nointerpolation float4 color: COLOR0; +}; + +OpaqueQuadFragmentInput opaque_quad_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { + uint quad_id = batch_start_index - instance_id; + Quad quad = quads[quad_id]; + + OpaqueQuadFragmentInput output; + if (!is_opaque_rectangle(quad)) { + output.position = CULLED_POSITION; + output.color = float4(0.0, 0.0, 0.0, 0.0); + return output; + } + + float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); + ClippedVertex vertex = clip_to_mask(unit_vertex, quad.bounds, quad.content_mask); + + output.position = to_device_position_impl(vertex.position); + output.position.z = quad_depth(quad_id); + output.color = hsla_to_rgba(quad.background.solid); + return output; +} + +float4 opaque_quad_fragment(OpaqueQuadFragmentInput input): SV_Target { + return input.color; +} + /* ** ** Shadows @@ -860,52 +888,100 @@ struct Shadow { Corners corner_radii; Bounds content_mask; Hsla color; - Bounds element_bounds; - Corners element_corner_radii; + Bounds shape_bounds; + Corners shape_corner_radii; uint inset; uint pad; // align to 8 bytes }; -struct ShadowVertexOutput { - nointerpolation uint shadow_id: TEXCOORD0; - float4 position: SV_Position; - nointerpolation float4 color: COLOR; - float4 clip_distance: SV_ClipDistance; +struct PreparedBlurredRoundedRect { + nointerpolation float4 shape: TEXCOORD1; + nointerpolation float4 r1: TEXCOORD2; + nointerpolation float4 exponent: TEXCOORD3; + nointerpolation float4 scale: TEXCOORD4; }; struct ShadowFragmentInput { - nointerpolation uint shadow_id: TEXCOORD0; - float4 position: SV_Position; - nointerpolation float4 color: COLOR; + nointerpolation uint shadow_id: TEXCOORD0; + float4 position: SV_Position; + nointerpolation float4 color: COLOR; + PreparedBlurredRoundedRect blur; }; StructuredBuffer shadows: register(t1); -ShadowVertexOutput shadow_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { +float erf7(float x) { + x = clamp(x, -10., 10.) * (2. / sqrt(M_PI_F)); + float xx = x * x; + x = x + (0.24295 + (0.03395 + 0.0104 * xx) * xx) * (x * xx); + return x / sqrt(1. + x * x); +} + +// Raph Levien's blurred rounded rectangle approximation, whose blur s is sigma * sqrt(2): +// https://raphlinus.github.io/graphics/2020/04/21/blurred-rounded-rects.html +PreparedBlurredRoundedRect prepare_blurred_rounded_rect(float2 size, Corners corner_radii, float sigma) { + float s = max(sigma * sqrt(2.), 1e-6); + float s_inv = 1. / s; + float min_edge = min(size.x, size.y); + float r_max = 0.5 * min_edge; + float4 radii = float4(corner_radii.top_left, corner_radii.top_right, + corner_radii.bottom_right, corner_radii.bottom_left); + float4 r0 = min(sqrt(radii * radii + 1.15 * 1.15 * s * s), r_max); + float4 r1 = min(sqrt(radii * radii + 4. * s * s), r_max); + + float2 half_extent = 0.5 * s_inv * size; + float delta = 1.25 * s * (exp(-half_extent.x * half_extent.x) - exp(-half_extent.y * half_extent.y)); + float2 adjusted_size = float2(size.x + min(delta, 0.), size.y - max(delta, 0.)); + float4 peak = s_inv * 0.5 * (max(adjusted_size.x, adjusted_size.y) - 0.5 * radii); + + PreparedBlurredRoundedRect output; + output.shape = float4(0.5 * adjusted_size, s_inv, min_edge); + output.r1 = r1; + output.exponent = 2. * r1 / r0; + output.scale = 0.5 * float4(erf7(peak.x), erf7(peak.y), erf7(peak.z), erf7(peak.w)); + return output; +} + +float pick_corner(float2 center_to_point, float4 values) { + Corners corners = { values.x, values.y, values.z, values.w }; + return pick_corner_radius(center_to_point, corners); +} + +float blurred_rounded_rect(float2 center_to_point, PreparedBlurredRoundedRect prepared) { + float r1 = pick_corner(center_to_point, prepared.r1); + float exponent = pick_corner(center_to_point, prepared.exponent); + float scale = pick_corner(center_to_point, prepared.scale); + float s_inv = prepared.shape.z; + float min_edge = prepared.shape.w; + + float2 p0 = abs(center_to_point) - (prepared.shape.xy - r1); + float2 p1 = max(p0, 0.); + float d_pos; + [branch] if (p1.x > 0. && p1.y > 0.) { + d_pos = pow(pow(p1.x, exponent) + pow(p1.y, exponent), 1. / exponent); + } else { + d_pos = p1.x + p1.y; + } + + float d_neg = min(max(p0.x, p0.y), 0.); + float d = d_pos + d_neg - r1; + return scale * (erf7(s_inv * (min_edge + d)) - erf7(s_inv * d)); +} + +ShadowFragmentInput shadow_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); uint shadow_id = batch_start_index + instance_id; Shadow shadow = shadows[shadow_id]; - Bounds bounds; - if (shadow.inset != 0u) { - bounds = shadow.element_bounds; - } else { - // Leave room for the gaussian tail outside the shadow rect. - float margin = 3.0 * shadow.blur_radius; - bounds = shadow.bounds; - bounds.origin -= margin; - bounds.size += 2.0 * margin; - } - - float4 device_position = to_device_position(unit_vertex, bounds); - float4 clip_distance = distance_from_clip_rect(unit_vertex, bounds, shadow.content_mask); + ClippedVertex vertex = clip_to_mask(unit_vertex, shadow.bounds, shadow.content_mask); + float4 device_position = to_device_position_impl(vertex.position); float4 color = hsla_to_rgba(shadow.color); - ShadowVertexOutput output; + ShadowFragmentInput output; output.position = device_position; output.color = color; output.shadow_id = shadow_id; - output.clip_distance = clip_distance; + output.blur = prepare_blurred_rounded_rect(shadow.shape_bounds.size, shadow.shape_corner_radii, shadow.blur_radius); return output; } @@ -913,40 +989,20 @@ ShadowVertexOutput shadow_vertex(uint vertex_id: SV_VertexID, uint instance_id: float4 shadow_fragment(ShadowFragmentInput input): SV_TARGET { Shadow shadow = shadows[input.shadow_id]; - float2 half_size = shadow.bounds.size / 2.; - float2 center = shadow.bounds.origin + half_size; - float2 point0 = input.position.xy - center; - float corner_radius = pick_corner_radius(point0, shadow.corner_radii); - float alpha; if (shadow.blur_radius == 0.) { - float distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii); + float distance = quad_sdf(input.position.xy, shadow.shape_bounds, shadow.shape_corner_radii); alpha = saturate(0.5 - distance); } else { - // The signal is only non-zero in a limited range, so don't waste samples - float low = point0.y - half_size.y; - float high = point0.y + half_size.y; - float start = clamp(-3. * shadow.blur_radius, low, high); - float end = clamp(3. * shadow.blur_radius, low, high); - - // Accumulate samples (we can get away with surprisingly few samples) - float step = (end - start) / 4.; - float y = start + step * 0.5; - alpha = 0.; - for (int i = 0; i < 4; i++) { - alpha += blur_along_x(point0.x, point0.y - y, shadow.blur_radius, - corner_radius, half_size) * - gaussian(y, shadow.blur_radius) * step; - y += step; - } + float2 center = shadow.shape_bounds.origin + shadow.shape_bounds.size / 2.; + alpha = blurred_rounded_rect(input.position.xy - center, input.blur); } if (shadow.inset != 0u) { // The inset shadow is the complement of the (blurred) hole rect, clipped to the element. // `saturate(0.5 - d)` gives a 1-pixel antialiased edge: d <= -0.5 -> 1, d >= 0.5 -> 0. alpha = 1.0 - alpha; - float element_distance = quad_sdf(input.position.xy, shadow.element_bounds, - shadow.element_corner_radii); + float element_distance = quad_sdf(input.position.xy, shadow.bounds, shadow.corner_radii); alpha *= saturate(0.5 - element_distance); } @@ -955,105 +1011,179 @@ float4 shadow_fragment(ShadowFragmentInput input): SV_TARGET { /* ** -** Path Rasterization +** Path Tiles ** */ -struct PathRasterizationSprite { - float2 xy_position; - float2 st_position; - Background color; +struct PathCurve { + float2 p0; + float2 p1; + float2 a; + float2 b; + float sign; + uint pad; +}; + +struct PathTile { + uint paint; + uint curve_start; + uint curve_count; + int backdrop; + float2 top_left; + float2 bottom_right; + float2 reference; + float2 curves_top_left; + float2 curves_bottom_right; +}; + +struct PathPaint { Bounds bounds; + Bounds content_mask; + Background color; + uint even_odd; + uint pad; }; -StructuredBuffer path_rasterization_sprites: register(t1); +StructuredBuffer path_tiles: register(t1); +StructuredBuffer path_curves: register(t2); +StructuredBuffer path_paints: register(t3); -struct PathVertexOutput { +struct PathTileFragmentInput { float4 position: SV_Position; - float2 st_position: TEXCOORD0; - nointerpolation uint vertex_id: TEXCOORD1; - float4 clip_distance: SV_ClipDistance; + nointerpolation uint tile_id: TEXCOORD0; + nointerpolation float4 curve_box: TEXCOORD1; + PreparedBackground background; }; -struct PathFragmentInput { - float4 position: SV_Position; - float2 st_position: TEXCOORD0; - nointerpolation uint vertex_id: TEXCOORD1; -}; +PathTileFragmentInput path_tile_vertex(uint vertex_id: SV_VertexID, uint tile_id: SV_InstanceID) { + uint tile_index = batch_start_index + tile_id; + PathTile tile = path_tiles[tile_index]; + PathPaint paint = path_paints[tile.paint]; -PathVertexOutput path_rasterization_vertex(uint vertex_id: SV_VertexID) { - PathRasterizationSprite sprite = path_rasterization_sprites[vertex_id]; - - PathVertexOutput output; - output.position = to_device_position_impl(sprite.xy_position); - output.st_position = sprite.st_position; - output.vertex_id = vertex_id; - output.clip_distance = distance_from_clip_rect_impl(sprite.xy_position, sprite.bounds); + // Neighboring tiles store their shared edge as the same number, so clipping each corner on its + // own gives them bit-identical edges, which the rasterizer neither overlaps nor leaves gaps + // between. Interpolating from an origin and a size would not. + float2 mask_top_left = paint.content_mask.origin; + float2 mask_bottom_right = paint.content_mask.origin + paint.content_mask.size; + float2 top_left = clamp(tile.top_left, mask_top_left, mask_bottom_right); + float2 bottom_right = clamp(tile.bottom_right, top_left, mask_bottom_right); + float2 position = float2( + (vertex_id & 1u) != 0u ? bottom_right.x : top_left.x, + (vertex_id & 2u) != 0u ? bottom_right.y : top_left.y); + PathTileFragmentInput output; + output.position = to_device_position_impl(position); + output.tile_id = tile_index; + output.curve_box = float4(tile.curves_top_left, tile.curves_bottom_right); + output.background = prepare_background(paint.color); return output; } -float4 path_rasterization_fragment(PathFragmentInput input): SV_Target { - float2 dx = ddx(input.st_position); - float2 dy = ddy(input.st_position); - PathRasterizationSprite sprite = path_rasterization_sprites[input.vertex_id]; +// Solves a*t^2 + b*t + c = 0 for the root in [0, 1] on a monotone piece. +float monotone_quadratic_root(float a, float b, float c, float direction) { + float discriminant = max(b * b - 4.0 * a * c, 0.0); + float denominator = b + direction * sqrt(discriminant); + if (denominator == 0.0) { + return 0.0; + } + return saturate(-2.0 * c / denominator); +} - Background background = sprite.color; - Bounds bounds = sprite.bounds; +// Coverage estimate adapted from https://github.com/EricLengyel/Slug/blob/be3c13eb7d63f9e8aa5c583e42d92c374cb91d98/SlugPixelShader.hlsl +// Copyright (c) 2017 Eric Lengyel. +// Licensed under the MIT license. - float alpha; - if (length(float2(dx.x, dy.x))) { - alpha = 1.0; - } else { - float2 gradient = 2.0 * input.st_position.xx * float2(dx.x, dy.x) - float2(dx.y, dy.y); - float f = input.st_position.x * input.st_position.x - input.st_position.y; - float distance = f / length(gradient); - alpha = saturate(0.5 - distance); +// Accumulates the curve's winding along the pixel's leftward and upward rays. Like Slug, a crossing +// within half a pixel of the center counts fractionally. +void add_curve_winding(PathCurve curve, float2 center, inout float2 winding, inout float2 weight) { + float min_x = min(curve.p0.x, curve.p1.x); + float max_x = max(curve.p0.x, curve.p1.x); + + [branch] + if (curve.p0.y <= center.y && center.y < curve.p1.y) { + [branch] + if (max_x <= center.x - 0.5) { + winding.x += curve.sign; + } else { + float t = monotone_quadratic_root(curve.a.y, curve.b.y, curve.p0.y - center.y, 1.0); + float x = (curve.a.x * t + curve.b.x) * t + curve.p0.x; + float distance = center.x - x; + winding.x += curve.sign * saturate(distance + 0.5); + weight.x = max(weight.x, saturate(1.0 - 2.0 * abs(distance))); + } } - GradientColor gradient = prepare_gradient_color( - background.tag, background.color_space, background.solid, background.colors); - - float4 color = gradient_color(background, input.position.xy, bounds, - gradient.solid, gradient.color0, gradient.color1); - return float4(color.rgb * color.a * alpha, alpha * color.a); + [branch] + if (min_x <= center.x && center.x < max_x) { + float direction = curve.p1.x > curve.p0.x ? 1.0 : -1.0; + [branch] + if (curve.p1.y <= center.y - 0.5) { + winding.y -= curve.sign * direction; + } else if (curve.p0.y < center.y + 0.5) { + float t = monotone_quadratic_root(curve.a.x, curve.b.x, curve.p0.x - center.x, direction); + float y = (curve.a.y * t + curve.b.y) * t + curve.p0.y; + float distance = center.y - y; + winding.y -= curve.sign * direction * saturate(distance + 0.5); + weight.y = max(weight.y, saturate(1.0 - 2.0 * abs(distance))); + } + } } -/* -** -** Path Sprites -** -*/ - -struct PathSprite { - Bounds bounds; -}; - -struct PathSpriteVertexOutput { - float4 position: SV_Position; - float2 texture_coords: TEXCOORD0; -}; - -StructuredBuffer path_sprites: register(t1); - -PathSpriteVertexOutput path_sprite_vertex(uint vertex_id: SV_VertexID, uint sprite_id: SV_InstanceID) { - float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); - PathSprite sprite = path_sprites[sprite_id]; - - // Don't apply content mask because it was already accounted for when rasterizing the path - float4 device_position = to_device_position(unit_vertex, sprite.bounds); - - float2 screen_position = sprite.bounds.origin + unit_vertex * sprite.bounds.size; - float2 texture_coords = screen_position / global_viewport_size; - - PathSpriteVertexOutput output; - output.position = device_position; - output.texture_coords = texture_coords; - return output; +// The backdrop gives the unlisted curves' winding along a leftward ray from the tile's reference +// corner. We need it at the current pixel, along both leftward and upward rays. Because paths are +// closed, chains of unlisted curves can only begin or end where a listed curve does. So, we can +// compute the winding at the current pixel by correcting the backdrop for each listed endpoint +// between its ray and the pixel. +void correct_for_endpoint(float2 endpoint, float step, float2 reference, float2 center, + inout float2 winding) { + if (endpoint.x <= reference.x) { + winding.x -= step * (float(endpoint.y <= center.y) - float(endpoint.y <= reference.y)); + } + if (endpoint.y <= reference.y && endpoint.x <= center.x) { + winding.y += step; + } } -float4 path_sprite_fragment(PathSpriteVertexOutput input): SV_Target { - return t_sprite.Sample(s_sprite, input.texture_coords); +float4 path_tile_fragment(PathTileFragmentInput input): SV_Target { + float2 center = floor(input.position.xy) + 0.5; + if (input.background.tag == 0u + && (any(center < input.curve_box.xy) || any(center > input.curve_box.zw))) { + return input.background.color0; + } + PathTile tile = path_tiles[input.tile_id]; + PathPaint paint = path_paints[tile.paint]; + + float2 winding = float(tile.backdrop); + float2 weight = float2(0.0, 0.0); + [loop] + for (uint i = 0u; i < tile.curve_count; i++) { + PathCurve curve = path_curves[tile.curve_start + i]; + if (min(curve.p0.x, curve.p1.x) >= center.x + 0.5) { + break; + } + if (curve.p0.y < center.y + 0.5) { + add_curve_winding(curve, center, winding, weight); + correct_for_endpoint(curve.p0, curve.sign, tile.reference, center, winding); + correct_for_endpoint(curve.p1, -curve.sign, tile.reference, center, winding); + } + } + + // Weight the winding computed by each ray by its nearest crossing's distance from the pixel center, + // using Slug's technique. + float coverage = max( + abs(dot(winding, weight)) / max(weight.x + weight.y, 1.0 / 65536.0), + min(abs(winding.x), abs(winding.y))); + coverage = paint.even_odd != 0u + ? 1.0 - abs(1.0 - frac(coverage * 0.5) * 2.0) + : saturate(coverage); + + if (coverage == 0.0) { + return float4(0.0, 0.0, 0.0, 0.0); + } + + float4 color = + background_color(input.background, paint.color, paint.bounds, input.position.xy); + return float4(color.rgb, color.a * coverage); } /* @@ -1072,13 +1202,6 @@ struct Underline { uint wavy; }; -struct UnderlineVertexOutput { - nointerpolation uint underline_id: TEXCOORD0; - float4 position: SV_Position; - nointerpolation float4 color: COLOR; - float4 clip_distance: SV_ClipDistance; -}; - struct UnderlineFragmentInput { nointerpolation uint underline_id: TEXCOORD0; float4 position: SV_Position; @@ -1087,20 +1210,18 @@ struct UnderlineFragmentInput { StructuredBuffer underlines: register(t1); -UnderlineVertexOutput underline_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { +UnderlineFragmentInput underline_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); uint underline_id = batch_start_index + instance_id; Underline underline = underlines[underline_id]; - float4 device_position = to_device_position(unit_vertex, underline.bounds); - float4 clip_distance = distance_from_clip_rect(unit_vertex, underline.bounds, - underline.content_mask); + ClippedVertex vertex = clip_to_mask(unit_vertex, underline.bounds, underline.content_mask); + float4 device_position = to_device_position_impl(vertex.position); float4 color = hsla_to_rgba(underline.color); - UnderlineVertexOutput output; + UnderlineFragmentInput output; output.position = device_position; output.color = color; - output.underline_id = underline_id; - output.clip_distance = clip_distance; + output.underline_id = underline_id | (underline.wavy == 0u ? SIMPLE_PRIMITIVE_FLAG : 0u); return output; } @@ -1108,27 +1229,27 @@ float4 underline_fragment(UnderlineFragmentInput input): SV_Target { const float WAVE_FREQUENCY = 2.0; const float WAVE_HEIGHT_RATIO = 0.8; - Underline underline = underlines[input.underline_id]; - if (underline.wavy) { - float half_thickness = underline.thickness * 0.5; - float2 origin = underline.bounds.origin; - - float2 st = ((input.position.xy - origin) / underline.bounds.size.y) - float2(0., 0.5); - float frequency = (M_PI_F * WAVE_FREQUENCY * underline.thickness) / underline.bounds.size.y; - float amplitude = (underline.thickness * WAVE_HEIGHT_RATIO) / underline.bounds.size.y; - - float sine = sin(st.x * frequency) * amplitude; - float dSine = cos(st.x * frequency) * amplitude * frequency; - float distance = (st.y - sine) / sqrt(1. + dSine * dSine); - float distance_in_pixels = distance * underline.bounds.size.y; - float distance_from_top_border = distance_in_pixels - half_thickness; - float distance_from_bottom_border = distance_in_pixels + half_thickness; - float alpha = saturate( - 0.5 - max(-distance_from_bottom_border, distance_from_top_border)); - return input.color * float4(1., 1., 1., alpha); - } else { + if ((input.underline_id & SIMPLE_PRIMITIVE_FLAG) != 0u) { return input.color; } + + Underline underline = underlines[input.underline_id]; + float half_thickness = underline.thickness * 0.5; + float2 origin = underline.bounds.origin; + + float2 st = ((input.position.xy - origin) / underline.bounds.size.y) - float2(0., 0.5); + float frequency = (M_PI_F * WAVE_FREQUENCY * underline.thickness) / underline.bounds.size.y; + float amplitude = (underline.thickness * WAVE_HEIGHT_RATIO) / underline.bounds.size.y; + + float sine = sin(st.x * frequency) * amplitude; + float dSine = cos(st.x * frequency) * amplitude * frequency; + float distance = (st.y - sine) / sqrt(1. + dSine * dSine); + float distance_in_pixels = distance * underline.bounds.size.y; + float distance_from_top_border = distance_in_pixels - half_thickness; + float distance_from_bottom_border = distance_in_pixels + half_thickness; + float alpha = saturate( + 0.5 - max(-distance_from_bottom_border, distance_from_top_border)); + return input.color * float4(1., 1., 1., alpha); } /* @@ -1147,13 +1268,6 @@ struct MonochromeSprite { TransformationMatrix transformation; }; -struct MonochromeSpriteVertexOutput { - float4 position: SV_Position; - float2 tile_position: POSITION; - nointerpolation float4 color: COLOR; - float4 clip_distance: SV_ClipDistance; -}; - struct MonochromeSpriteFragmentInput { float4 position: SV_Position; float2 tile_position: POSITION; @@ -1163,7 +1277,7 @@ struct MonochromeSpriteFragmentInput { StructuredBuffer mono_sprites: register(t1); -MonochromeSpriteVertexOutput monochrome_sprite_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { +MonochromeSpriteFragmentInput monochrome_sprite_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); uint sprite_id = batch_start_index + instance_id; MonochromeSprite sprite = mono_sprites[sprite_id]; @@ -1173,7 +1287,7 @@ MonochromeSpriteVertexOutput monochrome_sprite_vertex(uint vertex_id: SV_VertexI float2 tile_position = to_tile_position(unit_vertex, sprite.tile); float4 color = hsla_to_rgba(sprite.color); - MonochromeSpriteVertexOutput output; + MonochromeSpriteFragmentInput output; output.position = device_position; output.tile_position = tile_position; output.color = color; @@ -1187,7 +1301,7 @@ float4 monochrome_sprite_fragment(MonochromeSpriteFragmentInput input): SV_Targe return float4(input.color.rgb, input.color.a * alpha_corrected); } -MonochromeSpriteVertexOutput subpixel_sprite_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { +MonochromeSpriteFragmentInput subpixel_sprite_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { return monochrome_sprite_vertex(vertex_id, instance_id); } @@ -1221,48 +1335,43 @@ struct PolychromeSprite { Corners corner_radii; }; -struct PolychromeSpriteVertexOutput { - nointerpolation uint sprite_id: TEXCOORD0; - float4 position: SV_Position; - float2 tile_position: POSITION; - float4 clip_distance: SV_ClipDistance; -}; - struct PolychromeSpriteFragmentInput { nointerpolation uint sprite_id: TEXCOORD0; float4 position: SV_Position; float2 tile_position: POSITION; + nointerpolation float opacity: TEXCOORD1; }; StructuredBuffer poly_sprites: register(t1); -PolychromeSpriteVertexOutput polychrome_sprite_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { +PolychromeSpriteFragmentInput polychrome_sprite_vertex(uint vertex_id: SV_VertexID, uint instance_id: SV_InstanceID) { float2 unit_vertex = float2(float(vertex_id & 1u), 0.5 * float(vertex_id & 2u)); uint sprite_id = batch_start_index + instance_id; PolychromeSprite sprite = poly_sprites[sprite_id]; - float4 device_position = to_device_position(unit_vertex, sprite.bounds); - float4 clip_distance = distance_from_clip_rect(unit_vertex, sprite.bounds, - sprite.content_mask); - float2 tile_position = to_tile_position(unit_vertex, sprite.tile); + ClippedVertex vertex = clip_to_mask(unit_vertex, sprite.bounds, sprite.content_mask); + float4 device_position = to_device_position_impl(vertex.position); + float2 tile_position = to_tile_position(vertex.unit_vertex, sprite.tile); - PolychromeSpriteVertexOutput output; + PolychromeSpriteFragmentInput output; output.position = device_position; output.tile_position = tile_position; - output.sprite_id = sprite_id; - output.clip_distance = clip_distance; + bool simple = !has_rounded_corners(sprite.corner_radii) && sprite.grayscale == 0u; + output.sprite_id = sprite_id | (simple ? SIMPLE_PRIMITIVE_FLAG : 0u); + output.opacity = sprite.opacity; return output; } float4 polychrome_sprite_fragment(PolychromeSpriteFragmentInput input): SV_Target { - PolychromeSprite sprite = poly_sprites[input.sprite_id]; - float4 sample = t_sprite.Sample(s_sprite, input.tile_position); - float distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii); - - float4 color = sample; - if (sprite.grayscale != 0u) { - float3 grayscale = dot(color.rgb, GRAYSCALE_FACTORS); - color = float4(grayscale, sample.a); + float4 color = t_sprite.Sample(s_sprite, input.tile_position); + if ((input.sprite_id & SIMPLE_PRIMITIVE_FLAG) != 0u) { + return float4(color.rgb, color.a * input.opacity); } - color.a *= sprite.opacity * saturate(0.5 - distance); + + PolychromeSprite sprite = poly_sprites[input.sprite_id]; + if (sprite.grayscale != 0u) { + color.rgb = dot(color.rgb, GRAYSCALE_FACTORS); + } + float distance = quad_sdf(input.position.xy, sprite.bounds, sprite.corner_radii); + color.a *= input.opacity * saturate(0.5 - distance); return color; } diff --git a/crates/language/src/outline.rs b/crates/language/src/outline.rs index 536fd3b91c5..7075ca50169 100644 --- a/crates/language/src/outline.rs +++ b/crates/language/src/outline.rs @@ -1,5 +1,5 @@ use crate::{BufferSnapshot, Language, Point, ToPoint, ToTreeSitterPoint}; -use fuzzy_nucleo::{Case, LengthPenalty, StringMatch, StringMatchCandidate}; +use fuzzy_nucleo::{MaxResults, StringMatch, StringMatchCandidate, StringMatchOptions}; use gpui::{BackgroundExecutor, HighlightStyle, SharedString}; use std::{ops::Range, sync::Arc}; use theme::SyntaxTheme; @@ -215,10 +215,10 @@ impl Outline { let mut matches = fuzzy_nucleo::match_strings_async( &self.candidates, query, - Case::Smart, - LengthPenalty::On, - 100, - &Default::default(), + StringMatchOptions { + max_results: MaxResults::limit::<100>(), + ..Default::default() + }, executor, ) .await; diff --git a/crates/language_model/src/language_model.rs b/crates/language_model/src/language_model.rs index 050f07b44c5..bdd8b0fabd1 100644 --- a/crates/language_model/src/language_model.rs +++ b/crates/language_model/src/language_model.rs @@ -468,6 +468,7 @@ pub trait LanguageModelClient: 'static { Ok(LanguageModelCompletionEvent::Thinking { .. }) => None, Ok(LanguageModelCompletionEvent::RedactedThinking { .. }) => None, Ok(LanguageModelCompletionEvent::ReasoningDetails(_)) => None, + Ok(LanguageModelCompletionEvent::InputTransformations(_)) => None, Ok(LanguageModelCompletionEvent::Stop(_)) => None, Ok(LanguageModelCompletionEvent::ToolUse(_)) => None, Ok(LanguageModelCompletionEvent::ToolUseJsonParseError { diff --git a/crates/language_model_core/src/language_model_core.rs b/crates/language_model_core/src/language_model_core.rs index 7f033a6c0cf..5da3d25c0b9 100644 --- a/crates/language_model_core/src/language_model_core.rs +++ b/crates/language_model_core/src/language_model_core.rs @@ -66,6 +66,20 @@ pub enum LanguageModelCompletionEvent { ReasoningDetails(serde_json::Value), UsageUpdate(TokenUsage), Compaction(CompactionUpdate), + /// Transformations the provider applied or flagged while processing the request. + InputTransformations(Vec), +} + +/// A provider-reported transformation or mismatch affecting request content. +#[derive(Debug, PartialEq, Eq, Clone, Serialize, Deserialize)] +pub struct InputTransformation { + /// Provider-specific transformation type, including unrecognized future types. + #[serde(rename = "type")] + pub kind: String, + /// Provider-specific location, such as `messages.1.content.0`. + pub path: String, + /// Provider-specific reason, such as `prefix_binding_mismatch`. + pub reason: String, } #[derive(Debug, PartialEq, Clone, Serialize, Deserialize)] diff --git a/crates/language_models/src/provider/llama_cpp.rs b/crates/language_models/src/provider/llama_cpp.rs index 28962f77e3c..bd589c3058b 100644 --- a/crates/language_models/src/provider/llama_cpp.rs +++ b/crates/language_models/src/provider/llama_cpp.rs @@ -133,7 +133,7 @@ impl State { log::warn!("failed to load llama.cpp API key: {error}"); } } - let fetch_models_task = this.update(cx, |this, cx| this.fetch_models(cx))?; + let fetch_models_task = this.update(cx, |this, cx| this.start_fetch_models(cx))?; match fetch_models_task.await { Ok(()) => Ok(()), Err(err) => { @@ -267,6 +267,12 @@ impl State { self.model_event_task = Some(cx.spawn(async move |this, cx| { loop { + if this + .update(cx, |_, cx| crate::ai_disabled(cx)) + .unwrap_or(true) + { + return; + } match stream_model_events( http_client.as_ref(), &api_url, @@ -327,15 +333,19 @@ impl State { cx.background_executor() .timer(MODEL_EVENT_RECONNECT_INTERVAL) .await; - if this.update(cx, |_, _| ()).is_err() { - return; - } } })); } - fn restart_fetch_models_task(&mut self, cx: &mut Context) { + fn start_fetch_models(&mut self, cx: &mut Context) -> Task> { + if crate::ai_disabled(cx) { + self.fetch_model_task = None; + self.model_event_task = None; + return Task::ready(Ok(())); + } + let fetch_task = self.fetch_models(cx); + let (result_tx, result_rx) = futures::channel::oneshot::channel(); let task = cx.spawn(async move |this, cx| { let result = fetch_task.await; this.update(cx, |this, _cx| { @@ -343,9 +353,19 @@ impl State { result.as_ref().err().map(|error| format!("{error:#}")); }) .ok(); - result.log_err(); + if let Err(result) = result_tx.send(result) { + result.log_err(); + } }); self.fetch_model_task.replace(task); + + cx.spawn(async move |_this, _cx| result_rx.await.unwrap_or(Ok(()))) + } + + fn restart_fetch_models_task(&mut self, cx: &mut Context) { + let result = self.start_fetch_models(cx); + cx.spawn(async move |_this, _cx| result.await.log_err()) + .detach(); } } @@ -476,6 +496,7 @@ impl LlamaCppLanguageModelProvider { state: cx.new(|cx| { cx.observe_global::({ let mut last_settings = LlamaCppLanguageModelProvider::settings(cx).clone(); + let mut last_disable_ai = crate::ai_disabled(cx); move |this: &mut State, cx| { let current_settings = LlamaCppLanguageModelProvider::settings(cx); let settings_changed = current_settings != &last_settings; @@ -500,6 +521,11 @@ impl LlamaCppLanguageModelProvider { } cx.notify(); } + let disable_ai = crate::ai_disabled(cx); + if disable_ai != last_disable_ai { + last_disable_ai = disable_ai; + this.restart_fetch_models_task(cx); + } } }) .detach(); @@ -1924,6 +1950,242 @@ mod tests { assert!(pending_credentials.is_canceled()); } + #[gpui::test] + async fn does_not_fetch_models_when_ai_is_disabled(cx: &mut TestAppContext) { + cx.update(|cx| { + let mut store = SettingsStore::test(cx); + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(true.into()); + }); + cx.set_global(store); + }); + + let request_count = Arc::new(AtomicUsize::new(0)); + let (release_first_fetch, first_fetch_released) = futures::channel::oneshot::channel(); + let first_fetch_released = Arc::new(Mutex::new(Some(first_fetch_released))); + let http_client = FakeHttpClient::create({ + let request_count = request_count.clone(); + move |request| { + request_count.fetch_add(1, Ordering::SeqCst); + let first_fetch_released = first_fetch_released.clone(); + async move { + let first_fetch_released = first_fetch_released.lock().take(); + if let Some(first_fetch_released) = first_fetch_released { + first_fetch_released.await.ok(); + } + let (status, body) = match request.uri().path() { + "/v1/models" => (200, r#"{"data":[{"id":"test-model"}]}"#), + "/props" => (200, "{}"), + path => anyhow::bail!("unexpected request: {path}"), + }; + Ok(http_client::Response::builder() + .status(status) + .body(http_client::AsyncBody::from(body))?) + } + } + }); + let provider = cx.update(|cx| { + LlamaCppLanguageModelProvider::new( + http_client, + Arc::new(FakeCredentialsProvider::default()), + cx, + ) + }); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 0); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(false.into()); + }); + }); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 1); + assert!(cx.update(|cx| provider.provided_models(cx)).is_empty()); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(true.into()); + }); + }); + cx.run_until_parked(); + release_first_fetch.send(()).ok(); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 1); + assert!(cx.update(|cx| provider.provided_models(cx)).is_empty()); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(false.into()); + }); + }); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 3); + assert_eq!( + cx.update(|cx| provider + .provided_models(cx) + .into_iter() + .map(|model| model.id.0.to_string()) + .collect::>()), + ["test-model"] + ); + } + + #[gpui::test] + async fn disables_model_event_stream_when_ai_is_disabled(cx: &mut TestAppContext) { + cx.update(|cx| { + let store = SettingsStore::test(cx); + cx.set_global(store); + }); + + let model_event_request_count = Arc::new(AtomicUsize::new(0)); + let (release_event_stream, event_stream_released) = futures::channel::oneshot::channel(); + let event_stream_released = Arc::new(Mutex::new(Some(event_stream_released))); + let http_client = FakeHttpClient::create({ + let model_event_request_count = model_event_request_count.clone(); + move |request| { + let model_event_request_count = model_event_request_count.clone(); + let event_stream_released = event_stream_released.clone(); + async move { + if request.uri().path() == "/models/sse" { + model_event_request_count.fetch_add(1, Ordering::SeqCst); + let event_stream_released = event_stream_released.lock().take(); + if let Some(event_stream_released) = event_stream_released { + event_stream_released.await.ok(); + } + } + let (status, body) = match request.uri().path() { + "/v1/models" => ( + 200, + r#"{"data":[{"id":"test-model","status":{"value":"loaded"}}]}"#, + ), + "/props" => (200, "{}"), + "/models/sse" => (200, ""), + path => anyhow::bail!("unexpected request: {path}"), + }; + Ok(http_client::Response::builder() + .status(status) + .body(http_client::AsyncBody::from(body))?) + } + } + }); + let provider = cx.update(|cx| { + LlamaCppLanguageModelProvider::new( + http_client, + Arc::new(FakeCredentialsProvider::default()), + cx, + ) + }); + cx.run_until_parked(); + assert_eq!( + cx.update(|cx| provider + .provided_models(cx) + .into_iter() + .map(|model| model.id.0.to_string()) + .collect::>()), + ["test-model"] + ); + assert_eq!(model_event_request_count.load(Ordering::SeqCst), 1); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(true.into()); + }); + }); + cx.run_until_parked(); + release_event_stream.send(()).ok(); + cx.run_until_parked(); + assert_eq!(model_event_request_count.load(Ordering::SeqCst), 1); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(false.into()); + }); + }); + cx.run_until_parked(); + assert_eq!(model_event_request_count.load(Ordering::SeqCst), 2); + } + + #[gpui::test] + async fn authenticate_does_not_fetch_models_when_ai_is_disabled(cx: &mut TestAppContext) { + cx.update(|cx| { + let mut store = SettingsStore::test(cx); + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(true.into()); + }); + cx.set_global(store); + }); + + let request_count = Arc::new(AtomicUsize::new(0)); + let (release_fetch, fetch_released) = futures::channel::oneshot::channel(); + let fetch_released = Arc::new(Mutex::new(Some(fetch_released))); + let http_client = FakeHttpClient::create({ + let request_count = request_count.clone(); + move |request| { + request_count.fetch_add(1, Ordering::SeqCst); + let fetch_released = fetch_released.clone(); + async move { + let fetch_released = fetch_released.lock().take(); + if let Some(fetch_released) = fetch_released { + fetch_released.await.ok(); + } + let (status, body) = match request.uri().path() { + "/v1/models" => (200, r#"{"data":[{"id":"test-model"}]}"#), + "/props" => (200, "{}"), + path => anyhow::bail!("unexpected request: {path}"), + }; + Ok(http_client::Response::builder() + .status(status) + .body(http_client::AsyncBody::from(body))?) + } + } + }); + let credentials_provider = Arc::new(FakeCredentialsProvider::default()); + credentials_provider + .state + .lock() + .keys + .insert(LLAMA_CPP_API_URL.to_string(), b"loaded-key".to_vec()); + let provider = cx + .update(|cx| LlamaCppLanguageModelProvider::new(http_client, credentials_provider, cx)); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 0); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings + .language_models + .get_or_insert_default() + .llama_cpp + .get_or_insert_default() + .api_url = Some("http://localhost:9999".to_string()); + }); + }); + cx.run_until_parked(); + cx.update(|cx| provider.authenticate(cx)).await.ok(); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 0); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(false.into()); + }); + }); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 1); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(true.into()); + }); + }); + cx.run_until_parked(); + release_fetch.send(()).ok(); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 1); + assert!(cx.update(|cx| provider.provided_models(cx)).is_empty()); + } + #[gpui::test] async fn authenticate_fetches_models_after_loading_api_key(cx: &mut TestAppContext) { cx.update(|cx| { diff --git a/crates/language_models/src/provider/lmstudio.rs b/crates/language_models/src/provider/lmstudio.rs index 4712c9075ee..7f422828e7f 100644 --- a/crates/language_models/src/provider/lmstudio.rs +++ b/crates/language_models/src/provider/lmstudio.rs @@ -123,8 +123,14 @@ impl State { }) } - fn restart_fetch_models_task(&mut self, cx: &mut Context) { + fn start_fetch_models(&mut self, cx: &mut Context) -> Task> { + if crate::ai_disabled(cx) { + self.fetch_model_task = None; + return Task::ready(Ok(())); + } + let fetch_task = self.fetch_models(cx); + let (result_tx, result_rx) = futures::channel::oneshot::channel(); let task = cx.spawn(async move |this, cx| { let result = fetch_task.await; this.update(cx, |this, _cx| { @@ -132,9 +138,19 @@ impl State { result.as_ref().err().map(|error| format!("{error:#}")); }) .ok(); - result.log_err(); + if let Err(result) = result_tx.send(result) { + result.log_err(); + } }); self.fetch_model_task.replace(task); + + cx.spawn(async move |_this, _cx| result_rx.await.unwrap_or(Ok(()))) + } + + fn restart_fetch_models_task(&mut self, cx: &mut Context) { + let result = self.start_fetch_models(cx); + cx.spawn(async move |_this, _cx| result.await.log_err()) + .detach(); } fn authenticate(&mut self, cx: &mut Context) -> Task> { @@ -153,7 +169,7 @@ impl State { cx.spawn(async move |state, cx| { load_key.await?; - let fetch_models_task = state.update(cx, |state, cx| state.fetch_models(cx))?; + let fetch_models_task = state.update(cx, |state, cx| state.start_fetch_models(cx))?; match fetch_models_task.await { Ok(()) => Ok(()), Err(err) => { @@ -191,6 +207,7 @@ impl LmStudioLanguageModelProvider { state: cx.new(|cx| { let subscription = cx.observe_global::({ let mut settings = AllLanguageModelSettings::get_global(cx).lmstudio.clone(); + let mut old_disable_ai = crate::ai_disabled(cx); move |this: &mut State, cx| { let new_settings = AllLanguageModelSettings::get_global(cx).lmstudio.clone(); @@ -207,6 +224,11 @@ impl LmStudioLanguageModelProvider { this.restart_fetch_models_task(cx); cx.notify(); } + let new_disable_ai = crate::ai_disabled(cx); + if new_disable_ai != old_disable_ai { + old_disable_ai = new_disable_ai; + this.restart_fetch_models_task(cx); + } } }); @@ -920,6 +942,8 @@ mod tests { use credentials_provider::test_support::FakeCredentialsProvider; use gpui::TestAppContext; use http_client::{AsyncBody, FakeHttpClient, Response}; + use parking_lot::Mutex; + use std::sync::atomic::{AtomicUsize, Ordering}; #[gpui::test] async fn enabling_ai_discovers_models_with_stored_credentials(cx: &mut TestAppContext) { @@ -985,6 +1009,146 @@ mod tests { credentials.assert_reads(&[LMSTUDIO_API_URL]); } + #[gpui::test] + async fn authenticate_does_not_fetch_models_when_ai_is_disabled(cx: &mut TestAppContext) { + cx.update(|cx| { + let mut store = SettingsStore::test(cx); + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(true.into()); + }); + cx.set_global(store); + }); + + let request_count = Arc::new(AtomicUsize::new(0)); + let (release_fetch, fetch_released) = futures::channel::oneshot::channel(); + let fetch_released = Arc::new(Mutex::new(Some(fetch_released))); + let http_client = FakeHttpClient::create({ + let request_count = request_count.clone(); + move |_request| { + request_count.fetch_add(1, Ordering::SeqCst); + let fetch_released = fetch_released.clone(); + async move { + let fetch_released = fetch_released.lock().take(); + if let Some(fetch_released) = fetch_released { + fetch_released.await.ok(); + } + Ok(Response::builder().status(200).body(AsyncBody::from( + r#"{"data":[{"id":"test-model","object":"model","type":"llm","publisher":"test","compatibility_type":"gguf","state":"loaded"}]}"#, + ))?) + } + } + }); + let credentials_provider = Arc::new(FakeCredentialsProvider::default()); + credentials_provider + .state + .lock() + .keys + .insert(LMSTUDIO_API_URL.to_string(), b"stored-key".to_vec()); + let provider = cx + .update(|cx| LmStudioLanguageModelProvider::new(http_client, credentials_provider, cx)); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 0); + + cx.update(|cx| provider.authenticate(cx)).await.ok(); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 0); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(false.into()); + }); + }); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 1); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(true.into()); + }); + }); + cx.run_until_parked(); + release_fetch.send(()).ok(); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 1); + assert!(cx.update(|cx| provider.provided_models(cx)).is_empty()); + } + + #[gpui::test] + async fn does_not_fetch_models_when_ai_is_disabled(cx: &mut TestAppContext) { + cx.update(|cx| { + let mut store = SettingsStore::test(cx); + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(true.into()); + }); + cx.set_global(store); + }); + + let request_count = Arc::new(AtomicUsize::new(0)); + let (release_first_fetch, first_fetch_released) = futures::channel::oneshot::channel(); + let first_fetch_released = Arc::new(Mutex::new(Some(first_fetch_released))); + let http_client = FakeHttpClient::create({ + let request_count = request_count.clone(); + move |_request| { + request_count.fetch_add(1, Ordering::SeqCst); + let first_fetch_released = first_fetch_released.clone(); + async move { + let first_fetch_released = first_fetch_released.lock().take(); + if let Some(first_fetch_released) = first_fetch_released { + first_fetch_released.await.ok(); + } + Ok(Response::builder().status(200).body(AsyncBody::from( + r#"{"data":[{"id":"test-model","object":"model","type":"llm","publisher":"test","compatibility_type":"gguf","state":"loaded"}]}"#, + ))?) + } + } + }); + let provider = cx.update(|cx| { + LmStudioLanguageModelProvider::new( + http_client, + Arc::new(FakeCredentialsProvider::default()), + cx, + ) + }); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 0); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(false.into()); + }); + }); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 1); + assert!(cx.update(|cx| provider.provided_models(cx)).is_empty()); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(true.into()); + }); + }); + cx.run_until_parked(); + release_first_fetch.send(()).ok(); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 1); + assert!(cx.update(|cx| provider.provided_models(cx)).is_empty()); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.project.disable_ai = Some(false.into()); + }); + }); + cx.run_until_parked(); + assert_eq!(request_count.load(Ordering::SeqCst), 2); + assert_eq!( + cx.update(|cx| provider + .provided_models(cx) + .into_iter() + .map(|model| model.id.0.to_string()) + .collect::>()), + ["test-model"] + ); + } + #[gpui::test] async fn restart_fetch_models_task_records_error_on_failure(cx: &mut TestAppContext) { cx.update(|cx| { diff --git a/crates/language_models/src/provider/open_router.rs b/crates/language_models/src/provider/open_router.rs index 9d71eecc277..353c92297d1 100644 --- a/crates/language_models/src/provider/open_router.rs +++ b/crates/language_models/src/provider/open_router.rs @@ -464,7 +464,8 @@ pub fn into_open_router( // we need this distinction, we're just using this less invasive check instead. // If we ever have a more formal distionction between the models in the future, // we should revise this to use that instead. - let is_anthropic_model = model.id().starts_with("anthropic/"); + // OpenRouter aliases are prefixed with `~` (e.g. `~anthropic/claude-sonnet-latest`). + let is_anthropic_model = model.id().trim_start_matches('~').starts_with("anthropic/"); let session_id = open_router_session_id(request.thread_id); let mut messages = Vec::new(); @@ -1111,6 +1112,83 @@ mod tests { } } + #[gpui::test] + async fn test_anthropic_alias_model_uses_anthropic_request_handling() { + let model = open_router::Model::new( + "~anthropic/claude-sonnet-latest", + None, + Some(200000), + Some(true), + Some(false), + None, + None, + None, + false, + None, + ); + + let request = LanguageModelRequest { + messages: vec![ + language_model::LanguageModelRequestMessage { + role: Role::System, + content: vec![MessageContent::Text("You are helpful.".to_string())], + cache: false, + reasoning_details: None, + }, + language_model::LanguageModelRequestMessage { + role: Role::Assistant, + content: vec![MessageContent::Text("Hi there!".to_string())], + cache: false, + reasoning_details: Some(Arc::new(serde_json::json!([{ + "type": "reasoning.text" + }]))), + }, + language_model::LanguageModelRequestMessage { + role: Role::User, + content: vec![MessageContent::Text("What is 2+2?".to_string())], + cache: true, + reasoning_details: None, + }, + ], + ..Default::default() + }; + + let result = into_open_router(request, &model, None).unwrap(); + + let has_cache_control = result.messages.iter().any(|message| match message { + open_router::RequestMessage::System { + content: open_router::MessageContent::Multipart(parts), + } + | open_router::RequestMessage::User { + content: open_router::MessageContent::Multipart(parts), + } => parts.iter().any(|part| { + matches!( + part, + open_router::MessagePart::Text { + cache_control: Some(_), + .. + } + ) + }), + _ => false, + }); + assert!(has_cache_control, "Alias should get cache_control"); + + let echoes_reasoning_details = result.messages.iter().any(|message| { + matches!( + message, + open_router::RequestMessage::Assistant { + reasoning_details: Some(_), + .. + } + ) + }); + assert!( + !echoes_reasoning_details, + "Alias should not echo reasoning_details back" + ); + } + #[gpui::test] async fn test_into_open_router_sends_requested_effort() { let model = open_router::Model::new( diff --git a/crates/markdown/src/markdown.rs b/crates/markdown/src/markdown.rs index 7335744ddbd..466d5dab2c3 100644 --- a/crates/markdown/src/markdown.rs +++ b/crates/markdown/src/markdown.rs @@ -8189,37 +8189,43 @@ mod tests { }); cx.run_until_parked(); cx.update(|window, cx| { + // Quads are drawn in this order: by draw order, then in paint + // order. At an equal draw order, quads are drawn before underlines. let quads = window.painted_quads(); let selection_bounds = quads .iter() .find(|quad| quad.background == Background::from(gpui::red())) .expect("selection is painted") .bounds; - let order_for_color = |color| { - let orders = quads + // A quad can be painted as several pieces. + let positions_for_color = |color| { + let positions = quads .iter() - .filter(|quad| { + .enumerate() + .filter(|(_, quad)| { quad.background == Background::from(color) && quad.bounds.intersects(&selection_bounds) }) - .map(|quad| quad.order) + .map(|(position, _)| position) .collect::>(); - assert_eq!(orders.len(), 1); - orders[0] + let first = *positions.first().expect("quad is painted"); + let last = *positions.last().expect("quad is painted"); + first..=last }; - let chip_order = order_for_color(gpui::green()); - let search_order = order_for_color(cx.theme().colors().search_match_background); - let selection_order = order_for_color(gpui::red()); + let chip = positions_for_color(gpui::green()); + let search = positions_for_color(cx.theme().colors().search_match_background); + let selection = positions_for_color(gpui::red()); + let selection_order = quads[*selection.end()].order; let text_order = window .painted_underlines() .iter() .map(|underline| underline.order) .min() .expect("strikethrough is painted"); - assert!(chip_order < search_order); - assert!(search_order < selection_order); + assert!(chip.end() < search.start()); + assert!(search.end() < selection.start()); assert!( - selection_order < text_order, + selection_order <= text_order, "alignment={alignment}, text={text}, selection={selection_order}, glyphs={text_order}", ); }); @@ -8259,17 +8265,22 @@ mod tests { let highlight_color = cx.update(|_, cx| cx.theme().colors().search_match_background); cx.update(|window, _| { + // Quads are drawn in this order: by draw order, then in paint order. + // At an equal draw order, quads are drawn before underlines. let quads = window.painted_quads(); - let order_of_quad_with = |color: Hsla| { - quads - .iter() - .find(|quad| quad.background == color.into()) - .map(|quad| quad.order) - }; - let run_background_order = - order_of_quad_with(run_background_color).expect("link background should be painted"); - let highlight_order = - order_of_quad_with(highlight_color).expect("search highlight should be painted"); + let has_color = |color: Hsla| move |quad: &gpui::Quad| quad.background == color.into(); + let last_run_background = quads + .iter() + .rposition(has_color(run_background_color)) + .expect("link background should be painted"); + let first_highlight = quads + .iter() + .position(has_color(highlight_color)) + .expect("search highlight should be painted"); + let last_highlight = quads + .iter() + .rposition(has_color(highlight_color)) + .expect("search highlight should be painted"); // Strikethroughs are painted in the same layer as the glyphs let text_order = window .painted_underlines() @@ -8278,11 +8289,11 @@ mod tests { .min() .expect("strikethrough should be painted"); assert!( - run_background_order < highlight_order, + last_run_background < first_highlight, "text run backgrounds must not cover search highlights" ); assert!( - highlight_order < text_order, + quads[last_highlight].order <= text_order, "search highlight must be drawn below the text, otherwise opaque theme colors hide it" ); }); diff --git a/crates/markdown/src/mermaid.rs b/crates/markdown/src/mermaid.rs index be986540948..12553461555 100644 --- a/crates/markdown/src/mermaid.rs +++ b/crates/markdown/src/mermaid.rs @@ -224,8 +224,11 @@ impl CachedMermaidDiagram { async move |this, cx| { let value = cx .background_spawn(async move { - let svg_string = - mermaid_render::render_to_svg(&contents.contents, &mermaid_theme)?; + let svg_string = mermaid_render::render_to_svg( + &contents.contents, + &mermaid_theme, + &svg_renderer, + )?; let tree = svg_renderer .parse_svg(svg_string.as_bytes()) .map_err(|error| anyhow::anyhow!("{error}"))?; @@ -344,27 +347,6 @@ impl CachedMermaidDiagram { } } -/// Merman has somewhat limited text measurement capabilities. -/// -/// When it doesn't have metrics for any of the specified fonts, it chooses a -/// fairly narrow width, which causes visible overflow. Adding `sans-serif` -/// allows it to fall back to a more conservative (i.e. wider) measurement. -/// -/// This isn't perfect - very wide fonts will likely still cause overflow. A -/// proper fix would involve somehow piping `resvg`'s actual measurements into -/// `merman`, but that is a lot of work for a fairly uncommon edge case. -fn mermaid_font_family(font_family: &str) -> String { - let font_family = gpui::font_name_with_fallbacks(font_family, "system-ui"); - if font_family - .split(',') - .any(|family| family.trim().eq_ignore_ascii_case("sans-serif")) - { - font_family.to_string() - } else { - format!("{font_family}, sans-serif") - } -} - fn build_mermaid_theme(cx: &Context) -> mermaid_render::MermaidTheme { let colors = cx.theme().colors(); let theme_settings = ThemeSettings::get_global(cx); @@ -376,7 +358,11 @@ fn build_mermaid_theme(cx: &Context) -> mermaid_render::MermaidTheme { mermaid_render::MermaidTheme { dark_mode: is_dark, - font_family: mermaid_font_family(theme_settings.mermaid_font_family().as_ref()), + font_family: gpui::font_name_with_fallbacks( + theme_settings.mermaid_font_family().as_ref(), + "system-ui", + ) + .to_string(), background: colors.editor_background, primary_color: colors.surface_background, primary_text_color: colors.text, @@ -1117,31 +1103,6 @@ mod tests { .map(|(image, _)| image) } - #[test] - fn test_mermaid_font_family_resolves_zed_virtual_fonts() { - assert_eq!( - super::mermaid_font_family(".ZedSans"), - "IBM Plex Sans, sans-serif" - ); - assert_eq!( - super::mermaid_font_family("Zed Plex Sans"), - "IBM Plex Sans, sans-serif" - ); - assert_eq!(super::mermaid_font_family(".ZedMono"), "Lilex, sans-serif"); - assert_eq!( - super::mermaid_font_family(".SystemUIFont"), - "system-ui, sans-serif" - ); - assert_eq!( - super::mermaid_font_family("Custom Font"), - "Custom Font, sans-serif" - ); - assert_eq!( - super::mermaid_font_family("Custom Font, sans-serif"), - "Custom Font, sans-serif" - ); - } - #[test] fn test_parse_mermaid_info() { assert_eq!(parse_mermaid_info("mermaid"), Some(100)); diff --git a/crates/mermaid_render/Cargo.toml b/crates/mermaid_render/Cargo.toml index e0f79eee254..cc8248628d2 100644 --- a/crates/mermaid_render/Cargo.toml +++ b/crates/mermaid_render/Cargo.toml @@ -19,6 +19,19 @@ test-support = [] anyhow.workspace = true gpui.workspace = true merman = { workspace = true, features = [ + "diagram-class", + "diagram-er", + "diagram-flowchart", + "diagram-gantt", + "diagram-git-graph", + "diagram-journey", + "diagram-mindmap", + "diagram-pie", + "diagram-quadrant-chart", + "diagram-sequence", + "diagram-state", + "diagram-timeline", + "diagram-xychart", "layout-cytoscape", "svg", ] } @@ -28,6 +41,7 @@ tracing.workspace = true ztracing.workspace = true [dev-dependencies] +assets.workspace = true gpui = { workspace = true, features = ["test-support"] } mermaid_render = { workspace = true, features = ["test-support"] } usvg.workspace = true diff --git a/crates/mermaid_render/src/mermaid_render.rs b/crates/mermaid_render/src/mermaid_render.rs index 9550c2646ad..c0bd53673a0 100644 --- a/crates/mermaid_render/src/mermaid_render.rs +++ b/crates/mermaid_render/src/mermaid_render.rs @@ -23,8 +23,7 @@ //! `` and CSS/attribute forms that rasterizers do not handle. //! Since merman 0.6, that generic cleanup is exposed as merman's raster-safe SVG //! pipeline. Zed opts into that pipeline during rendering, then keeps -//! editor-specific theme and accent color rules in this crate. The [`gpui`] -//! dependency is only needed for the [`Hsla`] and [`Rgba`] color types. +//! editor-specific theme and accent color rules in this crate. //! //! The [`render_to_svg`] function operates in two stages: //! - [`render`] the mermaid text to raster-safe SVG using [`merman`]. @@ -67,7 +66,7 @@ mod postprocess; mod render; use anyhow::Result; -use gpui::{Hsla, Rgba}; +use gpui::{Hsla, Rgba, SvgRenderer}; #[derive(Debug, Clone, Copy)] pub struct AccentColor { @@ -176,8 +175,12 @@ pub use postprocess::util::text_color_for_background; /// See the [module-level docs][crate] for more info. #[ztracing::instrument(skip_all)] -pub fn render_to_svg(source: &str, theme: &MermaidTheme) -> Result { - let svg = render::render_mermaid(source, theme)?; +pub fn render_to_svg( + source: &str, + theme: &MermaidTheme, + svg_renderer: &SvgRenderer, +) -> Result { + let svg = render::render_mermaid(source, theme, svg_renderer)?; let svg = postprocess::postprocess(&svg, theme)?; Ok(svg) } @@ -195,7 +198,7 @@ mod tests { let zalgo = "Ne\u{0301}\u{0302}\u{0303}\u{0304}\u{0306}\u{0307}\u{0308}\u{030a}d"; let source = format!("flowchart TD\n A[\"**{zalgo}** {zalgo}\"]"); - let svg = render_to_svg(&source, &MermaidTheme::default()) + let svg = render_to_svg(&source, &MermaidTheme::default(), &svg_renderer()) .expect("mermaid diagram should render to SVG"); let mut db = usvg::fontdb::Database::new(); @@ -217,7 +220,7 @@ mod tests { #[test] fn er_multibyte_attribute_does_not_crash() { let source = "erDiagram\n顧客 {\n 文字列 名前\n}"; - let _ = render_to_svg(source, &MermaidTheme::default()); + let _ = render_to_svg(source, &MermaidTheme::default(), &svg_renderer()); } /// A flowchart with mutually nested subgraphs (`A` contains `B` and `B` @@ -226,7 +229,7 @@ mod tests { #[test] fn cyclic_subgraphs_do_not_crash() { let source = "flowchart TD\n subgraph A\n B\n end\n subgraph B\n A\n end"; - let result = render_to_svg(source, &MermaidTheme::default()); + let result = render_to_svg(source, &MermaidTheme::default(), &svg_renderer()); if let Err(err) = result { let message = format!("{err:#}"); assert!( @@ -235,4 +238,8 @@ mod tests { ); } } + + fn svg_renderer() -> SvgRenderer { + SvgRenderer::new(std::sync::Arc::new(())) + } } diff --git a/crates/mermaid_render/src/postprocess/accent_colors.rs b/crates/mermaid_render/src/postprocess/accent_colors.rs index 6cd72acea87..6f5689be5f7 100644 --- a/crates/mermaid_render/src/postprocess/accent_colors.rs +++ b/crates/mermaid_render/src/postprocess/accent_colors.rs @@ -231,7 +231,7 @@ fn detect_diagram_type(e: &BytesStart<'_>) -> DiagramType { for token in class.split_whitespace() { match token { "flowchart" => return DiagramType::Flowchart, - "mindmap" => return DiagramType::Mindmap, + "mindmap" | "mindmapDiagram" => return DiagramType::Mindmap, "classDiagram" => return DiagramType::ClassDiagram, "statediagram" => return DiagramType::StateDiagram, "journey" => return DiagramType::Unhandled, diff --git a/crates/mermaid_render/src/postprocess/accent_colors/class_diagram.rs b/crates/mermaid_render/src/postprocess/accent_colors/class_diagram.rs index 1893e3aee24..02ab80147f1 100644 --- a/crates/mermaid_render/src/postprocess/accent_colors/class_diagram.rs +++ b/crates/mermaid_render/src/postprocess/accent_colors/class_diagram.rs @@ -1,3 +1,5 @@ +use std::collections::HashMap; + use anyhow::Result; use quick_xml::XmlVersion; use quick_xml::events::Event; @@ -13,6 +15,8 @@ pub(crate) struct ClassDiagramAccents { node_counter: usize, nodes: NodeTracker, current_text_accent: Option, + label_accents: HashMap>, + label_definition_depth: Option, } impl ClassDiagramAccents { @@ -23,6 +27,8 @@ impl ClassDiagramAccents { node_counter: 0, nodes: NodeTracker::default(), current_text_accent: None, + label_accents: HashMap::new(), + label_definition_depth: None, } } @@ -38,6 +44,21 @@ impl ClassDiagramAccents { return Ok(event); } + let label_accent = match e.try_get_attribute("id")? { + Some(id) => self + .label_accents + .remove(id.normalized_value(XmlVersion::Implicit1_0)?.as_ref()), + None => None, + }; + if let Some(label_accent) = label_accent { + self.accent_g_stack.push(match label_accent { + Some(accent_idx) => AccentStackEntry::accent(accent_idx, false), + None => AccentStackEntry::none(), + }); + self.label_definition_depth = Some(self.accent_g_stack.len()); + return Ok(event); + } + let is_node = if let Some(class_attr) = e.try_get_attribute("class")? { let class = class_attr.normalized_value(XmlVersion::Implicit1_0)?; class @@ -69,6 +90,9 @@ impl ClassDiagramAccents { } Event::End(e) if e.name().as_ref() == b"g" => { + if self.label_definition_depth == Some(self.accent_g_stack.len()) { + self.label_definition_depth = None; + } if let Some(entry) = self.accent_g_stack.pop() { if entry.tracks_node() { self.nodes.maybe_finish_node(); @@ -77,6 +101,19 @@ impl ClassDiagramAccents { Ok(event) } + Event::Start(e) | Event::Empty(e) if e.name().as_ref() == b"use" => { + if let Some(href) = e.try_get_attribute("href")? { + let href = href.normalized_value(XmlVersion::Implicit1_0)?; + if let Some(id) = href.strip_prefix('#') { + self.label_accents.insert( + id.to_string(), + super::current_stack_accent(&self.accent_g_stack), + ); + } + } + Ok(event) + } + Event::Start(e) | Event::Empty(e) if matches!( e.name().as_ref(), @@ -96,12 +133,14 @@ impl ClassDiagramAccents { let is_start = matches!(event, Event::Start(_)); let is_text = e.name().as_ref() == b"text"; - let accent_idx = if is_text { + let accent_idx = if !is_text { + self.current_text_accent + } else if self.label_definition_depth.is_some() { + super::current_stack_accent(&self.accent_g_stack) + } else { self.nodes .lookup_accent(e) .or_else(|| super::current_stack_accent(&self.accent_g_stack)) - } else { - self.current_text_accent }; if let Some(idx) = accent_idx { diff --git a/crates/mermaid_render/src/postprocess/accent_colors/mindmap.rs b/crates/mermaid_render/src/postprocess/accent_colors/mindmap.rs index b978c8afd03..a56a68afed3 100644 --- a/crates/mermaid_render/src/postprocess/accent_colors/mindmap.rs +++ b/crates/mermaid_render/src/postprocess/accent_colors/mindmap.rs @@ -29,7 +29,7 @@ impl MindmapAccents { return Ok(event); } - let section_idx = self.parse_section_class(e)?; + let section_idx = self.parse_section_class(e, "class")?; if let Some(idx) = section_idx { let tracks_node = if let Some((tx, ty)) = super::parse_translate(e) { self.nodes.start_node(tx, ty, 0.0, idx); @@ -69,13 +69,16 @@ impl MindmapAccents { Event::Start(e) | Event::Empty(e) if e.name().as_ref() == b"text" || e.name().as_ref() == b"tspan" => { - let section_idx = self.current_section_accent().or_else(|| { - if e.name().as_ref() == b"text" { - self.nodes.lookup_accent(e) - } else { - None - } - }); + let section_idx = self + .parse_section_class(e, "data-merman-source-classes")? + .or_else(|| self.current_section_accent()) + .or_else(|| { + if e.name().as_ref() == b"text" { + self.nodes.lookup_accent(e) + } else { + None + } + }); if e.name().as_ref() == b"text" { self.current_text_section = section_idx; @@ -101,8 +104,12 @@ impl MindmapAccents { } } - fn parse_section_class(&mut self, e: &BytesStart<'_>) -> Result> { - let class_attr = match e.try_get_attribute("class")? { + fn parse_section_class( + &mut self, + e: &BytesStart<'_>, + attribute: &str, + ) -> Result> { + let class_attr = match e.try_get_attribute(attribute)? { Some(attr) => attr, None => return Ok(None), }; diff --git a/crates/mermaid_render/src/postprocess/inject_css.rs b/crates/mermaid_render/src/postprocess/inject_css.rs index 426433b0f6c..d0324bbac5d 100644 --- a/crates/mermaid_render/src/postprocess/inject_css.rs +++ b/crates/mermaid_render/src/postprocess/inject_css.rs @@ -374,7 +374,8 @@ fn build_injected_css(theme: &MermaidTheme, svg_id: &str) -> String { r#" text, tspan, foreignObject div, foreignObject span, foreignObject p {{ font-family: {font} !important; }} foreignObject div, foreignObject span, foreignObject p {{ font-size: 16px; color: {text}; }} - .merman-foreignobject-fallback-text {{ font-size: 16px !important; }} + .merman-foreignobject-fallback {{ font-weight: normal !important; letter-spacing: 0 !important; word-spacing: 0 !important; }} + defs svg {{ overflow: visible !important; }} foreignObject p {{ margin: 0; }} foreignObject {{ overflow: visible; }} foreignObject div {{ max-width: none !important; }} diff --git a/crates/mermaid_render/src/render.rs b/crates/mermaid_render/src/render.rs index 3db6f17fcb8..80468a5bc2a 100644 --- a/crates/mermaid_render/src/render.rs +++ b/crates/mermaid_render/src/render.rs @@ -1,36 +1,154 @@ -use std::sync::atomic::{AtomicU64, Ordering}; +use std::{ + collections::HashMap, + sync::{ + Arc, Mutex, OnceLock, PoisonError, + atomic::{AtomicU64, Ordering}, + }, +}; use anyhow::{Context as _, Result, anyhow}; +use gpui::{SvgRenderer, SvgTextFont}; +use merman::svg::{ + DeterministicTextMeasurer, MeasurementProfileId, TextMeasurementPolicy, TextMeasurementProfile, + TextMeasurementProfileIdentity, TextStyle, +}; use crate::{MermaidTheme, css_color}; -pub(super) fn render_mermaid(source: &str, theme: &MermaidTheme) -> Result { +pub(super) fn render_mermaid( + source: &str, + theme: &MermaidTheme, + svg_renderer: &SvgRenderer, +) -> Result { static COUNTER: AtomicU64 = AtomicU64::new(0); let id = COUNTER.fetch_add(1, Ordering::Relaxed); let diagram_id = format!("merman-{id}"); - let config = to_merman_config(theme); - let renderer = merman::svg::HeadlessRenderer::new() - .with_site_config(config) - .with_vendored_text_measurer() - .with_diagram_id(&diagram_id); + let edge_label_background = css_color(theme.edge_label_background); // Apply merman's raster-safe pipeline before Zed-specific styling. The // pipeline handles generic rasterizer compatibility cleanup: foreignObject // fallback text, unsupported CSS removal, and invalid SVG attribute cleanup. // Zed also strips merman's existing `!important` declarations before // injecting its own theme CSS so host styling wins consistently in usvg/resvg. let pipeline = merman::svg::SvgPipeline::resvg_safe() + .with_postprocessor( + merman::svg::ScopedCssPostprocessor::new(format!( + "span.edgeLabel.edgeLabel {{ background: {edge_label_background}; }}" + )) + .with_existing_style_merge(), + ) .with_postprocessor(merman::svg::CssOverridePostprocessor::strip_existing_important()); + let control = merman::OperationControl::new(); + let label_measurer = Arc::new(LabelMeasurer { + svg_renderer: svg_renderer.clone(), + font_family: theme.font_family.clone(), + measurements: Mutex::new(Measurements { + widths: HashMap::new(), + remaining_budget: MEASUREMENT_BUDGET, + }), + error: OnceLock::new(), + control: control.clone(), + }); + let text_measurer = DeterministicTextMeasurer::default().with_width_callback({ + let label_measurer = label_measurer.clone(); + move |text, style| label_measurer.width(text, style) + }); + let measurement_profile = TextMeasurementProfile::new( + TextMeasurementProfileIdentity::new(MeasurementProfileId::new("zed.svg-renderer")?, "1")?, + text_measurer, + ); + let request = merman::SvgRequest { + environment: merman::SvgEnvironment::deterministic() + .with_text_measurement_policy(TextMeasurementPolicy::uniform(measurement_profile)), + options: merman::svg::SvgRenderOptions { + diagram_id: Some(diagram_id), + ..merman::svg::SvgRenderOptions::default() + }, + pipeline: Some(pipeline), + ..merman::SvgRequest::default() + }; - let svg = renderer - .render_svg_with_pipeline_sync(source, &pipeline) - .context("merman render failed")? - .ok_or_else(|| anyhow!("merman returned no SVG for the given input"))?; + let output = merman::Renderer::new() + .with_engine(merman::Engine::new().with_site_config(to_merman_config(theme)?)) + .render(merman::RenderRequest::svg(source, control, request)); + if let Some(error) = label_measurer.error.get() { + return Err(anyhow!("failed to measure mermaid text: {error}")); + } + let merman::RenderOutput::Svg(Some(svg)) = output.context("merman render failed")? else { + return Err(anyhow!("merman returned no SVG for the given input")); + }; + let (svg, _) = svg.into_parts(); Ok(svg) } -fn to_merman_config(theme: &MermaidTheme) -> merman::MermaidConfig { +const MEASUREMENT_BUDGET: usize = 2 << 20; + +struct LabelMeasurer { + svg_renderer: SvgRenderer, + font_family: String, + measurements: Mutex, + error: OnceLock, + control: merman::OperationControl, +} + +struct Measurements { + widths: HashMap<(String, u64, Option, Option), f64>, + remaining_budget: usize, +} + +impl LabelMeasurer { + fn width(&self, text: &str, style: &TextStyle) -> f64 { + if self.error.get().is_some() { + return 0.0; + } + let key = ( + text.to_owned(), + style.font_size.to_bits(), + style.font_weight.clone(), + style.font_style.clone(), + ); + let mut measurements = self + .measurements + .lock() + .unwrap_or_else(PoisonError::into_inner); + if let Some(width) = measurements.widths.get(&key) { + return *width; + } + let Some(remaining_budget) = measurements + .remaining_budget + .checked_sub(measurement_cost(text)) + else { + return self.fail("the diagram has too much text".to_string()); + }; + measurements.remaining_budget = remaining_budget; + let font = SvgTextFont { + family: &self.font_family, + size: style.font_size as f32, + weight: style.font_weight.as_deref().unwrap_or("normal"), + style: style.font_style.as_deref().unwrap_or("normal"), + }; + let width = match self.svg_renderer.measure_text_width(text, &font) { + Ok(width) => f64::from(width), + Err(error) => return self.fail(error.to_string()), + }; + measurements.widths.insert(key, width); + width + } + + fn fail(&self, error: String) -> f64 { + self.error.get_or_init(|| error); + self.control.cancel(); + 0.0 + } +} + +fn measurement_cost(text: &str) -> usize { + let len = text.len(); + 64 + len + len.saturating_mul(len) / 4096 +} + +fn to_merman_config(theme: &MermaidTheme) -> Result { let primary = css_color(theme.primary_color); let primary_text = css_color(theme.primary_text_color); let primary_border = css_color(theme.primary_border_color); @@ -118,8 +236,18 @@ fn to_merman_config(theme: &MermaidTheme) -> merman::MermaidConfig { } } - merman::MermaidConfig::from_value(serde_json::json!({ + let mut secure_keys = merman::generated::default_site_config() + .as_value() + .get("secure") + .and_then(serde_json::Value::as_array) + .cloned() + .context("merman has no default secure keys")?; + secure_keys.extend(["themeVariables", "fontSize"].map(serde_json::Value::from)); + + Ok(merman::MermaidConfig::from_value(serde_json::json!({ "theme": "base", + "look": "classic", + "secure": secure_keys, "darkMode": theme.dark_mode, "fontFamily": theme.font_family, // resvg can't rasterize HTML `` labels, so merman's @@ -128,13 +256,22 @@ fn to_merman_config(theme: &MermaidTheme) -> merman::MermaidConfig { "flowchart": { "htmlLabels": true, "padding": 16, + "wrappingWidth": 200, + "minNodeWidth": 0, + }, + "state": { + "wrappingWidth": 200, + "minNodeWidth": 0, }, "themeVariables": theme_vars, - })) + }))) } #[cfg(test)] mod tests { + use assets::Assets; + use quick_xml::{Reader, events::Event}; + use super::*; #[test] @@ -142,7 +279,8 @@ mod tests { let html_label_source = "classDiagram\n class Shelter {\n -List~Animal~ animals\n }"; let html_label_svg = - render_mermaid(html_label_source, &MermaidTheme::default()).expect("render failed"); + render_mermaid(html_label_source, &MermaidTheme::default(), &svg_renderer()) + .expect("render failed"); assert!( !html_label_svg.contains(" \ |ambiguous or zero| B[\"Error describing where matches were found\"]"; - let svg = render_mermaid(source, &MermaidTheme::default()).expect("render failed"); + let svg = render_mermaid(source, &MermaidTheme::default(), &svg_renderer()) + .expect("render failed"); assert!(!svg.contains(" Teardown\n Teardown : members kicked\n Teardown : group deleted" + .to_string(), + ), + ( + "IBM Plex Sans", + "erDiagram\n ORDER {\n string shipping_address_line_one\n }".to_string(), + ), + ( + "IBM Plex Sans", + "mindmap\n root((Root))\n First\n second[A
B]".to_string(), + ), + ( + "IBM Plex Sans", + "classDiagram\nclass 顧客 {\n +文字列 名前😀\n}".to_string(), + ), + ]; + let svg_renderer = svg_renderer(); + + for (font_family, source) in diagrams { + let theme = MermaidTheme { + font_family: font_family.to_string(), + ..MermaidTheme::default() + }; + let svg = render_mermaid(&source, &theme, &svg_renderer).expect("render failed"); + let svg = crate::postprocess::postprocess(&svg, &theme).expect("postprocess failed"); + let labels = viewport_labels(&svg); + assert!(!labels.is_empty(), "no label viewports in: {svg}"); + + for label in labels { + let font = SvgTextFont { + family: font_family, + size: label.font_size, + weight: &label.font_weight, + style: &label.font_style, + }; + let text_width = svg_renderer + .measure_text_width(&label.text, &font) + .expect("measuring failed"); + assert!( + text_width <= label.viewport_width + 0.01, + "{:?} is {text_width}px wide in a {}px viewport of: {source}", + label.text, + label.viewport_width, + ); + } + } + } + + #[test] + fn state_descriptions_do_not_overlap() { + let source = "stateDiagram-v2\n [*] --> Teardown\n Teardown : members kicked\n Teardown : group deleted"; + let theme = MermaidTheme::default(); + let svg = render_mermaid(source, &theme, &svg_renderer()).expect("render failed"); + let svg = crate::postprocess::postprocess(&svg, &theme).expect("postprocess failed"); + let mut options = usvg::Options::default(); + options.fontdb_mut().load_system_fonts(); + let tree = usvg::Tree::from_str(&svg, &options).expect("SVG parsing failed"); + let bounds = |expected_text| text_node(tree.root(), expected_text).abs_bounding_box(); + + let first = bounds("members kicked"); + let second = bounds("group deleted"); + assert!( + first.bottom() <= second.top(), + "descriptions overlap: {first:?} and {second:?}" + ); + } + + #[test] + fn mindmap_labels_use_theme_text_color() { + let source = "mindmap\n root((Root))\n First\n second[A
B]"; + let theme = MermaidTheme::default(); + let svg = render_mermaid(source, &theme, &svg_renderer()).expect("render failed"); + let svg = crate::postprocess::postprocess(&svg, &theme).expect("postprocess failed"); + let mut options = usvg::Options::default(); + options.fontdb_mut().load_system_fonts(); + let tree = usvg::Tree::from_str(&svg, &options).expect("SVG parsing failed"); + + let fills = text_nodes(tree.root()) + .into_iter() + .flat_map(|text| text.chunks()) + .flat_map(|chunk| chunk.spans()) + .map(|span| match span.fill().map(|fill| fill.paint()) { + Some(usvg::Paint::Color(color)) => { + format!("#{:02x}{:02x}{:02x}", color.red, color.green, color.blue) + } + _ => String::new(), + }) + .collect::>(); + assert_eq!(fills, vec![css_color(theme.text_color); 4]); + } + + #[test] + fn inherited_styles_do_not_change_label_typography() { + let theme = MermaidTheme::default(); + let mut options = usvg::Options::default(); + options.fontdb_mut().load_system_fonts(); + let render = |source| { + let svg = render_mermaid(source, &theme, &svg_renderer()).expect("render failed"); + let svg = crate::postprocess::postprocess(&svg, &theme).expect("postprocess failed"); + usvg::Tree::from_str(&svg, &options).expect("SVG parsing failed") + }; + + let class_diagram = render("classDiagram\n class User"); + let title = text_node(class_diagram.root(), "User"); + assert_eq!(title.chunks()[0].spans()[0].font().weight(), 700); + + let flowchart = + render("flowchart LR\n A[Label]\n style A letter-spacing:3px,word-spacing:6px"); + let label = &text_node(flowchart.root(), "Label").chunks()[0].spans()[0]; + assert_eq!((label.letter_spacing(), label.word_spacing()), (0.0, 0.0)); + } + + #[test] + fn diagram_directives_cannot_restyle_diagrams() { + let sources = [ + "%%{init: {\"themeCSS\": \".node rect { fill: #abcdef; }\"}}%%\nflowchart LR\n A --> B", + "flowchart LR\n%%{init: {\"themeVariables\": {\"primaryColor\": \"#abcdef\", \"lineColor\": \"#abcdef\"}}}%%\n A --> B", + ]; + + for source in sources { + let svg = render_mermaid(source, &MermaidTheme::default(), &svg_renderer()) + .expect("render failed"); + assert_eq!(svg.matches("#abcdef").count(), 0, "{source}"); + } + } + + #[test] + fn edge_label_backgrounds_use_theme_color() { + let source = "classDiagram\n Animal <|-- Dog : inherits"; + let theme = MermaidTheme { + edge_label_background: gpui::Hsla::from(gpui::rgb(0x123456)), + ..MermaidTheme::default() + }; + let svg = render_mermaid(source, &theme, &svg_renderer()).expect("render failed"); + + assert_eq!(svg.matches(r##"fill="#123456""##).count(), 1); + } + + #[test] + fn label_viewports_do_not_clip_text() { + let source = "classDiagram\n class A {\n +e\u{301}\u{302}\u{303}\u{304}\u{306}\u{307}\u{308}\u{30a}\n }"; + let theme = MermaidTheme::default(); + let svg = render_mermaid(source, &theme, &svg_renderer()).expect("render failed"); + let svg = crate::postprocess::postprocess(&svg, &theme).expect("postprocess failed"); + let mut options = usvg::Options::default(); + options.fontdb_mut().load_system_fonts(); + let tree = usvg::Tree::from_str(&svg, &options).expect("SVG parsing failed"); + + assert_eq!(text_nodes(tree.root()).len(), 2); + assert_eq!(clipped_group_count(tree.root()), 0); + } + + #[test] + fn diagrams_with_too_much_text_to_measure_fail_to_render() { + let source = format!( + "flowchart TD\nA[\"{}{}\"]", + "\u{200b}\u{200c}".repeat(20_000), + "M ".repeat(100) + ); + let error = render_mermaid(&source, &MermaidTheme::default(), &svg_renderer()) + .expect_err("render succeeded"); + + assert_eq!( + error.to_string(), + "failed to measure mermaid text: the diagram has too much text" + ); + } + + #[test] + fn measuring_past_the_budget_cancels_the_render() { + let control = merman::OperationControl::new(); + let label_measurer = LabelMeasurer { + svg_renderer: svg_renderer(), + font_family: "IBM Plex Sans".to_string(), + measurements: Mutex::new(Measurements { + widths: HashMap::new(), + remaining_budget: 0, + }), + error: OnceLock::new(), + control: control.clone(), + }; + + assert_eq!(label_measurer.width("label", &TextStyle::default()), 0.0); + assert!(control.is_cancelled()); + } + + struct ViewportLabel { + viewport_width: f32, + text: String, + font_size: f32, + font_weight: String, + font_style: String, + } + + fn svg_renderer() -> SvgRenderer { + SvgRenderer::new(Arc::new(Assets)) + } + + fn viewport_labels(svg: &str) -> Vec { + let mut labels = Vec::new(); + let mut viewport_widths = Vec::::new(); + let mut label_style = None; + let mut reader = Reader::from_str(svg); + loop { + match reader.read_event().expect("SVG is not well-formed") { + Event::Eof => break, + Event::Start(element) if element.name().as_ref() == b"svg" => { + let width = attribute(&element, "width"); + viewport_widths.push(width.parse().unwrap_or(f32::INFINITY)); + } + Event::End(element) if element.name().as_ref() == b"svg" => { + viewport_widths.pop(); + } + Event::Start(element) + if element.name().as_ref() == b"text" && viewport_widths.len() > 1 => + { + label_style = Some(attribute(&element, "style")); + } + Event::Text(text) => { + if let Some(style) = label_style.take() { + let declaration = |name: &str| { + style + .split(';') + .filter_map(|declaration| declaration.split_once(':')) + .find(|(property, _)| property.trim() == name) + .map(|(_, value)| value.trim().to_string()) + .expect("label style is missing a declaration") + }; + labels.push(ViewportLabel { + viewport_width: viewport_widths + .last() + .copied() + .unwrap_or(f32::INFINITY), + text: text.decode().expect("label is not UTF-8").into_owned(), + font_size: declaration("font-size") + .trim_end_matches("px") + .parse() + .expect("label font size is not in pixels"), + font_weight: declaration("font-weight"), + font_style: declaration("font-style"), + }); + } + } + _ => {} + } + } + labels + } + + fn attribute(element: &quick_xml::events::BytesStart<'_>, name: &str) -> String { + element + .try_get_attribute(name) + .expect("attribute is not well-formed") + .map(|attribute| String::from_utf8_lossy(&attribute.value).into_owned()) + .unwrap_or_default() + } + + fn clipped_group_count(group: &usvg::Group) -> usize { + group + .children() + .iter() + .map(|node| match node { + usvg::Node::Group(group) => { + usize::from(group.clip_path().is_some()) + clipped_group_count(group) + } + usvg::Node::Text(_) | usvg::Node::Path(_) | usvg::Node::Image(_) => 0, + }) + .sum() + } + + fn text_node<'a>(group: &'a usvg::Group, expected_text: &str) -> &'a usvg::Text { + text_nodes(group) + .into_iter() + .find(|text| { + text.chunks() + .iter() + .any(|chunk| chunk.text() == expected_text) + }) + .expect("text is missing") + } + + fn text_nodes(group: &usvg::Group) -> Vec<&usvg::Text> { + group + .children() + .iter() + .flat_map(|node| match node { + usvg::Node::Group(group) => text_nodes(group), + usvg::Node::Text(text) => vec![&**text], + usvg::Node::Path(_) | usvg::Node::Image(_) => Vec::new(), + }) + .collect() + } + fn text_font_size(group: &usvg::Group, expected_text: &str) -> Option { for node in group.children() { match node { diff --git a/crates/mermaid_render/tests/check_invalid_attrs.rs b/crates/mermaid_render/tests/check_invalid_attrs.rs index 3c51ac69a9e..8fd3d1b6b27 100644 --- a/crates/mermaid_render/tests/check_invalid_attrs.rs +++ b/crates/mermaid_render/tests/check_invalid_attrs.rs @@ -1,4 +1,6 @@ -use gpui::Hsla; +use std::sync::Arc; + +use gpui::{Hsla, SvgRenderer}; use mermaid_render::MermaidTheme; fn rgb(r: u8, g: u8, b: u8) -> Hsla { @@ -233,7 +235,8 @@ fn accent_colors_auto_applied_to_nodes() { // automatic accent colors applied to its node groups. let source = "stateDiagram-v2\n [*] --> Idle\n Idle --> Processing\n Processing --> Done\n Done --> [*]"; - let svg = mermaid_render::render_to_svg(source, &theme).expect("render failed"); + let svg = + mermaid_render::render_to_svg(source, &theme, &svg_renderer()).expect("render failed"); // accent_fill_and_text darkens the background color for dark mode. // The stroke colors are direct hex conversions of the accent rgb values. @@ -259,7 +262,8 @@ fn accent_colors_auto_applied_to_nodes() { fn generics_not_double_escaped() { let theme = rgb_theme(); let source = "classDiagram\n class Shelter {\n -List~Animal~ animals\n +adopt(Animal a) bool\n }"; - let svg = mermaid_render::render_to_svg(source, &theme).expect("render failed"); + let svg = + mermaid_render::render_to_svg(source, &theme, &svg_renderer()).expect("render failed"); assert!( !svg.contains("&lt;"), "Double-escaped &lt; found in SVG" @@ -282,9 +286,10 @@ fn class_diagram_label_text_uses_accent_classes() { +String breed +bark() void } - Dog --|> Animal"#; + Dog --|> Animal : inherits"#; - let svg = mermaid_render::render_to_svg(source, &theme).expect("render failed"); + let svg = + mermaid_render::render_to_svg(source, &theme, &svg_renderer()).expect("render failed"); use quick_xml::XmlVersion; use quick_xml::events::Event; @@ -310,9 +315,16 @@ fn class_diagram_label_text_uses_accent_classes() { } } - assert!( - !accent_classes.is_empty(), - "expected zed-accent-N classes on label text elements", + assert_eq!( + accent_classes, + [ + "zed-accent-0", + "zed-accent-0", + "zed-accent-0", + "zed-accent-1", + "zed-accent-1", + "zed-accent-1", + ], ); } @@ -320,7 +332,8 @@ fn class_diagram_label_text_uses_accent_classes() { fn sequence_diagram_tspan_uses_accent_classes() { let theme = rgb_theme(); let source = "sequenceDiagram\n participant Database"; - let svg = mermaid_render::render_to_svg(source, &theme).expect("render failed"); + let svg = + mermaid_render::render_to_svg(source, &theme, &svg_renderer()).expect("render failed"); use quick_xml::XmlVersion; use quick_xml::events::Event; @@ -358,7 +371,7 @@ fn no_empty_attributes_or_nan_with_rgb_theme() { let mut all_issues = Vec::new(); for (name, source) in DIAGRAMS { - match mermaid_render::render_to_svg(source, &theme) { + match mermaid_render::render_to_svg(source, &theme, &svg_renderer()) { Ok(svg) => all_issues.extend(check_svg_issues(name, &svg)), Err(e) => eprintln!("{name}: render failed (skipped): {e}"), } @@ -372,3 +385,7 @@ fn no_empty_attributes_or_nan_with_rgb_theme() { ); } } + +fn svg_renderer() -> SvgRenderer { + SvgRenderer::new(Arc::new(())) +} diff --git a/crates/miniprofiler_ui/src/miniprofiler_ui.rs b/crates/miniprofiler_ui/src/miniprofiler_ui.rs index 6f6ccf7156d..088080a6ac4 100644 --- a/crates/miniprofiler_ui/src/miniprofiler_ui.rs +++ b/crates/miniprofiler_ui/src/miniprofiler_ui.rs @@ -153,6 +153,7 @@ fn open_performance_profiler( let default_bounds = size(px(1280.), px(720.)); cx.defer(move |cx| { + let display_id = cx.active_display().map(|display| display.id()); cx.open_window( WindowOptions { titlebar: Some(TitlebarOptions { @@ -167,7 +168,8 @@ fn open_performance_profiler( window_background, window_decorations: None, window_min_size: Some(default_bounds), - window_bounds: Some(WindowBounds::centered(default_bounds, cx)), + window_bounds: Some(WindowBounds::centered(display_id, default_bounds, cx)), + display_id, ..Default::default() }, |_window, cx| ProfilerWindow::new(startup_time, Some(workspace_handle), cx), diff --git a/crates/platform_title_bar/src/platform_title_bar.rs b/crates/platform_title_bar/src/platform_title_bar.rs index b69bb0d1ff0..16203410e48 100644 --- a/crates/platform_title_bar/src/platform_title_bar.rs +++ b/crates/platform_title_bar/src/platform_title_bar.rs @@ -1,5 +1,6 @@ pub mod platforms; mod system_window_tabs; +mod title_bar_settings; use gpui::{ Action, AnyElement, App, Context, Decorations, Entity, Hsla, InteractiveElement, IntoElement, @@ -16,14 +17,13 @@ use ui::{ }; use workspace::{MultiWorkspace, SidebarRenderState, SidebarSide}; -use crate::{ - platforms::{platform_linux, platform_windows}, - system_window_tabs::SystemWindowTabs, -}; +use crate::platforms::{platform_linux, platform_windows}; pub use system_window_tabs::{ - DraggedWindowTab, MergeAllWindows, MoveTabToNewWindow, ShowNextWindowTab, ShowPreviousWindowTab, + DraggedWindowTab, MergeAllWindows, MoveTabToNewWindow, ShowNextWindowTab, + ShowPreviousWindowTab, SystemWindowTabs, }; +pub use title_bar_settings::TitleBarSettings; /// With client-side decorations, the title bar is pulled over the window frame's /// border to avoid a transparent gap in the rounded corners, and a border in the @@ -48,12 +48,34 @@ pub fn apply_title_bar_insets( .when(right_window_controls, |header| header.pr(inset)) } +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub struct SidebarWindowControls { + pub traffic_lights: bool, + pub left: bool, + pub right: bool, +} + +impl SidebarWindowControls { + pub fn new(sidebar_side: SidebarSide, window: &Window, cx: &App) -> Self { + let visible = !window.is_fullscreen() + && !window.is_simple_fullscreen() + && TitleBarSettings::is_title_bar_visible(window, cx); + let is_macos = cfg!(target_os = "macos"); + let on_left = sidebar_side == SidebarSide::Left; + Self { + traffic_lights: visible && is_macos && on_left, + left: visible && !is_macos && on_left, + right: visible && !is_macos && !on_left, + } + } +} + pub struct PlatformTitleBar { id: ElementId, platform_style: PlatformStyle, children: SmallVec<[AnyElement; 2]>, should_move: bool, - system_window_tabs: Entity, + system_window_tabs: Option>, button_layout: Option, multi_workspace: Option>, } @@ -61,7 +83,7 @@ pub struct PlatformTitleBar { impl PlatformTitleBar { pub fn new(id: impl Into, cx: &mut Context) -> Self { let platform_style = PlatformStyle::platform(); - let system_window_tabs = cx.new(|_cx| SystemWindowTabs::new()); + let system_window_tabs = Some(cx.new(|_cx| SystemWindowTabs::new())); Self { id: id.into(), @@ -74,6 +96,11 @@ impl PlatformTitleBar { } } + pub fn without_system_window_tabs(mut self) -> Self { + self.system_window_tabs = None; + self + } + pub fn with_multi_workspace(mut self, multi_workspace: WeakEntity) -> Self { self.multi_workspace = Some(multi_workspace); self @@ -353,7 +380,7 @@ impl Render for PlatformTitleBar { v_flex() .w_full() .child(title_bar) - .child(self.system_window_tabs.clone().into_any_element()) + .children(self.system_window_tabs.clone()) } } diff --git a/crates/platform_title_bar/src/system_window_tabs.rs b/crates/platform_title_bar/src/system_window_tabs.rs index 507dac96327..55936ef6821 100644 --- a/crates/platform_title_bar/src/system_window_tabs.rs +++ b/crates/platform_title_bar/src/system_window_tabs.rs @@ -425,6 +425,7 @@ impl Render for SystemWindowTabs { } h_flex() + .debug_selector(|| "system-window-tabs".into()) .w_full() .h(Tab::container_height(cx)) .bg(inactive_background_color) diff --git a/crates/title_bar/src/title_bar_settings.rs b/crates/platform_title_bar/src/title_bar_settings.rs similarity index 70% rename from crates/title_bar/src/title_bar_settings.rs rename to crates/platform_title_bar/src/title_bar_settings.rs index 7821dff303c..775532a2ced 100644 --- a/crates/title_bar/src/title_bar_settings.rs +++ b/crates/platform_title_bar/src/title_bar_settings.rs @@ -1,8 +1,9 @@ -use gpui::WindowButtonLayout; -use settings::{RegisterSetting, Settings, SettingsContent}; +use gpui::{App, Window, WindowButtonLayout}; +use settings::{RegisterSetting, Settings, SettingsContent, TitleBarVisibility}; #[derive(Copy, Clone, Debug, RegisterSetting)] pub struct TitleBarSettings { + pub show: TitleBarVisibility, pub show_branch_status_icon: bool, pub show_onboarding_banner: bool, pub show_user_picture: bool, @@ -16,10 +17,23 @@ pub struct TitleBarSettings { pub button_layout: Option, } +impl TitleBarSettings { + pub fn is_title_bar_visible(window: &Window, cx: &App) -> bool { + match Self::get_global(cx).show { + TitleBarVisibility::Always => true, + TitleBarVisibility::Never => false, + TitleBarVisibility::HideInFullScreen => { + !window.is_fullscreen() && !window.is_simple_fullscreen() + } + } + } +} + impl Settings for TitleBarSettings { fn from_settings(s: &SettingsContent) -> Self { let content = s.title_bar.clone().unwrap(); TitleBarSettings { + show: content.show.unwrap(), show_branch_status_icon: content.show_branch_status_icon.unwrap(), show_onboarding_banner: content.show_onboarding_banner.unwrap(), show_user_picture: content.show_user_picture.unwrap(), diff --git a/crates/project/src/agent_server_store.rs b/crates/project/src/agent_server_store.rs index 8f0aff6b591..1d2234f0847 100644 --- a/crates/project/src/agent_server_store.rs +++ b/crates/project/src/agent_server_store.rs @@ -1688,6 +1688,10 @@ impl CustomAgentServerSettings { } pub fn default_config_option(&self, config_id: &str) -> Option<&AgentConfigOptionValue> { + self.default_config_options().get(config_id) + } + + pub fn default_config_options(&self) -> &HashMap { match self { CustomAgentServerSettings::Custom { default_config_options, @@ -1696,7 +1700,7 @@ impl CustomAgentServerSettings { | CustomAgentServerSettings::Registry { default_config_options, .. - } => default_config_options.get(config_id), + } => default_config_options, } } diff --git a/crates/project/src/environment.rs b/crates/project/src/environment.rs index c7b87ea8e35..9a5565eae43 100644 --- a/crates/project/src/environment.rs +++ b/crates/project/src/environment.rs @@ -66,6 +66,11 @@ impl ProjectEnvironment { } } + #[cfg(any(test, feature = "test-support"))] + pub fn inherited_cli_environment(&self) -> Option<&HashMap> { + self.cli_environment.as_ref() + } + /// Returns the inherited CLI environment, if this project was opened from the Zed CLI. pub(crate) fn get_cli_environment(&self) -> Option> { if cfg!(any(test, feature = "test-support")) { diff --git a/crates/project/src/git_store.rs b/crates/project/src/git_store.rs index 9310d612d08..0cbceb91553 100644 --- a/crates/project/src/git_store.rs +++ b/crates/project/src/git_store.rs @@ -2451,15 +2451,15 @@ impl GitStore { .iter() .any(|repo_id| self.active_repo_id == Some(*repo_id)); - for repo_id in repos_without_worktree { - self.display_diffs.remove(&repo_id); - self.repositories.remove(&repo_id); - self.worktree_ids.remove(&repo_id); + for repo_id in &repos_without_worktree { + self.display_diffs.remove(repo_id); + self.repositories.remove(repo_id); + self.worktree_ids.remove(repo_id); if let Some(updates_tx) = downstream.as_ref().map(|downstream| &downstream.updates_tx) { updates_tx - .unbounded_send(DownstreamUpdate::RemoveRepository(repo_id)) + .unbounded_send(DownstreamUpdate::RemoveRepository(*repo_id)) .ok(); } } @@ -2467,6 +2467,9 @@ impl GitStore { if is_active_repo_removed { self.select_fallback_active_repository(cx); } + for repo_id in repos_without_worktree { + cx.emit(GitStoreEvent::RepositoryRemoved(repo_id)); + } } _ => {} } @@ -2674,6 +2677,7 @@ impl GitStore { .unbounded_send(DownstreamUpdate::RemoveRepository(id)) .ok(); } + cx.emit(GitStoreEvent::RepositoryRemoved(id)); } } @@ -3162,6 +3166,23 @@ impl GitStore { &self.repositories } + /// The label to show for each repository, disambiguated against every other + /// repository in the workspace. See [`disambiguated_display_names`]. + pub fn display_names(&self, cx: &App) -> HashMap { + let path_style = self.worktree_store.read(cx).path_style(); + let (ids, work_directory_abs_paths): (Vec<_>, Vec<_>) = self + .repositories + .iter() + .map(|(id, repository)| (*id, repository.read(cx).work_directory_abs_path.clone())) + .unzip(); + ids.into_iter() + .zip(disambiguated_display_names( + &work_directory_abs_paths, + path_style, + )) + .collect() + } + /// Returns the main repository working directory for the given worktree. /// For normal checkouts this equals the worktree's own path. For linked /// worktrees it points back to the main worktree, if one exists. Linked @@ -6304,6 +6325,67 @@ impl RepositorySnapshot { } } +/// Computes the label to show for each of the given repositories: the leaf +/// directory name on its own where that already identifies the repository, and +/// as many parent components as it takes to tell colliding names apart where it +/// does not. +/// +/// A workspace that checks every project out into a directory of the same name +/// would otherwise render as a list of identical rows — git submodules parked +/// under `/src`, or worktrees under `/`. +pub fn disambiguated_display_names( + work_directory_abs_paths: &[Arc], + path_style: PathStyle, +) -> Vec { + // Leaf first, so a depth counts back from the directory name. `Path` would split + // by the host's rules, but a remote project's paths follow the remote's style, + // so split on the project's own separators instead. + let components: Vec> = work_directory_abs_paths + .iter() + .map(|path| { + let path = path.to_string_lossy(); + let mut components: Vec = path + .split(path_style.separators_ch()) + // `.` and `..` are not names a label can be built from, and the + // `Path::components` this replaces dropped them too. + .filter(|component| !matches!(*component, "" | "." | "..")) + .map(str::to_owned) + .collect(); + // A label is a suffix of the path, never the whole of it, which the root + // is already excluded from; drop a Windows drive prefix for the same + // reason, so a label is never capped at `C:`. + if path_style == PathStyle::Windows + && components + .first() + .is_some_and(|component| component.ends_with(':')) + { + components.remove(0); + } + components.reverse(); + if components.is_empty() { + vec![path.into_owned()] + } else { + components + } + }) + .collect(); + let label = |components: &Vec, detail: usize| -> String { + components + .iter() + .take(detail + 1) + .rev() + .cloned() + .collect::>() + .join(path_style.primary_separator()) + }; + let details = util::disambiguate::compute_disambiguation_details(&components, label); + components + .iter() + .zip(details) + .map(|(components, detail)| label(components, detail).into()) + .collect() +} + pub fn stash_to_proto(entry: &StashEntry) -> proto::StashEntry { proto::StashEntry { oid: entry.oid.as_bytes().to_vec(), @@ -11693,6 +11775,73 @@ mod tests { assert!(delegates.lock().is_empty()); } + #[test] + fn test_disambiguated_display_names() { + fn names_in(path_style: PathStyle, paths: &[&str]) -> Vec { + let paths: Vec> = paths + .iter() + .map(|path| Arc::from(Path::new(path))) + .collect(); + disambiguated_display_names(&paths, path_style) + .into_iter() + .map(|name| name.to_string()) + .collect() + } + fn names(paths: &[&str]) -> Vec { + names_in(PathStyle::Unix, paths) + } + + // Distinct leaf names are left alone, however deeply they are nested. + assert_eq!( + names(&["/home/me/foo", "/home/me/nested/bar"]), + vec!["foo", "bar"] + ); + + // Submodules parked under a directory of the same name: only the + // colliding entries grow a parent component. + assert_eq!( + names(&[ + "/work/platform", + "/work/platform/services/gateway/src", + "/work/platform/services/panel/src", + ]), + vec!["platform", "gateway/src", "panel/src"] + ); + + // One parent is not always enough. + assert_eq!( + names(&["/work/a/lib/protos", "/work/b/lib/protos"]), + vec!["a/lib/protos", "b/lib/protos"] + ); + + // Paths that stay equal all the way up terminate rather than growing + // forever, and a label never reaches past the first path component. + assert_eq!( + names(&["/work/src", "/work/src"]), + vec!["work/src", "work/src"] + ); + + assert!(names(&[]).is_empty()); + + // Windows paths are split and rejoined by the project's own separators, + // not the host's, so a Windows remote works from a Unix host. The drive + // letter is a prefix rather than a component a label can grow into. + assert_eq!( + names_in( + PathStyle::Windows, + &[r"C:\work\a\lib\protos", r"C:\work\b\lib\protos"], + ), + vec![r"a\lib\protos", r"b\lib\protos"] + ); + assert_eq!( + names_in(PathStyle::Windows, &[r"C:\src", r"C:\src"]), + vec!["src", "src"] + ); + + // Relative components are not names a label can be built from. + assert_eq!(names(&["/work/./a/../b"]), vec!["b"]); + } + #[test] fn test_is_submodule_git_dir() { assert!(is_submodule_git_dir(Path::new("/Foo/.git/modules/Bar"))); diff --git a/crates/project/src/project.rs b/crates/project/src/project.rs index 17859117649..069d189594e 100644 --- a/crates/project/src/project.rs +++ b/crates/project/src/project.rs @@ -41,7 +41,7 @@ use crate::{ git_store::GitStore, lsp_store::{SymbolLocation, log_store::LogKind}, project_search::SearchResultsHandle, - trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees}, + trusted_worktrees::{PathTrust, TrustedWorktrees}, worktree_store::WorktreeIdCounter, }; pub use agent_registry_store::{AgentRegistryStore, RegistryAgent}; @@ -1526,7 +1526,7 @@ impl Project { ( remote.proto_client(), remote.path_style(), - RemoteHostLocation::from(remote.connection_options()), + remote.connection_options().identity().into_owned(), ) }); let worktree_store = cx.new(|cx| { @@ -2640,13 +2640,13 @@ impl Project { #[inline] pub fn visibility_for_paths( &self, - paths: &[PathBuf], + paths: &[impl AsRef], exclude_sub_dirs: bool, cx: &App, ) -> Option { paths .iter() - .filter_map(|path| self.visibility_for_path(path, exclude_sub_dirs, cx)) + .filter_map(|path| self.visibility_for_path(path.as_ref(), exclude_sub_dirs, cx)) .max() } @@ -2682,10 +2682,10 @@ impl Project { .max() } - pub fn visibility_for_subpaths(&self, paths: &[PathBuf], cx: &App) -> Option { + pub fn visibility_for_subpaths(&self, paths: &[impl AsRef], cx: &App) -> Option { paths .iter() - .filter_map(|path| self.visibility_for_subpath(path, cx)) + .filter_map(|path| self.visibility_for_subpath(path.as_ref(), cx)) .max() } diff --git a/crates/project/src/task_inventory.rs b/crates/project/src/task_inventory.rs index 2dad9090f16..1dff2482ad7 100644 --- a/crates/project/src/task_inventory.rs +++ b/crates/project/src/task_inventory.rs @@ -42,6 +42,7 @@ pub struct DebugScenarioContext { /// Inventory tracks available tasks for a given project. pub struct Inventory { last_scheduled_tasks: VecDeque<(TaskSourceKind, ResolvedTask)>, + last_scheduled_task_id: Option, last_scheduled_scenarios: VecDeque<(DebugScenario, DebugScenarioContext)>, templates_from_settings: InventoryFor, scenarios_from_settings: InventoryFor, @@ -51,6 +52,7 @@ impl std::fmt::Debug for Inventory { fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { f.debug_struct("Inventory") .field("last_scheduled_tasks", &self.last_scheduled_tasks) + .field("last_scheduled_task_id", &self.last_scheduled_task_id) .field("last_scheduled_scenarios", &self.last_scheduled_scenarios) .field("templates_from_settings", &self.templates_from_settings) .field("scenarios_from_settings", &self.scenarios_from_settings) @@ -312,6 +314,7 @@ impl Inventory { pub fn new(cx: &mut App) -> Entity { cx.new(|_| Self { last_scheduled_tasks: VecDeque::default(), + last_scheduled_task_id: None, last_scheduled_scenarios: VecDeque::default(), templates_from_settings: InventoryFor::default(), scenarios_from_settings: InventoryFor::default(), @@ -642,7 +645,10 @@ impl Inventory { .find(|(_, task)| &task.id == task_id) .cloned() } else { - self.last_scheduled_tasks.back().cloned() + self.last_scheduled_tasks + .back() + .filter(|(_, task)| Some(&task.id) == self.last_scheduled_task_id.as_ref()) + .cloned() } } @@ -652,6 +658,7 @@ impl Inventory { task_source_kind: TaskSourceKind, resolved_task: ResolvedTask, ) { + self.last_scheduled_task_id = Some(resolved_task.id.clone()); self.last_scheduled_tasks .push_back((task_source_kind, resolved_task)); if self.last_scheduled_tasks.len() > 5_000 { @@ -662,7 +669,16 @@ impl Inventory { /// Deletes a resolved task from history, using its id. /// A similar may still resurface in `used_and_current_resolved_tasks` when its [`TaskTemplate`] is resolved again. pub fn delete_previously_used(&mut self, id: &TaskId) { + let deleted_rerun_target = self + .last_scheduled_task(None) + .is_some_and(|(_, task)| &task.id == id); self.last_scheduled_tasks.retain(|(_, task)| &task.id != id); + if deleted_rerun_target { + self.last_scheduled_task_id = self + .last_scheduled_tasks + .back() + .map(|(_, task)| task.id.clone()); + } } /// Returns global task templates with the provided tag. @@ -702,6 +718,16 @@ impl Inventory { .collect() } + fn retain_unchanged_tasks( + &mut self, + is_updated_source: impl Fn(&TaskSourceKind) -> bool, + new_templates: &[TaskTemplate], + ) { + self.last_scheduled_tasks.retain(|(kind, task)| { + !is_updated_source(kind) || new_templates.contains(task.original_task()) + }); + } + fn global_templates_from_settings( &self, ) -> impl '_ + Iterator { @@ -780,23 +806,42 @@ impl Inventory { Some(template) }); - let parsed_templates = &mut self.templates_from_settings; + let new_templates = new_templates.collect::>(); match location { TaskSettingsLocation::Global(path) => { - parsed_templates + self.retain_unchanged_tasks( + |kind| { + if let TaskSourceKind::AbsPath { abs_path, .. } = kind { + abs_path == path + } else { + false + } + }, + &new_templates, + ); + self.templates_from_settings .global .entry(path.to_owned()) - .insert_entry(new_templates.collect()); - self.last_scheduled_tasks.retain(|(kind, _)| { - if let TaskSourceKind::AbsPath { abs_path, .. } = kind { - abs_path != path - } else { - true - } - }); + .insert_entry(new_templates); } TaskSettingsLocation::Worktree(location) => { - let new_templates = new_templates.collect::>(); + self.retain_unchanged_tasks( + |kind| { + if let TaskSourceKind::Worktree { + directory_in_worktree, + id, + .. + } = kind + { + *id == location.worktree_id + && directory_in_worktree.as_ref() == location.path + } else { + false + } + }, + &new_templates, + ); + let parsed_templates = &mut self.templates_from_settings; if new_templates.is_empty() { if let Some(worktree_tasks) = parsed_templates.worktree.get_mut(&location.worktree_id) @@ -810,19 +855,6 @@ impl Inventory { .or_default() .insert(Arc::from(location.path), new_templates); } - self.last_scheduled_tasks.retain(|(kind, _)| { - if let TaskSourceKind::Worktree { - directory_in_worktree, - id, - .. - } = kind - { - *id != location.worktree_id - || directory_in_worktree.as_ref() != location.path - } else { - true - } - }); } } diff --git a/crates/project/src/trusted_worktrees.rs b/crates/project/src/trusted_worktrees.rs index 91037b2027b..b3493555498 100644 --- a/crates/project/src/trusted_worktrees.rs +++ b/crates/project/src/trusted_worktrees.rs @@ -1,6 +1,6 @@ //! A module, responsible for managing the trust logic in Zed. //! -//! It deals with multiple hosts, distinguished by [`RemoteHostLocation`]. +//! It deals with multiple hosts, distinguished by [`remote::RemoteConnectionIdentity`]. //! Each [`crate::Project`] and `HeadlessProject` should call [`init_global`], if wants to establish the trust mechanism. //! This will set up a [`gpui::Global`] with [`TrustedWorktrees`] entity that will persist, restore and allow querying for worktree trust. //! It's also possible to subscribe on [`TrustedWorktreesEvent`] events of this entity to track trust changes dynamically. @@ -41,10 +41,8 @@ use client::ProjectId; use collections::{HashMap, HashSet}; -use gpui::{ - App, AppContext as _, Context, Entity, EventEmitter, Global, SharedString, Task, WeakEntity, -}; -use remote::RemoteConnectionOptions; +use gpui::{App, AppContext as _, Context, Entity, EventEmitter, Global, Task, WeakEntity}; +use remote::RemoteConnectionIdentity; use rpc::{AnyProtoClient, proto}; use settings::{Settings as _, WorktreeId}; use std::{ @@ -65,7 +63,7 @@ pub fn init(db_trusted_paths: DbTrustedPaths, cx: &mut App) { /// An initialization call to set up trust global for a particular project (remote or local). pub fn track_worktree_trust( worktree_store: Entity, - remote_host: Option, + remote_host: Option>, downstream_client: Option<(AnyProtoClient, ProjectId)>, upstream_client: Option<(AnyProtoClient, ProjectId)>, cx: &mut App, @@ -144,43 +142,7 @@ pub struct TrustedWorktreesStore { struct StoreData { upstream_client: Option<(AnyProtoClient, ProjectId)>, downstream_client: Option<(AnyProtoClient, ProjectId)>, - host: Option, -} - -/// An identifier of a host to split the trust questions by. -/// Each trusted data change and event is done for a particular host. -/// A host may contain more than one worktree or even project open concurrently. -#[derive(Debug, PartialEq, Eq, Clone, Hash)] -pub struct RemoteHostLocation { - pub user_name: Option, - pub host_identifier: SharedString, -} - -impl From<&RemoteConnectionOptions> for RemoteHostLocation { - fn from(options: &RemoteConnectionOptions) -> Self { - let (user_name, host_name) = match options { - RemoteConnectionOptions::Ssh(ssh) => ( - ssh.username.as_ref().map(SharedString::new), - SharedString::new(ssh.host.to_string()), - ), - RemoteConnectionOptions::Wsl(wsl) => ( - wsl.user.as_ref().map(SharedString::new), - SharedString::new(&wsl.distro_name), - ), - RemoteConnectionOptions::Docker(docker_connection_options) => ( - Some(SharedString::new(&docker_connection_options.name)), - SharedString::new(&docker_connection_options.container_id), - ), - #[cfg(feature = "test-support")] - RemoteConnectionOptions::Mock(mock) => { - (None, SharedString::new(format!("mock-{}", mock.id))) - } - }; - Self { - user_name, - host_identifier: host_name, - } - } + host: Option>, } /// A unit of trust consideration inside a particular host: @@ -232,7 +194,7 @@ pub enum TrustedWorktreesEvent { impl EventEmitter for TrustedWorktreesStore {} type TrustedPaths = HashMap, HashSet>; -pub type DbTrustedPaths = HashMap, HashSet>; +pub type DbTrustedPaths = HashMap>, HashSet>; impl TrustedWorktreesStore { fn new(db_trusted_paths: DbTrustedPaths) -> Self { @@ -607,7 +569,10 @@ impl TrustedWorktreesStore { pub fn schedule_serialization(&mut self, cx: &mut Context, serialize: S) where - S: FnOnce(HashMap, HashSet>, &App) -> Task<()> + S: FnOnce( + HashMap>, HashSet>, + &App, + ) -> Task<()> + 'static, { self.worktree_trust_serialization = serialize(self.trusted_paths_for_serialization(cx), cx); @@ -616,7 +581,7 @@ impl TrustedWorktreesStore { fn trusted_paths_for_serialization( &mut self, cx: &mut Context, - ) -> HashMap, HashSet> { + ) -> HashMap>, HashSet> { let new_trusted_paths = self .trusted_paths .iter() @@ -651,7 +616,7 @@ impl TrustedWorktreesStore { fn add_worktree_store( &mut self, worktree_store: Entity, - remote_host: Option, + remote_host: Option>, downstream_client: Option<(AnyProtoClient, ProjectId)>, upstream_client: Option<(AnyProtoClient, ProjectId)>, cx: &mut Context, diff --git a/crates/project/tests/integration/git_store.rs b/crates/project/tests/integration/git_store.rs index e02ca05838f..5268d169ff4 100644 --- a/crates/project/tests/integration/git_store.rs +++ b/crates/project/tests/integration/git_store.rs @@ -2017,12 +2017,15 @@ mod resolve_worktree_tests { mod repository_activation_tests { use std::{ + cell::RefCell, path::{Path, PathBuf}, + rc::Rc, sync::Arc, }; use fs::{FakeFs, Fs, RemoveOptions}; use gpui::{BorrowAppContext, Entity, TestAppContext}; + use project::git_store::GitStoreEvent; use serde_json::json; use settings::{LocalSettingsKind, LocalSettingsPath, SettingsStore}; use util::{ @@ -2407,6 +2410,77 @@ mod repository_activation_tests { assert_repositories(&project, cx, &[path!("/root/nested/repo")], &[]); } + #[gpui::test] + async fn test_removing_worktree_emits_repository_removed(cx: &mut TestAppContext) { + init_test(cx); + let fs = FakeFs::new(cx.background_executor.clone()); + fs.insert_tree( + path!("/root"), + json!({ + "first": { ".git": {}, "a.txt": "" }, + "second": { ".git": {}, "b.txt": "" }, + }), + ) + .await; + let project = Project::test( + fs.clone(), + [ + path!("/root/first").as_ref(), + path!("/root/second").as_ref(), + ], + cx, + ) + .await; + cx.executor().run_until_parked(); + assert_repositories( + &project, + cx, + &[path!("/root/first"), path!("/root/second")], + &[], + ); + + let (second_worktree_id, second_repository_id) = project.read_with(cx, |project, cx| { + let worktree_id = project + .worktrees(cx) + .find(|worktree| { + worktree.read(cx).abs_path().as_ref() == Path::new(path!("/root/second")) + }) + .map(|worktree| worktree.read(cx).id()) + .expect("second worktree should exist"); + let repository_id = project + .repositories(cx) + .values() + .find(|repository| { + repository.read(cx).work_directory_abs_path.as_ref() + == Path::new(path!("/root/second")) + }) + .map(|repository| repository.read(cx).id) + .expect("second repository should exist"); + (worktree_id, repository_id) + }); + + let removed_repository_ids = Rc::new(RefCell::new(Vec::new())); + let git_store = project.read_with(cx, |project, _| project.git_store().clone()); + let _subscription = cx.update({ + let removed_repository_ids = removed_repository_ids.clone(); + |cx| { + cx.subscribe(&git_store, move |_, event, _| { + if let GitStoreEvent::RepositoryRemoved(id) = event { + removed_repository_ids.borrow_mut().push(*id); + } + }) + } + }); + + project.update(cx, |project, cx| { + project.remove_worktree(second_worktree_id, cx); + }); + cx.executor().run_until_parked(); + + assert_repositories(&project, cx, &[path!("/root/first")], &[]); + assert_eq!(*removed_repository_ids.borrow(), vec![second_repository_id]); + } + #[gpui::test] async fn test_nested_repository_inside_active_repository_not_parked(cx: &mut TestAppContext) { init_test(cx); diff --git a/crates/project/tests/integration/project_tests.rs b/crates/project/tests/integration/project_tests.rs index 64de3521afd..3e0b959b7c7 100644 --- a/crates/project/tests/integration/project_tests.rs +++ b/crates/project/tests/integration/project_tests.rs @@ -13185,15 +13185,15 @@ async fn test_visibility_for_paths_in_gitignored_dirs(cx: &mut gpui::TestAppCont let file_in_ignored_dir = PathBuf::from(path!("/dir/.checkouts/worktrees/foo/README.md")); assert_eq!( - project.visibility_for_paths(std::slice::from_ref(&root), true, cx), + project.visibility_for_paths(std::slice::from_ref(&root.as_path()), true, cx), Some(true) ); assert_eq!( - project.visibility_for_paths(std::slice::from_ref(&file), true, cx), + project.visibility_for_paths(std::slice::from_ref(&file.as_path()), true, cx), Some(true) ); assert_eq!( - project.visibility_for_subpaths(std::slice::from_ref(&file), cx), + project.visibility_for_subpaths(std::slice::from_ref(&file.as_path()), cx), Some(true) ); @@ -13202,17 +13202,17 @@ async fn test_visibility_for_paths_in_gitignored_dirs(cx: &mut gpui::TestAppCont // opening an unrelated path. for path in [&ignored_dir, &file_in_ignored_dir] { assert_eq!( - project.visibility_for_paths(std::slice::from_ref(path), true, cx), + project.visibility_for_paths(std::slice::from_ref(&path.as_path()), true, cx), None, "{path:?} should not be considered contained" ); assert_eq!( - project.visibility_for_paths(std::slice::from_ref(path), false, cx), + project.visibility_for_paths(std::slice::from_ref(&path.as_path()), false, cx), None, "{path:?} should not be considered contained" ); assert_eq!( - project.visibility_for_subpaths(std::slice::from_ref(path), cx), + project.visibility_for_subpaths(std::slice::from_ref(&path.as_path()), cx), None, "{path:?} should not be considered a contained subpath" ); diff --git a/crates/project/tests/integration/task_inventory.rs b/crates/project/tests/integration/task_inventory.rs index 6c51fa93571..ad8bf75b5c5 100644 --- a/crates/project/tests/integration/task_inventory.rs +++ b/crates/project/tests/integration/task_inventory.rs @@ -6,6 +6,7 @@ use serde_json::json; use settings::SettingsLocation; use std::path::Path; use std::sync::Arc; +use task::{ResolvedTask, TaskId}; use util::rel_path::rel_path; use project::task_store::{TaskSettingsLocation, TaskStore}; @@ -271,14 +272,14 @@ async fn test_task_list_sorting(cx: &mut TestAppContext) { resolved_task_names(&inventory, None, cx).await, vec![ "worktree_task_1".to_string(), - "1_a_task".to_string(), + "3_task".to_string(), "1_task".to_string(), "2_task".to_string(), - "3_task".to_string(), + "1_a_task".to_string(), "10_hello".to_string(), "11_hello".to_string(), ], - "After global tasks update, worktree task usage is not erased and it's the first still; global task is back to regular order as its file was updated" + "After global tasks update, usages of the tasks with unchanged definitions are kept" ); register_task_used(&inventory, "11_hello", cx).await; @@ -291,10 +292,10 @@ async fn test_task_list_sorting(cx: &mut TestAppContext) { vec![ "11_hello".to_string(), "worktree_task_1".to_string(), - "1_a_task".to_string(), + "3_task".to_string(), "1_task".to_string(), "2_task".to_string(), - "3_task".to_string(), + "1_a_task".to_string(), "10_hello".to_string(), ], ); @@ -608,6 +609,187 @@ async fn test_zed_tasks_take_precedence_over_vscode(cx: &mut TestAppContext) { ); } +#[gpui::test] +async fn test_tasks_file_update_keeps_history_of_unchanged_tasks(cx: &mut TestAppContext) { + init_test(cx); + let inventory = cx.update(|cx| Inventory::new(cx)); + let update_tasks = |tasks: String, cx: &mut TestAppContext| { + inventory.update(cx, |inventory, _| { + inventory + .update_file_based_tasks(TaskSettingsLocation::Global(tasks_file()), Some(&tasks)) + .unwrap(); + }); + }; + + update_tasks(mock_tasks_from_names(["first", "second"]), cx); + register_task_used(&inventory, "first", cx).await; + let first_id = newest_task(&inventory, cx).unwrap().id; + register_task_used(&inventory, "second", cx).await; + let second_id = newest_task(&inventory, cx).unwrap().id; + + update_tasks(mock_tasks_from_names(["first", "second"]), cx); + assert_eq!( + newest_task(&inventory, cx).map(|task| task.id), + Some(second_id.clone()), + "Saving the file without changes should keep the newest task" + ); + assert_eq!( + resolved_task_names(&inventory, None, cx).await, + vec!["second".to_string(), "first".to_string()], + ); + + let edited_second = serde_json::to_string(&json!([ + { "label": "first", "command": "echo", "args": ["first"] }, + { "label": "second", "command": "echo", "args": ["edited"] }, + ])) + .unwrap(); + update_tasks(edited_second.clone(), cx); + assert_eq!( + newest_task(&inventory, cx).map(|task| task.id), + None, + "Editing the newest task should not make the older task the rerun target" + ); + assert_eq!( + task_by_id(&inventory, &second_id, cx).map(|task| task.id), + None, + "An edited task should not rerun with its old definition" + ); + assert_eq!( + task_by_id(&inventory, &first_id, cx).map(|task| task.id), + Some(first_id.clone()), + "An unchanged task should stay reachable by its id" + ); + assert_eq!( + resolved_task_names(&inventory, None, cx).await, + vec!["first".to_string(), "second".to_string()], + ); + + register_task_used(&inventory, "first", cx).await; + assert_eq!( + newest_task(&inventory, cx).map(|task| task.id), + Some(first_id.clone()), + "Scheduling a task should restore the rerun target" + ); + + register_task_used(&inventory, "second", cx).await; + let edited_second_id = newest_task(&inventory, cx).unwrap().id; + let edited_first = serde_json::to_string(&json!([ + { "label": "first", "command": "echo", "args": ["edited"] }, + { "label": "second", "command": "echo", "args": ["edited"] }, + ])) + .unwrap(); + update_tasks(edited_first, cx); + assert_eq!( + newest_task(&inventory, cx).map(|task| task.id), + Some(edited_second_id), + "Editing an older task should not affect the rerun target" + ); +} + +#[gpui::test] +async fn test_deleting_tasks_from_history_updates_rerun_target(cx: &mut TestAppContext) { + init_test(cx); + let inventory = cx.update(|cx| Inventory::new(cx)); + let update_tasks = |tasks: String, cx: &mut TestAppContext| { + inventory.update(cx, |inventory, _| { + inventory + .update_file_based_tasks(TaskSettingsLocation::Global(tasks_file()), Some(&tasks)) + .unwrap(); + }); + }; + let delete_task = |task_id: &TaskId, cx: &mut TestAppContext| { + inventory.update(cx, |inventory, _| { + inventory.delete_previously_used(task_id); + }); + }; + + update_tasks(mock_tasks_from_names(["first", "second", "third"]), cx); + register_task_used(&inventory, "first", cx).await; + let first_id = newest_task(&inventory, cx).unwrap().id; + register_task_used(&inventory, "second", cx).await; + let second_id = newest_task(&inventory, cx).unwrap().id; + register_task_used(&inventory, "third", cx).await; + let third_id = newest_task(&inventory, cx).unwrap().id; + + delete_task(&third_id, cx); + assert_eq!( + newest_task(&inventory, cx).map(|task| task.id), + Some(second_id.clone()), + "Deleting the newest task should make the previous one the rerun target" + ); + + delete_task(&first_id, cx); + assert_eq!( + newest_task(&inventory, cx).map(|task| task.id), + Some(second_id.clone()), + "Deleting an older task should not affect the rerun target" + ); + + delete_task(&second_id, cx); + assert_eq!(newest_task(&inventory, cx).map(|task| task.id), None); + + register_task_used(&inventory, "first", cx).await; + register_task_used(&inventory, "second", cx).await; + register_task_used(&inventory, "third", cx).await; + let edited_third = serde_json::to_string(&json!([ + { "label": "first", "command": "echo", "args": ["first"] }, + { "label": "second", "command": "echo", "args": ["second"] }, + { "label": "third", "command": "echo", "args": ["edited"] }, + ])) + .unwrap(); + update_tasks(edited_third, cx); + delete_task(&third_id, cx); + assert_eq!( + newest_task(&inventory, cx).map(|task| task.id), + None, + "Deleting an already invalidated task should not make an older task the rerun target" + ); + delete_task(&second_id, cx); + assert_eq!( + newest_task(&inventory, cx).map(|task| task.id), + None, + "Deleting an older task should not restore the invalidated rerun target" + ); +} + +#[gpui::test] +async fn test_worktree_tasks_file_update_keeps_history_of_unchanged_tasks(cx: &mut TestAppContext) { + init_test(cx); + let inventory = cx.update(|cx| Inventory::new(cx)); + let worktree_id = WorktreeId::from_usize(0); + let update_tasks = |tasks: String, path: &str, cx: &mut TestAppContext| { + inventory.update(cx, |inventory, _| { + inventory + .update_file_based_tasks( + TaskSettingsLocation::Worktree(SettingsLocation { + worktree_id, + path: rel_path(path), + }), + Some(&tasks), + ) + .unwrap(); + }); + }; + + update_tasks(mock_tasks_from_names(["task"]), ".zed", cx); + register_worktree_task_used(&inventory, worktree_id, "task", cx).await; + let task_id = newest_task(&inventory, cx).unwrap().id; + + update_tasks(mock_tasks_from_names(["other"]), "nested/.zed", cx); + update_tasks(mock_tasks_from_names(["task", "new"]), ".zed", cx); + assert_eq!( + newest_task(&inventory, cx).map(|task| task.id), + Some(task_id.clone()), + ); + + update_tasks("[]".to_string(), ".zed", cx); + assert_eq!(newest_task(&inventory, cx).map(|task| task.id), None); + assert_eq!( + task_by_id(&inventory, &task_id, cx).map(|task| task.id), + None, + ); +} + fn init_test(_cx: &mut TestAppContext) { zlog::init_test(); TaskStore::init(None); @@ -635,6 +817,24 @@ fn resolved_task_names( }) } +fn newest_task(inventory: &Entity, cx: &mut TestAppContext) -> Option { + inventory.read_with(cx, |inventory, _| { + inventory.last_scheduled_task(None).map(|(_, task)| task) + }) +} + +fn task_by_id( + inventory: &Entity, + task_id: &TaskId, + cx: &mut TestAppContext, +) -> Option { + inventory.read_with(cx, |inventory, _| { + inventory + .last_scheduled_task(Some(task_id)) + .map(|(_, task)| task) + }) +} + fn mock_tasks_from_names<'a>(task_names: impl IntoIterator + 'a) -> String { serde_json::to_string(&serde_json::Value::Array( task_names diff --git a/crates/project_bookmarks/src/project_bookmarks.rs b/crates/project_bookmarks/src/project_bookmarks.rs index e86889760d3..aae62ae9f5a 100644 --- a/crates/project_bookmarks/src/project_bookmarks.rs +++ b/crates/project_bookmarks/src/project_bookmarks.rs @@ -1,7 +1,7 @@ use std::{collections::HashSet, sync::Arc}; use futures::future::{FutureExt, Shared}; -use fuzzy_nucleo::{Case, LengthPenalty, StringMatchCandidate, match_strings}; +use fuzzy_nucleo::{StringMatchCandidate, match_strings}; use gpui::{ App, Context, DismissEvent, Entity, ParentElement, SharedString, Task, WeakEntity, Window, actions, @@ -156,13 +156,7 @@ impl PickerDelegate for ProjectBookmarksDelegate { .map(|(i, bookmark)| StringMatchCandidate::new(i, &bookmark.label)) .collect(); - let matches = match_strings( - candidates.as_slice(), - &query, - Case::Smart, - LengthPenalty::On, - candidates.len(), - ); + let matches = match_strings(candidates.as_slice(), &query, Default::default()); picker .update(cx, |picker, cx| { diff --git a/crates/recent_projects/src/recent_projects.rs b/crates/recent_projects/src/recent_projects.rs index c3d1654a95e..c4447cd8554 100644 --- a/crates/recent_projects/src/recent_projects.rs +++ b/crates/recent_projects/src/recent_projects.rs @@ -10,8 +10,6 @@ use std::{ sync::Arc, }; -use chrono::{DateTime, Utc}; - use fs::Fs; #[cfg(target_os = "windows")] @@ -22,7 +20,9 @@ pub use remote_connection::{RemoteConnectionModal, connect, connect_with_modal}; pub use remote_connections::{navigate_to_positions, open_remote_project}; use disconnected_overlay::DisconnectedOverlay; -use fuzzy_nucleo::{StringMatch, StringMatchCandidate, match_strings}; +use fuzzy_nucleo::{ + MaxResults, StringMatch, StringMatchCandidate, StringMatchOptions, match_strings, +}; use gpui::{ Action, AnyElement, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, Subscription, Task, TaskExt, WeakEntity, Window, actions, px, @@ -43,7 +43,10 @@ use ui::{ ButtonLike, ContextMenu, Divider, HighlightedLabel, KeyBinding, ListItem, ListItemSpacing, ListSubHeader, PopoverMenu, PopoverMenuHandle, TintColor, Tooltip, prelude::*, }; -use util::{ResultExt, paths::PathExt}; +use util::{ + ResultExt, + paths::{PathExt, PathStyle}, +}; use workspace::{ HistoryManager, ModalView, MultiWorkspace, OpenMode, OpenOptions, OpenVisible, RecentWorkspace, SerializedWorkspaceLocation, Workspace, WorkspaceDb, WorkspaceId, @@ -56,15 +59,6 @@ actions!( [ToggleActionsMenu, RemoveSelected, AddToWorkspace,] ); -#[derive(Clone, Debug)] -pub struct RecentProjectEntry { - pub name: SharedString, - pub full_path: SharedString, - pub paths: Vec, - pub workspace_id: WorkspaceId, - pub timestamp: DateTime, -} - #[derive(Clone, Debug)] struct OpenFolderEntry { worktree_id: WorktreeId, @@ -118,78 +112,6 @@ enum ProjectPickerStyle { Popover, } -pub async fn get_recent_projects( - current_workspace_id: Option, - limit: Option, - fs: Arc, - db: &WorkspaceDb, -) -> Vec { - let workspaces = db - .recent_project_workspaces(fs.as_ref()) - .await - .unwrap_or_default(); - - let filtered: Vec<_> = workspaces - .into_iter() - .filter(|workspace| Some(workspace.workspace_id) != current_workspace_id) - .filter(|workspace| matches!(workspace.location, SerializedWorkspaceLocation::Local)) - .collect(); - - let mut all_paths: Vec = filtered - .iter() - .flat_map(|workspace| workspace.identity_paths.paths().iter().cloned()) - .collect(); - all_paths.sort_unstable(); - all_paths.dedup(); - let path_details = - util::disambiguate::compute_disambiguation_details(&all_paths, |path, detail| { - project::path_suffix(path, detail) - }); - let path_detail_map: std::collections::HashMap = - all_paths.into_iter().zip(path_details).collect(); - - let entries: Vec = filtered - .into_iter() - .map(|workspace| { - let paths: Vec = workspace.paths.paths().to_vec(); - let ordered_paths: Vec<&PathBuf> = workspace.identity_paths.ordered_paths().collect(); - - let name = ordered_paths - .iter() - .map(|p| { - let detail = path_detail_map.get(*p).copied().unwrap_or(0); - project::path_suffix(p, detail) - }) - .filter(|s| !s.is_empty()) - .collect::>() - .join(", "); - - let full_path = ordered_paths - .iter() - .map(|p| p.to_string_lossy().to_string()) - .collect::>() - .join("\n"); - - RecentProjectEntry { - name: SharedString::from(name), - full_path: SharedString::from(full_path), - paths, - workspace_id: workspace.workspace_id, - timestamp: workspace.timestamp, - } - }) - .collect(); - - match limit { - Some(n) => entries.into_iter().take(n).collect(), - None => entries, - } -} - -pub async fn delete_recent_project(workspace_id: WorkspaceId, db: &WorkspaceDb) { - let _ = db.delete_workspace_by_id(workspace_id).await; -} - fn get_open_folders(workspace: &Workspace, cx: &App) -> Vec { let project = workspace.project().read(cx); let connection_options = project.remote_connection_options(cx); @@ -970,7 +892,10 @@ impl PickerDelegate for RecentProjectsDelegate { cx: &mut Context>, ) -> gpui::Task<()> { let query = query.trim_start(); - let case = fuzzy_nucleo::Case::smart_if_uppercase_in(query); + let match_options = StringMatchOptions { + max_results: MaxResults::limit::<100>(), + ..Default::default() + }; let is_empty_query = query.is_empty(); let folder_matches = if self.open_folders.is_empty() { @@ -983,13 +908,7 @@ impl PickerDelegate for RecentProjectsDelegate { .map(|(id, folder)| StringMatchCandidate::new(id, folder.name.as_ref())) .collect(); - match_strings( - &candidates, - query, - case, - fuzzy_nucleo::LengthPenalty::On, - 100, - ) + match_strings(&candidates, query, match_options) }; let project_group_candidates: Vec<_> = self @@ -1007,13 +926,7 @@ impl PickerDelegate for RecentProjectsDelegate { }) .collect(); - let project_group_matches = match_strings( - &project_group_candidates, - query, - case, - fuzzy_nucleo::LengthPenalty::On, - 100, - ); + let project_group_matches = match_strings(&project_group_candidates, query, match_options); // Build candidates for recent projects (not current, not sibling, not open folder) let recent_candidates: Vec<_> = self @@ -1032,13 +945,7 @@ impl PickerDelegate for RecentProjectsDelegate { }) .collect(); - let recent_matches = match_strings( - &recent_candidates, - query, - case, - fuzzy_nucleo::LengthPenalty::On, - 100, - ); + let recent_matches = match_strings(&recent_candidates, query, match_options); let mut entries = Vec::new(); @@ -1363,14 +1270,19 @@ impl PickerDelegate for RecentProjectsDelegate { let tooltip_path: SharedString = ordered_paths.join("\n").into(); let icon = icon_for_project_group(key); let show_icon = self.filtered_entries_include_remote_project(); + let path_style = self.path_style_for_project_group(key, window, cx); let mut path_start_offset = 0; let (match_labels, path_highlights): (Vec<_>, Vec<_>) = paths .ordered_paths() .map(|p| p.compact()) .map(|path| { - let highlighted_text = - highlights_for_path(path.as_ref(), &hit.positions, path_start_offset); + let highlighted_text = highlights_for_path( + path.as_ref(), + path_style, + &hit.positions, + path_start_offset, + ); path_start_offset += highlighted_text.1.text.len(); highlighted_text }) @@ -1378,7 +1290,7 @@ impl PickerDelegate for RecentProjectsDelegate { let highlighted_match = HighlightedMatchWithPaths { prefix: None, - match_label: HighlightedMatch::join(match_labels.into_iter().flatten(), ", "), + match_label: HighlightedMatch::join(match_labels.into_iter(), ", "), paths: path_highlights, active: is_active, }; @@ -1478,6 +1390,7 @@ impl PickerDelegate for RecentProjectsDelegate { } ProjectPickerEntry::RecentProject(hit) => { let workspace = self.workspaces.get(hit.candidate_id)?; + let path_style = workspace.effective_path_style(); let location = &workspace.location; let raw_paths = &workspace.paths; let identity_paths = &workspace.identity_paths; @@ -1504,8 +1417,12 @@ impl PickerDelegate for RecentProjectsDelegate { .ordered_paths() .map(|p| p.compact()) .map(|path| { - let highlighted_text = - highlights_for_path(path.as_ref(), &hit.positions, path_start_offset); + let highlighted_text = highlights_for_path( + path.as_ref(), + path_style, + &hit.positions, + path_start_offset, + ); path_start_offset += highlighted_text.1.text.len(); highlighted_text }) @@ -1526,7 +1443,7 @@ impl PickerDelegate for RecentProjectsDelegate { let highlighted_match = HighlightedMatchWithPaths { prefix, - match_label: HighlightedMatch::join(match_labels.into_iter().flatten(), ", "), + match_label: HighlightedMatch::join(match_labels.into_iter(), ", "), paths, active: false, }; @@ -2012,11 +1929,11 @@ pub(crate) fn icon_for_remote_connection(options: Option<&RemoteConnectionOption // Compute the highlighted text for the name and path pub(crate) fn highlights_for_path( path: &Path, + path_style: PathStyle, match_positions: &Vec, path_start_offset: usize, -) -> (Option, HighlightedMatch) { - let path_string = path.to_string_lossy(); - let path_text = path_string.to_string(); +) -> (HighlightedMatch, HighlightedMatch) { + let path_text = path.to_string_lossy().into_owned(); let path_byte_len = path_text.len(); // Get the subset of match highlight positions that line up with the given path. // Also adjusts them to start at the path start @@ -2030,22 +1947,29 @@ pub(crate) fn highlights_for_path( // Again subset the highlight positions to just those that line up with the file_name // again adjusted to the start of the file_name - let file_name_text_and_positions = path.file_name().map(|file_name| { - let file_name_text = file_name.to_string_lossy().into_owned(); - let file_name_start_byte = path_byte_len - file_name_text.len(); - let highlight_positions = path_positions - .iter() - .copied() - .skip_while(|position| *position < file_name_start_byte) - .take_while(|position| *position < file_name_start_byte + file_name_text.len()) - .map(|position| position - file_name_start_byte) - .collect::>(); - HighlightedMatch { - text: file_name_text, - highlight_positions, + let file_name_text_and_positions = path_style + .file_name(path) + .and_then(|file_name| { + let file_name_text = file_name.to_string_lossy().into_owned(); + let file_name_start_byte = path_text.rfind(&file_name_text)?; + let highlight_positions = path_positions + .iter() + .copied() + .skip_while(|position| *position < file_name_start_byte) + .take_while(|position| *position < file_name_start_byte + file_name_text.len()) + .map(|position| position - file_name_start_byte) + .collect::>(); + Some(HighlightedMatch { + text: file_name_text, + highlight_positions, + color: Color::Default, + }) + }) + .unwrap_or_else(|| HighlightedMatch { + text: path_text.clone(), + highlight_positions: path_positions.clone(), color: Color::Default, - } - }); + }); ( file_name_text_and_positions, @@ -2413,6 +2337,40 @@ impl RecentProjectsDelegate { false } + fn path_style_for_project_group( + &self, + key: &ProjectGroupKey, + window: &Window, + cx: &App, + ) -> PathStyle { + if key.host().is_none() { + return PathStyle::local(); + } + + // Prefer a loaded workspace's live connection; fall back to the persisted value for + // groups that haven't connected yet (e.g. restored from a previous session). + let live_path_style = + window + .root::() + .flatten() + .and_then(|multi_workspace| { + multi_workspace + .read(cx) + .workspaces_for_project_group(key, cx) + .next() + .map(|workspace| workspace.read(cx).path_style(cx)) + }); + + live_path_style + .or_else(|| { + self.workspaces + .iter() + .find(|workspace| key.matches_identity(&workspace.project_group_key())) + .and_then(|workspace| workspace.path_style) + }) + .unwrap_or_else(PathStyle::local) + } + fn is_active_project_group(&self, key: &ProjectGroupKey, cx: &App) -> bool { if let Some(workspace) = self.workspace.upgrade() { return workspace.read(cx).project_group_key(cx) == *key; @@ -2466,6 +2424,7 @@ impl RecentProjectsDelegate { #[cfg(test)] mod tests { + use chrono::Utc; use gpui::{TestAppContext, UpdateGlobal, VisualTestContext}; use serde_json::json; @@ -2526,6 +2485,7 @@ mod tests { location: SerializedWorkspaceLocation::Local, paths: paths.clone(), identity_paths: paths, + path_style: Some(PathStyle::local()), timestamp: Utc::now(), } } @@ -2712,6 +2672,7 @@ mod tests { location: SerializedWorkspaceLocation::Local, paths: paths.clone(), identity_paths: paths.clone(), + path_style: Some(PathStyle::local()), timestamp: Utc::now(), }; let remote_workspace = RecentWorkspace { @@ -2721,6 +2682,7 @@ mod tests { )), paths: paths.clone(), identity_paths: paths, + path_style: Some(PathStyle::local()), timestamp: Utc::now(), }; @@ -3299,4 +3261,25 @@ mod tests { "the removed folder should no longer appear in any This Window group, got {groups_after:?}" ); } + + #[test] + fn test_highlights_for_path() { + // path should have name fallback + let path = Path::new(r"C:\"); + let (name_highlight, path_highlight) = + highlights_for_path(path, PathStyle::Windows, &vec![], 0); + assert_eq!(name_highlight.text, path_highlight.text); + + let path = Path::new(r"C:\éx\"); + let (name_highlight, path_highlight) = highlights_for_path( + path, + PathStyle::Windows, + &vec![3], // with é as the input character to match + 0, + ); + assert_eq!(name_highlight.text, String::from("éx")); + assert_eq!(name_highlight.highlight_positions, vec![0]); + assert_eq!(path_highlight.text, String::from(r"C:\éx\")); + assert_eq!(path_highlight.highlight_positions, vec![3]); + } } diff --git a/crates/recent_projects/src/remote_connections.rs b/crates/recent_projects/src/remote_connections.rs index 72dc75d5d27..e060ae376ec 100644 --- a/crates/recent_projects/src/remote_connections.rs +++ b/crates/recent_projects/src/remote_connections.rs @@ -16,7 +16,7 @@ use remote::{ }; pub use settings::SshConnection; use settings::{DevContainerConnection, ExtendingVec, RegisterSetting, Settings, WslConnection}; -use util::paths::PathWithPosition; +use util::paths::{PathStyle, PathWithPosition, url_path_to_path}; use workspace::{AppState, MultiWorkspace, OpenOptions, Workspace, find_existing_workspace}; pub use remote_connection::{ @@ -456,6 +456,7 @@ pub(crate) async fn determine_paths_with_positions( mut paths: Vec, ) -> (Vec, Vec) { let mut paths_with_positions = Vec::::new(); + url_paths_to_paths(&mut paths, remote_connection.path_style()); for path in &mut paths { if let Some(path_str) = path.to_str() { let path_with_position = PathWithPosition::parse_str(&path_str); @@ -472,6 +473,16 @@ pub(crate) async fn determine_paths_with_positions( (paths, paths_with_positions) } +/// `ssh://` URL paths are converted here rather than when the URL is parsed, because the remote's +/// path style is only known once connected. +fn url_paths_to_paths(paths: &mut [PathBuf], path_style: PathStyle) { + for path in paths { + if let Some(url_path) = path.to_str() { + *path = PathBuf::from(url_path_to_path(url_path, path_style)); + } + } +} + async fn path_exists(connection: &Arc, path: &Path) -> bool { let Ok(command) = connection.build_command( Some("test".to_string()), @@ -509,6 +520,234 @@ mod tests { use util::path; use workspace::find_existing_workspace; + // Each remote path style is set explicitly, so the client and remote styles differ on every + // platform the tests run on. + #[gpui::test] + async fn test_determine_paths_with_positions_converts_url_paths_for_remote_path_style( + cx: &mut TestAppContext, + server_cx: &mut TestAppContext, + ) { + init_test(cx); + // As parsed from `ssh://host/C:/`, `ssh://host/C:/project/src/lib.rs` and `ssh://host/a:12`. + let url_paths = ["/C:/", "/C:/project/src/lib.rs", "/a:12"]; + for (path_style, expected_paths) in [ + (PathStyle::Windows, ["C:/", "C:/project/src/lib.rs", "/a"]), + (PathStyle::Unix, ["/C:/", "/C:/project/src/lib.rs", "/a"]), + ] { + let (opts, _server_session, connect_guard) = RemoteClient::fake_server(cx, server_cx); + cx.update(|cx| remote::MockConnection::set_path_style(&opts, path_style, cx)); + drop(connect_guard); + let connection = + remote::connect(opts, Arc::new(remote::MockDelegate), &mut cx.to_async()) + .await + .unwrap(); + + let (paths, paths_with_positions) = determine_paths_with_positions( + &connection, + url_paths.iter().map(PathBuf::from).collect(), + ) + .await; + + let expected_paths = expected_paths.map(PathBuf::from).to_vec(); + assert_eq!(paths, expected_paths, "{path_style:?}"); + assert_eq!( + paths_with_positions + .iter() + .map(|path| (path.path.clone(), path.row)) + .collect::>(), + expected_paths + .into_iter() + .zip([None, None, Some(12)]) + .collect::>(), + "{path_style:?}" + ); + } + } + + // A remote workspace on a Unix host cannot hold a `C:` path, so this needs a Windows host. + #[cfg(target_os = "windows")] + #[gpui::test] + async fn test_drive_letter_url_path_matches_saved_connection_with_other_options( + cx: &mut TestAppContext, + server_cx: &mut TestAppContext, + ) { + let app_state = init_test(cx); + let (opts, _headless) = init_remote_server(cx, server_cx).await; + let host = || SshConnectionOptions { + host: "example.com".to_string().into(), + ..Default::default() + }; + // A saved connection keeps its timeout; options built from a URL leave it unset. + let saved = RemoteConnectionOptions::Ssh(SshConnectionOptions { + connection_timeout: Some(30), + ..host() + }); + cx.update(|cx| remote::MockConnection::report_connection_options(&opts, saved, cx)); + let mut async_cx = cx.to_async(); + let window = open_remote_project( + opts, + vec![PathBuf::from(path!("/project"))], + app_state, + workspace::OpenOptions::default(), + &mut async_cx, + ) + .await + .unwrap(); + cx.executor().run_until_parked(); + + let found = find_existing_workspace( + &[PathBuf::from("/C:/project/src/lib.rs")], + &workspace::OpenOptions::default(), + &ProjectHost::Remote(&RemoteConnectionOptions::Ssh(host())), + &mut async_cx, + ); + + assert_eq!(found.map(|target| target.window), Some(window)); + } + + // A retained workspace on a Windows host matches the requested host, which now answers with a + // Unix path style, as when an SSH alias is repointed. Its style must not leak into the paths + // sent over the fresh connection. It stays connected because the mock disconnect looks the + // connection up by its reported options; no lookup here depends on connection state. + #[gpui::test] + async fn test_url_path_reaches_fresh_connection_unconverted( + cx: &mut TestAppContext, + server_cx: &mut TestAppContext, + ) { + let app_state = init_test(cx); + let (opts, _headless) = init_remote_server(cx, server_cx).await; + let requested_paths = Arc::new(std::sync::Mutex::new(Vec::new())); + cx.update(|cx| { + remote::MockConnection::set_path_style(&opts, PathStyle::Unix, cx); + remote::MockConnection::intercept_messages( + &opts, + cx, + { + let requested_paths = requested_paths.clone(); + move |envelope| { + if let Some(proto::envelope::Payload::AddWorktree(request)) = + envelope.payload.as_mut() + { + // Record the path, then open one the fake server has. + let path = path!("/project/src/lib.rs").to_string(); + let requested = std::mem::replace(&mut request.path, path); + requested_paths.lock().unwrap().push(requested); + } + } + }, + |_| {}, + ); + }); + + let (stale_opts, stale_session, stale_guard) = RemoteClient::fake_server(cx, server_cx); + let ping_handler = server_cx.new(|_| ()); + stale_session.add_request_handler::( + ping_handler.downgrade(), + |_, _, _| async { Ok(proto::Ack {}) }, + ); + cx.update(|cx| { + remote::MockConnection::set_path_style(&stale_opts, PathStyle::Windows, cx); + remote::MockConnection::report_connection_options(&stale_opts, opts.clone(), cx); + }); + drop(stale_guard); + let stale_client = RemoteClient::connect_mock(stale_opts, cx).await; + let stale_project = cx.update(|cx| { + Project::remote( + stale_client.clone(), + app_state.client.clone(), + app_state.node_runtime.clone(), + app_state.user_store.clone(), + app_state.languages.clone(), + app_state.fs.clone(), + false, + cx, + ) + }); + cx.add_window(|window, cx| { + let workspace = cx.new(|cx| { + Workspace::new(None, stale_project.clone(), app_state.clone(), window, cx) + }); + MultiWorkspace::new(workspace, window, cx) + }); + cx.executor().run_until_parked(); + assert_eq!( + stale_project.read_with(cx, |project, cx| project.path_style(cx)), + PathStyle::Windows + ); + + // As parsed from `ssh://host/C:/project/src/lib.rs`, opened with `--new`. + open_remote_project( + opts, + vec![PathBuf::from("/C:/project/src/lib.rs")], + app_state, + workspace::OpenOptions { + workspace_matching: workspace::WorkspaceMatching::None, + ..Default::default() + }, + &mut cx.to_async(), + ) + .await + .unwrap(); + cx.executor().run_until_parked(); + + assert_eq!( + *requested_paths.lock().unwrap(), + vec!["/C:/project/src/lib.rs".to_string()] + ); + } + + // A remote workspace on a Unix host cannot hold a `C:` path, so this needs a Windows host. + #[cfg(target_os = "windows")] + #[gpui::test] + async fn test_drive_letter_url_path_reuses_open_remote_workspace( + cx: &mut TestAppContext, + server_cx: &mut TestAppContext, + ) { + let app_state = init_test(cx); + let (opts, _headless) = init_remote_server(cx, server_cx).await; + let mut async_cx = cx.to_async(); + + let window = open_remote_project( + opts.clone(), + vec![PathBuf::from(path!("/project"))], + app_state.clone(), + workspace::OpenOptions::default(), + &mut async_cx, + ) + .await + .unwrap(); + cx.executor().run_until_parked(); + + // As parsed from `ssh://host/C:/project/src/lib.rs`. + open_remote_project( + opts, + vec![PathBuf::from("/C:/project/src/lib.rs")], + app_state, + workspace::OpenOptions::default(), + &mut async_cx, + ) + .await + .unwrap(); + cx.executor().run_until_parked(); + + assert_eq!( + cx.update(|cx| cx.windows().len()), + 1, + "a drive-letter URL path into the open project should reuse its window" + ); + let opened = window + .read_with(cx, |multi_workspace, cx| { + multi_workspace + .workspace() + .read(cx) + .active_item(cx) + .and_then(|item| item.project_path(cx)) + .map(|project_path| project_path.path.as_unix_str().to_owned()) + }) + .unwrap(); + assert_eq!(opened.as_deref(), Some("src/lib.rs")); + } + #[gpui::test] async fn test_open_remote_project_with_mock_connection( cx: &mut TestAppContext, diff --git a/crates/recent_projects/src/remote_servers/filter.rs b/crates/recent_projects/src/remote_servers/filter.rs index 4472594292b..4da5633ffe3 100644 --- a/crates/recent_projects/src/remote_servers/filter.rs +++ b/crates/recent_projects/src/remote_servers/filter.rs @@ -201,15 +201,15 @@ fn build_server_result( } } +fn match_options() -> fuzzy_nucleo::StringMatchOptions<'static> { + fuzzy_nucleo::StringMatchOptions { + length_penalty: fuzzy_nucleo::LengthPenalty::Off, + ..Default::default() + } +} + pub(super) fn run_sync(data: &FilterData, query: &str) -> Vec { - let case = fuzzy_nucleo::Case::smart_if_uppercase_in(query); - let matches = fuzzy_nucleo::match_strings( - &data.candidates, - query, - case, - fuzzy_nucleo::LengthPenalty::Off, - data.candidates.len(), - ); + let matches = fuzzy_nucleo::match_strings(&data.candidates, query, match_options()); let mut results = build_filter_results(matches, data); results.sort_by(|a, b| b.score.total_cmp(&a.score)); results @@ -221,14 +221,13 @@ pub(super) async fn run_async( cancel: &AtomicBool, executor: BackgroundExecutor, ) -> Option> { - let case = fuzzy_nucleo::Case::smart_if_uppercase_in(query); let matches = fuzzy_nucleo::match_strings_async( &data.candidates, query, - case, - fuzzy_nucleo::LengthPenalty::Off, - data.candidates.len(), - cancel, + fuzzy_nucleo::StringMatchOptions { + cancel_flag: Some(cancel), + ..match_options() + }, executor, ) .await; diff --git a/crates/recent_projects/src/sidebar_recent_projects.rs b/crates/recent_projects/src/sidebar_recent_projects.rs index 0b93ee8aa59..a190582a3ff 100644 --- a/crates/recent_projects/src/sidebar_recent_projects.rs +++ b/crates/recent_projects/src/sidebar_recent_projects.rs @@ -1,6 +1,8 @@ use std::sync::Arc; -use fuzzy_nucleo::{StringMatch, StringMatchCandidate, match_strings}; +use fuzzy_nucleo::{ + MaxResults, StringMatch, StringMatchCandidate, StringMatchOptions, match_strings, +}; use gpui::{ Action, AnyElement, App, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, Subscription, Task, TaskExt, WeakEntity, Window, @@ -167,7 +169,6 @@ impl PickerDelegate for SidebarRecentProjectsDelegate { cx: &mut Context>, ) -> Task<()> { let query = query.trim_start(); - let case = fuzzy_nucleo::Case::smart_if_uppercase_in(query); let is_empty_query = query.is_empty(); let current_workspace_id = self @@ -211,9 +212,10 @@ impl PickerDelegate for SidebarRecentProjectsDelegate { self.filtered_workspaces = match_strings( &candidates, query, - case, - fuzzy_nucleo::LengthPenalty::On, - 100, + StringMatchOptions { + max_results: MaxResults::limit::<100>(), + ..Default::default() + }, ); } @@ -324,8 +326,12 @@ impl PickerDelegate for SidebarRecentProjectsDelegate { .ordered_paths() .map(|p| p.compact()) .map(|path| { - let (label, path_match) = - highlights_for_path(path.as_ref(), &hit.positions, path_start_offset); + let (label, path_match) = highlights_for_path( + path.as_ref(), + workspace.effective_path_style(), + &hit.positions, + path_start_offset, + ); path_start_offset += path_match.text.len(); label }) @@ -340,7 +346,7 @@ impl PickerDelegate for SidebarRecentProjectsDelegate { let highlighted_match = HighlightedMatchWithPaths { prefix, - match_label: HighlightedMatch::join(match_labels.into_iter().flatten(), ", "), + match_label: HighlightedMatch::join(match_labels.into_iter(), ", "), paths: Vec::new(), active: false, }; diff --git a/crates/recent_projects/src/wsl_picker.rs b/crates/recent_projects/src/wsl_picker.rs index 271be7d0f51..9a826da0a49 100644 --- a/crates/recent_projects/src/wsl_picker.rs +++ b/crates/recent_projects/src/wsl_picker.rs @@ -125,13 +125,13 @@ impl picker::PickerDelegate for WslPickerDelegate { .collect::>(); let query = query.trim_start(); - let case = fuzzy_nucleo::Case::smart_if_uppercase_in(query); self.matches = fuzzy_nucleo::match_strings( &candidates, query, - case, - fuzzy_nucleo::LengthPenalty::On, - 100, + fuzzy_nucleo::StringMatchOptions { + max_results: fuzzy_nucleo::MaxResults::limit::<100>(), + ..Default::default() + }, ); self.matches.sort_unstable_by_key(|m| m.candidate_id); diff --git a/crates/remote/src/transport/mock.rs b/crates/remote/src/transport/mock.rs index 798cd14e3d5..ccc2d9e2649 100644 --- a/crates/remote/src/transport/mock.rs +++ b/crates/remote/src/transport/mock.rs @@ -70,6 +70,8 @@ pub struct MockRemoteConnection { server_channel: Arc, server_cx: SendableCx, message_interceptors: parking_lot::Mutex>, + path_style: parking_lot::Mutex, + reported_options: parking_lot::Mutex>, pub(crate) proxy_tx: parking_lot::Mutex< Option< mpsc::UnboundedSender<( @@ -141,18 +143,40 @@ impl MockConnection { client_to_server: impl Fn(&mut Envelope) + Send + Sync + 'static, server_to_client: impl Fn(&mut Envelope) + Send + Sync + 'static, ) { + *Self::pending(options, cx).message_interceptors.lock() = Some(MessageInterceptors { + client_to_server: Arc::new(client_to_server), + server_to_client: Arc::new(server_to_client), + }); + } + + /// Makes the connection report `path_style`, as a connection to a host of another OS would. + pub fn set_path_style(options: &RemoteConnectionOptions, path_style: PathStyle, cx: &mut App) { + *Self::pending(options, cx).path_style.lock() = path_style; + } + + /// Makes the connection report `reported` as its options, as a real connection reports the + /// options it was opened with, such as a saved SSH connection. + pub fn report_connection_options( + options: &RemoteConnectionOptions, + reported: RemoteConnectionOptions, + cx: &mut App, + ) { + *Self::pending(options, cx).reported_options.lock() = Some(reported); + } + + fn pending<'a>( + options: &RemoteConnectionOptions, + cx: &'a App, + ) -> &'a Arc { let RemoteConnectionOptions::Mock(options) = options else { - panic!("message interception requires a mock connection"); + panic!("this requires a mock connection"); }; let (_, connection) = cx .global::() .pending .get(&options.id) - .expect("message interceptors must be installed before connecting"); - *connection.message_interceptors.lock() = Some(MessageInterceptors { - client_to_server: Arc::new(client_to_server), - server_to_client: Arc::new(server_to_client), - }); + .expect("the mock connection must be configured before connecting"); + connection } /// Creates a new mock connection pair for testing. @@ -202,6 +226,8 @@ impl MockConnection { server_channel: server_client.clone(), server_cx: SendableCx::new(server_cx), message_interceptors: parking_lot::Mutex::new(None), + path_style: parking_lot::Mutex::new(PathStyle::local()), + reported_options: parking_lot::Mutex::new(None), proxy_tx: Default::default(), }); @@ -286,7 +312,10 @@ impl RemoteConnection for MockRemoteConnection { } fn connection_options(&self) -> RemoteConnectionOptions { - RemoteConnectionOptions::Mock(self.options.clone()) + self.reported_options + .lock() + .clone() + .unwrap_or_else(|| RemoteConnectionOptions::Mock(self.options.clone())) } fn simulate_disconnect(&self, cx: &AsyncApp) { @@ -356,7 +385,7 @@ impl RemoteConnection for MockRemoteConnection { } fn path_style(&self) -> PathStyle { - PathStyle::local() + *self.path_style.lock() } fn remote_platform(&self) -> crate::RemotePlatform { diff --git a/crates/remote_server/src/headless_project.rs b/crates/remote_server/src/headless_project.rs index bfad457cf8d..b0b2570f9a7 100644 --- a/crates/remote_server/src/headless_project.rs +++ b/crates/remote_server/src/headless_project.rs @@ -29,7 +29,7 @@ use project::{ project_settings::SettingsObserver, search::SearchQuery, task_store::TaskStore, - trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees}, + trusted_worktrees::{PathTrust, TrustedWorktrees}, worktree_store::{WorktreeIdCounter, WorktreeStore}, }; use rpc::{ @@ -132,7 +132,7 @@ impl HeadlessProject { if init_worktree_trust { project::trusted_worktrees::track_worktree_trust( worktree_store.clone(), - None::, + None, Some((session.clone(), ProjectId(REMOTE_SERVER_PROJECT_ID))), None, cx, diff --git a/crates/repl/Cargo.toml b/crates/repl/Cargo.toml index b430b52d404..cccbffb029c 100644 --- a/crates/repl/Cargo.toml +++ b/crates/repl/Cargo.toml @@ -42,7 +42,7 @@ multi_buffer.workspace = true nbformat.workspace = true project.workspace = true remote.workspace = true -runtimelib.workspace = true +jupyter-zmq-client.workspace = true serde.workspace = true serde_json.workspace = true settings.workspace = true diff --git a/crates/repl/src/kernels/mod.rs b/crates/repl/src/kernels/mod.rs index 4e42eae3edd..31e22191e67 100644 --- a/crates/repl/src/kernels/mod.rs +++ b/crates/repl/src/kernels/mod.rs @@ -23,10 +23,11 @@ use std::collections::HashMap; use anyhow::Result; use futures::{FutureExt, StreamExt}; use gpui::{AppContext, AsyncWindowContext, Context}; -use jupyter_protocol::{JupyterKernelspec, JupyterMessageContent}; -use runtimelib::{ +use jupyter_protocol::{ + ExecutionState, JupyterKernelspec, JupyterMessage, JupyterMessageContent, KernelInfoReply, +}; +use jupyter_zmq_client::{ ClientControlConnection, ClientIoPubConnection, ClientShellConnection, ClientStdinConnection, - ExecutionState, JupyterMessage, KernelInfoReply, }; use ui::{Icon, IconName, SharedString}; use util::rel_path::RelPath; @@ -129,8 +130,8 @@ pub fn start_kernel_tasks( .ok(); } Err( - ref err @ (runtimelib::RuntimeError::ParseError { .. } - | runtimelib::RuntimeError::SerdeError(_)), + ref err @ (jupyter_zmq_client::RuntimeError::ParseError { .. } + | jupyter_zmq_client::RuntimeError::SerdeError(_)), ) => { let error_detail = format!("Kernel issue on {channel} channel\n\n{err}"); log::warn!("kernel: {error_detail}"); diff --git a/crates/repl/src/kernels/native_kernel.rs b/crates/repl/src/kernels/native_kernel.rs index d7ee106cab6..caf28e0f796 100644 --- a/crates/repl/src/kernels/native_kernel.rs +++ b/crates/repl/src/kernels/native_kernel.rs @@ -9,8 +9,8 @@ use jupyter_protocol::{ ExecutionState, JupyterKernelspec, JupyterMessage, KernelInfoReply, connection_info::{ConnectionInfo, Transport}, }; +use jupyter_zmq_client::dirs; use project::Fs; -use runtimelib::dirs; use smol::net::TcpListener; use std::{ env, @@ -157,20 +157,24 @@ impl NativeRunningKernel { let session_id = Uuid::new_v4().to_string(); - let iopub_socket = - runtimelib::create_client_iopub_connection(&connection_info, "", &session_id) - .await?; + let iopub_socket = jupyter_zmq_client::create_client_iopub_connection( + &connection_info, + "", + &session_id, + ) + .await?; let control_socket = - runtimelib::create_client_control_connection(&connection_info, &session_id).await?; + jupyter_zmq_client::create_client_control_connection(&connection_info, &session_id) + .await?; - let peer_identity = runtimelib::peer_identity_for_session(&session_id)?; - let shell_socket = runtimelib::create_client_shell_connection_with_identity( + let peer_identity = jupyter_zmq_client::peer_identity_for_session(&session_id)?; + let shell_socket = jupyter_zmq_client::create_client_shell_connection_with_identity( &connection_info, &session_id, peer_identity.clone(), ) .await?; - let stdin_socket = runtimelib::create_client_stdin_connection_with_identity( + let stdin_socket = jupyter_zmq_client::create_client_stdin_connection_with_identity( &connection_info, &session_id, peer_identity, diff --git a/crates/repl/src/kernels/remote_kernels.rs b/crates/repl/src/kernels/remote_kernels.rs index 69a41e85acc..3def0ef3741 100644 --- a/crates/repl/src/kernels/remote_kernels.rs +++ b/crates/repl/src/kernels/remote_kernels.rs @@ -247,11 +247,11 @@ impl Debug for RemoteRunningKernel { } impl RunningKernel for RemoteRunningKernel { - fn request_tx(&self) -> futures::channel::mpsc::Sender { + fn request_tx(&self) -> futures::channel::mpsc::Sender { self.request_tx.clone() } - fn stdin_tx(&self) -> futures::channel::mpsc::Sender { + fn stdin_tx(&self) -> futures::channel::mpsc::Sender { self.stdin_tx.clone() } @@ -259,19 +259,19 @@ impl RunningKernel for RemoteRunningKernel { &self.working_directory } - fn execution_state(&self) -> &runtimelib::ExecutionState { + fn execution_state(&self) -> &jupyter_protocol::ExecutionState { &self.execution_state } - fn set_execution_state(&mut self, state: runtimelib::ExecutionState) { + fn set_execution_state(&mut self, state: jupyter_protocol::ExecutionState) { self.execution_state = state; } - fn kernel_info(&self) -> Option<&runtimelib::KernelInfoReply> { + fn kernel_info(&self) -> Option<&jupyter_protocol::KernelInfoReply> { self.kernel_info.as_ref() } - fn set_kernel_info(&mut self, info: runtimelib::KernelInfoReply) { + fn set_kernel_info(&mut self, info: jupyter_protocol::KernelInfoReply) { self.kernel_info = Some(info); } diff --git a/crates/repl/src/kernels/ssh_kernel.rs b/crates/repl/src/kernels/ssh_kernel.rs index 0317270b2ad..c82c307c6ad 100644 --- a/crates/repl/src/kernels/ssh_kernel.rs +++ b/crates/repl/src/kernels/ssh_kernel.rs @@ -8,8 +8,8 @@ use futures::{ io::BufReader, }; use gpui::{App, Entity, Task, Window}; +use jupyter_protocol::{ExecutionState, JupyterMessage, KernelInfoReply}; use project::Project; -use runtimelib::{ExecutionState, JupyterMessage, KernelInfoReply}; use std::path::PathBuf; use util::ResultExt; @@ -206,7 +206,7 @@ impl SshRunningKernel { )?; // Parse connection info and create ZMQ connections - let connection_info_struct: runtimelib::ConnectionInfo = + let connection_info_struct: jupyter_protocol::ConnectionInfo = serde_json::from_value(local_connection_info)?; let session_id = uuid::Uuid::new_v4().to_string(); @@ -214,7 +214,7 @@ impl SshRunningKernel { let max_retries = 5; let mut retry = 0; loop { - match runtimelib::create_client_iopub_connection( + match jupyter_zmq_client::create_client_iopub_connection( &connection_info_struct, "", &session_id, @@ -243,8 +243,8 @@ impl SshRunningKernel { } }; - let peer_identity = runtimelib::peer_identity_for_session(&session_id)?; - let shell_socket = runtimelib::create_client_shell_connection_with_identity( + let peer_identity = jupyter_zmq_client::peer_identity_for_session(&session_id)?; + let shell_socket = jupyter_zmq_client::create_client_shell_connection_with_identity( &connection_info_struct, &session_id, peer_identity.clone(), @@ -252,10 +252,10 @@ impl SshRunningKernel { .await .context("failed to create shell connection")?; let control_socket = - runtimelib::create_client_control_connection(&connection_info_struct, &session_id) + jupyter_zmq_client::create_client_control_connection(&connection_info_struct, &session_id) .await .context("failed to create control connection")?; - let stdin_socket = runtimelib::create_client_stdin_connection_with_identity( + let stdin_socket = jupyter_zmq_client::create_client_stdin_connection_with_identity( &connection_info_struct, &session_id, peer_identity, diff --git a/crates/repl/src/kernels/wsl_kernel.rs b/crates/repl/src/kernels/wsl_kernel.rs index b4f6d356bf2..f994551c8c6 100644 --- a/crates/repl/src/kernels/wsl_kernel.rs +++ b/crates/repl/src/kernels/wsl_kernel.rs @@ -13,8 +13,8 @@ use jupyter_protocol::{ ExecutionState, JupyterMessage, KernelInfoReply, connection_info::{ConnectionInfo, Transport}, }; +use jupyter_zmq_client::dirs; use project::Fs; -use runtimelib::dirs; use smol::net::TcpListener; use std::{ fmt::Debug, @@ -322,7 +322,7 @@ impl WslRunningKernel { Err(_) => {} } - let output_socket = runtimelib::create_client_iopub_connection( + let output_socket = jupyter_zmq_client::create_client_iopub_connection( &client_connection_info, "", &session_id, @@ -330,8 +330,8 @@ impl WslRunningKernel { .await .context("Failed to create iopub connection. Is `ipykernel` installed in the WSL environment? Try running `pip install ipykernel` inside your WSL distribution.")?; - let peer_identity = runtimelib::peer_identity_for_session(&session_id)?; - let shell_socket = runtimelib::create_client_shell_connection_with_identity( + let peer_identity = jupyter_zmq_client::peer_identity_for_session(&session_id)?; + let shell_socket = jupyter_zmq_client::create_client_shell_connection_with_identity( &client_connection_info, &session_id, peer_identity.clone(), @@ -339,10 +339,10 @@ impl WslRunningKernel { .await?; let control_socket = - runtimelib::create_client_control_connection(&client_connection_info, &session_id) + jupyter_zmq_client::create_client_control_connection(&client_connection_info, &session_id) .await?; - let stdin_socket = runtimelib::create_client_stdin_connection_with_identity( + let stdin_socket = jupyter_zmq_client::create_client_stdin_connection_with_identity( &client_connection_info, &session_id, peer_identity, diff --git a/crates/repl/src/notebook/cell.rs b/crates/repl/src/notebook/cell.rs index 055b49f40ef..97e06a56e59 100644 --- a/crates/repl/src/notebook/cell.rs +++ b/crates/repl/src/notebook/cell.rs @@ -7,10 +7,10 @@ use gpui::{ App, Entity, EventEmitter, Focusable, Hsla, InteractiveElement, RetainAllImageCache, StatefulInteractiveElement, Task, prelude::*, }; +use jupyter_protocol::{JupyterMessage, JupyterMessageContent}; use language::{Buffer, Language, LanguageRegistry}; use markdown::{Markdown, MarkdownElement, MarkdownFont, MarkdownStyle}; use nbformat::v4::{CellId, CellMetadata, CellType}; -use runtimelib::{JupyterMessage, JupyterMessageContent}; use settings::Settings as _; use ui::{CommonAnimationExt, IconButtonShape, prelude::*}; use util::ResultExt; diff --git a/crates/repl/src/notebook/notebook_ui.rs b/crates/repl/src/notebook/notebook_ui.rs index 2467c7e3161..a36ccedb85c 100644 --- a/crates/repl/src/notebook/notebook_ui.rs +++ b/crates/repl/src/notebook/notebook_ui.rs @@ -38,8 +38,8 @@ use crate::kernels::{ use crate::notebook::MovementDirection; use crate::repl_store::ReplStore; +use jupyter_protocol::{ExecuteRequest, JupyterMessage, JupyterMessageContent}; use picker::Picker; -use runtimelib::{ExecuteRequest, JupyterMessage, JupyterMessageContent}; use ui::PopoverMenuHandle; use zed_actions::editor::{MoveDown, MoveUp}; use zed_actions::notebook::{ @@ -565,7 +565,7 @@ impl NotebookEditor { cx: &mut Context, ) { if let Kernel::RunningKernel(kernel) = &self.kernel { - let interrupt_request = runtimelib::InterruptRequest {}; + let interrupt_request = jupyter_protocol::InterruptRequest {}; let message: JupyterMessage = interrupt_request.into(); kernel.request_tx().try_send(message).ok(); cx.notify(); @@ -1698,19 +1698,7 @@ impl project::ProjectItem for NotebookItem { } }; - match notebook { - nbformat::Notebook::V4(notebook) => notebook, - // 4.1 - 4.4 are converted to 4.5 - nbformat::Notebook::Legacy(legacy_notebook) => { - // TODO: Decide if we want to mutate the notebook by including Cell IDs - // and any other conversions - - nbformat::upgrade_legacy_notebook(legacy_notebook)? - } - nbformat::Notebook::V3(v3_notebook) => { - nbformat::upgrade_v3_notebook(v3_notebook)? - } - } + upgrade_notebook(notebook)? }; let id = project @@ -1956,19 +1944,9 @@ impl Item for NotebookEditor { } let file_content = serde_json::to_string(&json)?; - let notebook = nbformat::parse_notebook(&file_content); - let notebook = match notebook { - Ok(nbformat::Notebook::V4(notebook)) => notebook, - Ok(nbformat::Notebook::Legacy(legacy_notebook)) => { - nbformat::upgrade_legacy_notebook(legacy_notebook)? - } - Ok(nbformat::Notebook::V3(v3_notebook)) => { - nbformat::upgrade_v3_notebook(v3_notebook)? - } - Err(e) => { - anyhow::bail!("Failed to parse notebook: {:?}", e); - } - }; + let notebook = nbformat::parse_notebook(&file_content) + .context("Failed to parse notebook") + .and_then(upgrade_notebook)?; this.update_in(cx, |this, window, cx| { let mut cell_order = vec![]; @@ -2053,6 +2031,19 @@ impl KernelSession for NotebookEditor { } } +fn upgrade_notebook(notebook: nbformat::Notebook) -> anyhow::Result { + match notebook { + nbformat::Notebook::V4(notebook) => Ok(notebook), + nbformat::Notebook::V4QuirksMode(notebook) => { + log::warn!("Repairing notebook cell IDs: {:?}", notebook.quirks()); + Ok(notebook.repair()) + } + nbformat::Notebook::Legacy(notebook) => nbformat::upgrade_legacy_notebook(notebook), + nbformat::Notebook::V3(notebook) => nbformat::upgrade_v3_notebook(notebook), + _ => anyhow::bail!("Unsupported notebook format"), + } +} + #[cfg(test)] mod tests { use super::*; @@ -2088,6 +2079,39 @@ mod tests { ] }"#; + #[test] + fn test_upgrade_notebook_repairs_missing_cell_ids() -> anyhow::Result<()> { + let mut value: serde_json::Value = serde_json::from_str(NOTEBOOK_WITH_ONE_CODE_CELL)?; + value["cells"][0] + .as_object_mut() + .context("cell is not an object")? + .remove("id"); + let notebook = nbformat::parse_notebook(&serde_json::to_string(&value)?)?; + assert!(matches!(notebook, nbformat::Notebook::V4QuirksMode(_))); + let repaired = upgrade_notebook(notebook)?; + let serialized = nbformat::serialize_notebook(&nbformat::Notebook::V4(repaired))?; + assert!(matches!( + nbformat::parse_notebook(&serialized)?, + nbformat::Notebook::V4(_) + )); + let saved: serde_json::Value = serde_json::from_str(&serialized)?; + assert_eq!(saved["cells"][0]["source"], value["cells"][0]["source"]); + assert!( + saved["cells"][0]["id"] + .as_str() + .is_some_and(|id| !id.is_empty()) + ); + Ok(()) + } + + #[test] + fn test_upgrade_notebook_preserves_cell_ids() -> anyhow::Result<()> { + let notebook = upgrade_notebook(nbformat::parse_notebook(NOTEBOOK_WITH_ONE_CODE_CELL)?)?; + let value = serde_json::to_value(notebook)?; + assert_eq!(value["cells"][0]["id"], "cell-one"); + Ok(()) + } + /// When the configured interpreter doesn't exist (e.g. Python isn't installed), /// running a cell must not leave it stuck in the executing state. It should /// instead surface the kernel launch error as an error output on the cell. diff --git a/crates/repl/src/outputs.rs b/crates/repl/src/outputs.rs index 54c058bb32f..bb75dbc4830 100644 --- a/crates/repl/src/outputs.rs +++ b/crates/repl/src/outputs.rs @@ -35,9 +35,9 @@ use editor::{Editor, MultiBuffer}; use gpui::{AnyElement, ClipboardItem, Entity, EventEmitter, Render, WeakEntity}; +use jupyter_protocol::{ExecutionState, JupyterMessage, JupyterMessageContent, Media, MediaType}; use language::Buffer; use menu; -use runtimelib::{ExecutionState, JupyterMessage, JupyterMessageContent, MimeBundle, MimeType}; use ui::{CommonAnimationExt, CopyButton, IconButton, Tooltip, prelude::*}; mod image; @@ -65,15 +65,15 @@ use crate::repl_settings::ReplSettings; use settings::Settings; /// When deciding what to render from a collection of mediatypes, we need to rank them in order of importance -fn rank_mime_type(mimetype: &MimeType) -> usize { +fn rank_mime_type(mimetype: &MediaType) -> usize { match mimetype { - MimeType::DataTable(_) => 7, - MimeType::Html(_) => 6, - MimeType::Json(_) => 5, - MimeType::Png(_) => 4, - MimeType::Jpeg(_) => 3, - MimeType::Markdown(_) => 2, - MimeType::Plain(_) => 1, + MediaType::DataTable(_) => 7, + MediaType::Html(_) => 6, + MediaType::Json(_) => 5, + MediaType::Png(_) => 4, + MediaType::Jpeg(_) => 3, + MediaType::Markdown(_) => 2, + MediaType::Plain(_) => 1, // All other media types are not supported in Zed at this time _ => 0, } @@ -390,42 +390,43 @@ impl Output { } pub fn new( - data: &MimeBundle, + data: &Media, display_id: Option, window: &mut Window, cx: &mut App, ) -> Self { match data.richest(rank_mime_type) { - Some(MimeType::Json(json_value)) => match JsonView::from_value(json_value.clone()) { + Some(MediaType::Json(json_value)) => match JsonView::from_value(json_value.clone()) { Ok(json_view) => Output::Json { content: cx.new(|_| json_view), display_id, }, Err(_) => Output::Message("Failed to parse JSON".to_string()), }, - Some(MimeType::Plain(text)) => Output::Plain { + Some(MediaType::Plain(text)) => Output::Plain { content: cx.new(|cx| TerminalOutput::from(text, window, cx)), display_id, }, - Some(MimeType::Markdown(text)) => { + Some(MediaType::Markdown(text)) => { let content = cx.new(|cx| MarkdownView::from(text.clone(), cx)); Output::Markdown { content, display_id, } } - Some(MimeType::Png(data)) | Some(MimeType::Jpeg(data)) => match ImageView::from(data) { + Some(MediaType::Png(data)) | Some(MediaType::Jpeg(data)) => match ImageView::from(data) + { Ok(view) => Output::Image { content: cx.new(|_| view), display_id, }, Err(error) => Output::Message(format!("Failed to load image: {}", error)), }, - Some(MimeType::DataTable(data)) => Output::Table { + Some(MediaType::DataTable(data)) => Output::Table { content: cx.new(|cx| TableView::new(data, window, cx)), display_id, }, - Some(MimeType::Html(html_content)) => match html::html_to_markdown(html_content) { + Some(MediaType::Html(html_content)) => match html::html_to_markdown(html_content) { Ok(markdown_text) => { let content = cx.new(|cx| MarkdownView::from(markdown_text, cx)); Output::Markdown { @@ -591,7 +592,7 @@ impl ExecutionView { } JupyterMessageContent::ExecuteReply(reply) => { for payload in reply.payload.iter() { - if let runtimelib::Payload::Page { data, .. } = payload { + if let jupyter_protocol::Payload::Page { data, .. } = payload { let output = Output::new(data, None, window, cx); self.outputs.push(output); } @@ -659,7 +660,7 @@ impl ExecutionView { pub fn update_display_data( &mut self, - data: &MimeBundle, + data: &Media, display_id: &str, window: &mut Window, cx: &mut Context, @@ -844,9 +845,9 @@ impl Render for ExecutionView { mod tests { use super::*; use gpui::TestAppContext; - use runtimelib::{ + use jupyter_protocol::{ ClearOutput, ErrorOutput, ExecutionState, InputRequest, JupyterMessage, - JupyterMessageContent, MimeType, Status, Stdio, StreamContent, + JupyterMessageContent, MediaType, Status, Stdio, StreamContent, }; use settings::SettingsStore; use std::path::Path; @@ -854,13 +855,13 @@ mod tests { #[test] fn test_rank_mime_type_ordering() { - let data_table = MimeType::DataTable(Box::default()); - let html = MimeType::Html(String::new()); - let json = MimeType::Json(serde_json::json!({})); - let png = MimeType::Png(String::new()); - let jpeg = MimeType::Jpeg(String::new()); - let markdown = MimeType::Markdown(String::new()); - let plain = MimeType::Plain(String::new()); + let data_table = MediaType::DataTable(Box::default()); + let html = MediaType::Html(String::new()); + let json = MediaType::Json(serde_json::json!({})); + let png = MediaType::Png(String::new()); + let jpeg = MediaType::Jpeg(String::new()); + let markdown = MediaType::Markdown(String::new()); + let plain = MediaType::Plain(String::new()); assert_eq!(rank_mime_type(&data_table), 7); assert_eq!(rank_mime_type(&html), 6); @@ -880,8 +881,8 @@ mod tests { #[test] fn test_rank_mime_type_unsupported_returns_zero() { - let svg = MimeType::Svg(String::new()); - let latex = MimeType::Latex(String::new()); + let svg = MediaType::Svg(String::new()); + let latex = MediaType::Latex(String::new()); assert_eq!(rank_mime_type(&svg), 0); assert_eq!(rank_mime_type(&latex), 0); diff --git a/crates/repl/src/outputs/table.rs b/crates/repl/src/outputs/table.rs index fc5ccaf75a5..e1d33dd03e3 100644 --- a/crates/repl/src/outputs/table.rs +++ b/crates/repl/src/outputs/table.rs @@ -55,8 +55,7 @@ //! display(df) //! ``` use gpui::{AnyElement, ClipboardItem, TextRun}; -use runtimelib::datatable::TableSchema; -use runtimelib::media::datatable::TabularDataResource; +use jupyter_protocol::media::datatable::{FieldType, TableSchema, TabularDataResource}; use serde_json::Value; use settings::Settings; use theme_settings::ThemeSettings; @@ -200,16 +199,16 @@ impl TableView { .zip(self.widths.iter()) .map(|(field, width)| { let container = match field.field_type { - runtimelib::datatable::FieldType::String => div(), + FieldType::String => div(), - runtimelib::datatable::FieldType::Number - | runtimelib::datatable::FieldType::Integer - | runtimelib::datatable::FieldType::Date - | runtimelib::datatable::FieldType::Time - | runtimelib::datatable::FieldType::Datetime - | runtimelib::datatable::FieldType::Year - | runtimelib::datatable::FieldType::Duration - | runtimelib::datatable::FieldType::Yearmonth => v_flex().items_end(), + FieldType::Number + | FieldType::Integer + | FieldType::Date + | FieldType::Time + | FieldType::Datetime + | FieldType::Year + | FieldType::Duration + | FieldType::Yearmonth => v_flex().items_end(), _ => div(), }; diff --git a/crates/repl/src/repl.rs b/crates/repl/src/repl.rs index 299641c47d8..85a27096fab 100644 --- a/crates/repl/src/repl.rs +++ b/crates/repl/src/repl.rs @@ -13,8 +13,8 @@ use std::{sync::Arc, time::Duration}; use async_dispatcher::{Dispatcher, Runnable, set_dispatcher}; use gpui::{App, PlatformDispatcher, Priority, RunnableMeta}; +pub use jupyter_protocol::ExecutionState; use project::Fs; -pub use runtimelib::ExecutionState; pub use crate::jupyter_settings::JupyterSettings; pub use crate::kernels::{Kernel, KernelSpecification, KernelStatus, PythonEnvKernelSpecification}; diff --git a/crates/repl/src/session.rs b/crates/repl/src/session.rs index 9b7bd759504..2f99fd1a210 100644 --- a/crates/repl/src/session.rs +++ b/crates/repl/src/session.rs @@ -32,12 +32,12 @@ use futures::FutureExt as _; use gpui::{ Context, Entity, EventEmitter, Render, Subscription, Task, WeakEntity, Window, div, prelude::*, }; -use language::Point; -use project::Fs; -use runtimelib::{ +use jupyter_protocol::{ ExecuteRequest, ExecutionState, InputReply, InterruptRequest, JupyterMessage, JupyterMessageContent, KernelInfoRequest, ReplyStatus, ShutdownRequest, }; +use language::Point; +use project::Fs; use settings::Settings as _; use std::{env::temp_dir, ops::Range, sync::Arc, time::Duration}; use theme::ActiveTheme; diff --git a/crates/sandbox/src/bwrap_test_helper.rs b/crates/sandbox/src/bwrap_test_helper.rs index 706991db77e..0b68bb7b793 100644 --- a/crates/sandbox/src/bwrap_test_helper.rs +++ b/crates/sandbox/src/bwrap_test_helper.rs @@ -196,6 +196,7 @@ mod imp { let fs = match check.fs { FsMode::Unrestricted => SandboxFsPolicy::Unrestricted { protected_paths: capture_protected_paths(&check.protected_paths), + protected_file_names: Vec::new(), }, FsMode::Restricted => { let mut writable_paths = Vec::new(); @@ -213,6 +214,7 @@ mod imp { SandboxFsPolicy::Restricted { writable_paths, protected_paths, + protected_file_names: Vec::new(), } } }; diff --git a/crates/sandbox/src/macos_seatbelt.rs b/crates/sandbox/src/macos_seatbelt.rs index a62803a84f5..94f70edc7f4 100644 --- a/crates/sandbox/src/macos_seatbelt.rs +++ b/crates/sandbox/src/macos_seatbelt.rs @@ -27,6 +27,8 @@ use std::{io::Write, path::PathBuf}; use anyhow::{Context, Result}; use tempfile::NamedTempFile; +use crate::ProtectedFileName; + /// Per-command relaxations of the default Seatbelt sandbox. /// /// All-false is the default, fully-sandboxed run. Setting any field @@ -91,12 +93,16 @@ impl SeatbeltConfigFile { /// `protected_paths` lists paths whose writes should be blocked even if they /// fall under a writable directory. Contents remain readable. /// + /// `protected_file_names` lists file names whose writes are blocked + /// wherever they appear (see [`ProtectedFileName`]). + /// /// `allowed_unix_socket_paths` lists Unix domain sockets the command may /// connect to for local IPC even when IP network access is otherwise /// disabled. This does not permit sending packets to other machines. pub fn new( writable_directories: &[&Path], protected_paths: &[&Path], + protected_file_names: &[ProtectedFileName], allowed_unix_socket_paths: &[&Path], permissions: SandboxPermissions, ) -> Result { @@ -106,6 +112,7 @@ impl SeatbeltConfigFile { let config = generate_seatbelt_config( writable_directories, protected_paths, + protected_file_names, allowed_unix_socket_paths, permissions, )?; @@ -139,6 +146,8 @@ impl SeatbeltConfigFile { /// the writable scope would let the model write outside the project). /// * `protected_paths` - Paths whose writes should be denied even if they fall /// under a writable directory. Contents remain readable. +/// * `protected_file_names` - File names whose writes should be denied wherever +/// they appear (see [`ProtectedFileName`]). Contents remain readable. /// * `allowed_unix_socket_paths` - Unix domain sockets the command may /// connect to for local IPC even when IP network access is otherwise /// disabled. This does not permit sending packets to other machines. @@ -152,12 +161,14 @@ pub fn wrap_invocation( args: &[String], writable_directories: &[&Path], protected_paths: &[&Path], + protected_file_names: &[ProtectedFileName], allowed_unix_socket_paths: &[&Path], permissions: SandboxPermissions, ) -> Result<(String, Vec, SeatbeltConfigFile)> { let config_file = SeatbeltConfigFile::new( writable_directories, protected_paths, + protected_file_names, allowed_unix_socket_paths, permissions, )?; @@ -190,10 +201,11 @@ pub fn wrap_invocation( /// worktree paths plus any per-command scratch directory the caller wants /// allowed) and the standard `/dev/*` write targets are also allowed by /// default. Writes to paths in `protected_paths` are denied even when they -/// would otherwise be writable; contents remain readable. Unix domain socket paths in -/// `allowed_unix_socket_paths` are reachable for local IPC even when IP -/// network access is otherwise blocked. This does not permit sending packets -/// to other machines. +/// would otherwise be writable; contents remain readable. The same holds for +/// any path whose final component matches one of `protected_file_names`. Unix +/// domain socket paths in `allowed_unix_socket_paths` are reachable for local +/// IPC even when IP network access is otherwise blocked. This does not permit +/// sending packets to other machines. /// /// Network access and unrestricted filesystem writes must be requested via /// [`SandboxPermissions`]. @@ -203,6 +215,7 @@ pub fn wrap_invocation( fn generate_seatbelt_config( writable_directories: &[&Path], protected_paths: &[&Path], + protected_file_names: &[ProtectedFileName], allowed_unix_socket_paths: &[&Path], permissions: SandboxPermissions, ) -> Result { @@ -354,6 +367,21 @@ fn generate_seatbelt_config( )); } + // Seatbelt applies the last matching rule, so these denies must follow the + // writable-path allows above. `file-write*` covers creating, writing, + // truncating, unlinking, renaming (source and destination), and creating + // hard or symbolic links. + for name in protected_file_names { + let escaped_regex = escape_sandbox_string(&protected_file_name_regex(name)); + config.push_str(&format!( + r#" +; Block writes to every file with a protected name +(deny file-write* + (regex "{escaped_regex}")) +"# + )); + } + match permissions.network { NetworkAccess::None => {} NetworkAccess::All => { @@ -447,7 +475,37 @@ fn escape_sandbox_path(path: &Path) -> Result { let path_str = path .to_str() .with_context(|| format!("path contains invalid UTF-8: {}", path.display()))?; - Ok(path_str.replace('\\', "\\\\").replace('"', "\\\"")) + Ok(escape_sandbox_string(path_str)) +} + +/// Escape text for use inside a double-quoted Seatbelt string literal. +fn escape_sandbox_string(text: &str) -> String { + text.replace('\\', "\\\\").replace('"', "\\\"") +} + +/// Build a regex matching any absolute path whose final component is `name`. +/// +/// Every regex metacharacter is backslash-escaped so the name matches +/// literally. ASCII letters become classes such as `[eE]` because APFS is +/// case-insensitive by default and Seatbelt's regex has no case-insensitive +/// flag. Non-ASCII characters are not case-folded. +fn protected_file_name_regex(name: &ProtectedFileName) -> String { + let mut regex = String::from("/"); + for character in name.as_str().chars() { + if character.is_ascii_alphabetic() { + regex.push('['); + regex.push(character.to_ascii_lowercase()); + regex.push(character.to_ascii_uppercase()); + regex.push(']'); + } else { + if r"\.^$|?*+()[]{}".contains(character) { + regex.push('\\'); + } + regex.push(character); + } + } + regex.push('$'); + regex } #[cfg(test)] @@ -475,9 +533,14 @@ mod tests { #[test] fn test_generate_seatbelt_config_contains_read_and_project_write_permissions_by_default() { let dir = PathBuf::from("/Users/test/projects/myproject"); - let config = - generate_seatbelt_config(&[dir.as_path()], &[], &[], SandboxPermissions::default()) - .unwrap(); + let config = generate_seatbelt_config( + &[dir.as_path()], + &[], + &[], + &[], + SandboxPermissions::default(), + ) + .unwrap(); assert!(config.contains("(allow file-read*)")); assert!(config.contains("/Users/test/projects/myproject")); @@ -493,6 +556,7 @@ mod tests { &[dir.as_path()], &[], &[], + &[], SandboxPermissions { network: NetworkAccess::None, allow_fs_write: true, @@ -510,9 +574,14 @@ mod tests { #[test] fn test_generate_seatbelt_config_allows_terminal_ioctls_by_default() { let dir = PathBuf::from("/Users/test/projects/myproject"); - let config = - generate_seatbelt_config(&[dir.as_path()], &[], &[], SandboxPermissions::default()) - .unwrap(); + let config = generate_seatbelt_config( + &[dir.as_path()], + &[], + &[], + &[], + SandboxPermissions::default(), + ) + .unwrap(); assert!(config.contains("(allow file-ioctl")); assert!(config.contains("/dev/ptmx")); @@ -522,9 +591,14 @@ mod tests { #[test] fn test_generate_seatbelt_config_scopes_mach_lookup_and_excludes_escape_services() { let dir = PathBuf::from("/Users/test/projects/myproject"); - let config = - generate_seatbelt_config(&[dir.as_path()], &[], &[], SandboxPermissions::default()) - .unwrap(); + let config = generate_seatbelt_config( + &[dir.as_path()], + &[], + &[], + &[], + SandboxPermissions::default(), + ) + .unwrap(); // Assert on the rules only: the mach-lookup comment intentionally spells // out the blanket `(allow mach-lookup)` form it avoids, which a raw // `config.contains` would match. @@ -554,6 +628,7 @@ mod tests { &[dir.as_path()], &[], &[], + &[], SandboxPermissions { network: NetworkAccess::All, allow_fs_write: false, @@ -577,6 +652,7 @@ mod tests { let config = generate_seatbelt_config( &[dir.as_path()], &[], + &[], &[socket_path.as_path()], SandboxPermissions::default(), ) @@ -643,6 +719,7 @@ mod tests { ], &[temp_dir.path()], &[], + &[], &[socket_path.as_path(), canonical_socket_path.as_path()], SandboxPermissions::default(), ) @@ -670,6 +747,7 @@ mod tests { &[dir.as_path()], &[protected.as_path()], &[], + &[], SandboxPermissions::default(), ) .unwrap(); @@ -707,6 +785,7 @@ mod tests { &[dir.as_path()], &[protected_file.as_path()], &[], + &[], SandboxPermissions::default(), ) .unwrap(); @@ -752,6 +831,7 @@ mod tests { &[dir.as_path()], &[protected_file.as_path()], &[], + &[], SandboxPermissions { network: NetworkAccess::None, allow_fs_write: true, @@ -776,6 +856,167 @@ mod tests { ); } + #[test] + fn test_sandbox_blocks_every_write_to_protected_file_names() { + struct Case { + description: &'static str, + envrc_exists: bool, + command: &'static str, + target: &'static str, + } + let cases = [ + Case { + description: "create at the writable root", + envrc_exists: false, + command: "echo x > .envrc", + target: ".envrc", + }, + Case { + description: "create in a directory made by the same command", + envrc_exists: false, + command: "mkdir -p nested/deeper && echo x > nested/deeper/.envrc", + target: "nested/deeper/.envrc", + }, + Case { + description: "create with different ASCII case", + envrc_exists: false, + command: "echo x > .ENVRC", + target: ".ENVRC", + }, + Case { + description: "append to an existing file", + envrc_exists: true, + command: "echo x >> .envrc", + target: ".envrc", + }, + Case { + description: "delete an existing file", + envrc_exists: true, + command: "rm .envrc", + target: ".envrc", + }, + Case { + description: "rename another file onto it", + envrc_exists: true, + command: "mv other .envrc", + target: ".envrc", + }, + Case { + description: "create a hard link with the name", + envrc_exists: false, + command: "ln other .envrc", + target: ".envrc", + }, + Case { + description: "create a symlink with the name", + envrc_exists: false, + command: "ln -s other .envrc", + target: ".envrc", + }, + ]; + let protected_names = [ProtectedFileName::new(".envrc").unwrap()]; + + for allow_fs_write in [false, true] { + for case in &cases { + let temp_dir = tempfile::tempdir().unwrap(); + // Canonicalize so the writable subpath resolves the macOS `/var` + // -> `/private/var` symlink that Seatbelt matches against. + let dir = std::fs::canonicalize(temp_dir.path()).unwrap(); + std::fs::write(dir.join("other"), "other\n").unwrap(); + if case.envrc_exists { + std::fs::write(dir.join(".envrc"), "original\n").unwrap(); + } + + let (program, args, _config_file) = wrap_invocation( + "/bin/sh", + &[ + "-c".to_string(), + format!("echo ok > ordinary && {}", case.command), + ], + &[dir.as_path()], + &[], + &protected_names, + &[], + SandboxPermissions { + network: NetworkAccess::None, + allow_fs_write, + }, + ) + .unwrap(); + let output = std::process::Command::new(&program) + .args(&args) + .current_dir(&dir) + .output() + .expect("failed to execute sandbox-exec"); + + let context = format!( + "{} (allow_fs_write: {allow_fs_write}): stderr={}", + case.description, + String::from_utf8_lossy(&output.stderr), + ); + assert!(!output.status.success(), "should be denied: {context}"); + assert_eq!( + std::fs::read_to_string(dir.join("ordinary")) + .ok() + .as_deref(), + Some("ok\n"), + "ordinary file should stay writable: {context}" + ); + let target = dir.join(case.target); + if case.envrc_exists { + assert_eq!( + std::fs::read_to_string(&target).ok().as_deref(), + Some("original\n"), + "existing file should be untouched: {context}" + ); + } else { + assert!( + std::fs::symlink_metadata(&target).is_err(), + "file should not have been created: {context}" + ); + } + } + } + } + + #[test] + fn test_protected_file_name_with_regex_metacharacters_matches_literally() { + let name = ProtectedFileName::new("a.b+c").unwrap(); + assert_eq!(protected_file_name_regex(&name), r"/[aA]\.[bB]\+[cC]$"); + + let temp_dir = tempfile::tempdir().unwrap(); + let dir = std::fs::canonicalize(temp_dir.path()).unwrap(); + let (program, args, _config_file) = wrap_invocation( + "/bin/sh", + &[ + "-c".to_string(), + // `axbbc` would match the unescaped regex `a.b+c`. + "echo ok > axbbc && echo ok > a.bbc && ! sh -c 'echo x > a.b+c' 2>/dev/null" + .to_string(), + ], + &[dir.as_path()], + &[], + &[name], + &[], + SandboxPermissions::default(), + ) + .unwrap(); + let output = std::process::Command::new(&program) + .args(&args) + .current_dir(&dir) + .output() + .expect("failed to execute sandbox-exec"); + + assert!( + output.status.success(), + "only the literal name should be protected: stderr={}", + String::from_utf8_lossy(&output.stderr), + ); + assert!(dir.join("axbbc").exists()); + assert!(dir.join("a.bbc").exists()); + assert!(!dir.join("a.b+c").exists()); + } + #[test] fn test_generate_seatbelt_config_contains_network_when_allowed() { let dir = PathBuf::from("/Users/test/projects/myproject"); @@ -783,6 +1024,7 @@ mod tests { &[dir.as_path()], &[], &[], + &[], SandboxPermissions { network: NetworkAccess::All, allow_fs_write: false, @@ -803,6 +1045,7 @@ mod tests { &[dir.as_path()], &[], &[], + &[], SandboxPermissions { network: NetworkAccess::LocalhostPort(54321), allow_fs_write: false, @@ -824,6 +1067,7 @@ mod tests { &[project_dir.as_path(), scratch_dir.as_path()], &[], &[], + &[], SandboxPermissions::default(), ) .unwrap(); @@ -861,6 +1105,7 @@ mod tests { &[temp_dir.path()], &[], &[], + &[], SandboxPermissions::default(), ) .unwrap(); @@ -884,6 +1129,7 @@ mod tests { &[temp_dir.path()], &[], &[], + &[], SandboxPermissions::default(), ) .unwrap(); @@ -911,6 +1157,7 @@ mod tests { &[temp_dir.path()], &[], &[], + &[], SandboxPermissions::default(), ) .unwrap(); @@ -938,6 +1185,7 @@ mod tests { &[temp_dir.path()], &[], &[], + &[], SandboxPermissions { network: NetworkAccess::None, allow_fs_write: true, @@ -973,6 +1221,7 @@ mod tests { &[temp_dir.path()], &[], &[], + &[], SandboxPermissions { network: NetworkAccess::None, allow_fs_write: true, @@ -1014,6 +1263,7 @@ mod tests { &[project_path.as_path(), scratch_path.as_path()], &[], &[], + &[], SandboxPermissions::default(), ) .unwrap(); @@ -1050,6 +1300,7 @@ mod tests { &[dir.as_path()], &[], &[], + &[], SandboxPermissions::default(), ) .unwrap(); @@ -1084,6 +1335,7 @@ mod tests { &[project_dir.path()], &[], &[], + &[], SandboxPermissions { network: NetworkAccess::None, allow_fs_write: true, @@ -1124,6 +1376,7 @@ mod tests { &[project_dir.path()], &[], &[], + &[], SandboxPermissions::default(), ) .unwrap(); diff --git a/crates/sandbox/src/sandbox.rs b/crates/sandbox/src/sandbox.rs index 9b19321dba0..2c4fa582699 100644 --- a/crates/sandbox/src/sandbox.rs +++ b/crates/sandbox/src/sandbox.rs @@ -90,10 +90,12 @@ pub struct SandboxPolicy { /// Filesystem policy for a sandboxed command. #[derive(Clone, Debug, Eq, PartialEq)] pub enum SandboxFsPolicy { - /// Allow unrestricted filesystem writes except for protected paths, which - /// remain readable but not writable. + /// Allow unrestricted filesystem writes except for protected paths and + /// protected file names, which remain readable but not writable. Unrestricted { protected_paths: Vec, + /// See [`ProtectedFileName`]. + protected_file_names: Vec, }, /// Reads are allowed everywhere; writes are confined to these locations /// (and the standard ephemeral locations the platform provides). Each is a @@ -102,9 +104,65 @@ pub enum SandboxFsPolicy { Restricted { writable_paths: Vec, protected_paths: Vec, + /// See [`ProtectedFileName`]. + protected_file_names: Vec, }, } +/// A file name whose writes are denied wherever it appears on the filesystem. +/// +/// Matching is on the final path component only, anywhere on the filesystem, +/// including in directories that do not exist yet when the sandbox is built. +/// The match is ASCII case-insensitive, because the default macOS filesystem +/// is case-insensitive and would otherwise let `.ENVRC` stand in for `.envrc`. +/// Files of that name stay readable; the sandbox denies creating, writing, +/// truncating, deleting, renaming onto, and linking (hard or symbolic) to a +/// path whose final component is the name. +/// +/// This complements path-based protected paths for files whose consumers look +/// them up by name, such as direnv's `.envrc`, which is read from the working +/// directory or any of its ancestors. +/// +/// Only the macOS backend can enforce this today. The Linux and WSL backends +/// reject any policy that contains protected file names, pending the planned +/// Linux syscall-interception backend. +#[derive(Clone, Debug, Eq, PartialEq, Hash)] +pub struct ProtectedFileName(String); + +impl ProtectedFileName { + /// Validate `name` as a single, non-empty path component. + /// + /// # Errors + /// + /// Returns [`SandboxError::InvalidRequest`] if `name` is empty, is `.` or + /// `..`, or contains `/` or a NUL byte. + pub fn new(name: impl Into) -> Result { + let name = name.into(); + let problem = if name.is_empty() { + Some("must not be empty") + } else if name == "." || name == ".." { + Some("must not be `.` or `..`") + } else if name.contains('/') { + Some("must not contain `/`") + } else if name.contains('\0') { + Some("must not contain a NUL byte") + } else { + None + }; + match problem { + Some(problem) => Err(SandboxError::InvalidRequest(format!( + "invalid protected file name {name:?}: {problem}" + ))), + None => Ok(Self(name)), + } + } + + /// The validated file name. + pub fn as_str(&self) -> &str { + &self.0 + } +} + /// Outbound-network policy for a sandboxed command. #[derive(Clone, Debug, Eq, PartialEq)] pub enum SandboxNetPolicy { @@ -176,6 +234,7 @@ impl SandboxPolicy { match &mut self.fs { SandboxFsPolicy::Unrestricted { protected_paths: existing, + .. } | SandboxFsPolicy::Restricted { protected_paths: existing, @@ -184,6 +243,37 @@ impl SandboxPolicy { } self } + + /// Replace the protected file names in the filesystem policy, keeping + /// every other part of the policy unchanged. + pub fn with_protected_file_names( + mut self, + protected_file_names: Vec, + ) -> Self { + match &mut self.fs { + SandboxFsPolicy::Unrestricted { + protected_file_names: existing, + .. + } + | SandboxFsPolicy::Restricted { + protected_file_names: existing, + .. + } => *existing = protected_file_names, + } + self + } +} + +fn merge_file_names( + mut names: Vec, + other: Vec, +) -> Vec { + for name in other { + if !names.contains(&name) { + names.push(name); + } + } + names } fn merge_locations( @@ -295,50 +385,62 @@ fn linux_location_is_equal_or_descendant( impl SandboxFsPolicy { /// Unrestricted access dominates; otherwise the writable subtrees union. + /// Protected paths and protected file names always union. pub fn merge(self, other: SandboxFsPolicy) -> SandboxFsPolicy { match (self, other) { ( SandboxFsPolicy::Unrestricted { protected_paths: protected_a, + protected_file_names: names_a, }, SandboxFsPolicy::Unrestricted { protected_paths: protected_b, + protected_file_names: names_b, }, ) => SandboxFsPolicy::Unrestricted { protected_paths: merge_locations(protected_a, protected_b), + protected_file_names: merge_file_names(names_a, names_b), }, ( SandboxFsPolicy::Unrestricted { protected_paths: protected_a, + protected_file_names: names_a, }, SandboxFsPolicy::Restricted { protected_paths: protected_b, + protected_file_names: names_b, .. }, ) | ( SandboxFsPolicy::Restricted { protected_paths: protected_a, + protected_file_names: names_a, .. }, SandboxFsPolicy::Unrestricted { protected_paths: protected_b, + protected_file_names: names_b, }, ) => SandboxFsPolicy::Unrestricted { protected_paths: merge_locations(protected_a, protected_b), + protected_file_names: merge_file_names(names_a, names_b), }, ( SandboxFsPolicy::Restricted { writable_paths: writable_a, protected_paths: protected_a, + protected_file_names: names_a, }, SandboxFsPolicy::Restricted { writable_paths: writable_b, protected_paths: protected_b, + protected_file_names: names_b, }, ) => SandboxFsPolicy::Restricted { writable_paths: merge_locations(writable_a, writable_b), protected_paths: merge_locations(protected_a, protected_b), + protected_file_names: merge_file_names(names_a, names_b), }, } } @@ -459,6 +561,10 @@ struct FsSetup { allow_fs_write: bool, writable_paths: Vec, protected_paths: Vec, + /// Only the Seatbelt backend can enforce these; other platforms reject a + /// non-empty list in [`Sandbox::new`]. + #[cfg(target_os = "macos")] + protected_file_names: Vec, } /// Resolved network plan derived from [`SandboxNetPolicy`]. For the restricted @@ -516,27 +622,48 @@ impl Sandbox { /// created lazily on the first [`Sandbox::wrap`] (so it can chain through an /// upstream proxy named in the command's environment), and `bwrap` /// availability is checked separately via [`Sandbox::can_create`]. + /// + /// # Errors + /// + /// Returns [`SandboxError::UnsupportedPolicy`] on Linux and Windows when the + /// policy has any [`ProtectedFileName`]s, because those backends cannot + /// enforce them yet. pub fn new(policy: SandboxPolicy) -> Result { - let fs = match policy.fs { - SandboxFsPolicy::Unrestricted { protected_paths } => FsSetup { - allow_fs_write: true, - writable_paths: Vec::new(), - protected_paths, - }, - SandboxFsPolicy::Restricted { - writable_paths, - protected_paths, - } => { - validate_writable_paths_do_not_overlap_protected_paths( - &writable_paths, - &protected_paths, - )?; - FsSetup { - allow_fs_write: false, + let (allow_fs_write, writable_paths, protected_paths, protected_file_names) = + match policy.fs { + SandboxFsPolicy::Unrestricted { + protected_paths, + protected_file_names, + } => (true, Vec::new(), protected_paths, protected_file_names), + SandboxFsPolicy::Restricted { writable_paths, protected_paths, + protected_file_names, + } => { + validate_writable_paths_do_not_overlap_protected_paths( + &writable_paths, + &protected_paths, + )?; + (false, writable_paths, protected_paths, protected_file_names) } - } + }; + + // Bubblewrap can only protect inodes that exist when the sandbox is + // built, so it cannot deny a name in a directory created later. Fail + // closed until the planned Linux syscall-interception backend lands. + #[cfg(not(target_os = "macos"))] + if !protected_file_names.is_empty() { + return Err(SandboxError::UnsupportedPolicy( + "protected file names are not yet supported by this platform's sandbox".to_string(), + )); + } + + let fs = FsSetup { + allow_fs_write, + writable_paths, + protected_paths, + #[cfg(target_os = "macos")] + protected_file_names, }; let network = match policy.network { @@ -855,6 +982,7 @@ impl Sandbox { &command.args, &writable, &protected, + &self.fs.protected_file_names, &[], permissions, ) @@ -1153,6 +1281,7 @@ mod tests { fs: SandboxFsPolicy::Restricted { writable_paths: vec![writable_path], protected_paths: vec![protected_git.clone()], + protected_file_names: Vec::new(), }, network: SandboxNetPolicy::Blocked, }); @@ -1185,6 +1314,7 @@ mod tests { fs: SandboxFsPolicy::Restricted { writable_paths: vec![writable_displayed_inside_git], protected_paths: vec![protected_git], + protected_file_names: Vec::new(), }, network: SandboxNetPolicy::Blocked, }) @@ -1206,40 +1336,64 @@ mod tests { let a = SandboxFsPolicy::Restricted { writable_paths: vec![location(&dir_a), location(&dir_b)], protected_paths: vec![location(&dir_c)], + protected_file_names: Vec::new(), }; let b = SandboxFsPolicy::Restricted { writable_paths: vec![location(&dir_b), location(&dir_c)], protected_paths: vec![location(&dir_c), location(&dir_d)], + protected_file_names: Vec::new(), }; assert_eq!( a.clone().merge(b), SandboxFsPolicy::Restricted { writable_paths: vec![location(&dir_a), location(&dir_b), location(&dir_c)], protected_paths: vec![location(&dir_c), location(&dir_d)], + protected_file_names: Vec::new(), } ); assert_eq!( a.merge(SandboxFsPolicy::Unrestricted { protected_paths: vec![location(&dir_a)], + protected_file_names: Vec::new(), }), SandboxFsPolicy::Unrestricted { protected_paths: vec![location(&dir_c), location(&dir_a)], + protected_file_names: Vec::new(), } ); assert_eq!( SandboxFsPolicy::Unrestricted { protected_paths: vec![location(&dir_d)], + protected_file_names: Vec::new(), } .merge(SandboxFsPolicy::Restricted { writable_paths: vec![location(&dir_a)], protected_paths: vec![location(&dir_c)], + protected_file_names: Vec::new(), }), SandboxFsPolicy::Unrestricted { protected_paths: vec![location(&dir_d), location(&dir_c)], + protected_file_names: Vec::new(), } ); } + #[test] + fn protected_file_name_rejects_anything_but_one_path_component() { + for name in ["", ".", "..", "a/b", "/", ".envrc/", "a\0b"] { + assert!( + matches!( + ProtectedFileName::new(name), + Err(SandboxError::InvalidRequest(_)) + ), + "{name:?} should be rejected" + ); + } + for name in [".envrc", "...", "a.b+c", "with space"] { + assert_eq!(ProtectedFileName::new(name).unwrap().as_str(), name); + } + } + #[test] fn net_merge_unrestricted_dominates_blocked_is_identity_else_unions() { let hosts = |list: &[&str]| SandboxNetPolicy::Restricted { diff --git a/crates/sandbox/src/wsl_sandbox_test_helper.rs b/crates/sandbox/src/wsl_sandbox_test_helper.rs index 0aba220fdcc..a9c9345e216 100644 --- a/crates/sandbox/src/wsl_sandbox_test_helper.rs +++ b/crates/sandbox/src/wsl_sandbox_test_helper.rs @@ -512,6 +512,7 @@ mod imp { fs: if permissions.allow_fs_write { SandboxFsPolicy::Unrestricted { protected_paths: Vec::new(), + protected_file_names: Vec::new(), } } else { SandboxFsPolicy::Restricted { @@ -522,6 +523,7 @@ mod imp { .filter_map(|path| HostFilesystemLocation::capture(path).ok()) .collect(), protected_paths: Vec::new(), + protected_file_names: Vec::new(), } }, network: match permissions.network { diff --git a/crates/settings_content/src/title_bar.rs b/crates/settings_content/src/title_bar.rs index d4fc6fe990d..6da390d86a5 100644 --- a/crates/settings_content/src/title_bar.rs +++ b/crates/settings_content/src/title_bar.rs @@ -78,9 +78,36 @@ impl From for WindowButtonLayoutContent { } } +#[derive( + Copy, + Clone, + Debug, + PartialEq, + Eq, + Serialize, + Deserialize, + JsonSchema, + MergeFrom, + strum::VariantArray, + strum::VariantNames, +)] +#[serde(rename_all = "snake_case")] +pub enum TitleBarVisibility { + /// Always show the title bar. + Always, + /// Never show the title bar. + Never, + /// Show the title bar, but hide it while the window is in full screen. + HideInFullScreen, +} + #[with_fallible_options] #[derive(Clone, PartialEq, Default, Serialize, Deserialize, JsonSchema, MergeFrom, Debug)] pub struct TitleBarSettingsContent { + /// When to show the title bar. + /// + /// Default: always + pub show: Option, /// Whether to show git status indicators on the branch icon in the title bar. /// When enabled, the branch icon changes to reflect the current repository /// status (e.g. modified, added, deleted, or conflict). diff --git a/crates/settings_ui/src/page_data.rs b/crates/settings_ui/src/page_data.rs index 3c96ecd45c6..82bdbbec380 100644 --- a/crates/settings_ui/src/page_data.rs +++ b/crates/settings_ui/src/page_data.rs @@ -4423,9 +4423,23 @@ fn window_and_layout_page() -> SettingsPage { ] } - fn title_bar_section() -> [SettingsPageItem; 12] { + fn title_bar_section() -> [SettingsPageItem; 13] { [ SettingsPageItem::SectionHeader("Title Bar"), + SettingsPageItem::SettingItem(SettingItem { + title: "Show Title Bar", + description: "When to show the title bar and its window controls.", + field: Box::new(SettingField { + organization_override: None, + json_path: Some("title_bar.show"), + pick: |settings_content| settings_content.title_bar.as_ref()?.show.as_ref(), + write: |settings_content, value, _| { + settings_content.title_bar.get_or_insert_default().show = value; + }, + }), + metadata: None, + files: USER, + }), SettingsPageItem::SettingItem(SettingItem { title: "Show Branch Status Icon", description: "Show git status indicators on the branch icon in the titlebar.", diff --git a/crates/settings_ui/src/pages/audio_test_window.rs b/crates/settings_ui/src/pages/audio_test_window.rs index f1441b08339..26de0b460a3 100644 --- a/crates/settings_ui/src/pages/audio_test_window.rs +++ b/crates/settings_ui/src/pages/audio_test_window.rs @@ -282,6 +282,7 @@ pub fn open_audio_test_window(_window: &mut Window, cx: &mut App) { width: px(400.0), height: px(240.0), }; + let display_id = cx.active_display().map(|display| display.id()); cx.open_window( WindowOptions { @@ -297,7 +298,8 @@ pub fn open_audio_test_window(_window: &mut Window, cx: &mut App) { window_background: cx.theme().window_background_appearance(), app_id: Some(app_id.to_owned()), window_decorations: Some(gpui::WindowDecorations::Client), - window_bounds: Some(WindowBounds::centered(window_size, cx)), + window_bounds: Some(WindowBounds::centered(display_id, window_size, cx)), + display_id, window_min_size: Some(window_min_size), ..Default::default() }, diff --git a/crates/settings_ui/src/settings_ui.rs b/crates/settings_ui/src/settings_ui.rs index e167c5cc7e2..26a6e9b9269 100644 --- a/crates/settings_ui/src/settings_ui.rs +++ b/crates/settings_ui/src/settings_ui.rs @@ -670,6 +670,7 @@ fn init_renderers(cx: &mut App) { .add_basic_renderer::(render_dropdown) .add_basic_renderer::(render_dropdown) .add_basic_renderer::(render_dropdown) + .add_basic_renderer::(render_dropdown) .add_basic_renderer::(render_dropdown) .add_basic_renderer::(render_dropdown) .add_basic_renderer::(render_editable_number_field) @@ -881,6 +882,7 @@ fn open_settings_editor_with( let default_rem_size = 16.0; let scale_factor = current_rem_size / default_rem_size; let scaled_bounds: gpui::Size = default_bounds.map(|axis| axis * scale_factor); + let display_id = cx.active_display().map(|display| display.id()); let app_id = ReleaseChannel::global(cx).app_id(); let window_decorations = match std::env::var("ZED_WINDOW_DECORATIONS") { @@ -914,7 +916,8 @@ fn open_settings_editor_with( width: SIDEBAR_WIDTH + CONTENT_MIN_WIDTH, height: px(240.0), }), - window_bounds: Some(WindowBounds::centered(scaled_bounds, cx)), + window_bounds: Some(WindowBounds::centered(display_id, scaled_bounds, cx)), + display_id, ..Default::default() }, |window, cx| { diff --git a/crates/sidebar/src/sidebar.rs b/crates/sidebar/src/sidebar.rs index fe99729a61d..60a0d4e5745 100644 --- a/crates/sidebar/src/sidebar.rs +++ b/crates/sidebar/src/sidebar.rs @@ -39,7 +39,7 @@ use menu::{ Cancel, Confirm, SelectChild, SelectFirst, SelectLast, SelectNext, SelectParent, SelectPrevious, }; use notifications::status_toast::StatusToast; -use platform_title_bar::apply_title_bar_insets; +use platform_title_bar::{SidebarWindowControls, TitleBarSettings, apply_title_bar_insets}; use project::{AgentId, AgentRegistryStore, Event as ProjectEvent, WorktreeId}; use recent_projects::sidebar_recent_projects::SidebarRecentProjects; use remote::RemoteConnectionOptions; @@ -7377,26 +7377,35 @@ impl Sidebar { cx: &mut Context, ) -> impl IntoElement { let has_query = self.has_filter_query(cx); - let sidebar_on_left = self.side(cx) == SidebarSide::Left; - let sidebar_on_right = self.side(cx) == SidebarSide::Right; - let not_fullscreen = !window.is_fullscreen() && !window.is_simple_fullscreen(); - let traffic_lights = cfg!(target_os = "macos") && not_fullscreen && sidebar_on_left; - let left_window_controls = !cfg!(target_os = "macos") && not_fullscreen && sidebar_on_left; - let right_window_controls = - !cfg!(target_os = "macos") && not_fullscreen && sidebar_on_right; - let header_height = platform_title_bar_height(window); + let SidebarWindowControls { + traffic_lights, + left: left_window_controls, + right: right_window_controls, + } = SidebarWindowControls::new(self.side(cx), window, cx); + let title_bar_visible = TitleBarSettings::is_title_bar_visible(window, cx); + let header_height = if title_bar_visible { + platform_title_bar_height(window) + } else { + Tab::container_height(cx) + }; h_flex() + .debug_selector(|| "sidebar-header".into()) .h(header_height) - .map(|header| match window.window_decorations() { - // Without projects there's no bottom border to match the title bar's. - Decorations::Client { .. } => apply_title_bar_insets( - header, - left_window_controls, - right_window_controls, - no_open_projects, - ), - Decorations::Server => header.mt_px().pb_px(), + .map(|header| { + if !title_bar_visible { + return header.mt_px(); + } + match window.window_decorations() { + // Without projects there's no bottom border to match the title bar's. + Decorations::Client { .. } => apply_title_bar_insets( + header, + left_window_controls, + right_window_controls, + no_open_projects, + ), + Decorations::Server => header.mt_px().pb_px(), + } }) .when(left_window_controls, |this| { this.children(Self::render_left_window_controls(window, cx)) @@ -7419,11 +7428,14 @@ impl Sidebar { this.child(Divider::vertical().color(ui::DividerColor::Border)) }) .child( - div().ml_1().child( - Icon::new(IconName::MagnifyingGlass) - .size(IconSize::Small) - .color(Color::Muted), - ), + div() + .debug_selector(|| "sidebar-header-search".into()) + .ml_1() + .child( + Icon::new(IconName::MagnifyingGlass) + .size(IconSize::Small) + .color(Color::Muted), + ), ) .child(self.render_filter_input(cx)) .child( diff --git a/crates/sidebar/src/sidebar_tests.rs b/crates/sidebar/src/sidebar_tests.rs index 8c18bfe172f..cf1cb8348fb 100644 --- a/crates/sidebar/src/sidebar_tests.rs +++ b/crates/sidebar/src/sidebar_tests.rs @@ -16,15 +16,25 @@ use agent_ui::{ }; use chrono::DateTime; use fs::{FakeFs, Fs}; -use gpui::{App, Bounds, Hsla, Point, Rgba, TestAppContext, UpdateGlobal, VisualTestContext}; +use gpui::{ + AnyView, App, Bounds, Corners, Decorations, Hsla, Point, Rgba, ScaledPixels, TestAppContext, + Tiling, UpdateGlobal, VisualTestContext, point, +}; +use platform_title_bar::PlatformTitleBar; use pretty_assertions::assert_eq; use project::AgentId; -use settings::{Settings, SettingsStore}; +use settings::{ + FontSize, Settings, SettingsStore, SidebarDockPosition, TitleBarVisibility, UiDensity, +}; use std::{ path::{Path, PathBuf}, sync::Arc, }; use util::{path_list::PathList, rel_path::rel_path}; +use workspace::{ + dock::{DockPosition, PanelEvent, test::TestPanel}, + item::test::TestItem, +}; fn use_unique_metadata_databases(cx: &mut TestAppContext) { use std::sync::atomic::{AtomicUsize, Ordering}; @@ -1931,6 +1941,318 @@ async fn test_refocus_sidebar_with_selection_preserves_it(cx: &mut TestAppContex }); } +#[gpui::test] +async fn test_leaving_sidebar_after_previous_focus_target_is_removed(cx: &mut TestAppContext) { + let project = init_test_project("/my-project", cx).await; + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx)); + let sidebar = setup_sidebar_closed(&multi_workspace, cx); + let workspace = multi_workspace.read_with(cx, |multi_workspace, _cx| { + multi_workspace.workspace().clone() + }); + let title_bar = cx.new(TestItem::new); + let panel = workspace.update_in(cx, |workspace, window, cx| { + workspace.set_titlebar_item(AnyView::from(title_bar.clone()), window, cx); + let panel = cx.new(|cx| TestPanel::new(DockPosition::Right, 100, cx)); + workspace.add_panel(panel.clone(), window, cx); + workspace.toggle_dock(DockPosition::Right, window, cx); + panel + }); + cx.run_until_parked(); + panel.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn)); + cx.run_until_parked(); + title_bar.update_in(cx, |title_bar, window, cx| { + title_bar.focus_handle(cx).focus(window, cx); + }); + cx.run_until_parked(); + let focus_state = |cx: &mut VisualTestContext| { + cx.update(|window, cx| { + let focused_region = [ + (FocusedRegion::TitleBar, title_bar.focus_handle(cx)), + (FocusedRegion::Sidebar, sidebar.focus_handle(cx)), + (FocusedRegion::Panel, panel.focus_handle(cx)), + (FocusedRegion::Pane, workspace.focus_handle(cx)), + ] + .into_iter() + .find_map(|(region, focus_handle)| { + focus_handle.contains_focused(window, cx).then_some(region) + }); + (focused_region, panel.read(cx).zoomed) + }) + }; + assert_eq!(focus_state(cx), (Some(FocusedRegion::TitleBar), true)); + + cx.dispatch_action(FocusWorkspaceSidebar); + cx.run_until_parked(); + assert_eq!(focus_state(cx), (Some(FocusedRegion::Sidebar), true)); + + cx.dispatch_action(FocusWorkspaceSidebar); + cx.run_until_parked(); + assert_eq!(focus_state(cx), (Some(FocusedRegion::TitleBar), true)); + + cx.dispatch_action(FocusWorkspaceSidebar); + cx.run_until_parked(); + workspace.update_in(cx, |workspace, window, cx| { + workspace.clear_titlebar_item(window, cx); + }); + cx.run_until_parked(); + assert_eq!(focus_state(cx), (Some(FocusedRegion::Sidebar), true)); + + cx.dispatch_action(FocusWorkspaceSidebar); + cx.run_until_parked(); + assert_eq!(focus_state(cx), (Some(FocusedRegion::Panel), true)); +} + +#[gpui::test] +async fn test_window_frame_corners_follow_content(cx: &mut TestAppContext) { + let project = init_test_project("/my-project", cx).await; + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx)); + setup_sidebar_closed(&multi_workspace, cx); + let workspace = multi_workspace.read_with(cx, |multi_workspace, _cx| { + multi_workspace.workspace().clone() + }); + let window_handle = cx.update(|window, _| window.window_handle()); + cx.simulate_window_decorations_change( + window_handle, + Decorations::Client { + tiling: Tiling::default(), + }, + ); + let title_bar = cx.new(|cx| { + PlatformTitleBar::new("title-bar", cx).with_multi_workspace(multi_workspace.downgrade()) + }); + workspace.update_in(cx, |workspace, window, cx| { + workspace.set_titlebar_item(AnyView::from(title_bar), window, cx); + }); + cx.run_until_parked(); + assert_eq!( + window_corners(cx), + WindowCorners { + top_left: WindowCorner::Rounded, + top_right: WindowCorner::Rounded, + bottom_left: WindowCorner::Rounded, + bottom_right: WindowCorner::Rounded, + }, + "title bar and status bar shown" + ); + + workspace.update_in(cx, |workspace, window, cx| { + workspace.clear_titlebar_item(window, cx); + }); + cx.run_until_parked(); + assert_eq!( + window_corners(cx), + WindowCorners { + top_left: WindowCorner::Square, + top_right: WindowCorner::Square, + bottom_left: WindowCorner::Rounded, + bottom_right: WindowCorner::Rounded, + }, + "title bar hidden" + ); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.status_bar.get_or_insert_default().show = Some(false); + }); + }); + cx.run_until_parked(); + assert_eq!( + window_corners(cx), + WindowCorners { + top_left: WindowCorner::Square, + top_right: WindowCorner::Square, + bottom_left: WindowCorner::Square, + bottom_right: WindowCorner::Square, + }, + "title bar and status bar hidden" + ); + + multi_workspace.update_in(cx, |multi_workspace, window, cx| { + multi_workspace.toggle_sidebar(window, cx); + }); + cx.run_until_parked(); + assert_eq!( + window_corners(cx), + WindowCorners { + top_left: WindowCorner::Rounded, + top_right: WindowCorner::Square, + bottom_left: WindowCorner::Rounded, + bottom_right: WindowCorner::Square, + }, + "title bar and status bar hidden, sidebar open on the left" + ); + + cx.update(|_, cx| { + let mut settings = AgentSettings::get_global(cx).clone(); + settings.threads_sidebar.position = SidebarDockPosition::Right; + AgentSettings::override_global(settings, cx); + }); + multi_workspace.update(cx, |_, cx| cx.notify()); + cx.run_until_parked(); + assert_eq!( + window_corners(cx), + WindowCorners { + top_left: WindowCorner::Square, + top_right: WindowCorner::Rounded, + bottom_left: WindowCorner::Square, + bottom_right: WindowCorner::Rounded, + }, + "title bar and status bar hidden, sidebar open on the right" + ); +} + +#[cfg(target_os = "macos")] +#[gpui::test] +async fn test_headers_follow_title_bar_visibility(cx: &mut TestAppContext) { + let project = init_test_project_with_agent_panel("/my-project", cx).await; + cx.update(|cx| AgentRegistryStore::init_test_global(cx, Vec::new())); + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx)); + let (sidebar, _panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx); + + let thread_list = header_search_offsets("sidebar-header-search", cx); + assert_eq!(thread_list.hidden, thread_list.fullscreen); + assert_ne!(thread_list.hidden, thread_list.shown); + + sidebar.update_in(cx, |sidebar, window, cx| sidebar.show_archive(window, cx)); + cx.run_until_parked(); + let archive = header_search_offsets("threads-archive-header-search", cx); + assert_eq!(archive.hidden, archive.fullscreen); + assert_ne!(archive.hidden, archive.shown); +} + +#[gpui::test] +async fn test_header_alignment_with_title_bar_and_tabs(cx: &mut TestAppContext) { + let project = init_test_project_with_agent_panel("/my-project", cx).await; + cx.update(|cx| AgentRegistryStore::init_test_global(cx, Vec::new())); + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project, window, cx)); + let (sidebar, _panel) = setup_sidebar_with_agent_panel(&multi_workspace, cx); + let workspace = + multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone()); + let title_bar = cx.new(|cx| { + PlatformTitleBar::new("title-bar", cx).with_multi_workspace(multi_workspace.downgrade()) + }); + workspace.update_in(cx, |workspace, window, cx| { + let item = cx.new(TestItem::new); + workspace.add_item_to_active_pane(Box::new(item), None, false, window, cx); + }); + let window_handle = cx.update(|window, _| window.window_handle()); + + for (header_selector, search_selector) in [ + ("sidebar-header", "sidebar-header-search"), + ("threads-archive-header", "threads-archive-header-search"), + ] { + if header_selector == "threads-archive-header" { + sidebar.update_in(cx, |sidebar, window, cx| sidebar.show_archive(window, cx)); + } + for ((font_size, density, decorations, position), scale_factor) in [ + ( + 12., + UiDensity::Compact, + Decorations::Server, + SidebarDockPosition::Left, + ), + ( + 16., + UiDensity::Default, + Decorations::Client { + tiling: Tiling::default(), + }, + SidebarDockPosition::Left, + ), + ( + 24., + UiDensity::Comfortable, + Decorations::Client { + tiling: Tiling::default(), + }, + SidebarDockPosition::Right, + ), + ( + 16., + UiDensity::Comfortable, + Decorations::Client { + tiling: Tiling { + top: true, + left: true, + right: true, + bottom: true, + }, + }, + SidebarDockPosition::Right, + ), + ] + .into_iter() + .cartesian_product([1., 2.]) + { + cx.simulate_scale_factor_change(scale_factor); + cx.simulate_window_decorations_change(window_handle, decorations); + for (visibility, fullscreen, title_bar_visible) in [ + (TitleBarVisibility::Always, false, true), + (TitleBarVisibility::Never, false, false), + (TitleBarVisibility::HideInFullScreen, false, true), + (TitleBarVisibility::HideInFullScreen, true, false), + (TitleBarVisibility::Always, true, true), + ] { + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.title_bar.get_or_insert_default().show = Some(visibility); + settings.theme.ui_font_size = Some(FontSize(font_size)); + settings.theme.ui_density = Some(density); + settings + .agent + .get_or_insert_default() + .threads_sidebar + .get_or_insert_default() + .position = Some(position); + }); + }); + workspace.update_in(cx, |workspace, window, cx| { + if window.is_fullscreen() != fullscreen { + window.toggle_fullscreen(); + } + if title_bar_visible { + workspace.set_titlebar_item(AnyView::from(title_bar.clone()), window, cx); + } else { + workspace.clear_titlebar_item(window, cx); + } + cx.refresh_windows(); + }); + cx.run_until_parked(); + + let header = cx + .debug_bounds(header_selector) + .expect("header is rendered"); + let tab = cx.debug_bounds("TAB-0").expect("tab is rendered"); + let search = cx + .debug_bounds(search_selector) + .expect("search is rendered"); + let center = if title_bar_visible { + assert_eq!(header.bottom(), tab.top()); + match decorations { + Decorations::Client { .. } => header.center().y, + Decorations::Server => header.center().y - px(1.), + } + } else { + assert_eq!(header.top(), tab.top()); + assert_eq!(header.bottom(), tab.bottom()); + tab.center().y - px(0.5) + }; + let expected_top = + ((center - search.size.height / 2.) * scale_factor).floor() / scale_factor; + assert_eq!( + search.top(), + expected_top, + "{header_selector}, {visibility:?}, {font_size}px, {scale_factor}x" + ); + } + } + } +} + #[gpui::test] async fn test_keyboard_confirm_on_project_header_toggles_collapse(cx: &mut TestAppContext) { let project = init_test_project("/my-project", cx).await; @@ -16110,3 +16432,146 @@ fn sidebar_painted_background_at(position: Point, cx: &mut VisualTestCon u32::from(Rgba::from(color)) }) } + +#[derive(Debug, PartialEq)] +enum FocusedRegion { + TitleBar, + Sidebar, + Panel, + Pane, +} + +#[derive(Debug, PartialEq)] +struct WindowCorners { + top_left: WindowCorner, + top_right: WindowCorner, + bottom_left: WindowCorner, + bottom_right: WindowCorner, +} + +#[derive(Debug, PartialEq)] +enum WindowCorner { + Rounded, + Square, + Overflow, + Gap, +} + +fn window_corners(cx: &mut VisualTestContext) -> WindowCorners { + cx.update(|window, _| { + let scale_factor = window.scale_factor(); + let frame = Bounds::new(Point::default(), window.viewport_size()) + .inset(theme::CLIENT_SIDE_DECORATION_SHADOW) + .scale(scale_factor); + let quads = window.painted_quads(); + let outline = quads + .iter() + .find(|quad| quad.bounds == frame && !quad.border_color.is_transparent()) + .expect("window frame border"); + let probe_offset = 1.5 * scale_factor; + let corner = |x: ScaledPixels, y: ScaledPixels, direction_x: f32, direction_y: f32| { + let probe = point( + ScaledPixels(x.0 + direction_x * probe_offset), + ScaledPixels(y.0 + direction_y * probe_offset), + ); + let inside_outline = + rounded_bounds_contain(outline.bounds, outline.corner_radii, probe); + let painted = quads.iter().any(|quad| { + !quad.background.is_transparent() + && quad.content_mask.bounds.contains(&probe) + && rounded_bounds_contain(quad.bounds, quad.corner_radii, probe) + }); + match (inside_outline, painted) { + (false, false) => WindowCorner::Rounded, + (true, true) => WindowCorner::Square, + (false, true) => WindowCorner::Overflow, + (true, false) => WindowCorner::Gap, + } + }; + WindowCorners { + top_left: corner(frame.left(), frame.top(), 1., 1.), + top_right: corner(frame.right(), frame.top(), -1., 1.), + bottom_right: corner(frame.right(), frame.bottom(), -1., -1.), + bottom_left: corner(frame.left(), frame.bottom(), 1., -1.), + } + }) +} + +fn rounded_bounds_contain( + bounds: Bounds, + corner_radii: Corners, + position: Point, +) -> bool { + bounds.contains(&position) + && [ + (corner_radii.top_left, bounds.left(), bounds.top(), 1., 1.), + ( + corner_radii.top_right, + bounds.right(), + bounds.top(), + -1., + 1., + ), + ( + corner_radii.bottom_right, + bounds.right(), + bounds.bottom(), + -1., + -1., + ), + ( + corner_radii.bottom_left, + bounds.left(), + bounds.bottom(), + 1., + -1., + ), + ] + .into_iter() + .all( + |(radius, x, y, direction_x, direction_y): (_, _, _, f32, f32)| { + let center_x = x.0 + direction_x * radius.0; + let center_y = y.0 + direction_y * radius.0; + let distance_x = (center_x - position.x.0) * direction_x; + let distance_y = (center_y - position.y.0) * direction_y; + distance_x <= 0. || distance_y <= 0. || distance_x.hypot(distance_y) <= radius.0 + }, + ) +} + +#[cfg(target_os = "macos")] +struct HeaderSearchOffsets { + shown: Pixels, + hidden: Pixels, + fullscreen: Pixels, +} + +#[cfg(target_os = "macos")] +fn header_search_offsets( + selector: &'static str, + cx: &mut VisualTestContext, +) -> HeaderSearchOffsets { + let offset = |visibility, cx: &mut VisualTestContext| { + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.title_bar.get_or_insert_default().show = Some(visibility); + }); + }); + cx.run_until_parked(); + cx.debug_bounds(selector) + .expect("header search is rendered") + .left() + }; + let shown = offset(TitleBarVisibility::Always, cx); + let hidden = offset(TitleBarVisibility::Never, cx); + cx.update(|window, _| window.toggle_fullscreen()); + cx.run_until_parked(); + let fullscreen = offset(TitleBarVisibility::Always, cx); + cx.update(|window, _| window.toggle_fullscreen()); + cx.run_until_parked(); + HeaderSearchOffsets { + shown, + hidden, + fullscreen, + } +} diff --git a/crates/snippet_provider/src/registry.rs b/crates/snippet_provider/src/registry.rs index 17c6096295c..574f414d7c8 100644 --- a/crates/snippet_provider/src/registry.rs +++ b/crates/snippet_provider/src/registry.rs @@ -1,7 +1,10 @@ -use std::{path::Path, sync::Arc}; +use std::{ + path::{Path, PathBuf}, + sync::Arc, +}; use anyhow::Result; -use collections::HashMap; +use collections::{HashMap, IndexMap}; use gpui::{App, Global, ReadGlobal, UpdateGlobal}; use parking_lot::RwLock; use util::ResultExt; @@ -14,7 +17,7 @@ impl Global for GlobalSnippetRegistry {} #[derive(Default)] pub struct SnippetRegistry { - snippets: RwLock>>>, + snippets: RwLock>>>>, } impl SnippetRegistry { @@ -43,20 +46,26 @@ impl SnippetRegistry { let kind = file_path .file_stem() .and_then(|stem| stem.to_str().and_then(file_stem_to_key)); - let new_snippets = - crate::file_to_snippets(snippets_in_file, file_path).filter_map(Result::log_err); + let new_snippets = crate::file_to_snippets(snippets_in_file, file_path) + .filter_map(Result::log_err) + .collect(); self.snippets .write() .entry(kind) .or_default() - .extend(new_snippets); + .insert(file_path.to_path_buf(), new_snippets); Ok(()) } pub fn get_snippets(&self, kind: &SnippetKind) -> Vec> { - self.snippets.read().get(kind).cloned().unwrap_or_default() + self.snippets + .read() + .get(kind) + .into_iter() + .flat_map(|snippets_by_file| snippets_by_file.values().flatten().cloned()) + .collect() } } @@ -86,13 +95,13 @@ mod tests { let registry = SnippetRegistry::new(); registry .register_snippets( - Path::new("ruby.json"), + Path::new("first_extension/ruby.json"), r#"{"Snippet One": {"prefix": "one", "body": "snippet_one"}}"#, ) .unwrap(); registry .register_snippets( - Path::new("ruby.json"), + Path::new("second_extension/ruby.json"), r#"{"Snippet Two": {"prefix": "two", "body": "snippet_two"}}"#, ) .unwrap(); @@ -108,15 +117,38 @@ mod tests { assert!(names.contains(&"Snippet Two")); } + #[test] + fn test_register_snippets_same_file_replaces_previous_contents() -> Result<()> { + let registry = SnippetRegistry::new(); + let file_path = Path::new("extension/snippets/ruby.json"); + registry.register_snippets( + file_path, + r#"{"Hello": {"prefix": "hello", "body": "Hello ${1:world}"}}"#, + )?; + registry.register_snippets( + file_path, + r#"{"Hello": {"prefix": "hello", "body": "Hello ${1:Zed}"}}"#, + )?; + + let snippets = registry.get_snippets(&Some("ruby".to_owned())); + assert_eq!( + snippets.len(), + 1, + "Registering the same file again should replace its snippets" + ); + assert_eq!(snippets[0].body, "Hello ${1:Zed}"); + Ok(()) + } + #[test] fn test_register_snippets_same_first_prefix_preserved() -> Result<()> { let registry = SnippetRegistry::new(); registry.register_snippets( - Path::new("ruby.json"), + Path::new("first_extension/ruby.json"), r#"{"For Loop": {"prefix": "for", "body": "for ${1:i} in ${2:iter} do\n$0\nend"}}"#, )?; registry.register_snippets( - Path::new("ruby.json"), + Path::new("second_extension/ruby.json"), r#"{"Different Name": {"prefix": "for", "body": "${2:iter}.each do |${1:item}|\n$0\nend"}}"#, )?; @@ -137,11 +169,11 @@ mod tests { fn test_register_snippets_same_first_prefix_with_extra_prefixes_preserved() -> Result<()> { let registry = SnippetRegistry::new(); registry.register_snippets( - Path::new("ruby.json"), + Path::new("first_extension/ruby.json"), r#"{"For Loop": {"prefix": "for", "body": "for ${1:i} in ${2:iter} do\n$0\nend"}}"#, )?; registry.register_snippets( - Path::new("ruby.json"), + Path::new("second_extension/ruby.json"), r#"{"For Loop Alt": {"prefix": ["for", "floop"], "body": "${2:iter}.each do |${1:item}|\n$0\nend"}}"#, )?; @@ -166,13 +198,13 @@ mod tests { let registry = SnippetRegistry::new(); registry .register_snippets( - Path::new("ruby.json"), + Path::new("first_extension/ruby.json"), r#"{"For Loop": {"prefix": "for", "body": "for ${1:i} in ${2:iter} do\n$0\nend"}}"#, ) .unwrap(); registry .register_snippets( - Path::new("ruby.json"), + Path::new("second_extension/ruby.json"), r#"{"While Loop": {"prefix": "while", "body": "while ${1:cond}\n$0\nend"}}"#, ) .unwrap(); diff --git a/crates/tab_switcher/src/tab_switcher.rs b/crates/tab_switcher/src/tab_switcher.rs index aa921dde3d0..ecfedfe1297 100644 --- a/crates/tab_switcher/src/tab_switcher.rs +++ b/crates/tab_switcher/src/tab_switcher.rs @@ -461,9 +461,10 @@ impl TabSwitcherDelegate { fuzzy_nucleo::match_strings( &candidates, &query, - fuzzy_nucleo::Case::Smart, - fuzzy_nucleo::LengthPenalty::On, - 10000, + fuzzy_nucleo::StringMatchOptions { + max_results: fuzzy_nucleo::MaxResults::limit::<10_000>(), + ..Default::default() + }, ) .into_iter() .map(|m| all_items[m.candidate_id].clone()) diff --git a/crates/tasks_ui/src/tasks_ui.rs b/crates/tasks_ui/src/tasks_ui.rs index b2e7162d75d..a50f175831f 100644 --- a/crates/tasks_ui/src/tasks_ui.rs +++ b/crates/tasks_ui/src/tasks_ui.rs @@ -8,7 +8,9 @@ use collections::HashMap; use editor::{Editor, MultiBufferOffset, ToPoint as _}; use gpui::{App, AppContext as _, Context, Entity, Task, TaskExt, Window}; use project::{Location, TaskContexts, TaskSourceKind, Worktree}; -use task::{RevealTarget, TaskContext, TaskId, TaskTemplate, TaskVariables, VariableName}; +use task::{ + RevealTarget, SpawnInTerminal, TaskContext, TaskId, TaskTemplate, TaskVariables, VariableName, +}; use tree_sitter::{Query, StreamingIterator as _}; use workspace::Workspace; @@ -121,26 +123,30 @@ pub fn init(cx: &mut App) { }) { if action.reevaluate_context { - let mut original_task = last_scheduled_task.original_task().clone(); - if let Some(allow_concurrent_runs) = action.allow_concurrent_runs { - original_task.allow_concurrent_runs = allow_concurrent_runs; - } - if let Some(use_new_terminal) = action.use_new_terminal { - original_task.use_new_terminal = use_new_terminal; - } + let original_task = last_scheduled_task.original_task().clone(); + let action = action.clone(); let task_contexts = task_contexts(workspace, window, cx); cx.spawn_in(window, async move |workspace, cx| { let task_contexts = task_contexts.await; let default_context = TaskContext::default(); workspace .update_in(cx, |workspace, window, cx| { + if !workspace.can_schedule_tasks(cx) { + return; + } let task_context = task_contexts .context_for_task(&task_source_kind, &original_task) .unwrap_or(&default_context); - workspace.schedule_task( - task_source_kind, - &original_task, + let Some(mut resolved_task) = original_task.resolve_task( + &task_source_kind.to_id_base(), task_context, + ) else { + return; + }; + apply_rerun_overrides(&action, &mut resolved_task.resolved); + workspace.schedule_resolved_task( + task_source_kind, + resolved_task, false, window, cx, @@ -150,14 +156,7 @@ pub fn init(cx: &mut App) { }) .detach(); } else { - let resolved = &mut last_scheduled_task.resolved; - - if let Some(allow_concurrent_runs) = action.allow_concurrent_runs { - resolved.allow_concurrent_runs = allow_concurrent_runs; - } - if let Some(use_new_terminal) = action.use_new_terminal { - resolved.use_new_terminal = use_new_terminal; - } + apply_rerun_overrides(action, &mut last_scheduled_task.resolved); workspace.schedule_resolved_task( task_source_kind, @@ -183,6 +182,15 @@ pub fn init(cx: &mut App) { .detach(); } +fn apply_rerun_overrides(action: &Rerun, resolved: &mut SpawnInTerminal) { + if let Some(allow_concurrent_runs) = action.allow_concurrent_runs { + resolved.allow_concurrent_runs = allow_concurrent_runs; + } + if let Some(use_new_terminal) = action.use_new_terminal { + resolved.use_new_terminal = use_new_terminal; + } +} + fn spawn_task_or_modal( workspace: &mut Workspace, action: &Spawn, @@ -725,6 +733,53 @@ mod tests { assert_reevaluated_rerun_in_project_root(&workspace, cx); } + #[gpui::test] + async fn test_reevaluated_rerun_overrides_keep_task_definition(cx: &mut TestAppContext) { + let (project, workspace, cx) = init_project_with_worktree_task(cx).await; + assert_global_task_spawned_in_project_root(&project, &workspace, cx).await; + let spawned_task = last_scheduled_task(&workspace, cx); + + cx.dispatch_action(Rerun { + reevaluate_context: true, + allow_concurrent_runs: Some(true), + use_new_terminal: Some(true), + ..Rerun::default() + }); + cx.run_until_parked(); + let overridden_task = last_scheduled_task(&workspace, cx); + assert_eq!(overridden_task.id, spawned_task.id); + assert_eq!( + overridden_task.original_task(), + spawned_task.original_task() + ); + assert!(overridden_task.resolved.allow_concurrent_runs); + assert!(overridden_task.resolved.use_new_terminal); + + task_inventory(&workspace, cx) + .update(cx, |inventory, _| { + inventory.update_file_based_tasks( + TaskSettingsLocation::Global(Path::new(path!("/zed-config/tasks.json"))), + Some(GLOBAL_TASKS_JSON), + ) + }) + .unwrap(); + let task_after_save = last_scheduled_task(&workspace, cx); + assert_eq!( + task_after_save.id, spawned_task.id, + "Saving the file without changes should keep the rerun target" + ); + assert!(task_after_save.resolved.use_new_terminal); + + cx.dispatch_action(Rerun { + reevaluate_context: true, + ..Rerun::default() + }); + cx.run_until_parked(); + let rerun_without_overrides = last_scheduled_task(&workspace, cx); + assert!(!rerun_without_overrides.resolved.allow_concurrent_runs); + assert!(!rerun_without_overrides.resolved.use_new_terminal); + } + #[gpui::test] async fn test_reevaluated_rerun_resolves_worktree_task_with_invisible_worktree_editor_active( cx: &mut TestAppContext, diff --git a/crates/telemetry_events/src/telemetry_events.rs b/crates/telemetry_events/src/telemetry_events.rs index e98a2c025fd..de1af3f7f5a 100644 --- a/crates/telemetry_events/src/telemetry_events.rs +++ b/crates/telemetry_events/src/telemetry_events.rs @@ -21,6 +21,9 @@ pub struct EventRequestBody { pub app_version: String, pub os_name: String, pub os_version: Option, + /// The Linux or FreeBSD desktop environment, from `XDG_CURRENT_DESKTOP`. + #[serde(default, skip_serializing_if = "Option::is_none")] + pub desktop_environment: Option, pub architecture: String, /// Zed release channel (stable, preview, dev) pub release_channel: Option, diff --git a/crates/terminal/src/alacritty.rs b/crates/terminal/src/alacritty.rs index b2e2107da9a..5f47be765c4 100644 --- a/crates/terminal/src/alacritty.rs +++ b/crates/terminal/src/alacritty.rs @@ -31,7 +31,7 @@ use alacritty_terminal::{ use anyhow::{Context as _, Result}; use futures::channel::mpsc::UnboundedSender; use util::paths::PathStyle; -use vte::ansi::Handler; +use vte::ansi::{Handler, Processor, Rgb, StdSyncHandler}; #[cfg(target_os = "windows")] use windows::Win32::{Foundation::HANDLE, System::Threading::GetProcessId}; @@ -244,6 +244,40 @@ pub(super) fn display_offset(term: &AlacrittyTerm) -> usize { term.grid().display_offset() } +pub(super) fn history_size(term: &AlacrittyTerm) -> usize { + term.history_size() +} + +pub(super) fn cursor_line(term: &AlacrittyTerm) -> i32 { + term.grid().cursor.point.line.0 +} + +pub(super) fn cursor_blinking(term: &AlacrittyTerm) -> bool { + term.cursor_style().blinking +} + +/// A color set by the running program (OSC 4/10/11), if any. +pub(super) fn palette_color(term: &AlacrittyTerm, index: usize) -> Option { + term.colors()[index] +} + +pub(super) fn renderable_cells(term: &AlacrittyTerm) -> RenderableCells<'_> { + RenderableCells::new(term.renderable_content().display_iter) +} + +/// Feeds output that doesn't come through the PTY event loop into a terminal. +pub(super) struct OutputParser(Processor); + +impl OutputParser { + pub(super) fn new() -> Self { + Self(Processor::new()) + } + + pub(super) fn advance(&mut self, term: &mut AlacrittyTerm, bytes: &[u8]) { + self.0.advance(term, bytes); + } +} + pub(super) fn scroll_display(term: &mut AlacrittyTerm, scroll: Scroll) { term.scroll_display(scroll.to_alacritty()); } diff --git a/crates/terminal/src/terminal.rs b/crates/terminal/src/terminal.rs index 8f6550235c1..ca6e4f838ab 100644 --- a/crates/terminal/src/terminal.rs +++ b/crates/terminal/src/terminal.rs @@ -15,7 +15,6 @@ use futures::{ channel::mpsc::{UnboundedReceiver, unbounded}, }; -use alacritty_terminal::grid::Dimensions as _; use itertools::Itertools as _; use mappings::mouse::{ alt_scroll, grid_point, grid_point_and_side, mouse_button_report, mouse_moved_report, @@ -63,10 +62,11 @@ use gpui::{ use crate::alacritty::current_child_signal_mask; use crate::alacritty::{ AlacrittyCell, AlacrittyGridIterator, AlacrittyHyperlink, AlacrittySearch, AlacrittyTerm, - AlacrittyTermConfig, AlacrittyTermLock, HyperlinkMatch, PtySender, RegexSearches, - append_text_to_term, apply_config, clear_saved_screen, content_text, display_offset, - display_only_term_config, find_from_terminal_point, full_content_range, last_non_empty_lines, - make_content, new_term, open_pty, pty_options, pty_term_config, resize, screen_lines, + AlacrittyTermConfig, AlacrittyTermLock, HyperlinkMatch, OutputParser, PtySender, RegexSearches, + append_text_to_term, apply_config, clear_saved_screen, content_text, cursor_blinking, + cursor_line, display_offset, display_only_term_config, find_from_terminal_point, + full_content_range, history_size, last_non_empty_lines, make_content, new_term, open_pty, + palette_color, pty_options, pty_term_config, renderable_cells, resize, screen_lines, scroll_display, scroll_to_point, search_matches, selection_text, set_default_cursor_style, set_selection as set_term_selection, shrink_to_used, spawn_event_loop, toggle_vi_mode as toggle_term_vi_mode, total_lines, update_selection as update_term_selection, @@ -1527,7 +1527,7 @@ pub struct Terminal { completion_tx: Option>>, term: Arc, term_config: AlacrittyTermConfig, - output_processor: Option>, + output_processor: Option, output_events_tx: Option>, output_generation: u64, events: VecDeque, @@ -1687,8 +1687,7 @@ impl Terminal { self.write_to_pty(format(self.last_content.terminal_bounds).into_bytes()) } TerminalBackendEvent::CursorBlinkingChange => { - let terminal = self.term.lock(); - let blinking = terminal.cursor_style().blinking; + let blinking = cursor_blinking(&self.term.lock()); cx.emit(Event::BlinkChanged(blinking)); } TerminalBackendEvent::Bell => { @@ -1716,7 +1715,7 @@ impl Terminal { // we might respond with out of date value if a "set color" sequence is immediately // followed by a color request sequence. - let color = self.term.lock().colors()[index] + let color = palette_color(&self.term.lock(), index) .unwrap_or_else(|| to_vte_rgb(get_color_at_index(index, cx.theme().as_ref()))); self.write_to_pty(format(color).into_bytes()); } @@ -1869,7 +1868,7 @@ impl Terminal { self.path_style, ) { Some(hyperlink) => { - let history_size = term.history_size(); + let history_size = history_size(term); self.process_hyperlink(hyperlink, *open, history_size, cx); } None => { @@ -1880,7 +1879,7 @@ impl Terminal { InternalEvent::ProcessHyperlink(hyperlink, open) => { // history_size must be read here since process_hyperlink cannot lock term // (sync() already holds the lock when dispatching events) - let history_size = term.history_size(); + let history_size = history_size(term); self.process_hyperlink(hyperlink.clone(), *open, history_size, cx); } } @@ -1996,8 +1995,8 @@ impl Terminal { pub fn write_raw_output(&mut self, bytes: &[u8], cx: &mut Context) { let mut term = self.term.lock(); self.output_processor - .get_or_insert_with(Processor::::new) - .advance(&mut *term, bytes); + .get_or_insert_with(OutputParser::new) + .advance(&mut term, bytes); drop(term); self.detect_init_command_startup_marker(); cx.emit(Event::Wakeup); @@ -2049,9 +2048,7 @@ impl Terminal { self.cwd_history.clear(); self.pending_cwd_boundary = None; self.write_raw_output(bytes, cx); - cx.emit(Event::BlinkChanged( - self.term.lock().cursor_style().blinking, - )); + cx.emit(Event::BlinkChanged(cursor_blinking(&self.term.lock()))); cx.emit(Event::BreadcrumbsChanged); cx.emit(Event::NewNavigationTarget(None)); cx.emit(Event::OutputReplaced); @@ -2325,8 +2322,8 @@ impl Terminal { if !self.is_remote_terminal && input.contains(&b'\r') { let term = self.term.lock_unfair(); self.pending_cwd_boundary = Some(Self::scrollback_position( - term.grid().cursor.point.line.0, - term.history_size(), + cursor_line(&term), + history_size(&term), )); } @@ -2518,8 +2515,7 @@ impl Terminal { pub fn with_renderable_cells(&self, f: impl for<'a> FnOnce(RenderableCells<'a>) -> R) -> R { let term = self.term.lock_unfair(); - let content = term.renderable_content(); - f(RenderableCells::new(content.display_iter)) + f(renderable_cells(&term)) } pub fn get_content(&self) -> String { @@ -3011,7 +3007,7 @@ impl Terminal { let scrollback_position = self.pending_cwd_boundary.take().unwrap_or_else(|| { let term = self.term.lock_unfair(); - Self::scrollback_position(term.grid().cursor.point.line.0, term.history_size()) + Self::scrollback_position(cursor_line(&term), history_size(&term)) }); self.cwd_history.push(CwdHistoryEntry { scrollback_position, @@ -3414,7 +3410,7 @@ fn spawn_task_subprocess( let events_tx = events_tx.clone(); async move { let Some(mut reader) = reader else { return }; - let mut processor = Processor::::new(); + let mut processor = OutputParser::new(); let mut buffer = [0u8; 8192]; let mut previous_byte_was_cr = false; loop { @@ -3429,7 +3425,7 @@ fn spawn_task_subprocess( convert_lf_to_crlf(&buffer[..count], &mut previous_byte_was_cr); { let mut term = term.lock(); - processor.advance(&mut *term, &converted); + processor.advance(&mut term, &converted); } events_tx .unbounded_send(PtyEvent::Event( diff --git a/crates/title_bar/src/application_menu.rs b/crates/title_bar/src/application_menu.rs index ced552d53ff..bde4ff6f2b5 100644 --- a/crates/title_bar/src/application_menu.rs +++ b/crates/title_bar/src/application_menu.rs @@ -9,7 +9,7 @@ use serde::Deserialize; use smallvec::SmallVec; use ui::{ContextMenu, PopoverMenu, PopoverMenuHandle, Tooltip, prelude::*}; -use crate::title_bar_settings::TitleBarSettings; +use platform_title_bar::TitleBarSettings; actions!( app_menu, diff --git a/crates/title_bar/src/collab.rs b/crates/title_bar/src/collab.rs index fe418bef36d..42c617ecea2 100644 --- a/crates/title_bar/src/collab.rs +++ b/crates/title_bar/src/collab.rs @@ -5,8 +5,8 @@ use call::{ActiveCall, Room}; use channel::ChannelStore; use client::{User, proto::PeerId}; use gpui::{ - AnyElement, Empty, Hsla, IntoElement, MouseButton, Path, ScreenCaptureSource, Styled, TaskExt, - WeakEntity, canvas, point, + AnyElement, Empty, Hsla, IntoElement, MouseButton, PathBuilder, ScreenCaptureSource, Styled, + TaskExt, WeakEntity, canvas, point, }; use gpui::{App, Task, Window}; use icons::IconName; @@ -123,18 +123,21 @@ fn render_color_ribbon(color: Hsla) -> impl Element { let height = bounds.size.height; let horizontal_offset = height; let vertical_offset = height / 2.0; - let mut path = Path::new(bounds.bottom_left()); - path.curve_to( + let mut builder = PathBuilder::fill(); + builder.move_to(bounds.bottom_left()); + builder.curve_to( bounds.origin + point(horizontal_offset, vertical_offset), bounds.origin + point(px(0.0), vertical_offset), ); - path.line_to(bounds.top_right() + point(-horizontal_offset, vertical_offset)); - path.curve_to( + builder.line_to(bounds.top_right() + point(-horizontal_offset, vertical_offset)); + builder.curve_to( bounds.bottom_right(), bounds.top_right() + point(px(0.0), vertical_offset), ); - path.line_to(bounds.bottom_left()); - window.paint_path(path, color); + builder.close(); + if let Ok(path) = builder.build() { + window.paint_path(path, color); + } }, ) .h_1() diff --git a/crates/title_bar/src/title_bar.rs b/crates/title_bar/src/title_bar.rs index 4f1b09ca13b..dceb1a5a489 100644 --- a/crates/title_bar/src/title_bar.rs +++ b/crates/title_bar/src/title_bar.rs @@ -2,7 +2,6 @@ mod application_menu; pub mod collab; mod onboarding_banner; mod plan_chip; -mod title_bar_settings; mod update_version; use crate::application_menu::{ApplicationMenu, show_menus}; @@ -15,6 +14,7 @@ pub use platform_title_bar::{ self, DraggedWindowTab, MergeAllWindows, MoveTabToNewWindow, PlatformTitleBar, ShowNextWindowTab, ShowPreviousWindowTab, }; +use platform_title_bar::{SystemWindowTabs, TitleBarSettings}; use project::{linked_worktree_short_name, repo_identity_path}; #[cfg(not(target_os = "macos"))] @@ -28,8 +28,8 @@ use client::{Client, UserStore, zed_urls}; use command_palette_hooks::CommandPaletteFilter; use gpui::{ - Action, Anchor, Animation, AnimationExt, AnyElement, App, Context, Element, Entity, Focusable, - InteractiveElement, IntoElement, MouseButton, ParentElement, Render, + Action, Anchor, Animation, AnimationExt, AnyElement, AnyView, App, Context, Element, Entity, + Focusable, InteractiveElement, IntoElement, MouseButton, ParentElement, Render, StatefulInteractiveElement, Styled, Subscription, TaskExt, WeakEntity, Window, actions, div, pulsating_between, }; @@ -45,7 +45,6 @@ use std::any::TypeId; use std::sync::Arc; use std::time::Duration; use theme::ActiveTheme; -use title_bar_settings::TitleBarSettings; use ui::{ Avatar, ButtonLike, ContextMenu, ContextMenuEntry, IconWithIndicator, Indicator, PopoverMenu, PopoverMenuHandle, TintColor, Tooltip, prelude::*, utils::platform_title_bar_height, @@ -101,9 +100,14 @@ pub fn init(cx: &mut App) { let Some(window) = window else { return; }; - let multi_workspace = workspace.multi_workspace().cloned(); - let item = cx.new(|cx| TitleBar::new("title-bar", workspace, multi_workspace, window, cx)); - workspace.set_titlebar_item(item.into(), window, cx); + let window_tabs = cx.new(|_| SystemWindowTabs::new()); + workspace.set_window_tabs_item(AnyView::from(window_tabs), cx); + apply_title_bar_visibility(workspace, window, cx); + + cx.observe_global_in::(window, apply_title_bar_visibility) + .detach(); + cx.observe_window_bounds(window, apply_title_bar_visibility) + .detach(); workspace.register_action(|_workspace, _: &UseClassicLayout, _window, cx| { set_window_layout(WindowLayout::Editor(None), cx); @@ -173,6 +177,25 @@ pub fn init(cx: &mut App) { .detach(); } +fn apply_title_bar_visibility( + workspace: &mut Workspace, + window: &mut Window, + cx: &mut Context, +) { + let visible = TitleBarSettings::is_title_bar_visible(window, cx); + + if !visible { + workspace.clear_titlebar_item(window, cx); + } else if workspace.titlebar_item().is_none() { + let multi_workspace = workspace.multi_workspace().cloned(); + let item = cx.new(|cx| TitleBar::new("title-bar", workspace, multi_workspace, window, cx)); + workspace.set_titlebar_item(AnyView::from(item), window, cx); + } + + #[cfg(target_os = "macos")] + window.set_native_titlebar_visibility(visible); +} + /// Hides or shows the panel layout actions in the command palette based on /// whether AI is currently disabled. fn update_layout_action_filter(cx: &mut App) { @@ -500,7 +523,7 @@ impl TitleBar { let update_version = cx.new(|cx| UpdateVersion::new(cx)); let platform_titlebar = cx.new(|cx| { - let mut titlebar = PlatformTitleBar::new(id, cx); + let mut titlebar = PlatformTitleBar::new(id, cx).without_system_window_tabs(); if let Some(mw) = multi_workspace.clone() { titlebar = titlebar.with_multi_workspace(mw); } @@ -1425,3 +1448,185 @@ impl TitleBar { .anchor(Anchor::TopRight) } } + +#[cfg(test)] +mod tests { + use super::*; + use gpui::{ + AnyWindowHandle, Empty, EntityId, SystemWindowTab, SystemWindowTabController, + TestAppContext, VisualTestContext, + }; + use platform_title_bar::SidebarWindowControls; + use settings::{SidebarSide, TitleBarVisibility}; + + #[gpui::test] + async fn test_title_bar_visibility(cx: &mut TestAppContext) { + let (workspace, cx) = init_test(TitleBarVisibility::Never, cx).await; + assert_eq!(chrome(&workspace, cx), Chrome::HIDDEN); + + set_visibility(Some(TitleBarVisibility::Always), cx); + assert_eq!(chrome(&workspace, cx), Chrome::SHOWN); + let title_bar = title_bar_id(&workspace, cx); + + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.title_bar.get_or_insert_default().show_menus = Some(true); + }); + }); + cx.run_until_parked(); + assert_eq!(title_bar_id(&workspace, cx), title_bar); + + toggle_fullscreen(&workspace, cx); + assert_eq!( + chrome(&workspace, cx), + Chrome { + title_bar: true, + ..Chrome::HIDDEN + } + ); + + set_visibility(Some(TitleBarVisibility::HideInFullScreen), cx); + assert_eq!(chrome(&workspace, cx), Chrome::HIDDEN); + + toggle_fullscreen(&workspace, cx); + assert_eq!(chrome(&workspace, cx), Chrome::SHOWN); + + toggle_fullscreen(&workspace, cx); + assert_eq!(chrome(&workspace, cx), Chrome::HIDDEN); + + toggle_fullscreen(&workspace, cx); + set_visibility(Some(TitleBarVisibility::Never), cx); + assert_eq!(chrome(&workspace, cx), Chrome::HIDDEN); + + set_visibility(None, cx); + assert_eq!(chrome(&workspace, cx), Chrome::SHOWN); + } + + #[gpui::test] + async fn test_window_tabs_stay_mounted_without_title_bar(cx: &mut TestAppContext) { + let other_window = cx.add_window(|_, _| Empty); + let (workspace, cx) = init_test(TitleBarVisibility::Never, cx).await; + workspace.update_in(cx, |_, window, cx| { + let workspace_window = window.window_handle(); + SystemWindowTabController::add_tab( + cx, + workspace_window.window_id(), + Vec::from([ + SystemWindowTab::new(SharedString::from("workspace"), workspace_window), + SystemWindowTab::new( + SharedString::from("other"), + AnyWindowHandle::from(other_window), + ), + ]), + ); + SystemWindowTabController::set_visible(cx, true); + cx.notify(); + }); + cx.run_until_parked(); + assert_eq!(chrome(&workspace, cx), Chrome::HIDDEN); + assert!(window_tabs_mounted(cx)); + + set_visibility(Some(TitleBarVisibility::HideInFullScreen), cx); + assert_eq!(chrome(&workspace, cx), Chrome::SHOWN); + assert!(window_tabs_mounted(cx)); + + toggle_fullscreen(&workspace, cx); + assert_eq!(chrome(&workspace, cx), Chrome::HIDDEN); + assert!(window_tabs_mounted(cx)); + } + + #[derive(Debug, PartialEq)] + struct Chrome { + title_bar: bool, + left_sidebar: SidebarWindowControls, + right_sidebar: SidebarWindowControls, + } + + impl Chrome { + const SHOWN: Self = Self { + title_bar: true, + left_sidebar: SidebarWindowControls { + traffic_lights: cfg!(target_os = "macos"), + left: !cfg!(target_os = "macos"), + right: false, + }, + right_sidebar: SidebarWindowControls { + traffic_lights: false, + left: false, + right: !cfg!(target_os = "macos"), + }, + }; + const HIDDEN: Self = Self { + title_bar: false, + left_sidebar: NO_WINDOW_CONTROLS, + right_sidebar: NO_WINDOW_CONTROLS, + }; + } + + const NO_WINDOW_CONTROLS: SidebarWindowControls = SidebarWindowControls { + traffic_lights: false, + left: false, + right: false, + }; + + async fn init_test( + visibility: TitleBarVisibility, + cx: &mut TestAppContext, + ) -> (Entity, &mut VisualTestContext) { + cx.update(|cx| { + let mut settings = SettingsStore::test(cx); + settings.update_user_settings(cx, |settings| { + settings.title_bar.get_or_insert_default().show = Some(visibility); + }); + cx.set_global(settings); + cx.set_global(db::AppDatabase::test_new()); + theme_settings::init(theme::LoadThemes::JustBase, cx); + command_palette_hooks::init(cx); + }); + let project = Project::test(fs::FakeFs::new(cx.executor()), [], cx).await; + cx.update(|cx| { + let project = project.read(cx); + call::init(project.client(), project.user_store(), cx); + init(cx); + }); + let (workspace, cx) = + cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx)); + cx.run_until_parked(); + (workspace, cx) + } + + fn set_visibility(visibility: Option, cx: &mut VisualTestContext) { + cx.update_global::(|store, cx| { + store.update_user_settings(cx, |settings| { + settings.title_bar.get_or_insert_default().show = visibility; + }); + }); + cx.run_until_parked(); + } + + fn toggle_fullscreen(workspace: &Entity, cx: &mut VisualTestContext) { + workspace.update_in(cx, |_, window, _| window.toggle_fullscreen()); + cx.run_until_parked(); + } + + fn chrome(workspace: &Entity, cx: &mut VisualTestContext) -> Chrome { + workspace.update_in(cx, |workspace, window, cx| Chrome { + title_bar: workspace.titlebar_item().is_some(), + left_sidebar: SidebarWindowControls::new(SidebarSide::Left, window, cx), + right_sidebar: SidebarWindowControls::new(SidebarSide::Right, window, cx), + }) + } + + fn title_bar_id(workspace: &Entity, cx: &mut VisualTestContext) -> Option { + workspace.read_with(cx, |workspace, _| { + workspace.titlebar_item().map(|item| item.entity_id()) + }) + } + + fn window_tabs_mounted(cx: &mut VisualTestContext) -> bool { + cx.update(|window, _| window.refresh()); + cx.run_until_parked(); + cx.debug_bounds("system-window-tabs") + .is_some_and(|bounds| bounds.size.height > px(0.)) + } +} diff --git a/crates/util/src/paths.rs b/crates/util/src/paths.rs index 8029d34cae4..b4a7419b89f 100644 --- a/crates/util/src/paths.rs +++ b/crates/util/src/paths.rs @@ -1589,6 +1589,23 @@ impl UrlExt for url::Url { } } +/// Converts the already-decoded path of a URL into a path on a host with `path_style`. +/// +/// URL paths keep a `/` before a Windows drive letter (`/C:/x`), which Windows cannot open. +/// The `/` is only dropped when what follows is an absolute drive path, so `/a:12` stays the +/// rooted file `/a` at line 12. +/// Unlike [`UrlExt::to_file_path_ext`], this takes a decoded path, not a whole URL, so it also +/// serves URLs whose authority is not a file host, such as `ssh://`. +pub fn url_path_to_path(url_path: &str, path_style: PathStyle) -> &str { + if path_style.is_windows() + && let Some(path) = url_path.strip_prefix('/') + && path_style.is_absolute(Path::new(path)) + { + return path; + } + url_path +} + #[cfg(test)] mod tests { use super::*; @@ -3468,6 +3485,30 @@ mod tests { assert_eq!(WslPath::from_path(&path), None); } + #[test] + fn test_url_path_to_path() { + let windows = |path| url_path_to_path(path, PathStyle::Windows); + assert_eq!(windows("/C:/project/main.rs"), "C:/project/main.rs"); + assert_eq!(windows("/C:/project/main.rs:12"), "C:/project/main.rs:12"); + assert_eq!(windows("/d:\\project"), "d:\\project"); + // Drive roots keep their separator. + assert_eq!(windows("/C:/"), "C:/"); + assert_eq!(windows("/d:\\"), "d:\\"); + // Not a drive path: left as it is. + assert_eq!(windows("/~/project"), "/~/project"); + assert_eq!(windows("/1:/project"), "/1:/project"); + assert_eq!(windows("C:/project"), "C:/project"); + // A rooted file with a row, or a drive without a root, is not an absolute drive path. + assert_eq!(windows("/a:12"), "/a:12"); + assert_eq!(windows("/C:"), "/C:"); + assert_eq!(windows("/C:project"), "/C:project"); + // On a Unix host `/C:/x` is a valid absolute path. + assert_eq!( + url_path_to_path("/C:/project", PathStyle::Unix), + "/C:/project" + ); + } + #[test] fn test_url_to_file_path_ext_posix_basic() { use super::UrlExt; diff --git a/crates/which_key/Cargo.toml b/crates/which_key/Cargo.toml index 18e2bf1c756..7c34edc3c4f 100644 --- a/crates/which_key/Cargo.toml +++ b/crates/which_key/Cargo.toml @@ -26,4 +26,6 @@ zed_actions.workspace = true [dev-dependencies] collections.workspace = true gpui = { workspace = true, features = ["test-support"] } +project = { workspace = true, features = ["test-support"] } theme.workspace = true +workspace = { workspace = true, features = ["test-support"] } diff --git a/crates/which_key/src/which_key.rs b/crates/which_key/src/which_key.rs index 11605431870..5950e15c524 100644 --- a/crates/which_key/src/which_key.rs +++ b/crates/which_key/src/which_key.rs @@ -128,7 +128,9 @@ pub fn init(cx: &mut App) { .await; workspace_handle .update_in(cx, |workspace, window, cx| { - if workspace.active_modal::(cx).is_some() { + // The modal layer holds one modal at a time, so showing which-key + // would dismiss an open modal such as the commit editor or a picker. + if workspace.has_active_modal(window, cx) { return; }; @@ -185,7 +187,12 @@ mod tests { use std::cell::Cell; use collections::HashMap; - use gpui::PlatformKeyboardMapper; + use gpui::{ + BorrowAppContext, Context, DismissEvent, Entity, EventEmitter, FocusHandle, Focusable, + InteractiveElement, IntoElement, KeyBinding, PlatformKeyboardMapper, Render, + TestAppContext, VisualTestContext, actions, div, + }; + use workspace::{AppState, ModalView, MultiWorkspace}; use super::*; @@ -266,4 +273,105 @@ mod tests { assert_eq!(binding_label(&action), "lazygit"); } + + actions!(which_key_test, [TestChordAction]); + + struct TestModal { + focus_handle: FocusHandle, + chord_action_count: usize, + } + + impl TestModal { + fn new(_: &mut Window, cx: &mut Context) -> Self { + Self { + focus_handle: cx.focus_handle(), + chord_action_count: 0, + } + } + } + + impl EventEmitter for TestModal {} + + impl Focusable for TestModal { + fn focus_handle(&self, _cx: &App) -> FocusHandle { + self.focus_handle.clone() + } + } + + impl ModalView for TestModal {} + + impl Render for TestModal { + fn render(&mut self, _window: &mut Window, cx: &mut Context) -> impl IntoElement { + div().track_focus(&self.focus_handle).on_action(cx.listener( + |this, _: &TestChordAction, _, _| { + this.chord_action_count += 1; + }, + )) + } + } + + async fn init_workspace_test( + cx: &mut TestAppContext, + ) -> (Entity, &mut VisualTestContext) { + let app_state = cx.update(|cx| { + let app_state = AppState::test(cx); + theme_settings::init(theme::LoadThemes::JustBase, cx); + workspace::init(app_state.clone(), cx); + init(cx); + cx.update_global::(|store, cx| { + store + .set_user_settings(r#"{ "which_key": { "enabled": true, "delay_ms": 0 } }"#, cx) + .expect("valid test settings"); + }); + cx.bind_keys([KeyBinding::new("ctrl-k ctrl-x", TestChordAction, None)]); + app_state + }); + let project = project::Project::test(app_state.fs.clone(), [], cx).await; + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx)); + let workspace = + multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone()); + (workspace, cx) + } + + #[gpui::test] + async fn test_which_key_shows_for_pending_chord(cx: &mut TestAppContext) { + let (workspace, cx) = init_workspace_test(cx).await; + + cx.simulate_keystrokes("ctrl-k"); + cx.run_until_parked(); + + workspace.read_with(cx, |workspace, cx| { + assert!(workspace.active_modal::(cx).is_some()); + }); + } + + #[gpui::test] + async fn test_which_key_does_not_replace_open_modal(cx: &mut TestAppContext) { + let (workspace, cx) = init_workspace_test(cx).await; + workspace.update_in(cx, |workspace, window, cx| { + workspace.toggle_modal(window, cx, TestModal::new); + }); + cx.run_until_parked(); + + cx.simulate_keystrokes("ctrl-k"); + cx.run_until_parked(); + + workspace.read_with(cx, |workspace, cx| { + assert!( + workspace.active_modal::(cx).is_some(), + "which-key should not dismiss the open modal" + ); + }); + + cx.simulate_keystrokes("ctrl-x"); + cx.run_until_parked(); + + workspace.read_with(cx, |workspace, cx| { + let modal = workspace + .active_modal::(cx) + .expect("modal should still be open"); + assert_eq!(modal.read(cx).chord_action_count, 1); + }); + } } diff --git a/crates/workspace/src/multi_workspace.rs b/crates/workspace/src/multi_workspace.rs index ec35dd8ff11..44498442346 100644 --- a/crates/workspace/src/multi_workspace.rs +++ b/crates/workspace/src/multi_workspace.rs @@ -2,9 +2,9 @@ use anyhow::{Context as _, Result}; use fs::Fs; use gpui::{ - AnyView, App, Context, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle, Focusable, - ManagedView, MouseButton, Pixels, Render, Subscription, Task, TaskExt, WeakEntity, Window, - WindowId, actions, deferred, px, + AnyView, App, Context, Corners, DragMoveEvent, Entity, EntityId, EventEmitter, FocusHandle, + Focusable, ManagedView, MouseButton, Pixels, Render, Subscription, Task, TaskExt, WeakEntity, + Window, WindowId, actions, deferred, px, }; pub use project::ProjectGroupKey; use project::{DisableAiSettings, Project}; @@ -28,8 +28,8 @@ const SIDEBAR_RESIZE_HANDLE_SIZE: Pixels = px(6.0); use crate::open_remote_project_with_existing_connection; use crate::{ CloseIntent, CloseWindow, DockPosition, Event as WorkspaceEvent, Item, ModalView, OpenMode, - OpenOptions, OpenVisible, Panel, Workspace, WorkspaceId, client_side_decorations, - persistence::model::MultiWorkspaceState, + OpenOptions, OpenVisible, Panel, Workspace, WorkspaceId, + client_side_decorations_with_rounded_corners, persistence::model::MultiWorkspaceState, }; actions!( @@ -544,11 +544,9 @@ impl MultiWorkspace { self.previous_focus_handle.clone() }; - if let Some(previous_focus) = focus_handle { - previous_focus.focus(window, cx); - } else { - let pane = self.workspace().read(cx).active_pane().clone(); - window.focus(&pane.read(cx).focus_handle(cx), cx); + match focus_handle.filter(|focus_handle| focus_handle.is_rendered(window)) { + Some(previous_focus) => previous_focus.focus(window, cx), + None => self.focus_active_workspace(window, cx), } } @@ -2141,8 +2139,21 @@ impl Render for MultiWorkspace { let workspace = self.workspace().clone(); let workspace_key_context = workspace.update(cx, |workspace, cx| workspace.key_context(cx)); let root = workspace.update(cx, |workspace, cx| workspace.actions(h_flex(), window, cx)); + let (has_title_bar, has_status_bar) = { + let workspace = workspace.read(cx); + ( + workspace.titlebar_item().is_some(), + workspace.status_bar_visible(cx), + ) + }; + let rounded_corners = Corners { + top_left: has_title_bar || left_sidebar.is_some(), + top_right: has_title_bar || right_sidebar.is_some(), + bottom_right: has_status_bar || right_sidebar.is_some(), + bottom_left: has_status_bar || left_sidebar.is_some(), + }; - client_side_decorations( + client_side_decorations_with_rounded_corners( root.key_context(workspace_key_context) .relative() .size_full() @@ -2263,6 +2274,7 @@ impl Render for MultiWorkspace { )) .with_priority(2) })), + rounded_corners, window, cx, ) diff --git a/crates/workspace/src/persistence.rs b/crates/workspace/src/persistence.rs index 4c7baadc9e1..b8cd6beb08a 100644 --- a/crates/workspace/src/persistence.rs +++ b/crates/workspace/src/persistence.rs @@ -24,7 +24,7 @@ use project::{ ProjectGroupKey, bookmark_store::SerializedBookmark, debugger::breakpoint_store::{BreakpointState, SourceBreakpoint}, - trusted_worktrees::{DbTrustedPaths, RemoteHostLocation}, + trusted_worktrees::DbTrustedPaths, }; use language::{LanguageName, Toolchain, ToolchainScope}; @@ -40,7 +40,7 @@ use sqlez::{ }; use ui::{App, SharedString, px}; -use util::{ResultExt, maybe, rel_path::RelPath}; +use util::{ResultExt, maybe, paths::PathStyle, rel_path::RelPath}; use uuid::Uuid; use crate::{ @@ -533,6 +533,25 @@ impl sqlez::bindable::Bind for SerializedPixels { } } +struct PathListColumns(SerializedPathList); + +impl StaticColumnCount for PathListColumns { + fn column_count() -> usize { + 2 + } +} + +impl Column for PathListColumns { + fn column(statement: &mut Statement, start_index: i32) -> anyhow::Result<(Self, i32)> { + let (paths, next_index) = String::column(statement, start_index)?; + let (order, next_index) = String::column(statement, next_index)?; + Ok(( + PathListColumns(SerializedPathList { paths, order }), + next_index, + )) + } +} + pub struct WorkspaceDb(ThreadSafeConnection); impl Domain for WorkspaceDb { @@ -1065,6 +1084,56 @@ impl Domain for WorkspaceDb { sql!( ALTER TABLE workspaces ADD COLUMN native_window_state BLOB; ), + sql!( + ALTER TABLE workspaces ADD COLUMN path_style TEXT; + ), + sql!( + CREATE TABLE restricted_worktrees ( + absolute_path BLOB NOT NULL, + connection_kind TEXT, + host TEXT, + user TEXT, + port INTEGER + ) STRICT; + CREATE INDEX restricted_worktrees_absolute_path ON restricted_worktrees(absolute_path); + ), + sql!( + CREATE TABLE trusted_worktrees_2 ( + trust_id INTEGER PRIMARY KEY AUTOINCREMENT, + absolute_path TEXT, + connection_kind TEXT, + host TEXT, + user TEXT, + port INTEGER + ) STRICT; + + INSERT INTO trusted_worktrees_2 (absolute_path) + SELECT absolute_path + FROM trusted_worktrees + WHERE user_name IS NULL AND host_name IS NULL; + + INSERT INTO trusted_worktrees_2 (absolute_path, connection_kind, host, user, port) + SELECT DISTINCT + trusted.absolute_path, + connections.kind, + trusted.host_name, + connections.user, + connections.port + FROM trusted_worktrees AS trusted + JOIN remote_connections AS connections ON + (connections.kind = "ssh" + AND connections.host = trusted.host_name + AND connections.user IS trusted.user_name) + OR (connections.kind = "wsl" + AND connections.distro = trusted.host_name + AND connections.user IS trusted.user_name) + OR (connections.kind = "docker" + AND connections.container_id = trusted.host_name + AND connections.name IS trusted.user_name); + + DROP TABLE trusted_worktrees; + ALTER TABLE trusted_worktrees_2 RENAME TO trusted_worktrees; + ), ]; // Allow recovering from bad migration that was initially shipped to nightly @@ -1088,6 +1157,10 @@ impl WorkspaceDb { self.workspace_for_roots_internal(worktree_roots, None) } + pub fn has_workspace_for_roots>(&self, worktree_roots: &[P]) -> bool { + self.workspace_for_roots(worktree_roots).is_some() + } + pub(crate) fn remote_workspace_for_roots>( &self, worktree_roots: &[P], @@ -1115,26 +1188,24 @@ impl WorkspaceDb { // and we've grabbed the most recent workspace let ( workspace_id, - paths, - paths_order, - identity_paths, - identity_paths_order, + paths_list, + identity_paths_list, window_bounds, display, centered_layout, docks, window_id, + path_style, ): ( WorkspaceId, - String, - String, - Option, - Option, + PathListColumns, + Option, Option, Option, Option, DockStructure, Option, + Option, ) = self .select_row_bound(sql! { SELECT @@ -1159,7 +1230,8 @@ impl WorkspaceDb { bottom_dock_visible, bottom_dock_active_panel, bottom_dock_zoom, - window_id + window_id, + path_style FROM workspaces WHERE paths IS ? AND @@ -1176,16 +1248,8 @@ impl WorkspaceDb { .warn_on_err() .flatten()?; - let paths = PathList::deserialize(&SerializedPathList { - paths, - order: paths_order, - }); - let identity_paths = identity_paths.map(|paths| { - PathList::deserialize(&SerializedPathList { - paths, - order: identity_paths_order.unwrap_or_default(), - }) - }); + let paths = PathList::deserialize(&paths_list.0); + let identity_paths = identity_paths_list.map(|paths| PathList::deserialize(&paths.0)); let remote_connection_options = if let Some(remote_connection_id) = remote_connection_id { self.remote_connection(remote_connection_id) @@ -1195,6 +1259,10 @@ impl WorkspaceDb { None }; + let path_style = path_style + .and_then(deserialize_path_style) + .unwrap_or(PathStyle::local()); + Some(SerializedWorkspace { id: workspace_id, location: match remote_connection_options { @@ -1217,6 +1285,7 @@ impl WorkspaceDb { window_id, user_toolchains: self.user_toolchains(workspace_id, remote_connection_id), recent_navigation_history: self.recent_navigation_history(workspace_id), + path_style, }) } @@ -1226,27 +1295,25 @@ impl WorkspaceDb { workspace_id: WorkspaceId, ) -> Option { let ( - paths, - paths_order, - identity_paths, - identity_paths_order, + paths_list, + identity_paths_list, window_bounds, display, centered_layout, docks, window_id, remote_connection_id, + path_style, ): ( - String, - String, - Option, - Option, + PathListColumns, + Option, Option, Option, Option, DockStructure, Option, Option, + Option, ) = self .select_row_bound(sql! { SELECT @@ -1271,7 +1338,8 @@ impl WorkspaceDb { bottom_dock_active_panel, bottom_dock_zoom, window_id, - remote_connection_id + remote_connection_id, + path_style FROM workspaces WHERE workspace_id = ? }) @@ -1280,16 +1348,8 @@ impl WorkspaceDb { .warn_on_err() .flatten()?; - let paths = PathList::deserialize(&SerializedPathList { - paths, - order: paths_order, - }); - let identity_paths = identity_paths.map(|paths| { - PathList::deserialize(&SerializedPathList { - paths, - order: identity_paths_order.unwrap_or_default(), - }) - }); + let paths = PathList::deserialize(&paths_list.0); + let identity_paths = identity_paths_list.map(|paths| PathList::deserialize(&paths.0)); let remote_connection_id = remote_connection_id.map(|id| RemoteConnectionId(id as u64)); let remote_connection_options = if let Some(remote_connection_id) = remote_connection_id { @@ -1300,6 +1360,10 @@ impl WorkspaceDb { None }; + let path_style = path_style + .and_then(deserialize_path_style) + .unwrap_or(PathStyle::local()); + Some(SerializedWorkspace { id: workspace_id, location: match remote_connection_options { @@ -1322,6 +1386,7 @@ impl WorkspaceDb { window_id, user_toolchains: self.user_toolchains(workspace_id, remote_connection_id), recent_navigation_history: self.recent_navigation_history(workspace_id), + path_style, }) } @@ -1497,6 +1562,7 @@ impl WorkspaceDb { pub(crate) async fn save_workspace(&self, workspace: SerializedWorkspace) { let paths = workspace.paths.serialize(); let identity_paths = workspace.identity_paths.map(|paths| paths.serialize()); + let path_style = serialize_path_style(workspace.path_style); log::debug!("Saving workspace at location: {:?}", workspace.location); self.write(move |conn| { conn.with_savepoint("update_worktrees", || { @@ -1626,9 +1692,10 @@ impl WorkspaceDb { bottom_dock_zoom, session_id, window_id, + path_style, timestamp ) - VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, CURRENT_TIMESTAMP) + VALUES (?1, ?2, ?3, ?4, ?5, ?6, ?7, ?8, ?9, ?10, ?11, ?12, ?13, ?14, ?15, ?16, ?17, ?18, CURRENT_TIMESTAMP) ON CONFLICT DO UPDATE SET paths = ?2, @@ -1647,6 +1714,7 @@ impl WorkspaceDb { bottom_dock_zoom = ?15, session_id = ?16, window_id = ?17, + path_style = ?18, timestamp = CURRENT_TIMESTAMP ); let mut prepared_query = conn.exec_bound(query)?; @@ -1660,6 +1728,7 @@ impl WorkspaceDb { workspace.docks, workspace.session_id, workspace.window_id, + path_style ); prepared_query(args).context("Updating workspace")?; @@ -1832,6 +1901,7 @@ impl WorkspaceDb { Option, Option, Option, + Option, DateTime, )>, > { @@ -1841,25 +1911,20 @@ impl WorkspaceDb { .map( |( id, - paths, - order, - identity_paths, - identity_paths_order, + paths_list, + identity_paths_list, remote_connection_id, session_id, + path_style, timestamp, )| { ( id, - PathList::deserialize(&SerializedPathList { paths, order }), - identity_paths.map(|paths| { - PathList::deserialize(&SerializedPathList { - paths, - order: identity_paths_order.unwrap_or_default(), - }) - }), + PathList::deserialize(&paths_list.0), + identity_paths_list.map(|paths| PathList::deserialize(&paths.0)), remote_connection_id.map(RemoteConnectionId), session_id, + path_style.and_then(deserialize_path_style), parse_timestamp(×tamp), ) }, @@ -1868,8 +1933,8 @@ impl WorkspaceDb { } query! { - fn recent_workspaces_query() -> Result, Option, Option, Option, String)>> { - SELECT workspace_id, paths, paths_order, identity_paths, identity_paths_order, remote_connection_id, session_id, timestamp + fn recent_workspaces_query() -> Result, Option, Option, Option, String)>> { + SELECT workspace_id, paths, paths_order, identity_paths, identity_paths_order, remote_connection_id, session_id, path_style, timestamp FROM workspaces WHERE paths IS NOT NULL OR @@ -1893,10 +1958,10 @@ impl WorkspaceDb { .session_workspaces_query(session_id)? .into_iter() .map( - |(workspace_id, paths, order, window_id, remote_connection_id)| { + |(workspace_id, paths_list, window_id, remote_connection_id)| { ( WorkspaceId(workspace_id), - PathList::deserialize(&SerializedPathList { paths, order }), + PathList::deserialize(&paths_list.0), window_id, remote_connection_id.map(RemoteConnectionId), ) @@ -1906,7 +1971,7 @@ impl WorkspaceDb { } query! { - fn session_workspaces_query(session_id: String) -> Result, Option)>> { + fn session_workspaces_query(session_id: String) -> Result, Option)>> { SELECT workspace_id, paths, paths_order, window_id, remote_connection_id FROM workspaces WHERE session_id = ?1 @@ -2050,8 +2115,15 @@ impl WorkspaceDb { ) -> Result> { let remote_connections = self.remote_connections()?; let mut result = Vec::new(); - for (id, paths, identity_paths_hint, remote_connection_id, _session_id, timestamp) in - self.recent_workspaces()? + for ( + id, + paths, + identity_paths_hint, + remote_connection_id, + _session_id, + path_style, + timestamp, + ) in self.recent_workspaces()? { if let Some(remote_connection_id) = remote_connection_id { if let Some(connection_options) = remote_connections.get(&remote_connection_id) { @@ -2060,6 +2132,7 @@ impl WorkspaceDb { location: SerializedWorkspaceLocation::Remote(connection_options.clone()), paths: paths.clone(), identity_paths: identity_paths_hint.unwrap_or(paths), + path_style, timestamp, }); } @@ -2080,6 +2153,7 @@ impl WorkspaceDb { location: SerializedWorkspaceLocation::Local, paths, identity_paths, + path_style, timestamp, }); } @@ -2112,7 +2186,7 @@ impl WorkspaceDb { let remote_connections = self.remote_connections()?; let mut workspace_ids = Vec::new(); - for (workspace_id, paths, identity_paths, remote_connection_id, _, _) in + for (workspace_id, paths, identity_paths, remote_connection_id, _, _, _) in self.recent_workspaces()? { let remote_connection = if let Some(id) = remote_connection_id { @@ -2155,7 +2229,7 @@ impl WorkspaceDb { let remote_connections = self.remote_connections()?; let now = Utc::now(); let mut workspaces_to_delete = Vec::new(); - for (id, paths, _identity_paths_hint, remote_connection_id, session_id, timestamp) in + for (id, paths, _identity_paths_hint, remote_connection_id, session_id, _, timestamp) in self.recent_workspaces()? { if let Some(session_id) = session_id.as_deref() { @@ -2574,7 +2648,7 @@ impl WorkspaceDb { pub(crate) async fn save_trusted_worktrees( &self, - trusted_worktrees: HashMap, HashSet>, + trusted_worktrees: DbTrustedPaths, ) -> anyhow::Result<()> { use anyhow::Context as _; use db::sqlez::statement::Statement; @@ -2594,10 +2668,10 @@ impl WorkspaceDb { .collect::>(); let mut first_worktree; let mut last_worktree = 0_usize; - for (count, placeholders) in std::iter::once("(?, ?, ?)") + for (count, placeholders) in std::iter::once("(?, ?, ?, ?, ?)") .cycle() .take(trusted_worktrees.len()) - .chunks(MAX_QUERY_PLACEHOLDERS / 3) + .chunks(MAX_QUERY_PLACEHOLDERS / 5) .into_iter() .map(|chunk| { let mut count = 0; @@ -2613,7 +2687,7 @@ impl WorkspaceDb { first_worktree = last_worktree; last_worktree = last_worktree + count; let query = format!( - r#"INSERT INTO trusted_worktrees(absolute_path, user_name, host_name) + r#"INSERT INTO trusted_worktrees(absolute_path, connection_kind, host, user, port) VALUES {placeholders};"# ); @@ -2627,16 +2701,8 @@ VALUES {placeholders};"# &abs_path.as_ref().map(|abs_path| abs_path.as_ref()), next_index, )?; - next_index = statement.bind( - &host - .as_ref() - .and_then(|host| Some(host.user_name.as_ref()?.as_str())), - next_index, - )?; - next_index = statement.bind( - &host.as_ref().map(|host| host.host_identifier.as_str()), - next_index, - )?; + next_index = + statement.bind(&remote_identity_columns(host.as_ref()), next_index)?; } statement.exec() }) @@ -2650,19 +2716,9 @@ VALUES {placeholders};"# let trusted_worktrees = self.trusted_worktrees()?; Ok(trusted_worktrees .into_iter() - .filter_map(|(abs_path, user_name, host_name)| { - let db_host = match (user_name, host_name) { - (None, Some(host_name)) => Some(RemoteHostLocation { - user_name: None, - host_identifier: SharedString::new(host_name), - }), - (Some(user_name), Some(host_name)) => Some(RemoteHostLocation { - user_name: Some(SharedString::new(user_name)), - host_identifier: SharedString::new(host_name), - }), - _ => None, - }; - Some((db_host, abs_path?)) + .filter_map(|(abs_path, kind, host, user, port)| { + let remote_host = remote_identity_from_columns(kind, host, user, port)?; + Some((remote_host, abs_path?)) }) .fold(HashMap::default(), |mut acc, (remote_host, abs_path)| { acc.entry(remote_host) @@ -2673,8 +2729,8 @@ VALUES {placeholders};"# } query! { - fn trusted_worktrees() -> Result, Option, Option)>> { - SELECT absolute_path, user_name, host_name + fn trusted_worktrees() -> Result, Option, Option, Option, Option)>> { + SELECT absolute_path, connection_kind, host, user, port FROM trusted_worktrees } } @@ -2684,6 +2740,146 @@ VALUES {placeholders};"# DELETE FROM trusted_worktrees } } + + pub(crate) async fn has_undecided_restricted_worktrees( + &self, + abs_paths: Vec>, + connection_identity: Option>, + ) -> Result { + self.write(move |connection| { + let columns = remote_identity_columns(connection_identity.as_ref()); + for abs_path in &abs_paths { + if !is_worktree_kept_restricted(connection, abs_path, &columns)? { + return Ok(true); + } + } + Ok(false) + }) + .await + } + + pub(crate) fn keep_worktrees_restricted( + &self, + abs_paths: Vec>, + connection_identity: Option>, + ) { + // The write is queued by this call and runs even if the returned future is dropped. + drop(self.write(move |connection| { + connection + .with_savepoint("keep_worktrees_restricted", || { + let columns = remote_identity_columns(connection_identity.as_ref()); + let mut insert = + connection.exec_bound::<(&Path, RemoteIdentityColumns)>(sql!( + INSERT INTO restricted_worktrees(absolute_path, connection_kind, host, user, port) + VALUES (?, ?, ?, ?, ?) + ))?; + for abs_path in &abs_paths { + if !is_worktree_kept_restricted(connection, abs_path, &columns)? { + insert((abs_path.as_ref(), columns.clone()))?; + } + } + Ok(()) + }) + .log_err(); + })); + } + + query! { + pub(crate) async fn clear_restricted_worktrees() -> Result<()> { + DELETE FROM restricted_worktrees + } + } +} + +type RemoteIdentityColumns = ( + Option<&'static str>, + Option, + Option, + Option, +); + +fn remote_identity_columns( + connection_identity: Option<&RemoteConnectionIdentity<'_>>, +) -> RemoteIdentityColumns { + match connection_identity { + None => (None, None, None, None), + Some(RemoteConnectionIdentity::Ssh { + host, + username, + port, + }) => ( + Some(RemoteConnectionKind::Ssh.serialize()), + Some(host.to_string()), + username.as_ref().map(ToString::to_string), + *port, + ), + Some(RemoteConnectionIdentity::Wsl { distro_name, user }) => ( + Some(RemoteConnectionKind::Wsl.serialize()), + Some(distro_name.to_string()), + user.as_ref().map(ToString::to_string), + None, + ), + Some(RemoteConnectionIdentity::Docker { + container_id, + remote_user, + }) => ( + Some(RemoteConnectionKind::Docker.serialize()), + Some(container_id.to_string()), + Some(remote_user.to_string()), + None, + ), + #[cfg(any(test, feature = "test-support"))] + Some(RemoteConnectionIdentity::Mock { id }) => { + (Some("mock"), Some(id.to_string()), None, None) + } + } +} + +fn remote_identity_from_columns( + kind: Option, + host: Option, + user: Option, + port: Option, +) -> Option>> { + let Some(kind) = kind else { + return Some(None); + }; + #[cfg(any(test, feature = "test-support"))] + if kind == "mock" { + let id = host?.parse().ok()?; + return Some(Some(RemoteConnectionIdentity::Mock { id })); + } + let host = Cow::Owned(host?); + let user = user.map(Cow::Owned); + let identity = match RemoteConnectionKind::deserialize(&kind)? { + RemoteConnectionKind::Ssh => RemoteConnectionIdentity::Ssh { + host, + username: user, + port, + }, + RemoteConnectionKind::Wsl => RemoteConnectionIdentity::Wsl { + distro_name: host, + user, + }, + RemoteConnectionKind::Docker => RemoteConnectionIdentity::Docker { + container_id: host, + remote_user: user?, + }, + }; + Some(Some(identity)) +} + +fn is_worktree_kept_restricted( + connection: &Connection, + abs_path: &Path, + columns: &RemoteIdentityColumns, +) -> Result { + let mut select = connection.select_row_bound::<(&Path, RemoteIdentityColumns), PathBuf>(sql!( + SELECT absolute_path + FROM restricted_worktrees + WHERE absolute_path = ? AND connection_kind IS ? AND host IS ? AND user IS ? AND port IS ? + ))?; + Ok(select((abs_path, columns.clone()))?.is_some()) } #[derive(Clone, Debug, PartialEq)] @@ -2692,6 +2888,7 @@ pub struct RecentWorkspace { pub location: SerializedWorkspaceLocation, pub paths: PathList, pub identity_paths: PathList, + pub path_style: Option, pub timestamp: DateTime, } @@ -2703,6 +2900,16 @@ impl RecentWorkspace { }; ProjectGroupKey::new(host, self.identity_paths.clone()) } + + /// Local workspaces always use this machine's path style, so the persisted value is only + /// consulted for remote workspaces. Remote rows saved before `path_style` was persisted + /// have no value and fall back to the local style. + pub fn effective_path_style(&self) -> PathStyle { + match &self.location { + SerializedWorkspaceLocation::Local => PathStyle::local(), + SerializedWorkspaceLocation::Remote(_) => self.path_style.unwrap_or(PathStyle::local()), + } + } } async fn resolve_local_workspace_identity(fs: &dyn Fs, paths: &PathList) -> Option { @@ -2792,6 +2999,21 @@ pub fn delete_unloaded_items( }) } +fn serialize_path_style(path_style: PathStyle) -> String { + match path_style { + PathStyle::Windows => "windows".to_string(), + PathStyle::Unix => "unix".to_string(), + } +} + +fn deserialize_path_style(path_style: String) -> Option { + match path_style.as_str() { + "windows" => Some(PathStyle::Windows), + "unix" => Some(PathStyle::Unix), + _ => None, + } +} + #[cfg(test)] mod tests { use super::*; @@ -2799,10 +3021,11 @@ mod tests { use crate::ProjectGroupKey; use crate::RemovalIntent; use crate::{ + item::test::TestItem, multi_workspace::MultiWorkspace, persistence::{ model::{ - SerializedItem, SerializedPane, SerializedPaneGroup, SerializedWorkspace, + DockData, SerializedItem, SerializedPane, SerializedPaneGroup, SerializedWorkspace, SessionWorkspace, }, read_multi_workspace_state, @@ -2811,11 +3034,16 @@ mod tests { use gpui::TaskExt; use gpui::AppContext as _; + use language::Point; use pretty_assertions::assert_eq; - use project::Project; + use project::{ + Project, + debugger::breakpoint_store::{self, BreakpointEditAction, BreakpointWithPosition}, + }; use remote::SshConnectionOptions; use serde_json::json; - use std::{thread, time::Duration}; + use std::{cell::RefCell, rc::Rc, thread, time::Duration}; + use util::path; /// Creates a unique directory in a FakeFs, returning the path. /// Uses a UUID suffix to avoid collisions with other tests sharing the global DB. @@ -3003,6 +3231,7 @@ mod tests { window_id: None, user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; db.save_workspace(workspace.clone()).await; @@ -3127,6 +3356,7 @@ mod tests { window_id: None, user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; db.save_workspace(workspace.clone()).await; @@ -3164,6 +3394,7 @@ mod tests { window_id: None, user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; db.save_workspace(workspace_without_breakpoint.clone()) @@ -3226,6 +3457,276 @@ mod tests { assert_eq!(test_text_1, "test-text-1"); } + #[gpui::test] + async fn test_restricted_worktrees_are_scoped_to_path_and_connection() { + let db = WorkspaceDb::open_test_db("test_restricted_worktrees").await; + let path = Path::new("/project"); + let other_path = Path::new("/other"); + let ssh = + |username: Option<&'static str>, port: Option| RemoteConnectionIdentity::Ssh { + host: Cow::Borrowed("host"), + username: username.map(Cow::Borrowed), + port, + }; + let declined_connection = ssh(Some("user"), Some(2222)); + + db.keep_worktrees_restricted( + Vec::from([Arc::from(path), Arc::from(path), Arc::from(other_path)]), + Some(declined_connection.clone()), + ); + + for (paths, connection_identity, expected_undecided) in [ + ( + Vec::from([path, other_path]), + Some(declined_connection.clone()), + false, + ), + ( + Vec::from([path, Path::new("/project/nested")]), + Some(declined_connection.clone()), + true, + ), + (Vec::from([path]), None, true), + (Vec::from([path]), Some(ssh(None, Some(2222))), true), + (Vec::from([path]), Some(ssh(Some("user"), Some(2223))), true), + (Vec::from([path]), Some(ssh(Some("user"), None)), true), + ( + Vec::from([path]), + Some(RemoteConnectionIdentity::Wsl { + distro_name: Cow::Borrowed("host"), + user: Some(Cow::Borrowed("user")), + }), + true, + ), + ] { + assert_eq!( + db.has_undecided_restricted_worktrees( + paths.iter().copied().map(Arc::from).collect::>(), + connection_identity.clone(), + ) + .await + .unwrap(), + expected_undecided, + "{paths:?} on {connection_identity:?}" + ); + } + + db.keep_worktrees_restricted(Vec::from([Arc::from(Path::new("/late"))]), None); + db.keep_worktrees_restricted(Vec::from([Arc::from(Path::new("/late"))]), None); + assert_eq!( + db.select_row::(sql!(SELECT COUNT(*) FROM restricted_worktrees)) + .unwrap()() + .unwrap(), + Some(3) + ); + + db.clear_restricted_worktrees().await.unwrap(); + assert_eq!( + db.select_row::(sql!(SELECT COUNT(*) FROM restricted_worktrees)) + .unwrap()() + .unwrap(), + Some(0) + ); + } + + #[test] + fn test_trusted_worktrees_migration_splits_hosts_by_known_connections() { + let connection = Connection::open_memory(Some( + "test_trusted_worktrees_migration_splits_hosts_by_known_connections", + )); + let trusted_worktrees_migration = WorkspaceDb::MIGRATIONS + .iter() + .position(|migration| migration.contains("CREATE TABLE trusted_worktrees_2")) + .expect("trusted worktrees migration should exist"); + let old_migrations = &WorkspaceDb::MIGRATIONS[..trusted_worktrees_migration]; + connection + .migrate(WorkspaceDb::NAME, old_migrations, &mut |_, _, _| false) + .unwrap(); + connection + .exec( + " + INSERT INTO remote_connections (kind, host, port, user, distro, name, container_id) + VALUES + ('ssh', 'server', 2222, 'user', NULL, NULL, NULL), + ('ssh', 'server', 2223, 'user', NULL, NULL, NULL), + ('ssh', 'server', 2224, 'other', NULL, NULL, NULL), + ('ssh', 'no-user', NULL, NULL, NULL, NULL, NULL), + ('wsl', NULL, NULL, 'user', 'Ubuntu', NULL, NULL), + ('docker', NULL, NULL, 'vscode', NULL, 'dev', 'container'); + INSERT INTO trusted_worktrees (absolute_path, user_name, host_name) + VALUES + ('/local', NULL, NULL), + ('/ssh', 'user', 'server'), + ('/ssh_no_user', NULL, 'no-user'), + ('/wsl', 'user', 'Ubuntu'), + ('/docker', 'dev', 'container'), + ('/unknown_connection', 'user', 'forgotten'), + ('/unknown_shape', 'user', NULL);", + ) + .unwrap()() + .unwrap(); + + connection + .migrate( + WorkspaceDb::NAME, + WorkspaceDb::MIGRATIONS, + &mut |_, _, _| false, + ) + .unwrap(); + + let migrated_rows = connection + .select::<( + String, + Option, + Option, + Option, + Option, + )>( + "SELECT absolute_path, connection_kind, host, user, port + FROM trusted_worktrees + ORDER BY absolute_path, port", + ) + .unwrap()() + .unwrap(); + let row = |path: &str, kind: Option<&str>, host: Option<&str>, user: Option<&str>, port| { + ( + path.to_string(), + kind.map(String::from), + host.map(String::from), + user.map(String::from), + port, + ) + }; + assert_eq!( + migrated_rows, + Vec::from([ + row( + "/docker", + Some("docker"), + Some("container"), + Some("vscode"), + None + ), + row("/local", None, None, None, None), + row( + "/ssh", + Some("ssh"), + Some("server"), + Some("user"), + Some(2222) + ), + row( + "/ssh", + Some("ssh"), + Some("server"), + Some("user"), + Some(2223) + ), + row("/ssh_no_user", Some("ssh"), Some("no-user"), None, None), + row("/wsl", Some("wsl"), Some("Ubuntu"), Some("user"), None), + ]) + ); + } + + #[gpui::test] + async fn test_trusted_worktrees_round_trip_all_connection_kinds() { + let db = WorkspaceDb::open_test_db("test_trusted_worktrees_round_trip").await; + let connections = [ + None, + Some(RemoteConnectionIdentity::Ssh { + host: Cow::Borrowed("server"), + username: Some(Cow::Borrowed("user")), + port: Some(2222), + }), + Some(RemoteConnectionIdentity::Ssh { + host: Cow::Borrowed("server"), + username: Some(Cow::Borrowed("user")), + port: Some(2223), + }), + Some(RemoteConnectionIdentity::Ssh { + host: Cow::Borrowed("server"), + username: None, + port: None, + }), + Some(RemoteConnectionIdentity::Wsl { + distro_name: Cow::Borrowed("server"), + user: Some(Cow::Borrowed("user")), + }), + Some(RemoteConnectionIdentity::Docker { + container_id: Cow::Borrowed("server"), + remote_user: Cow::Borrowed("user"), + }), + Some(RemoteConnectionIdentity::Mock { id: 7 }), + ]; + let trusted_paths = connections + .into_iter() + .map(|connection_identity| { + ( + connection_identity, + HashSet::from_iter([PathBuf::from("/project")]), + ) + }) + .collect::(); + + db.save_trusted_worktrees(trusted_paths.clone()) + .await + .unwrap(); + + assert_eq!(db.fetch_trusted_worktrees().unwrap(), trusted_paths); + } + + #[test] + fn test_restricted_worktree_lookup_waits_for_pending_saves() { + futures::executor::block_on(async { + let db = WorkspaceDb( + ThreadSafeConnection::builder::( + "test_restricted_worktree_lookup", + false, + ) + .build() + .await + .unwrap(), + ); + let path = Arc::::from(Path::new("/project")); + let (release_writer, writer_released) = std::sync::mpsc::channel::<()>(); + drop(db.write(move |_| { + writer_released.recv().ok(); + })); + + db.keep_worktrees_restricted(Vec::from([path.clone()]), None); + let (has_undecided_worktrees, ()) = futures::join!( + db.has_undecided_restricted_worktrees(Vec::from([path]), None), + async { + release_writer.send(()).unwrap(); + } + ); + + assert_eq!(has_undecided_worktrees.unwrap(), false); + }); + } + + #[cfg(unix)] + #[gpui::test] + async fn test_restricted_worktrees_keep_non_utf8_paths_distinct() { + use std::{ffi::OsStr, os::unix::ffi::OsStrExt as _}; + + let db = WorkspaceDb::open_test_db("test_restricted_worktrees_non_utf8").await; + let declined_path = Path::new(OsStr::from_bytes(b"/tmp/\xff/project")); + let other_path = Path::new(OsStr::from_bytes(b"/tmp/\xfe/project")); + + db.keep_worktrees_restricted(Vec::from([Arc::from(declined_path)]), None); + + for (path, expected_undecided) in [(declined_path, false), (other_path, true)] { + assert_eq!( + db.has_undecided_restricted_worktrees(Vec::from([Arc::from(path)]), None) + .await + .unwrap(), + expected_undecided, + "{path:?}" + ); + } + } + #[gpui::test] async fn test_native_window_state_round_trip() { zlog::init_test(); @@ -3255,6 +3756,7 @@ mod tests { window_id: None, user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }) .await; assert_eq!(db.native_window_state(id).unwrap(), Some((None, None))); @@ -3337,6 +3839,7 @@ mod tests { window_id: None, user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; let workspace_2 = SerializedWorkspace { @@ -3355,6 +3858,7 @@ mod tests { window_id: None, user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; db.save_workspace(workspace_1.clone()).await; @@ -3467,6 +3971,7 @@ mod tests { recent_navigation_history: (0..20) .map(|index| PathBuf::from(format!("/tmp2/src/{index}.rs"))) .collect(), + path_style: non_local_path_style(), }; db.save_workspace(workspace.clone()).await; @@ -3485,6 +3990,142 @@ mod tests { assert!(db.recent_navigation_history(workspace.id).is_empty()); } + fn non_local_path_style() -> PathStyle { + match PathStyle::local() { + PathStyle::Unix => PathStyle::Windows, + PathStyle::Windows => PathStyle::Unix, + } + } + + #[gpui::test] + async fn test_path_style_round_trip(cx: &mut gpui::TestAppContext) { + let fs = fs::FakeFs::new(cx.executor()); + let db = WorkspaceDb::open_test_db("test_path_style_round_trip").await; + + // The recent-workspaces list only includes local workspaces whose paths exist. + fs.insert_tree("/path-style/local", json!({})).await; + fs.insert_tree("/path-style/remote", json!({})).await; + + let local_paths = [Path::new("/path-style/local")]; + let remote_paths = [Path::new("/path-style/remote")]; + + let mut local_workspace = workspace_with(1, &local_paths, empty_pane_group(), None); + local_workspace.path_style = non_local_path_style(); + db.save_workspace(local_workspace.clone()).await; + + let remote_connection_id = db + .get_or_create_remote_connection(RemoteConnectionOptions::Ssh(SshConnectionOptions { + host: "path-style-host".into(), + ..Default::default() + })) + .await + .unwrap(); + let mut remote_workspace = remote_workspace_with(2, "path-style-host", &remote_paths); + remote_workspace.path_style = non_local_path_style(); + db.save_workspace(remote_workspace).await; + + assert_eq!( + db.workspace_for_id(WorkspaceId(1)).unwrap().path_style, + local_workspace.path_style + ); + assert_eq!( + db.workspace_for_roots(&local_paths).unwrap().path_style, + local_workspace.path_style + ); + assert_eq!( + db.remote_workspace_for_roots(&remote_paths, remote_connection_id) + .unwrap() + .path_style, + non_local_path_style() + ); + + let recent_workspaces = db.recent_project_workspaces(fs.as_ref()).await.unwrap(); + let recent_local_workspace = recent_workspaces + .iter() + .find(|workspace| workspace.workspace_id == WorkspaceId(1)) + .expect("local workspace should be listed as a recent workspace"); + assert_eq!( + recent_local_workspace.path_style, + Some(non_local_path_style()) + ); + + let mut updated_workspace = local_workspace; + updated_workspace.path_style = PathStyle::local(); + db.save_workspace(updated_workspace).await; + assert_eq!( + db.workspace_for_id(WorkspaceId(1)).unwrap().path_style, + PathStyle::local() + ); + } + + #[gpui::test] + async fn test_missing_or_unknown_path_style(cx: &mut gpui::TestAppContext) { + let fs = fs::FakeFs::new(cx.executor()); + let db = WorkspaceDb::open_test_db("test_missing_or_unknown_path_style").await; + let workspace_id = WorkspaceId(1); + + // The recent-workspaces list only includes local workspaces whose paths exist. + fs.insert_tree("/legacy/path-style", json!({})).await; + + let mut workspace = workspace_with( + 1, + &[Path::new("/legacy/path-style")], + empty_pane_group(), + None, + ); + workspace.path_style = non_local_path_style(); + db.save_workspace(workspace).await; + + // The NULL case + db.write(move |conn| { + conn.exec_bound(sql!( + UPDATE workspaces SET path_style = NULL WHERE workspace_id = ?1 + ))?(workspace_id) + }) + .await + .unwrap(); + + assert_eq!( + db.workspace_for_id(workspace_id).unwrap().path_style, + PathStyle::local() + ); + assert_eq!( + recent_workspace_path_style(&db, fs.as_ref(), workspace_id).await, + None + ); + + // The invalid case + db.write(move |conn| { + conn.exec_bound(sql!( + UPDATE workspaces SET path_style = ?2 WHERE workspace_id = ?1 + ))?((workspace_id, "plan9")) + }) + .await + .unwrap(); + assert_eq!( + db.workspace_for_id(workspace_id).unwrap().path_style, + PathStyle::local() + ); + assert_eq!( + recent_workspace_path_style(&db, fs.as_ref(), workspace_id).await, + None + ); + } + + async fn recent_workspace_path_style( + db: &WorkspaceDb, + fs: &dyn Fs, + workspace_id: WorkspaceId, + ) -> Option { + db.recent_project_workspaces(fs) + .await + .unwrap() + .into_iter() + .find(|workspace| workspace.workspace_id == workspace_id) + .expect("workspace should be listed as a recent workspace") + .path_style + } + #[gpui::test] async fn test_workspace_assignment() { zlog::init_test(); @@ -3507,6 +4148,7 @@ mod tests { window_id: Some(1), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; let mut workspace_2 = SerializedWorkspace { @@ -3525,6 +4167,7 @@ mod tests { window_id: Some(2), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; db.save_workspace(workspace_1.clone()).await; @@ -3570,6 +4213,7 @@ mod tests { window_id: Some(3), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; db.save_workspace(workspace_3.clone()).await; @@ -3611,6 +4255,7 @@ mod tests { window_id: Some(10), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; let workspace_2 = SerializedWorkspace { @@ -3629,6 +4274,7 @@ mod tests { window_id: Some(20), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; let workspace_3 = SerializedWorkspace { @@ -3647,6 +4293,7 @@ mod tests { window_id: Some(30), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; let workspace_4 = SerializedWorkspace { @@ -3665,6 +4312,7 @@ mod tests { window_id: None, user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; let connection_id = db @@ -3694,6 +4342,7 @@ mod tests { window_id: Some(50), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; let workspace_6 = SerializedWorkspace { @@ -3712,6 +4361,7 @@ mod tests { window_id: Some(60), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; db.save_workspace(workspace_1.clone()).await; @@ -3772,6 +4422,7 @@ mod tests { window_id: None, user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), } } @@ -3816,6 +4467,7 @@ mod tests { window_id: Some(window_id), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }) .collect::>(); @@ -3916,6 +4568,7 @@ mod tests { window_id: Some(id), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), } } @@ -3941,6 +4594,7 @@ mod tests { window_id: Some(id), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), } } @@ -3958,6 +4612,7 @@ mod tests { location: SerializedWorkspaceLocation::Local, paths, identity_paths, + path_style: Some(PathStyle::local()), timestamp, } } @@ -4200,6 +4855,7 @@ mod tests { window_id: Some(window_id), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }) .collect::>(); @@ -4564,6 +5220,7 @@ mod tests { window_id: None, user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }; // Save the workspace (this creates the record with empty paths) @@ -4643,6 +5300,7 @@ mod tests { window_id: Some(*window_id), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }) .await; } @@ -4828,6 +5486,374 @@ mod tests { ); } + #[gpui::test] + async fn test_restoring_workspace_saves_what_it_restores_and_what_was_added( + cx: &mut gpui::TestAppContext, + ) { + crate::tests::init_test(cx); + cx.update(crate::register_serializable_item::); + + let fs = fs::FakeFs::new(cx.executor()); + fs.insert_tree( + path!("/project"), + json!({ "saved.rs": "one\ntwo\n", "added.rs": "one\ntwo\n" }), + ) + .await; + let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await; + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx)); + let workspace = + multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone()); + let db = cx.update(|_, cx| WorkspaceDb::global(cx)); + let workspace_id = db.next_id().await.unwrap(); + workspace.update(cx, |workspace, _| workspace.set_database_id(workspace_id)); + + let added_item = cx.new(TestItem::new); + let added_item_id = added_item.entity_id().as_u64(); + workspace.update_in(cx, |workspace, window, cx| { + workspace.add_item_to_active_pane(Box::new(added_item.clone()), None, true, window, cx); + }); + let buffer = project + .update(cx, |project, cx| { + project.open_local_buffer(path!("/project/added.rs"), cx) + }) + .await + .unwrap(); + project.update(cx, |project, cx| { + let position = buffer.read(cx).anchor_before(Point::new(1, 0)); + project.bookmark_store().update(cx, |bookmark_store, cx| { + bookmark_store.toggle_bookmark(buffer.clone(), position, String::new(), cx); + }); + project + .breakpoint_store() + .update(cx, |breakpoint_store, cx| { + breakpoint_store.toggle_breakpoint( + buffer.clone(), + BreakpointWithPosition { + position, + bp: breakpoint_store::Breakpoint::new_standard(), + }, + BreakpointEditAction::Toggle, + cx, + ); + }); + }); + + let saved_path = Arc::::from(Path::new(path!("/project/saved.rs"))); + let added_path = Arc::::from(Path::new(path!("/project/added.rs"))); + let bookmark = |row| SerializedBookmark { + row, + label: String::new(), + }; + let breakpoint = |row, path: &Arc| SourceBreakpoint { + row, + path: path.clone(), + message: None, + condition: None, + hit_condition: None, + state: BreakpointState::Enabled, + }; + let saved_docks = DockStructure { + left: DockData { + visible: true, + active_panel: Some("SavedPanel".to_owned()), + zoom: false, + }, + ..Default::default() + }; + let restoring_from = SerializedWorkspace { + id: workspace_id, + paths: PathList::new(&[path!("/project")]), + identity_paths: None, + location: SerializedWorkspaceLocation::Local, + center_group: SerializedPaneGroup::Pane(SerializedPane::new( + vec![ + SerializedItem::new("Terminal", added_item_id, true, false), + SerializedItem::new("TestItem", added_item_id + 1, false, false), + ], + true, + 1, + )), + window_bounds: Default::default(), + display: Default::default(), + docks: saved_docks.clone(), + centered_layout: false, + bookmarks: BTreeMap::from_iter([(saved_path.clone(), vec![bookmark(0)])]), + breakpoints: BTreeMap::from_iter([( + saved_path.clone(), + vec![breakpoint(0, &saved_path)], + )]), + session_id: None, + window_id: None, + user_toolchains: Default::default(), + recent_navigation_history: Default::default(), + path_style: PathStyle::local(), + }; + workspace.update(cx, |workspace, _| { + workspace.restoring_workspace.set(true); + workspace.restoring_from.replace(Some(restoring_from)); + }); + multi_workspace + .update_in(cx, |multi_workspace, window, cx| { + multi_workspace.workspace().update(cx, |workspace, cx| { + workspace.flush_serialization(window, cx) + }) + }) + .await; + + let both_breakpoints = BTreeMap::from_iter([ + (added_path.clone(), vec![breakpoint(1, &added_path)]), + (saved_path.clone(), vec![breakpoint(0, &saved_path)]), + ]); + let saved = db.workspace_for_id(workspace_id).unwrap(); + assert_eq!( + ( + saved.center_group, + saved.docks, + saved.bookmarks, + saved.breakpoints + ), + ( + SerializedPaneGroup::Group { + axis: SerializedAxis(Axis::Horizontal), + children: vec![ + SerializedPaneGroup::Pane(SerializedPane::new( + vec![SerializedItem::new( + "TestItem", + added_item_id + 1, + false, + false + )], + false, + 0, + )), + SerializedPaneGroup::Pane(SerializedPane::new( + vec![SerializedItem::new("TestItem", added_item_id, true, false)], + true, + 0, + )), + ], + flexes: None, + }, + saved_docks, + BTreeMap::from_iter([ + (added_path.clone(), vec![bookmark(1)]), + (saved_path.clone(), vec![bookmark(0)]), + ]), + both_breakpoints.clone(), + ) + ); + + workspace.update(cx, |workspace, _| workspace.restoring_workspace.set(false)); + multi_workspace + .update_in(cx, |multi_workspace, window, cx| { + multi_workspace.workspace().update(cx, |workspace, cx| { + workspace.flush_serialization(window, cx) + }) + }) + .await; + + let saved = db.workspace_for_id(workspace_id).unwrap(); + assert_eq!( + ( + saved.center_group, + saved.docks, + saved.bookmarks, + saved.breakpoints + ), + ( + SerializedPaneGroup::Pane(SerializedPane::new( + vec![SerializedItem::new("TestItem", added_item_id, true, false)], + true, + 0, + )), + DockStructure::default(), + BTreeMap::from_iter([(added_path.clone(), vec![bookmark(1)])]), + both_breakpoints, + ) + ); + } + + #[test] + fn test_saved_layout_is_unchanged_when_nothing_was_opened_while_restoring() { + let saved = SerializedPaneGroup::Pane(SerializedPane::new( + vec![SerializedItem::new("Terminal", 5, true, false)], + true, + 1, + )); + let nothing_opened = SerializedPaneGroup::Pane(SerializedPane::new(Vec::new(), true, 0)); + + assert_eq!( + saved + .clone() + .with_panes_opened_while_restoring(nothing_opened), + saved + ); + } + + #[gpui::test] + async fn test_restoring_workspace_keeps_its_saved_breakpoints_until_they_are_loaded( + cx: &mut gpui::TestAppContext, + ) { + crate::tests::init_test(cx); + + let fs = fs::FakeFs::new(cx.executor()); + fs.insert_tree(path!("/project"), json!({ "saved.rs": "one\ntwo\n" })) + .await; + let project = Project::test(fs.clone(), [path!("/project").as_ref()], cx).await; + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx)); + let workspace = + multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone()); + let db = cx.update(|_, cx| WorkspaceDb::global(cx)); + let workspace_id = db.next_id().await.unwrap(); + workspace.update(cx, |workspace, _| workspace.set_database_id(workspace_id)); + + let saved_path = Arc::::from(Path::new(path!("/project/saved.rs"))); + let saved_breakpoints = BTreeMap::from_iter([( + saved_path.clone(), + vec![SourceBreakpoint { + row: 1, + path: saved_path.clone(), + message: None, + condition: None, + hit_condition: None, + state: BreakpointState::Enabled, + }], + )]); + let restoring_from = SerializedWorkspace { + id: workspace_id, + paths: PathList::new(&[path!("/project")]), + identity_paths: None, + location: SerializedWorkspaceLocation::Local, + center_group: Default::default(), + window_bounds: Default::default(), + display: Default::default(), + docks: Default::default(), + centered_layout: false, + bookmarks: Default::default(), + breakpoints: saved_breakpoints.clone(), + session_id: None, + window_id: None, + user_toolchains: Default::default(), + recent_navigation_history: Default::default(), + path_style: PathStyle::local(), + }; + + let breakpoints_when_the_tabs_were_in_place = Rc::new(RefCell::new(None)); + let _tabs_in_place = cx.update(|_, cx| { + cx.observe(&workspace, { + let breakpoints_when_the_tabs_were_in_place = + breakpoints_when_the_tabs_were_in_place.clone(); + move |workspace, cx| { + let workspace = workspace.read(cx); + if !workspace.is_restoring() + && breakpoints_when_the_tabs_were_in_place.borrow().is_none() + { + let restoring_from = workspace.restoring_from.borrow(); + breakpoints_when_the_tabs_were_in_place.replace(Some( + restoring_from + .as_ref() + .map(|restoring_from| restoring_from.breakpoints.clone()), + )); + } + } + }) + }); + workspace.update(cx, |workspace, _| { + workspace.restoring_workspace.set(true); + workspace + .restoring_from + .replace(Some(restoring_from.clone())); + }); + workspace + .update_in(cx, |_, window, cx| { + crate::Workspace::load_workspace(restoring_from, Vec::new(), window, cx) + }) + .await + .unwrap(); + + let loaded_breakpoints = project.read_with(cx, |project, cx| { + project + .breakpoint_store() + .read(cx) + .all_source_breakpoints(cx) + }); + let still_restoring_from = workspace.read_with(cx, |workspace, _| { + workspace.restoring_from.borrow().is_some() + }); + assert_eq!( + ( + breakpoints_when_the_tabs_were_in_place.take(), + loaded_breakpoints, + still_restoring_from, + ), + ( + Some(Some(saved_breakpoints.clone())), + saved_breakpoints, + false + ) + ); + } + + #[gpui::test] + async fn test_workspace_whose_restore_is_cancelled_is_no_longer_restoring( + cx: &mut gpui::TestAppContext, + ) { + crate::tests::init_test(cx); + + let fs = fs::FakeFs::new(cx.executor()); + let project = Project::test(fs.clone(), [], cx).await; + let (multi_workspace, cx) = + cx.add_window_view(|window, cx| MultiWorkspace::test_new(project.clone(), window, cx)); + let workspace = + multi_workspace.read_with(cx, |multi_workspace, _| multi_workspace.workspace().clone()); + let db = cx.update(|_, cx| WorkspaceDb::global(cx)); + let workspace_id = db.next_id().await.unwrap(); + workspace.update(cx, |workspace, _| { + workspace.set_database_id(workspace_id); + workspace.keeps_saved_state_while_restoring = true; + }); + + let restoring_from = SerializedWorkspace { + id: workspace_id, + paths: PathList::default(), + identity_paths: None, + location: SerializedWorkspaceLocation::Local, + center_group: Default::default(), + window_bounds: Default::default(), + display: Default::default(), + docks: Default::default(), + centered_layout: false, + bookmarks: Default::default(), + breakpoints: Default::default(), + session_id: None, + window_id: None, + user_toolchains: Default::default(), + recent_navigation_history: Default::default(), + path_style: PathStyle::local(), + }; + let restoring_state = |cx: &mut gpui::VisualTestContext| { + workspace.read_with(cx, |workspace, _| { + ( + workspace.is_restoring(), + workspace.restoring_from.borrow().is_some(), + ) + }) + }; + let restore = workspace.update_in(cx, |workspace, window, cx| { + crate::open_items(workspace, Some(restoring_from), Vec::new(), window, cx) + }); + let while_restoring = restoring_state(cx); + drop(restore); + cx.run_until_parked(); + + assert_eq!( + (while_restoring, restoring_state(cx)), + ((true, true), (false, false)) + ); + } + #[gpui::test] async fn test_pending_serialization_flushed_on_shutdown(cx: &mut gpui::TestAppContext) { crate::tests::init_test(cx); @@ -4982,6 +6008,7 @@ mod tests { window_id: Some(99), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }) .await; @@ -5080,6 +6107,7 @@ mod tests { window_id: Some(window_id_val), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }) .await; @@ -5099,6 +6127,7 @@ mod tests { window_id: Some(window_id_val), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }) .await; @@ -5180,6 +6209,7 @@ mod tests { window_id: Some(88), user_toolchains: Default::default(), recent_navigation_history: Default::default(), + path_style: PathStyle::local(), }) .await; cx.run_until_parked(); diff --git a/crates/workspace/src/persistence/model.rs b/crates/workspace/src/persistence/model.rs index 9483e5a4545..a422f05a06d 100644 --- a/crates/workspace/src/persistence/model.rs +++ b/crates/workspace/src/persistence/model.rs @@ -5,12 +5,12 @@ use crate::{ }; use anyhow::{Context, Result}; use async_recursion::async_recursion; -use collections::IndexSet; +use collections::{HashSet, IndexSet}; use db::sqlez::{ bindable::{Bind, Column, StaticColumnCount}, statement::Statement, }; -use gpui::{AsyncWindowContext, Entity, WeakEntity, WindowId}; +use gpui::{AsyncWindowContext, Axis, Entity, WeakEntity, WindowId}; use language::{Toolchain, ToolchainScope}; use project::{ @@ -24,7 +24,7 @@ use std::{ path::{Path, PathBuf}, sync::Arc, }; -use util::{ResultExt, path_list::SerializedPathList}; +use util::{ResultExt, path_list::SerializedPathList, paths::PathStyle}; use uuid::Uuid; #[derive( @@ -148,6 +148,7 @@ pub(crate) struct SerializedWorkspace { pub(crate) user_toolchains: BTreeMap>, pub(crate) recent_navigation_history: Vec, pub(crate) window_id: Option, + pub(crate) path_style: PathStyle, } #[derive(Debug, PartialEq, Clone, Default, Serialize, Deserialize)] @@ -241,6 +242,63 @@ pub(crate) enum SerializedPaneGroup { Pane(SerializedPane), } +impl SerializedPaneGroup { + pub(crate) fn with_panes_opened_while_restoring(mut self, mut opened: Self) -> Self { + let mut opened_item_ids = HashSet::default(); + let mut opened_pane_is_active = false; + opened.for_each_pane(&mut |pane| { + opened_item_ids.extend(pane.children.iter().map(|item| item.item_id)); + opened_pane_is_active |= pane.active; + }); + if opened_item_ids.is_empty() { + return self; + } + self.for_each_pane(&mut |pane| { + let replaced_pinned_items = pane + .children + .iter() + .take(pane.pinned_count) + .filter(|item| opened_item_ids.contains(&item.item_id)) + .count(); + pane.children + .retain(|item| !opened_item_ids.contains(&item.item_id)); + pane.pinned_count -= replaced_pinned_items; + pane.active &= !opened_pane_is_active; + }); + Self::Group { + axis: SerializedAxis(Axis::Horizontal), + children: vec![self, opened], + flexes: None, + } + } + + fn for_each_pane(&mut self, update: &mut impl FnMut(&mut SerializedPane)) { + match self { + Self::Pane(pane) => update(pane), + Self::Group { children, .. } => { + for child in children { + child.for_each_pane(update); + } + } + } + } +} + +pub(crate) fn add_saved_rows( + rows: &mut BTreeMap, Vec>, + saved_rows: BTreeMap, Vec>, + row: impl Fn(&T) -> u32, +) { + for (path, saved_rows) in saved_rows { + let rows = rows.entry(path).or_default(); + for saved_row in saved_rows { + if !rows.iter().any(|existing| row(existing) == row(&saved_row)) { + rows.push(saved_row); + } + } + } +} + #[cfg(test)] impl Default for SerializedPaneGroup { fn default() -> Self { diff --git a/crates/workspace/src/security_modal.rs b/crates/workspace/src/security_modal.rs index c436fea161d..5fc0daba11d 100644 --- a/crates/workspace/src/security_modal.rs +++ b/crates/workspace/src/security_modal.rs @@ -13,9 +13,10 @@ use gpui::{ use project::{ WorktreeId, - trusted_worktrees::{PathTrust, RemoteHostLocation, TrustedWorktrees}, + trusted_worktrees::{PathTrust, TrustedWorktrees}, worktree_store::WorktreeStore, }; +use remote::RemoteConnectionIdentity; use smallvec::SmallVec; use theme::ActiveTheme; use ui::{ @@ -26,7 +27,7 @@ use ui_input::InputField; use util::{ResultExt, paths::PathStyle}; -use crate::{DismissDecision, ModalView, ToggleWorktreeSecurity}; +use crate::{DismissDecision, ModalView, ToggleWorktreeSecurity, WorkspaceDb}; pub struct SecurityModal { restricted_paths: HashMap, @@ -34,10 +35,11 @@ pub struct SecurityModal { _home_dir_task: Task<()>, trust_parents: bool, worktree_store: WeakEntity, - remote_host: Option, + remote_host: Option>, focus_handle: FocusHandle, project_list_scroll_handle: ScrollHandle, trusted: Option, + restriction_inherited: bool, /// Editable trust scope shown inline with the checkbox when a single /// project is being prompted for; read-only until the checkbox is ticked. trust_path_input: Entity, @@ -47,7 +49,7 @@ pub struct SecurityModal { struct RestrictedPath { abs_path: Arc, is_file: bool, - host: Option, + host: Option>, } impl Focusable for SecurityModal { @@ -63,10 +65,20 @@ impl ModalView for SecurityModal { true } - fn on_before_dismiss(&mut self, _: &mut Window, _: &mut Context) -> DismissDecision { + fn on_before_dismiss(&mut self, _: &mut Window, cx: &mut Context) -> DismissDecision { + if self.restriction_inherited { + return DismissDecision::Dismiss(true); + } match self.trusted { Some(false) => { telemetry::event!("Open in Restricted", source = "Worktree Trust Modal"); + let abs_paths = self + .restricted_paths + .values() + .map(|restricted_path| restricted_path.abs_path.clone()) + .collect::>(); + WorkspaceDb::global(cx) + .keep_worktrees_restricted(abs_paths, self.remote_host.clone()); DismissDecision::Dismiss(true) } Some(true) => { @@ -111,8 +123,7 @@ impl Render for SecurityModal { this.trust_and_dismiss(cx); })) .on_action(cx.listener(|security_modal, _: &ToggleWorktreeSecurity, _window, cx| { - security_modal.trusted = Some(false); - security_modal.dismiss(cx); + security_modal.stay_restricted_and_dismiss(cx); })) .header( v_flex() @@ -146,28 +157,14 @@ impl Render for SecurityModal { } else { Some(restricted_path.abs_path.as_ref()) }?; + let path = self.shorten_path(abs_path, path_style); let label = match &restricted_path.host { - Some(remote_host) => { - match &remote_host.user_name { - Some(user_name) => format!( - "{} ({}@{})", - self.shorten_path(abs_path, path_style) - .display(), - user_name, - remote_host.host_identifier - ), - None => format!( - "{} ({})", - self.shorten_path(abs_path, path_style) - .display(), - remote_host.host_identifier - ), - } - } - None => self - .shorten_path(abs_path, path_style) - .display() - .to_string(), + Some(remote_host) => format!( + "{} ({})", + path.display(), + remote_host_label(remote_host), + ), + None => path.display().to_string(), }; Some( h_flex() @@ -286,8 +283,7 @@ impl Render for SecurityModal { .map(|kb| kb.size(rems_from_px(12_f32))), ) .on_click(cx.listener(move |security_modal, _, _, cx| { - security_modal.trusted = Some(false); - security_modal.dismiss(cx); + security_modal.stay_restricted_and_dismiss(cx); cx.stop_propagation(); })), ) @@ -312,7 +308,7 @@ impl Render for SecurityModal { impl SecurityModal { pub fn new( worktree_store: WeakEntity, - remote_host: Option>, + remote_host: Option>, home_dir_task: Task>, window: &mut Window, cx: &mut Context, @@ -328,7 +324,7 @@ impl SecurityModal { }); let mut this = Self { worktree_store, - remote_host: remote_host.map(|host| host.into()), + remote_host, restricted_paths: HashMap::default(), focus_handle: cx.focus_handle(), project_list_scroll_handle: ScrollHandle::new(), @@ -336,6 +332,7 @@ impl SecurityModal { home_dir: None, _home_dir_task: task, trusted: None, + restriction_inherited: false, trust_path_input, }; this.refresh_restricted_paths(cx); @@ -471,6 +468,16 @@ impl SecurityModal { cx.emit(DismissEvent); } + pub(crate) fn dismiss_inherited_restriction(&mut self, cx: &mut Context) { + self.restriction_inherited = true; + self.dismiss(cx); + } + + fn stay_restricted_and_dismiss(&mut self, cx: &mut Context) { + self.trusted = Some(false); + self.dismiss(cx); + } + /// The sole untrusted, non-file project, when exactly one is being prompted /// for. This is the case where the trust scope can be edited (Delta opens /// one worktree per thread); with zero or several we keep the static label. @@ -558,9 +565,40 @@ fn validate_trust_scope( Ok(expanded) } +fn remote_host_label(remote_host: &RemoteConnectionIdentity<'_>) -> String { + let (user, host) = match remote_host { + RemoteConnectionIdentity::Ssh { + host, + username, + port, + } => ( + username.as_deref(), + match port { + Some(port) if host.contains(':') => format!("[{host}]:{port}"), + Some(port) => format!("{host}:{port}"), + None => host.to_string(), + }, + ), + RemoteConnectionIdentity::Wsl { distro_name, user } => { + (user.as_deref(), distro_name.to_string()) + } + RemoteConnectionIdentity::Docker { + container_id, + remote_user, + } => (Some(remote_user.as_ref()), container_id.to_string()), + #[cfg(any(test, feature = "test-support"))] + RemoteConnectionIdentity::Mock { id } => (None, format!("mock-{id}")), + }; + match user { + Some(user) => format!("{user}@{host}"), + None => host, + } +} + #[cfg(test)] mod tests { use super::*; + use remote::{RemoteConnectionOptions, SshConnectionOptions}; #[test] fn accepts_ancestor_or_equal() { @@ -676,4 +714,31 @@ mod tests { PathBuf::from("/Users/me"), ); } + + #[test] + fn remote_host_label_matches_ssh_connection_string() { + for (host, username, port) in [ + ("server", Some("user"), Some(2222)), + ("server", Some("user"), None), + ("server", None, Some(2222)), + ("server", None, None), + ("::1", Some("user"), Some(2222)), + ("::1", None, None), + ("127.0.0.1", None, Some(2222)), + ] { + let options = RemoteConnectionOptions::Ssh(SshConnectionOptions { + host: host.into(), + username: username.map(String::from), + port, + ..SshConnectionOptions::default() + }); + let RemoteConnectionOptions::Ssh(ssh_options) = &options else { + unreachable!(); + }; + assert_eq!( + remote_host_label(&options.identity()), + ssh_options.connection_string(), + ); + } + } } diff --git a/crates/workspace/src/tasks.rs b/crates/workspace/src/tasks.rs index 85ed9b661ef..c53629406e4 100644 --- a/crates/workspace/src/tasks.rs +++ b/crates/workspace/src/tasks.rs @@ -2,7 +2,7 @@ use std::process::ExitStatus; use anyhow::Result; use collections::HashSet; -use gpui::{AppContext, AsyncWindowContext, Context, Entity, Task, TaskExt, WeakEntity}; +use gpui::{App, AppContext, AsyncWindowContext, Context, Entity, Task, TaskExt, WeakEntity}; use language::Buffer; use project::{TaskSourceKind, WorktreeId, trusted_worktrees::TrustedWorktrees}; use remote::ConnectionState; @@ -26,6 +26,21 @@ pub enum ScheduledTaskResult { type TaskCompletionHandler = Box; impl Workspace { + pub fn can_schedule_tasks(&self, cx: &App) -> bool { + match self.project.read(cx).remote_connection_state(cx) { + None | Some(ConnectionState::Connected) => true, + Some( + ConnectionState::Connecting + | ConnectionState::Disconnected + | ConnectionState::HeartbeatMissed + | ConnectionState::Reconnecting, + ) => { + log::warn!("Cannot schedule tasks when disconnected from a remote host"); + false + } + } + } + pub fn schedule_task( self: &mut Workspace, task_source_kind: TaskSourceKind, @@ -35,17 +50,8 @@ impl Workspace { window: &mut Window, cx: &mut Context, ) { - match self.project.read(cx).remote_connection_state(cx) { - None | Some(ConnectionState::Connected) => {} - Some( - ConnectionState::Connecting - | ConnectionState::Disconnected - | ConnectionState::HeartbeatMissed - | ConnectionState::Reconnecting, - ) => { - log::warn!("Cannot schedule tasks when disconnected from a remote host"); - return; - } + if !self.can_schedule_tasks(cx) { + return; } if let Some(spawn_in_terminal) = diff --git a/crates/workspace/src/workspace.rs b/crates/workspace/src/workspace.rs index f8177139acd..933733800e7 100644 --- a/crates/workspace/src/workspace.rs +++ b/crates/workspace/src/workspace.rs @@ -103,7 +103,7 @@ use project::{ git_store::{GitStoreEvent, RepositoryEvent}, project_settings::ProjectSettings, toolchain_store::ToolchainStoreEvent, - trusted_worktrees::{RemoteHostLocation, TrustedWorktrees, TrustedWorktreesEvent}, + trusted_worktrees::{TrustedWorktrees, TrustedWorktreesEvent}, }; use release_channel::ReleaseChannel; use remote::{ @@ -142,7 +142,7 @@ use std::{ time::Duration, }; use task::{DebugScenario, SharedTaskContext, SpawnInTerminal}; -use theme::{ActiveTheme, ClientDecorationsExt, SystemAppearance}; +use theme::{ActiveTheme, SystemAppearance}; use theme_settings::ThemeSettings; pub use toolbar::{ PaneSearchBarCallbacks, Toolbar, ToolbarItemEvent, ToolbarItemLocation, ToolbarItemView, @@ -168,7 +168,7 @@ use crate::{dock::PanelSizeState, item::ItemBufferKind, notifications::Notificat use crate::{ persistence::{ SerializedAxis, - model::{SerializedItem, SerializedPane, SerializedPaneGroup}, + model::{SerializedItem, SerializedPane, SerializedPaneGroup, add_saved_rows}, }, security_modal::SecurityModal, }; @@ -491,6 +491,7 @@ actions!( ToggleWorktreeSecurity, /// Clears all trusted worktrees, placing them in restricted mode on next open. /// Requires restart to take effect on already opened projects. + /// Also forgets which worktrees were chosen to stay in restricted mode. ClearTrustedWorktrees, /// Stops following a collaborator. Unfollow, @@ -1671,6 +1672,7 @@ pub struct Workspace { pub(crate) modal_layer: Entity, toast_layer: Entity, titlebar_item: Option, + window_tabs_item: Option, titlebar_focus_handle: FocusHandle, region_focus_handles: RegionFocusHandles, notifications: Notifications, @@ -1696,6 +1698,7 @@ pub struct Workspace { _observe_current_user: Task>, _schedule_serialize_workspace: Option>, _serialize_workspace_task: Option>, + worktree_trust_prompt_check: Option>, _schedule_serialize_ssh_paths: Option>, pane_history_timestamp: Arc, bounds: Bounds, @@ -1727,7 +1730,9 @@ pub struct Workspace { deferred_save_items: Vec>, persisted_recent_navigation_history: Vec, last_active_project_path: Option, - restoring_workspace: bool, + restoring_workspace: Rc>, + restoring_from: Rc>>, + keeps_saved_state_while_restoring: bool, } impl EventEmitter for Workspace {} @@ -2177,6 +2182,7 @@ impl Workspace { modal_layer, toast_layer, titlebar_item: None, + window_tabs_item: None, titlebar_focus_handle: cx.focus_handle(), region_focus_handles: RegionFocusHandles::new(cx), notifications: Notifications::default(), @@ -2201,6 +2207,7 @@ impl Workspace { _apply_leader_updates, _schedule_serialize_workspace: None, _serialize_workspace_task: None, + worktree_trust_prompt_check: None, _schedule_serialize_ssh_paths: None, leader_updates_tx, _subscriptions: subscriptions, @@ -2230,7 +2237,9 @@ impl Workspace { deferred_save_items: Vec::new(), persisted_recent_navigation_history: Vec::new(), last_active_project_path: None, - restoring_workspace: false, + restoring_workspace: Rc::new(Cell::new(false)), + restoring_from: Rc::default(), + keeps_saved_state_while_restoring: false, } } @@ -2458,8 +2467,8 @@ impl Workspace { let all_paths_resolved = project_paths.iter().all(|(_, path)| path.is_some()); let opened_items = window .update(cx, |_, window, cx| { - workspace.update(cx, |_workspace: &mut Workspace, cx| { - open_items(serialized_workspace, project_paths, window, cx) + workspace.update(cx, |workspace: &mut Workspace, cx| { + open_items(workspace, serialized_workspace, project_paths, window, cx) }) })? .await @@ -3001,12 +3010,12 @@ impl Workspace { } pub fn is_restoring(&self) -> bool { - self.restoring_workspace + self.restoring_workspace.get() } #[cfg(any(test, feature = "test-support"))] pub fn set_restoring_workspace(&mut self, restoring: bool) { - self.restoring_workspace = restoring; + self.restoring_workspace.set(restoring); } pub fn set_panels_task(&mut self, task: Task>) { @@ -3297,7 +3306,7 @@ impl Workspace { } fn remember_navigation_history_path(&mut self, project_path: &ProjectPath, cx: &App) -> bool { - if self.restoring_workspace { + if self.restoring_workspace.get() { return false; } let Some(absolute_path) = self.project.read(cx).absolute_path(project_path, cx) else { @@ -3521,6 +3530,20 @@ impl Workspace { cx.notify(); } + pub fn clear_titlebar_item(&mut self, window: &mut Window, cx: &mut Context) { + if self.titlebar_item.take().is_some() { + if self.titlebar_focus_handle.contains_focused(window, cx) { + window.focus(&self.fallback_focus_handle(window, cx), cx); + } + cx.notify(); + } + } + + pub fn set_window_tabs_item(&mut self, item: AnyView, cx: &mut Context) { + self.window_tabs_item = Some(item); + cx.notify(); + } + pub fn set_prompt_for_new_path(&mut self, prompt: PromptForNewPath) { self.on_prompt_for_new_path = Some(prompt) } @@ -4231,6 +4254,8 @@ impl Workspace { let fs = self.app_state.fs.clone(); let caller_ordered_abs_paths = abs_paths.clone(); + let mut caller_indices = (0..abs_paths.len()).collect::>(); + caller_indices.sort_by(|left, right| abs_paths.get(*left).cmp(&abs_paths.get(*right))); // Sort the paths to ensure we add worktrees for parents before their children. abs_paths.sort_unstable(); @@ -4399,7 +4424,14 @@ impl Workspace { } } - results + let mut results_in_caller_order = (0..results.len()).map(|_| None).collect::>(); + for (caller_index, result) in caller_indices.into_iter().zip(results) { + if let Some(result_in_caller_order) = results_in_caller_order.get_mut(caller_index) + { + *result_in_caller_order = result; + } + } + results_in_caller_order }) } @@ -8024,7 +8056,6 @@ impl Workspace { let Some(database_id) = self.database_id() else { return Task::ready(()); }; - fn build_serialized_pane_group( pane_group: &Member, window: &mut Window, @@ -8060,14 +8091,14 @@ impl Workspace { match self.workspace_location(cx) { WorkspaceLocation::Location(location, paths) => { - let bookmarks = self.project.update(cx, |project, cx| { + let mut bookmarks = self.project.update(cx, |project, cx| { project .bookmark_store() .read(cx) .all_serialized_bookmarks(cx) }); - let breakpoints = self.project.update(cx, |project, cx| { + let mut breakpoints = self.project.update(cx, |project, cx| { project .breakpoint_store() .read(cx) @@ -8079,14 +8110,29 @@ impl Workspace { .user_toolchains(cx) .unwrap_or_default(); - let center_group = build_serialized_pane_group(&self.center.root, window, cx); - let docks = build_serialized_docks(self, window, cx); + let mut center_group = build_serialized_pane_group(&self.center.root, window, cx); + let mut docks = build_serialized_docks(self, window, cx); + if let Some(restoring_from) = self.restoring_from.borrow().clone() { + if self.restoring_workspace.get() { + center_group = restoring_from + .center_group + .with_panes_opened_while_restoring(center_group); + docks = restoring_from.docks; + add_saved_rows(&mut bookmarks, restoring_from.bookmarks, |bookmark| { + bookmark.row + }); + } + add_saved_rows(&mut breakpoints, restoring_from.breakpoints, |breakpoint| { + breakpoint.row + }); + } let default_docks = (paths.is_empty() && location == SerializedWorkspaceLocation::Local) .then(|| docks.clone()); let window_bounds = Some(SerializedWindowBounds(window.window_bounds())); let identity_paths_hint = self.project_group_key(cx).path_list().clone(); let recent_navigation_history = self.persisted_recent_navigation_history.clone(); + let path_style = self.path_style(cx); let serialized_workspace = SerializedWorkspace { id: database_id, @@ -8104,6 +8150,7 @@ impl Workspace { window_id: Some(window.window_handle().window_id().as_u64()), user_toolchains, recent_navigation_history, + path_style, }; let db = WorkspaceDb::global(cx); @@ -8212,7 +8259,7 @@ impl Workspace { let recent_navigation_history = serialized_workspace.recent_navigation_history.clone(); workspace.update(cx, |workspace, _| { workspace.persisted_recent_navigation_history = recent_navigation_history; - workspace.restoring_workspace = true; + workspace.restoring_workspace.set(true); })?; let project = workspace.read_with(cx, |workspace, _| workspace.project().clone())?; @@ -8259,6 +8306,32 @@ impl Workspace { // Remove old panes from workspace panes list workspace.update_in(cx, |workspace, window, cx| { if let Some((center_group, active_pane)) = center_group { + let item_in_use = workspace.active_item(cx); + let panes_used_while_restoring = if workspace.restoring_from.borrow().is_some() + { + workspace + .center + .panes() + .into_iter() + .cloned() + .collect::>() + } else { + Vec::new() + }; + let mut items_opened_while_restoring = Vec::new(); + for pane in panes_used_while_restoring { + let items = pane + .read(cx) + .items() + .map(|item| item.boxed_clone()) + .collect::>(); + pane.update(cx, |pane, cx| { + for item in &items { + pane.remove_item(item.item_id(), false, false, window, cx); + } + }); + items_opened_while_restoring.extend(items); + } workspace.remove_panes(workspace.center.root.clone(), window, cx); // Swap workspace center group @@ -8272,6 +8345,50 @@ impl Workspace { } else { workspace.set_active_pane(&workspace.center.first_pane(), window, cx); } + + let restored_pane = workspace.active_pane.clone(); + let mut kept_item_in_use = None; + for item in items_opened_while_restoring { + let was_in_use = item_in_use + .as_ref() + .is_some_and(|item_in_use| item_in_use.item_id() == item.item_id()); + let restored_item = item.project_path(cx).and_then(|project_path| { + workspace.panes.iter().find_map(|pane| { + pane.read(cx).item_for_path(project_path.clone(), cx) + }) + }); + let kept_item = match restored_item { + Some(restored_item) => restored_item, + None => { + if let Some(serializable_item) = + item.to_serializable_item_handle(cx) + && let Some(item_ids) = item_ids_by_kind + .get_mut(&serializable_item.serialized_item_kind()) + { + item_ids.push(item.item_id().as_u64() as ItemId); + } + restored_pane.update(cx, |pane, cx| { + let end = pane.items_len(); + pane.add_item_inner( + item.boxed_clone(), + false, + false, + false, + Some(end), + window, + cx, + ); + }); + item + } + }; + if was_in_use { + kept_item_in_use = Some(kept_item); + } + } + if let Some(item) = kept_item_in_use { + workspace.activate_item(item.as_ref(), true, true, window, cx); + } } let docks = serialized_workspace.docks; @@ -8288,7 +8405,7 @@ impl Workspace { }); } - workspace.restoring_workspace = false; + workspace.restoring_workspace.set(false); cx.notify(); })?; @@ -8311,6 +8428,9 @@ impl Workspace { }) }) .await; + workspace.update(cx, |workspace, _| { + workspace.restoring_from.borrow_mut().take(); + })?; // Clean up all the items that have _not_ been loaded. Our ItemIds aren't stable. That means // after loading the items, we might have different items and in order to avoid @@ -8596,6 +8716,7 @@ impl Workspace { }); let db = WorkspaceDb::global(cx); cx.spawn(async move |_, cx| { + db.clear_restricted_worktrees().await.log_err(); if db.clear_trusted_worktrees().await.log_err().is_some() { cx.update(|cx| reload(cx)); } @@ -9406,6 +9527,9 @@ impl Workspace { window: &mut Window, cx: &mut Context, ) { + if toggle { + self.worktree_trust_prompt_check = None; + } if let Some(security_modal) = self.active_modal::(cx) { if toggle { security_modal.update(cx, |security_modal, cx| { @@ -9416,33 +9540,128 @@ impl Workspace { security_modal.refresh_restricted_paths(cx); }); } + } else if toggle { + self.open_worktree_trust_security_modal(window, cx); } else { - let has_restricted_worktrees = TrustedWorktrees::has_restricted_worktrees( - &self.project().read(cx).worktree_store(), - cx, - ); - if has_restricted_worktrees { - let project = self.project().read(cx); - let remote_host = project - .remote_connection_options(cx) - .map(RemoteHostLocation::from); - let worktree_store = project.worktree_store().downgrade(); - let home_dir_task = if project.is_local() { - Task::ready(std::env::home_dir()) - } else { - let resolve_task = project.resolve_abs_path("~", cx); - cx.spawn(async |_, _| { - let resolved_path = resolve_task - .await - .and_then(|path| path.into_abs_path()) - .map(PathBuf::from); - resolved_path - }) - }; - self.toggle_modal(window, cx, |window, cx| { - SecurityModal::new(worktree_store, remote_host, home_dir_task, window, cx) - }); + self.check_worktree_trust_prompt(window, cx); + } + } + + pub fn inherit_restricted_worktrees( + &mut self, + source_workspace: &Entity, + window: &mut Window, + cx: &mut Context, + ) -> Task<()> { + if source_workspace.entity_id() == cx.entity_id() { + return Task::ready(()); + } + let Some((source_paths, source_connection_identity)) = + source_workspace.read(cx).restricted_worktree_paths(cx) + else { + return Task::ready(()); + }; + let Some((restricted_paths, connection_identity)) = self.restricted_worktree_paths(cx) + else { + return Task::ready(()); + }; + + let db = WorkspaceDb::global(cx); + cx.spawn_in(window, async move |workspace, cx| { + let source_has_undecided_worktrees = db + .has_undecided_restricted_worktrees(source_paths, source_connection_identity) + .await + .log_err() + .unwrap_or(true); + if source_has_undecided_worktrees { + return; } + db.keep_worktrees_restricted(restricted_paths, connection_identity); + workspace + .update(cx, |workspace, cx| { + workspace.worktree_trust_prompt_check = None; + if let Some(security_modal) = workspace.active_modal::(cx) { + security_modal.update(cx, |security_modal, cx| { + security_modal.dismiss_inherited_restriction(cx); + }); + } + }) + .ok(); + }) + } + + fn restricted_worktree_paths( + &self, + cx: &App, + ) -> Option<(Vec>, Option>)> { + let trusted_worktrees = TrustedWorktrees::try_get_global(cx)?; + let project = self.project().read(cx); + let restricted_paths = trusted_worktrees + .read(cx) + .restricted_worktrees(&project.worktree_store(), cx) + .into_iter() + .map(|(_, abs_path)| abs_path) + .collect::>(); + if restricted_paths.is_empty() { + return None; + } + let connection_identity = project + .remote_connection_identity(cx) + .map(RemoteConnectionIdentity::into_owned); + Some((restricted_paths, connection_identity)) + } + + fn check_worktree_trust_prompt(&mut self, window: &mut Window, cx: &mut Context) { + let Some((restricted_paths, connection_identity)) = self.restricted_worktree_paths(cx) + else { + return; + }; + + let db = WorkspaceDb::global(cx); + self.worktree_trust_prompt_check = Some(cx.spawn_in(window, async move |workspace, cx| { + let has_undecided_worktrees = db + .has_undecided_restricted_worktrees(restricted_paths, connection_identity) + .await + .log_err() + .unwrap_or(true); + if has_undecided_worktrees { + workspace + .update_in(cx, |workspace, window, cx| { + if workspace.active_modal::(cx).is_none() { + workspace.open_worktree_trust_security_modal(window, cx); + } + }) + .ok(); + } + })); + } + + fn open_worktree_trust_security_modal(&mut self, window: &mut Window, cx: &mut Context) { + let has_restricted_worktrees = TrustedWorktrees::has_restricted_worktrees( + &self.project().read(cx).worktree_store(), + cx, + ); + if has_restricted_worktrees { + let project = self.project().read(cx); + let remote_host = project + .remote_connection_identity(cx) + .map(RemoteConnectionIdentity::into_owned); + let worktree_store = project.worktree_store().downgrade(); + let home_dir_task = if project.is_local() { + Task::ready(std::env::home_dir()) + } else { + let resolve_task = project.resolve_abs_path("~", cx); + cx.spawn(async |_, _| { + let resolved_path = resolve_task + .await + .and_then(|path| path.into_abs_path()) + .map(PathBuf::from); + resolved_path + }) + }; + self.toggle_modal(window, cx, |window, cx| { + SecurityModal::new(worktree_store, remote_host, home_dir_task, window, cx) + }); } } } @@ -9612,12 +9831,38 @@ fn window_bounds_env_override() -> Option> { }) } +struct StopRestoringOnDrop { + restoring_workspace: Rc>, + restoring_from: Rc>>, +} + +impl Drop for StopRestoringOnDrop { + fn drop(&mut self) { + self.restoring_workspace.set(false); + self.restoring_from.borrow_mut().take(); + } +} + fn open_items( + workspace: &mut Workspace, serialized_workspace: Option, mut project_paths_to_open: Vec<(PathBuf, Option)>, window: &mut Window, cx: &mut Context, ) -> impl 'static + Future>>>>> + use<> { + let restoring = serialized_workspace + .as_ref() + .filter(|_| workspace.keeps_saved_state_while_restoring) + .map(|serialized_workspace| { + workspace.restoring_workspace.set(true); + workspace + .restoring_from + .replace(Some(serialized_workspace.clone())); + StopRestoringOnDrop { + restoring_workspace: workspace.restoring_workspace.clone(), + restoring_from: workspace.restoring_from.clone(), + } + }); let restored_items = serialized_workspace.map(|serialized_workspace| { Workspace::load_workspace( serialized_workspace, @@ -9632,6 +9877,7 @@ fn open_items( }); cx.spawn_in(window, async move |workspace, cx| { + let _restoring = restoring; let mut opened_items = Vec::with_capacity(project_paths_to_open.len()); if let Some(restored_items) = restored_items { @@ -10012,6 +10258,7 @@ impl Render for Workspace { .child(item), ) }) + .children(self.window_tabs_item.clone()) .on_modifiers_changed(move |_, _, cx| { for &id in ¬ification_entities { cx.notify(id); @@ -10608,26 +10855,9 @@ pub async fn restore_multiworkspace( state, } = multi_workspace; - let workspace_result = if active_workspace.paths.is_empty() { - cx.update(|cx| { - open_workspace_by_id(active_workspace.workspace_id, app_state.clone(), None, cx) - }) - .await - } else { - cx.update(|cx| { - Workspace::new_local( - active_workspace.paths.paths().to_vec(), - app_state.clone(), - None, - None, - None, - OpenMode::Add, - cx, - ) - }) - .await - .map(|result| result.window) - }; + let workspace_result = cx + .update(|cx| open_saved_workspace(&active_workspace, app_state.clone(), false, cx)) + .await; let window_handle = match workspace_result { Ok(handle) => { @@ -10685,6 +10915,44 @@ pub async fn restore_multiworkspace( Ok(window_handle) } +pub fn open_saved_workspace( + saved: &SessionWorkspace, + app_state: Arc, + keeps_saved_state_while_restoring: bool, + cx: &mut App, +) -> impl Future>> + use<> { + if saved.paths.is_empty() { + open_workspace_by_id( + saved.workspace_id, + app_state, + None, + keeps_saved_state_while_restoring, + cx, + ) + .left_future() + } else { + let init = keeps_saved_state_while_restoring.then(|| { + Box::new( + |workspace: &mut Workspace, _: &mut Window, _: &mut Context| { + workspace.keeps_saved_state_while_restoring = true; + }, + ) + as Box) + Send> + }); + Workspace::new_local( + saved.paths.paths().to_vec(), + app_state, + None, + None, + init, + OpenMode::Add, + cx, + ) + .map(|result| result.map(|result| result.window)) + .right_future() + } +} + pub async fn apply_restored_multiworkspace_state( window_handle: WindowHandle, state: &MultiWorkspaceState, @@ -10757,7 +11025,7 @@ pub async fn apply_restored_multiworkspace_state( } } -fn restore_native_window_state( +pub fn restore_native_window_state( window_handle: WindowHandle, workspace_id: WorkspaceId, cx: &mut AsyncApp, @@ -11293,8 +11561,29 @@ fn preferred_workspace_target( } } +/// `ssh://` URL paths arrive unconverted, because each remote has its own path style. Every +/// candidate converts its own copy, so the caller's paths reach a fresh connection unchanged. +fn paths_for_candidate<'a>( + abs_paths: &'a [impl AsRef], + host: &ProjectHost<'_>, + path_style: PathStyle, +) -> Vec<&'a Path> { + abs_paths + .iter() + .map(|path| { + let path = path.as_ref(); + match (host, path.to_str()) { + (ProjectHost::Remote(_), Some(url_path)) => { + Path::new(util::paths::url_path_to_path(url_path, path_style)) + } + _ => path, + } + }) + .collect() +} + pub fn find_existing_workspace( - abs_paths: &[PathBuf], + abs_paths: &[impl AsRef], open_options: &OpenOptions, host: &ProjectHost<'_>, cx: &mut AsyncApp, @@ -11324,16 +11613,17 @@ pub fn find_existing_workspace( continue; } + let paths = paths_for_candidate(abs_paths, host, project.path_style(cx)); let visibility = match open_options.workspace_matching { WorkspaceMatching::None => None, WorkspaceMatching::MatchExact => { - project.visibility_for_paths(abs_paths, true, cx) + project.visibility_for_paths(&paths, true, cx) } WorkspaceMatching::MatchSubpaths => { - project.visibility_for_subpaths(abs_paths, cx) + project.visibility_for_subpaths(&paths, cx) } WorkspaceMatching::MatchSubdirectory => { - project.visibility_for_paths(abs_paths, false, cx) + project.visibility_for_paths(&paths, false, cx) } }; @@ -11361,8 +11651,9 @@ pub fn find_existing_workspace( let workspace = target.workspace.read(cx); let project = workspace.project.read(cx); let path_style = workspace.path_style(cx); + let paths = paths_for_candidate(abs_paths, host, path_style); - !abs_paths.iter().any(|path| { + !paths.iter().any(|path| { let path = util::paths::SanitizedPath::new(path); project @@ -11463,6 +11754,7 @@ pub fn open_workspace_by_id( workspace_id: WorkspaceId, app_state: Arc, requesting_window: Option>, + keeps_saved_state_while_restoring: bool, cx: &mut App, ) -> Task>> { let project_handle = Project::local( @@ -11557,8 +11849,15 @@ pub fn open_workspace_by_id( // Restore items from the serialized workspace window .update(cx, |_, window, cx| { - workspace.update(cx, |_workspace, cx| { - open_items(Some(serialized_workspace), Vec::new(), window, cx) + workspace.update(cx, |workspace, cx| { + workspace.keeps_saved_state_while_restoring = keeps_saved_state_while_restoring; + open_items( + workspace, + Some(serialized_workspace), + Vec::new(), + window, + cx, + ) }) })? .await?; @@ -11995,8 +12294,14 @@ async fn open_remote_project_inner( let items = window .update(cx, |_, window, cx| { window.activate_window(); - workspace.update(cx, |_workspace, cx| { - open_items(serialized_workspace, project_paths_to_open, window, cx) + workspace.update(cx, |workspace, cx| { + open_items( + workspace, + serialized_workspace, + project_paths_to_open, + window, + cx, + ) }) })? .await?; @@ -12352,6 +12657,25 @@ pub fn client_side_decorations( element: impl IntoElement, window: &mut Window, cx: &mut App, +) -> Stateful

{ + client_side_decorations_with_rounded_corners( + element, + Corners { + top_left: true, + top_right: true, + bottom_right: true, + bottom_left: true, + }, + window, + cx, + ) +} + +pub(crate) fn client_side_decorations_with_rounded_corners( + element: impl IntoElement, + rounded_corners: Corners, + window: &mut Window, + cx: &mut App, ) -> Stateful
{ let decorations = window.window_decorations(); let is_resizable = window.is_resizable(); @@ -12359,23 +12683,24 @@ pub fn client_side_decorations( Decorations::Server => Tiling::default(), Decorations::Client { tiling } => tiling, }; + let radius = |rounded| { + if rounded { + theme::CLIENT_SIDE_DECORATION_ROUNDING + } else { + px(0.0) + } + }; + let corner_radii = Corners { + top_left: radius(rounded_corners.top_left && !tiling.top && !tiling.left), + top_right: radius(rounded_corners.top_right && !tiling.top && !tiling.right), + bottom_left: radius(rounded_corners.bottom_left && !tiling.bottom && !tiling.left), + bottom_right: radius(rounded_corners.bottom_right && !tiling.bottom && !tiling.right), + }; match decorations { Decorations::Client { .. } => { window.set_client_inset(theme::CLIENT_SIDE_DECORATION_SHADOW); - let radius = |rounded| { - if rounded { - theme::CLIENT_SIDE_DECORATION_ROUNDING - } else { - px(0.0) - } - }; - window.set_client_corner_radii(Corners { - top_left: radius(!tiling.top && !tiling.left), - top_right: radius(!tiling.top && !tiling.right), - bottom_left: radius(!tiling.bottom && !tiling.left), - bottom_right: radius(!tiling.bottom && !tiling.right), - }); + window.set_client_corner_radii(corner_radii); } Decorations::Server => { window.set_client_inset(px(0.0)); @@ -12391,8 +12716,7 @@ pub fn client_side_decorations( .bg(transparent_black()) .map(|div| match decorations { Decorations::Server => div, - Decorations::Client { .. } => div - .rounded_client_corners(tiling) + Decorations::Client { .. } => with_corner_radii(div, corner_radii) .when(!tiling.top, |div| { div.pt(theme::CLIENT_SIDE_DECORATION_SHADOW) }) @@ -12447,9 +12771,8 @@ pub fn client_side_decorations( .cursor(CursorStyle::Arrow) .map(|div| match decorations { Decorations::Server => div, - Decorations::Client { .. } => div + Decorations::Client { .. } => with_corner_radii(div, corner_radii) .border_color(cx.theme().colors().border) - .rounded_client_corners(tiling) .when(!tiling.top, |div| { div.border_t(theme::CLIENT_SIDE_DECORATION_BORDER) }) @@ -12530,6 +12853,14 @@ pub fn client_side_decorations( }) } +fn with_corner_radii(element: E, corner_radii: Corners) -> E { + element + .rounded_tl(corner_radii.top_left) + .rounded_tr(corner_radii.top_right) + .rounded_bl(corner_radii.bottom_left) + .rounded_br(corner_radii.bottom_right) +} + fn resize_edge( pos: Point, shadow_size: Pixels, @@ -13048,6 +13379,74 @@ mod tests { assert!(!noise.branch); } + #[gpui::test] + async fn test_clearing_title_bar_restores_editor_focus(cx: &mut TestAppContext) { + init_test(cx); + + let fs = FakeFs::new(cx.executor()); + let project = Project::test(fs, [], cx).await; + let (workspace, cx) = + cx.add_window_view(|window, cx| Workspace::test_new(project, window, cx)); + let title_bar = cx.new(|cx| TestItem::new(cx)); + workspace.update_in(cx, |workspace, window, cx| { + workspace.set_titlebar_item(title_bar.clone().into(), window, cx); + }); + cx.run_until_parked(); + + workspace.update_in(cx, |workspace, window, cx| { + window.focus(&workspace.titlebar_focus_handle, cx); + assert!(workspace.titlebar_focus_handle.contains_focused(window, cx)); + + workspace.clear_titlebar_item(window, cx); + assert!(workspace.titlebar_item().is_none()); + assert!(workspace.active_pane.focus_handle(cx).is_focused(window)); + + workspace.clear_titlebar_item(window, cx); + assert!(workspace.active_pane.focus_handle(cx).is_focused(window)); + }); + + let panel = workspace.update_in(cx, |workspace, window, cx| { + workspace.set_titlebar_item(title_bar.into(), window, cx); + let panel = + cx.new(|cx| TestPanel::new_with_activation_child(DockPosition::Right, 100, cx)); + workspace.add_panel(panel.clone(), window, cx); + workspace.toggle_dock(DockPosition::Right, window, cx); + panel + }); + cx.run_until_parked(); + panel.update(cx, |_, cx| cx.emit(PanelEvent::ZoomIn)); + cx.run_until_parked(); + + workspace.update_in(cx, |workspace, window, cx| { + window.focus(&workspace.titlebar_focus_handle, cx); + }); + cx.run_until_parked(); + + workspace.update_in(cx, |workspace, window, cx| { + assert_eq!(workspace.zoomed_position, Some(DockPosition::Right)); + workspace.clear_titlebar_item(window, cx); + }); + cx.run_until_parked(); + workspace.update(cx, |_, cx| cx.notify()); + cx.run_until_parked(); + + workspace.update_in(cx, |workspace, window, cx| { + assert!(workspace.titlebar_item().is_none()); + assert!(workspace.right_dock().read(cx).is_open()); + assert_eq!(workspace.zoomed, Some(panel.to_any().downgrade())); + assert_eq!(workspace.zoomed_position, Some(DockPosition::Right)); + assert!( + panel + .read(cx) + .activation_focus_handle + .as_ref() + .unwrap() + .is_focused(window) + ); + assert!(panel.read(cx).focus_handle(cx).contains_focused(window, cx)); + }); + } + #[gpui::test] async fn test_tab_disambiguation(cx: &mut TestAppContext) { init_test(cx); diff --git a/crates/zed/Cargo.toml b/crates/zed/Cargo.toml index 59c40094786..839f7299d54 100644 --- a/crates/zed/Cargo.toml +++ b/crates/zed/Cargo.toml @@ -2,7 +2,7 @@ description = "The fast, collaborative code editor." edition.workspace = true name = "zed" -version = "1.29.0" +version = "1.30.0" publish.workspace = true license = "GPL-3.0-or-later" authors = ["Zed Team "] diff --git a/crates/zed/src/main.rs b/crates/zed/src/main.rs index 9d4a63a3958..1390452c1bd 100644 --- a/crates/zed/src/main.rs +++ b/crates/zed/src/main.rs @@ -27,11 +27,16 @@ use db::kvp::{GlobalKeyValueStore, KeyValueStore}; use editor::Editor; use extension::ExtensionHostProxy; use fs::{Fs, RealFs}; -use futures::{FutureExt, StreamExt, channel::oneshot, future}; +use futures::{ + FutureExt, StreamExt, + channel::{mpsc, oneshot}, + future::{self, FusedFuture}, +}; use git::GitHostingProviderRegistry; use git_ui::clone::clone_and_open; use gpui::{ - App, AppContext, Application, AsyncApp, QuitMode, Task, TaskExt, UpdateGlobal as _, block_on, + App, AppContext, Application, AsyncApp, EntityId, QuitMode, Task, TaskExt, UpdateGlobal as _, + WindowHandle, block_on, }; use gpui_platform; @@ -46,28 +51,31 @@ use reqwest_client::ReqwestClient; use assets::Assets; use node_runtime::{NodeBinaryOptions, NodeRuntime}; use parking_lot::Mutex; -use project::{project_settings::ProjectSettings, trusted_worktrees}; +use project::{Project, ProjectGroupKey, project_settings::ProjectSettings, trusted_worktrees}; use recent_projects::{RemoteSettings, open_remote_project}; use release_channel::{AppCommitSha, AppVersion, ReleaseChannel}; use session::{AppSession, Session}; use settings::{BaseKeymap, Settings, SettingsStore, watch_config_file}; use smol::future::poll_once; use std::{ - cell::RefCell, + cell::{Cell, RefCell}, env, io::{self, IsTerminal}, path::{Path, PathBuf}, process, rc::Rc, sync::{Arc, LazyLock, OnceLock}, - time::Instant, + time::{Duration, Instant}, }; use theme::{ActiveTheme, GlobalTheme, ThemeRegistry}; use theme_settings::load_user_theme; -use util::{ResultExt, maybe}; +use util::{ + ResultExt, maybe, + paths::{PathStyle, SanitizedPath}, +}; use uuid::Uuid; use workspace::{ - AppState, MultiWorkspace, SerializedWorkspaceLocation, SessionWorkspace, Toast, + AppState, MultiWorkspace, PathList, SerializedWorkspaceLocation, SessionWorkspace, Toast, WorkspaceSettings, WorkspaceStore, notifications::{NotificationId, NotifyResultExt}, restore_multiworkspace, @@ -75,7 +83,8 @@ use workspace::{ use zed::{ OpenListener, OpenRequest, RawOpenRequest, app_menus, build_window_options, derive_paths_with_position, edit_prediction_registry, handle_cli_connection, - handle_keymap_file_changes, initialize_workspace, open_paths_with_positions, + handle_cli_request, handle_keymap_file_changes, initialize_workspace, + open_paths_with_positions, }; use crate::zed::{CrashHandler, OpenRequestKind, eager_load_active_theme_and_icon_theme}; @@ -312,7 +321,7 @@ fn main() { app_version, app_commit_sha, *release_channel::RELEASE_CHANNEL, - client::telemetry::os_name(), + client::telemetry::guessed_os_name(), client::telemetry::os_version(), ); println!("Zed System Specs (from CLI):\n{}", system_specs); @@ -926,11 +935,14 @@ fn main() { ) }; - let restore_task = match open_rx + let initial_request = open_rx .try_recv() .ok() - .and_then(|request| OpenRequest::parse(request, cx).log_err()) - { + .and_then(|request| OpenRequest::parse(request, cx).log_err()); + let runs_full_restore = initial_request + .as_ref() + .is_none_or(|request| request.is_focus_app_only()); + let restore_task = match initial_request { Some(request) if request.is_focus_app_only() => cx.spawn({ let app_state = app_state.clone(); async move |cx| { @@ -940,8 +952,8 @@ fn main() { } }), Some(request) => { - handle_open_request(request, app_state.clone(), cx); - Task::ready(()) + let restore_wait = cx.background_executor().timer(STARTUP_RESTORE_WAIT); + open_startup_request(request, app_state.clone(), restore_wait, cx) } None => cx.spawn({ let app_state = app_state.clone(); @@ -956,7 +968,7 @@ fn main() { let (first_window_tx, first_window_rx) = oneshot::channel::<()>(); let first_window_tx = Rc::new(RefCell::new(Some(first_window_tx))); let _first_window_subscription = cx.observe_new::(move |_, _, _| { - if let Some(tx) = first_window_tx.borrow_mut().take() { + if runs_full_restore && let Some(tx) = first_window_tx.borrow_mut().take() { tx.send(()).ok(); } }); @@ -1005,6 +1017,485 @@ fn main() { }); } +const STARTUP_RESTORE_WAIT: Duration = Duration::from_secs(5); + +pub(crate) fn open_startup_request( + request: OpenRequest, + app_state: Arc, + restore_wait: impl Future + 'static, + cx: &mut App, +) -> Task<()> { + let is_cli_connection = matches!(request.kind, Some(OpenRequestKind::CliConnection(_))); + if !is_cli_connection && RequestedPaths::of_request(&request).is_none() { + handle_open_request(request, app_state, cx); + return Task::ready(()); + } + + cx.spawn(async move |cx| { + let restore_wait = restore_wait.fuse(); + futures::pin_mut!(restore_wait); + let Some(mut request) = + StartupRequest::read(request, &mut restore_wait, &app_state, cx).await + else { + return; + }; + let Some(requested) = cx.update(|cx| request.requested_paths(cx)) else { + request.open(app_state, cx); + return; + }; + + let mut requested = cx + .spawn({ + let fs = app_state.fs.clone(); + let db = cx.update(|cx| workspace::WorkspaceDb::global(cx)); + async move |_| RequestedProject::new(fs.as_ref(), &db, &requested).await + }) + .fuse(); + let requested = futures::select_biased! { + requested = requested => Some(requested), + () = restore_wait => None, + }; + let Some(requested) = requested else { + request.open(app_state, cx); + return; + }; + let joins_restored_windows = requested.joins_restored_windows; + let restored_in_time = + restore_local_windows(&app_state, requested, &mut restore_wait, cx).await; + if !joins_restored_windows || !restored_in_time { + request.open_in_new_window(); + } + request.open(app_state, cx); + }) +} + +enum StartupRequest { + Cli { + request: cli::CliRequest, + requests: mpsc::UnboundedReceiver, + responses: Box, + }, + Other(OpenRequest), +} + +impl StartupRequest { + async fn read( + request: OpenRequest, + mut restore_wait: &mut (impl FusedFuture + Unpin), + app_state: &Arc, + cx: &mut AsyncApp, + ) -> Option { + match request.kind { + Some(OpenRequestKind::CliConnection((mut requests, responses))) => { + let request = futures::select_biased! { + request = requests.next() => Some(request), + () = restore_wait => None, + }; + let Some(request) = request else { + cx.spawn({ + let app_state = app_state.clone(); + async move |cx| { + handle_cli_connection((requests, responses), app_state, cx).await + } + }) + .detach(); + return None; + }; + Some(Self::Cli { + request: request?, + requests, + responses, + }) + } + _ => Some(Self::Other(request)), + } + } + + fn requested_paths(&self, cx: &App) -> Option { + match self { + Self::Cli { request, .. } => RequestedPaths::of_cli_request(request, cx), + Self::Other(request) => RequestedPaths::of_request(request), + } + } + + fn open_in_new_window(&mut self) { + match self { + Self::Cli { + request: cli::CliRequest::Open { open_behavior, .. }, + .. + } => *open_behavior = cli::OpenBehavior::AlwaysNew, + Self::Cli { .. } => {} + Self::Other(request) => request.open_behavior = Some(cli::OpenBehavior::AlwaysNew), + } + } + + fn open(self, app_state: Arc, cx: &mut AsyncApp) { + match self { + Self::Cli { + request, + requests, + responses, + } => cx + .spawn(async move |cx| { + handle_cli_request(request, requests, responses, app_state, cx).await + }) + .detach(), + Self::Other(request) => cx.update(|cx| handle_open_request(request, app_state, cx)), + } + } +} + +struct RequestedPaths { + paths: Vec, + reuses_windows: bool, +} + +impl RequestedPaths { + fn of_request(request: &OpenRequest) -> Option { + let opens_local_paths = request.kind.is_none() + && request.remote_connection.is_none() + && request.open_channel_notes.is_empty() + && request.join_channel.is_none() + && (!request.open_paths.is_empty() || !request.diff_paths.is_empty()); + opens_local_paths.then(|| Self { + paths: request.open_paths.clone(), + reuses_windows: !request.open_paths.is_empty() + && request.diff_paths.is_empty() + && !request.dev_container + && matches!( + request.open_behavior, + None | Some(cli::OpenBehavior::Default | cli::OpenBehavior::ExistingWindow) + ), + }) + } + + fn of_cli_request(request: &cli::CliRequest, cx: &App) -> Option { + let cli::CliRequest::Open { + urls, + paths, + diff_paths, + diff_all, + wait, + wsl, + open_behavior, + dev_container, + env, + cwd, + .. + } = request + else { + return None; + }; + if *wait { + return None; + } + if !urls.is_empty() { + let request = OpenRequest::parse( + RawOpenRequest { + urls: urls.clone(), + diff_paths: diff_paths.clone(), + diff_all: *diff_all, + dev_container: *dev_container, + wsl: wsl.clone(), + open_behavior: Some(*open_behavior), + }, + cx, + ) + .ok()?; + return Self::of_request(&request); + } + if paths.is_empty() + && diff_paths.is_empty() + && *open_behavior != cli::OpenBehavior::AlwaysNew + { + return None; + } + let mut requested = paths.clone(); + if paths.is_empty() + && !diff_paths.is_empty() + && let Some(cwd) = cwd + { + requested.push(cwd.to_string_lossy().into_owned()); + } + Some(Self { + paths: requested, + reuses_windows: !paths.is_empty() + && diff_paths.is_empty() + && !dev_container + && env.is_none() + && matches!( + open_behavior, + cli::OpenBehavior::Default | cli::OpenBehavior::ExistingWindow + ), + }) + } +} + +struct RequestedProject { + paths: Vec, + roots: Vec, + repositories: PathList, + joins_restored_windows: bool, +} + +impl RequestedProject { + async fn new(fs: &dyn Fs, db: &workspace::WorkspaceDb, requested: &RequestedPaths) -> Self { + let paths = derive_paths_with_position(fs, &requested.paths) + .await + .into_iter() + .map(|path| path.path) + .collect::>(); + let mut joins_restored_windows = + requested.reuses_windows && !db.has_workspace_for_roots(&paths); + for path in &paths { + if fs.is_dir(path).await { + joins_restored_windows = false; + } + } + let paths = resolved_paths(fs, &paths).await; + let roots = outermost_paths(&paths); + let repositories = PathList::new(&repository_paths(fs, &roots).await); + Self { + paths, + roots, + repositories, + joins_restored_windows, + } + } + + async fn opens(&self, fs: &dyn Fs, roots: &[PathBuf]) -> bool { + if roots.is_empty() { + return false; + } + let roots = resolved_paths(fs, roots).await; + let outermost_roots = outermost_paths(&roots); + if outermost_roots.iter().all(|root| self.paths.contains(root)) + && self.roots.iter().all(|path| outermost_roots.contains(path)) + { + return true; + } + PathList::new(&repository_paths(fs, &roots).await) == self.repositories + } + + async fn window_to_restore( + &self, + fs: &dyn Fs, + mut multi_workspace: workspace::SerializedMultiWorkspace, + ) -> Option { + let saved = &multi_workspace.active_workspace; + if saved.location != SerializedWorkspaceLocation::Local { + return None; + } + if self.opens(fs, saved.paths.paths()).await { + return None; + } + let mut project_groups = Vec::new(); + for group in std::mem::take(&mut multi_workspace.state.project_groups) { + let key = ProjectGroupKey::from(group.clone()); + if key.host().is_some() || !self.opens(fs, key.path_list().paths()).await { + project_groups.push(group); + } + } + multi_workspace.state.project_groups = project_groups; + Some(multi_workspace) + } +} + +async fn restore_local_windows( + app_state: &Arc, + requested: RequestedProject, + mut restore_wait: &mut (impl FusedFuture + Unpin), + cx: &mut AsyncApp, +) -> bool { + let fs = app_state.fs.clone(); + let mut windows_to_restore = cx + .spawn({ + let app_state = app_state.clone(); + let fs = fs.clone(); + async move |cx| { + let mut multi_workspaces = restorable_workspaces(cx, &app_state).await?; + if requested.joins_restored_windows { + multi_workspaces.sort_by_key(|multi_workspace| { + let roots = multi_workspace.active_workspace.paths.paths(); + requested + .paths + .iter() + .any(|path| roots.iter().any(|root| path.starts_with(root))) + }); + } + let mut windows_to_restore = Vec::new(); + for multi_workspace in multi_workspaces { + windows_to_restore.extend( + requested + .window_to_restore(fs.as_ref(), multi_workspace) + .await, + ); + } + Some(windows_to_restore) + } + }) + .fuse(); + let windows_to_restore = futures::select_biased! { + windows_to_restore = windows_to_restore => windows_to_restore, + () = restore_wait => return false, + }; + + let mut error_count = 0; + let mut restored_in_time = true; + for multi_workspace in windows_to_restore.into_iter().flatten() { + let saved = multi_workspace.active_workspace; + let state = multi_workspace.state; + let restored_project = Rc::new(Cell::new(None)); + let project_created = cx.update(|cx| { + cx.observe_new::({ + let restored_project = restored_project.clone(); + move |_, _, cx| { + if restored_project.get().is_none() { + restored_project.set(Some(cx.entity_id())); + } + } + }) + }); + let restoring = + cx.update(|cx| workspace::open_saved_workspace(&saved, app_state.clone(), true, cx)); + drop(project_created); + let mut restoring = restoring + .then({ + let mut cx = cx.clone(); + let fs = fs.clone(); + let workspace_id = saved.workspace_id; + async move |window| { + let window = window?; + workspace::restore_native_window_state(window, workspace_id, &mut cx); + workspace::apply_restored_multiworkspace_state(window, &state, fs, &mut cx) + .await; + anyhow::Ok(window) + } + }) + .boxed_local() + .fuse(); + let restored = futures::select_biased! { + restored = restoring => Some(restored), + () = restore_wait => None, + }; + match restored { + Some(Ok(window)) => { + window + .update(cx, |_, window, _| window.activate_window()) + .log_err(); + } + Some(Err(error)) => { + log::error!("Failed to restore workspace: {error:#}"); + error_count += 1; + } + None => { + let window = restored_project + .get() + .and_then(|project| cx.update(|cx| window_of_project(project, cx))); + if let Some(window) = window { + window + .update(cx, |_, window, _| window.activate_window()) + .log_err(); + cx.spawn(async move |_| { + restoring.await.log_err(); + }) + .detach(); + } + restored_in_time = false; + break; + } + } + } + if error_count > 0 { + let message = restore_errors_message(error_count); + cx.update(|cx| show_toast_in_active_workspace(&message, cx)); + } + restored_in_time +} + +fn window_of_project(project: EntityId, cx: &App) -> Option> { + cx.windows() + .into_iter() + .filter_map(|window| window.downcast::()) + .find(|window| { + window.read(cx).is_ok_and(|multi_workspace| { + multi_workspace + .workspaces() + .any(|workspace| workspace.read(cx).project().entity_id() == project) + }) + }) +} + +async fn resolved_paths(fs: &dyn Fs, paths: &[PathBuf]) -> Vec { + let mut resolved = Vec::with_capacity(paths.len()); + for path in paths { + let path = fs.canonicalize(path).await.unwrap_or_else(|_| path.clone()); + resolved.push( + SanitizedPath::from_arc(Arc::from(path.as_path())) + .as_path() + .to_path_buf(), + ); + } + resolved +} + +fn outermost_paths(paths: &[PathBuf]) -> Vec { + paths + .iter() + .filter(|path| { + !paths + .iter() + .any(|other| other != *path && path.starts_with(other)) + }) + .cloned() + .collect() +} + +async fn repository_paths(fs: &dyn Fs, paths: &[PathBuf]) -> Vec { + let mut repositories = Vec::with_capacity(paths.len()); + for path in paths { + repositories.push( + match project::discover_root_repo_common_dir(path, fs).await { + Some(common_dir) if !project::is_submodule_git_dir(&common_dir) => { + project::repo_identity_path(&common_dir, PathStyle::local()).to_path_buf() + } + _ => path.clone(), + }, + ); + } + repositories +} + +fn restore_errors_message(error_count: usize) -> String { + if error_count == 1 { + "Failed to restore 1 workspace. Check logs for details.".to_string() + } else { + format!( + "Failed to restore {} workspaces. Check logs for details.", + error_count + ) + } +} + +fn show_toast_in_active_workspace(message: &str, cx: &mut App) -> bool { + if let Some(window) = cx.active_window() + && let Some(multi_workspace) = window.downcast::() + { + multi_workspace + .update(cx, |multi_workspace, _, cx| { + multi_workspace.workspace().update(cx, |workspace, cx| { + workspace.show_toast( + Toast::new(NotificationId::unique::<()>(), message.to_string()), + cx, + ) + }); + }) + .ok(); + return true; + } + false +} + fn handle_open_request(request: OpenRequest, app_state: Arc, cx: &mut App) { if let Some(kind) = request.kind { match kind { @@ -1485,34 +1976,10 @@ pub(crate) async fn restore_or_create_workspace( } if error_count > 0 { - let message = if error_count == 1 { - "Failed to restore 1 workspace. Check logs for details.".to_string() - } else { - format!( - "Failed to restore {} workspaces. Check logs for details.", - error_count - ) - }; + let message = restore_errors_message(error_count); // Try to find an active workspace to show the toast - let toast_shown = cx.update(|cx| { - if let Some(window) = cx.active_window() - && let Some(multi_workspace) = window.downcast::() - { - multi_workspace - .update(cx, |multi_workspace, _, cx| { - multi_workspace.workspace().update(cx, |workspace, cx| { - workspace.show_toast( - Toast::new(NotificationId::unique::<()>(), message.clone()), - cx, - ) - }); - }) - .ok(); - return true; - } - false - }); + let toast_shown = cx.update(|cx| show_toast_in_active_workspace(&message, cx)); // If we couldn't show a toast (no windows opened successfully), // open a fallback empty workspace and show the error there diff --git a/crates/zed/src/watcher_debug.rs b/crates/zed/src/watcher_debug.rs index 4d432ea51d4..7077a729cec 100644 --- a/crates/zed/src/watcher_debug.rs +++ b/crates/zed/src/watcher_debug.rs @@ -42,10 +42,16 @@ pub fn init(app_state: Arc, cx: &mut App) { } let app_state = app_state.clone(); + let display_id = cx.active_display().map(|display| display.id()); cx.open_window( WindowOptions { titlebar: Some(TitlebarOptions::default()), - window_bounds: Some(WindowBounds::centered(size(px(1000.), px(700.)), cx)), + window_bounds: Some(WindowBounds::centered( + display_id, + size(px(1000.), px(700.)), + cx, + )), + display_id, ..Default::default() }, |window, cx| { @@ -401,7 +407,7 @@ impl WatcherDebug { let watcher = recording.snapshot(); let worktree_scan_exclusions = worktree_exclusions(&self.app_state, cx); let zed_version = AppVersion::global(cx).to_string(); - let os_name = client::telemetry::os_name(); + let os_name = client::telemetry::os_name(cx); let directory = std::env::home_dir().unwrap_or_default(); let path = cx.prompt_for_new_path(&directory, Some("filesystem-watcher.json")); let fs = self.app_state.fs.clone(); @@ -889,7 +895,10 @@ mod tests { cx.run_until_parked(); let json: serde_json::Value = serde_json::from_str(&fs.load(&path).await.unwrap()).unwrap(); assert_eq!(json["zed_version"], "1.2.3+dev.test"); - assert_eq!(json["os_name"], client::telemetry::os_name()); + assert_eq!( + json["os_name"], + cx.update(|cx| client::telemetry::os_name(cx)) + ); let os_version = cx .background_executor .spawn(async { client::telemetry::os_version() }) diff --git a/crates/zed/src/zed.rs b/crates/zed/src/zed.rs index 739202e348b..4f6f54711b2 100644 --- a/crates/zed/src/zed.rs +++ b/crates/zed/src/zed.rs @@ -1727,6 +1727,7 @@ fn open_about_window(cx: &mut App) { width: px(440.), height: px(300.), }; + let display_id = cx.active_display().map(|display| display.id()); cx.open_window( WindowOptions { @@ -1735,7 +1736,8 @@ fn open_about_window(cx: &mut App) { appears_transparent: true, traffic_light_position: Some(point(px(12.), px(12.))), }), - window_bounds: Some(WindowBounds::centered(window_size, cx)), + window_bounds: Some(WindowBounds::centered(display_id, window_size, cx)), + display_id, is_resizable: false, is_minimizable: false, kind: WindowKind::Floating, @@ -2911,7 +2913,9 @@ mod tests { use serde_json::json; use settings::{SaturatingBool, SettingsStore, SplicingVec, watch_config_file}; use std::{ + cell::RefCell, path::{Path, PathBuf}, + rc::Rc, sync::Arc, time::Duration, }; @@ -8710,6 +8714,1970 @@ mod tests { }); } + async fn init_startup_test(cx: &mut TestAppContext) -> Arc { + cx.update(|cx| cx.set_global(db::AppDatabase::test_new())); + let app_state = init_test(cx); + cx.update(|cx| db::kvp::KeyValueStore::global(cx)) + .write_kvp(onboarding::FIRST_OPEN.to_owned(), "false".to_owned()) + .await + .unwrap(); + app_state + } + + async fn restart_startup_test_session(app_state: &Arc, cx: &mut TestAppContext) { + use session::Session; + + let session_id = cx.read(|cx| app_state.session.read(cx).id().to_owned()); + for window in cx.windows() { + let window = window.downcast::().unwrap(); + flush_workspace_serialization(&window, cx).await; + VisualTestContext::from_window(window.into(), cx).deactivate_window(); + window + .update(cx, |_, window, _| window.remove_window()) + .unwrap(); + } + cx.run_until_parked(); + assert_eq!(cx.read(|cx| cx.active_window()), None); + cx.update(|cx| { + app_state.session.update(cx, |session, _| { + session.replace_session_for_test(Session::test_with_old_session(session_id)); + }); + }); + } + + async fn add_unsaved_buffer( + window: WindowHandle, + text: &str, + cx: &mut TestAppContext, + ) { + let editor = window + .update(cx, |multi_workspace, window, cx| { + multi_workspace.workspace().update(cx, |workspace, cx| { + Editor::new_in_workspace(workspace, window, cx) + }) + }) + .unwrap() + .await + .unwrap(); + window + .update(cx, |_, window, cx| { + editor.update(cx, |editor, cx| editor.insert(text, window, cx)); + }) + .unwrap(); + cx.run_until_parked(); + } + + async fn save_project_and_other_session(cx: &mut TestAppContext) -> Arc { + let app_state = init_startup_test(cx).await; + app_state + .fs + .as_fake() + .insert_tree( + path!("/"), + json!({ + "other": { "note.txt": "note" }, + "project": { "file.txt": "project file" }, + "new": { "readme.txt": "readme" }, + "outside.txt": "outside", + }), + ) + .await; + open_test_workspace_paths(vec![PathBuf::from(path!("/other"))], app_state.clone(), cx) + .await; + let project_window = open_test_workspace_paths( + vec![PathBuf::from(path!("/project"))], + app_state.clone(), + cx, + ) + .await + .window; + add_unsaved_buffer(project_window, "project draft", cx).await; + restart_startup_test_session(&app_state, cx).await; + app_state + } + + async fn save_session_without_folders(cx: &mut TestAppContext) -> Arc { + let app_state = init_startup_test(cx).await; + app_state + .fs + .as_fake() + .insert_tree(path!("/"), json!({ "outside.txt": "outside" })) + .await; + cx.update(|cx| { + workspace::open_new( + Default::default(), + app_state.clone(), + cx, + |workspace, window, cx| { + Editor::new_file(workspace, &Default::default(), window, cx); + }, + ) + }) + .await + .unwrap(); + let window = cx.windows()[0].downcast::().unwrap(); + window + .update(cx, |multi_workspace, window, cx| { + multi_workspace + .active_item_as::(cx) + .unwrap() + .update(cx, |editor, cx| editor.insert("UNSAVED", window, cx)); + }) + .unwrap(); + cx.run_until_parked(); + restart_startup_test_session(&app_state, cx).await; + app_state + } + + async fn open_on_startup( + request: OpenRequest, + app_state: &Arc, + cx: &mut TestAppContext, + ) { + cx.update(|cx| { + crate::open_startup_request(request, app_state.clone(), futures::future::pending(), cx) + }) + .await; + cx.run_until_parked(); + } + + fn startup_windows(cx: &TestAppContext) -> Vec<(Vec, Vec<(String, bool)>)> { + let mut windows = cx + .windows() + .into_iter() + .map(|window| window_contents(window, cx)) + .collect::>(); + windows.sort(); + windows + } + + fn window_contents( + window: gpui::AnyWindowHandle, + cx: &TestAppContext, + ) -> (Vec, Vec<(String, bool)>) { + window + .downcast::() + .unwrap() + .read_with(cx, |multi_workspace, cx| { + let workspace = multi_workspace.workspace().read(cx); + let roots = workspace + .root_paths(cx) + .iter() + .map(|path| path.to_path_buf()) + .collect(); + let mut items = workspace + .items_of_type::(cx) + .map(|editor| { + let editor = editor.read(cx); + (editor.text(cx), editor.is_dirty(cx)) + }) + .collect::>(); + items.sort(); + (roots, items) + }) + .unwrap() + } + + fn active_window_roots(cx: &TestAppContext) -> Vec { + let active_window = cx.read(|cx| cx.active_window()).unwrap(); + window_contents(active_window, cx).0 + } + + fn cli_environment_of(root: &str, cx: &TestAppContext) -> Option { + cx.windows() + .into_iter() + .filter_map(|window| window.downcast::()) + .find_map(|window| { + window + .read_with(cx, |multi_workspace, cx| { + let workspace = multi_workspace.workspace().read(cx); + (workspace + .root_paths(cx) + .first() + .map(|path| path.to_path_buf()) + == Some(PathBuf::from(root))) + .then(|| { + workspace + .project() + .read(cx) + .environment() + .read(cx) + .inherited_cli_environment() + .and_then(|env| env.get("REVIEW_ENV").cloned()) + }) + }) + .unwrap() + }) + .unwrap() + } + + struct IgnoredCliResponses; + + impl cli::CliResponseSink for IgnoredCliResponses { + fn send(&self, _: cli::CliResponse) -> anyhow::Result<()> { + Ok(()) + } + } + + fn cli_request( + paths: &[&str], + open_behavior: cli::OpenBehavior, + ) -> (OpenRequest, mpsc::UnboundedSender) { + cli_connection(cli_open_request(paths, &[], open_behavior, None)) + } + + fn terminal_cli_request( + paths: &[&str], + open_behavior: cli::OpenBehavior, + ) -> (OpenRequest, mpsc::UnboundedSender) { + cli_connection(cli_open_request( + paths, + &[], + open_behavior, + Some(terminal_environment()), + )) + } + + fn terminal_environment() -> collections::HashMap { + collections::HashMap::from_iter([("REVIEW_ENV".to_owned(), "cli".to_owned())]) + } + + fn cli_open_request( + paths: &[&str], + urls: &[String], + open_behavior: cli::OpenBehavior, + env: Option>, + ) -> cli::CliRequest { + cli::CliRequest::Open { + paths: paths.iter().map(|path| path.to_string()).collect(), + urls: urls.to_vec(), + diff_paths: Vec::new(), + diff_all: false, + wsl: None, + wait: false, + open_behavior, + env, + user_data_dir: None, + dev_container: false, + cwd: None, + } + } + + fn cli_connection( + request: cli::CliRequest, + ) -> (OpenRequest, mpsc::UnboundedSender) { + let (cli_requests, cli_receiver) = mpsc::unbounded(); + cli_requests.unbounded_send(request).unwrap(); + let request = OpenRequest { + kind: Some(OpenRequestKind::CliConnection(( + cli_receiver, + Box::new(IgnoredCliResponses), + ))), + ..OpenRequest::default() + }; + (request, cli_requests) + } + + fn project_window_with(items: &[(&str, bool)]) -> (Vec, Vec<(String, bool)>) { + let mut items = items + .iter() + .map(|(text, dirty)| (text.to_string(), *dirty)) + .collect::>(); + items.sort(); + (vec![PathBuf::from(path!("/project"))], items) + } + + fn other_window() -> (Vec, Vec<(String, bool)>) { + (vec![PathBuf::from(path!("/other"))], Vec::new()) + } + + #[gpui::test] + async fn test_startup_file_request_opens_in_its_restored_project(cx: &mut TestAppContext) { + let app_state = save_project_and_other_session(cx).await; + let (request, _cli) = + cli_request(&[path!("/project/file.txt")], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + other_window(), + project_window_with(&[("project draft", true), ("project file", false)]), + ] + ); + assert_eq!( + active_window_roots(cx), + vec![PathBuf::from(path!("/project"))] + ); + assert_eq!(cli_environment_of(path!("/project"), cx), None); + } + + #[gpui::test] + async fn test_startup_request_for_file_links_with_positions_puts_each_cursor_in_its_file( + cx: &mut TestAppContext, + ) { + let app_state = init_startup_test(cx).await; + app_state + .fs + .as_fake() + .insert_tree( + path!("/project"), + json!({ "a.txt": "a1\na2\na3\n", "b.txt": "b1\nb2\nb3\n" }), + ) + .await; + open_test_workspace_paths( + vec![PathBuf::from(path!("/project"))], + app_state.clone(), + cx, + ) + .await; + restart_startup_test_session(&app_state, cx).await; + + let file_link = |path_with_position: &str| { + format!("file://{}", urlencoding::encode(path_with_position)) + }; + let (request, _cli) = cli_connection(cli_open_request( + &[], + &[ + file_link(&format!("{}:3", path!("/project/b.txt"))), + file_link(&format!("{}:2", path!("/project/a.txt"))), + ], + cli::OpenBehavior::Default, + None, + )); + open_on_startup(request, &app_state, cx).await; + + let windows = cx.windows(); + assert_eq!(windows.len(), 1); + let mut cursor_lines = windows[0] + .downcast::() + .unwrap() + .update(cx, |multi_workspace, _, cx| { + let editors = multi_workspace + .workspace() + .read(cx) + .items_of_type::(cx) + .collect::>(); + editors + .into_iter() + .map(|editor| { + editor.update(cx, |editor, cx| { + let cursor_row = editor + .selections + .newest_adjusted(&editor.display_snapshot(cx)) + .head() + .row; + editor + .text(cx) + .lines() + .nth(cursor_row as usize) + .map(str::to_owned) + }) + }) + .collect::>() + }) + .unwrap(); + cursor_lines.sort(); + assert_eq!( + cursor_lines, + vec![Some("a2".to_owned()), Some("b3".to_owned())] + ); + } + + #[gpui::test] + async fn test_startup_file_link_from_the_cli_opens_in_its_restored_project( + cx: &mut TestAppContext, + ) { + let app_state = save_project_and_other_session(cx).await; + let (request, _cli) = cli_connection(cli_open_request( + &[], + &[project_file_link()], + cli::OpenBehavior::Default, + None, + )); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + other_window(), + project_window_with(&[("project draft", true), ("project file", false)]), + ] + ); + } + + #[gpui::test] + async fn test_startup_file_request_without_the_cli_opens_in_its_restored_project( + cx: &mut TestAppContext, + ) { + let app_state = save_project_and_other_session(cx).await; + let request = OpenRequest { + open_paths: vec![path!("/project/file.txt").to_owned()], + ..OpenRequest::default() + }; + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + other_window(), + project_window_with(&[("project draft", true), ("project file", false)]), + ] + ); + } + + #[gpui::test] + async fn test_startup_file_request_joins_a_restored_window_without_folders( + cx: &mut TestAppContext, + ) { + let app_state = save_session_without_folders(cx).await; + let (request, _cli) = cli_request(&[path!("/outside.txt")], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![( + Vec::new(), + vec![("UNSAVED".to_owned(), true), ("outside".to_owned(), false)] + )] + ); + } + + #[gpui::test] + async fn test_startup_file_request_without_a_saved_session_opens_only_the_file( + cx: &mut TestAppContext, + ) { + let app_state = init_startup_test(cx).await; + app_state + .fs + .as_fake() + .insert_tree(path!("/"), json!({ "outside.txt": "outside" })) + .await; + let (request, _cli) = + terminal_cli_request(&[path!("/outside.txt")], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![( + vec![PathBuf::from(path!("/outside.txt"))], + vec![("outside".to_owned(), false)] + )] + ); + assert_eq!( + cli_environment_of(path!("/outside.txt"), cx), + Some("cli".to_owned()) + ); + } + + #[gpui::test] + async fn test_startup_folder_request_for_a_restored_folder_opens_it_once_with_its_environment( + cx: &mut TestAppContext, + ) { + let app_state = save_project_and_other_session(cx).await; + let (request, _cli) = + terminal_cli_request(&[path!("/project")], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + other_window(), + project_window_with(&[("project draft", true)]), + ] + ); + assert_eq!( + cli_environment_of(path!("/project"), cx), + Some("cli".to_owned()) + ); + assert_eq!(cli_environment_of(path!("/other"), cx), None); + assert_eq!( + active_window_roots(cx), + vec![PathBuf::from(path!("/project"))] + ); + } + + #[gpui::test] + async fn test_startup_new_window_request_for_a_restored_folder_and_a_file_in_it_opens_it_once( + cx: &mut TestAppContext, + ) { + let app_state = save_project_and_other_session(cx).await; + let (request, _cli) = cli_request( + &[path!("/project"), path!("/project/file.txt")], + cli::OpenBehavior::AlwaysNew, + ); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx) + .into_iter() + .map(|(roots, _)| roots) + .collect::>(), + vec![ + vec![PathBuf::from(path!("/other"))], + vec![PathBuf::from(path!("/project"))], + ] + ); + } + + #[gpui::test] + async fn test_startup_folder_request_for_a_new_folder_opens_its_own_window( + cx: &mut TestAppContext, + ) { + let app_state = save_project_and_other_session(cx).await; + let (request, _cli) = + terminal_cli_request(&[path!("/new")], cli::OpenBehavior::ExistingWindow); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + (vec![PathBuf::from(path!("/new"))], Vec::new()), + other_window(), + project_window_with(&[("project draft", true)]), + ] + ); + assert_eq!( + cli_environment_of(path!("/new"), cx), + Some("cli".to_owned()) + ); + assert_eq!(active_window_roots(cx), vec![PathBuf::from(path!("/new"))]); + } + + #[gpui::test] + async fn test_startup_folder_request_without_the_cli_opens_its_own_window( + cx: &mut TestAppContext, + ) { + let app_state = save_project_and_other_session(cx).await; + let request = OpenRequest { + open_paths: vec![path!("/new").to_owned()], + ..OpenRequest::default() + }; + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + (vec![PathBuf::from(path!("/new"))], Vec::new()), + other_window(), + project_window_with(&[("project draft", true)]), + ] + ); + assert_eq!(active_window_roots(cx), vec![PathBuf::from(path!("/new"))]); + } + + #[gpui::test] + async fn test_startup_new_window_request_restores_a_window_without_folders( + cx: &mut TestAppContext, + ) { + let app_state = save_session_without_folders(cx).await; + let (request, _cli) = cli_request(&[], cli::OpenBehavior::AlwaysNew); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + (Vec::new(), vec![(String::new(), false)]), + (Vec::new(), vec![("UNSAVED".to_owned(), true)]), + ] + ); + } + + #[gpui::test] + async fn test_bare_startup_cli_request_restores_the_session_once(cx: &mut TestAppContext) { + let app_state = save_project_and_other_session(cx).await; + let (request, _cli) = cli_request(&[], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + other_window(), + project_window_with(&[("project draft", true)]), + ] + ); + } + + #[gpui::test] + async fn test_startup_link_request_opens_only_its_window(cx: &mut TestAppContext) { + let app_state = save_project_and_other_session(cx).await; + let request = OpenRequest { + kind: Some(OpenRequestKind::GitCommit { + sha: "0123456789abcdef".to_owned(), + }), + open_paths: vec![path!("/new").to_owned()], + ..OpenRequest::default() + }; + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![(vec![PathBuf::from(path!("/new"))], Vec::new())] + ); + } + + async fn save_session_with_a_project_tab(cx: &mut TestAppContext) -> Arc { + let app_state = init_startup_test(cx).await; + let fs = app_state.fs.as_fake(); + fs.insert_tree( + path!("/"), + json!({ + "project": { "file.txt": "project file" }, + "new": { "readme.txt": "readme" }, + "outside.txt": "outside", + }), + ) + .await; + open_test_workspace_paths( + vec![ + PathBuf::from(path!("/project")), + PathBuf::from(path!("/project/file.txt")), + ], + app_state.clone(), + cx, + ) + .await; + restart_startup_test_session(&app_state, cx).await; + app_state + } + + fn run_until_a_window_opens(cx: &mut TestAppContext) { + let mut steps = 0; + while cx.windows().is_empty() { + steps += 1; + assert!(steps < 100_000, "no window was opened"); + if !cx.executor().tick() { + cx.executor().advance_clock(Duration::from_millis(1)); + } + } + } + + #[gpui::test] + async fn test_startup_file_request_opens_after_the_session_is_restored( + cx: &mut TestAppContext, + ) { + let app_state = save_session_with_a_project_tab(cx).await; + let (request, _cli) = cli_request(&[path!("/outside.txt")], cli::OpenBehavior::Default); + let mut ready = cx.update(|cx| { + crate::open_startup_request(request, app_state.clone(), futures::future::pending(), cx) + }); + run_until_a_window_opens(cx); + assert!((&mut ready).now_or_never().is_none()); + assert_eq!( + startup_windows(cx) + .into_iter() + .map(|(roots, _)| roots) + .collect::>(), + vec![vec![PathBuf::from(path!("/project"))]] + ); + + ready.await; + cx.run_until_parked(); + assert_eq!( + startup_windows(cx), + vec![project_window_with(&[ + ("outside", false), + ("project file", false) + ])] + ); + } + + #[gpui::test] + async fn test_startup_folder_request_does_not_join_an_open_window(cx: &mut TestAppContext) { + let app_state = init_startup_test(cx).await; + app_state + .fs + .as_fake() + .insert_tree( + path!("/"), + json!({ "open": { "a.txt": "" }, "new": { "readme.txt": "readme" } }), + ) + .await; + open_test_workspace_paths(vec![PathBuf::from(path!("/open"))], app_state.clone(), cx).await; + let (request, _cli) = cli_request(&[path!("/new")], cli::OpenBehavior::ExistingWindow); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + (vec![PathBuf::from(path!("/new"))], Vec::new()), + (vec![PathBuf::from(path!("/open"))], Vec::new()), + ] + ); + } + + #[gpui::test] + async fn test_startup_new_window_file_request_opens_beside_the_restored_session( + cx: &mut TestAppContext, + ) { + let app_state = save_project_and_other_session(cx).await; + let (request, _cli) = + cli_request(&[path!("/project/file.txt")], cli::OpenBehavior::AlwaysNew); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + other_window(), + project_window_with(&[("project draft", true)]), + ( + vec![PathBuf::from(path!("/project/file.txt"))], + vec![("project file".to_owned(), false)] + ), + ] + ); + assert_eq!( + active_window_roots(cx), + vec![PathBuf::from(path!("/project/file.txt"))] + ); + } + + #[gpui::test] + async fn test_startup_reuse_window_file_request_does_not_replace_a_restored_window( + cx: &mut TestAppContext, + ) { + let app_state = save_project_and_other_session(cx).await; + let (request, _cli) = cli_request(&[path!("/project/file.txt")], cli::OpenBehavior::Reuse); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + other_window(), + project_window_with(&[("project draft", true)]), + ( + vec![PathBuf::from(path!("/project/file.txt"))], + vec![("project file".to_owned(), false)] + ), + ] + ); + } + + #[gpui::test] + async fn test_startup_file_request_reopens_its_own_saved_window_with_its_unsaved_edits( + cx: &mut TestAppContext, + ) { + let app_state = init_startup_test(cx).await; + app_state + .fs + .as_fake() + .insert_tree( + path!("/"), + json!({ + "project": { "file.txt": "project file" }, + "notes.txt": "notes", + }), + ) + .await; + open_test_workspace_paths( + vec![PathBuf::from(path!("/project"))], + app_state.clone(), + cx, + ) + .await; + let notes_window = open_test_workspace_paths( + vec![PathBuf::from(path!("/notes.txt"))], + app_state.clone(), + cx, + ) + .await + .window; + notes_window + .update(cx, |multi_workspace, window, cx| { + multi_workspace + .active_item_as::(cx) + .unwrap() + .update(cx, |editor, cx| editor.insert("unsaved ", window, cx)); + }) + .unwrap(); + cx.run_until_parked(); + let edited_notes = startup_windows(cx) + .into_iter() + .find(|(roots, _)| roots == &[PathBuf::from(path!("/notes.txt"))]) + .unwrap(); + assert!(edited_notes.1[0].1); + restart_startup_test_session(&app_state, cx).await; + + let (request, _cli) = cli_request(&[path!("/notes.txt")], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![edited_notes, project_window_with(&[])] + ); + } + + #[gpui::test] + async fn test_startup_folder_request_takes_its_project_out_of_a_restored_sidebar( + cx: &mut TestAppContext, + ) { + use util::path_list::PathList; + use workspace::{OpenMode, ProjectGroupKey}; + + let app_state = init_startup_test(cx).await; + app_state + .fs + .as_fake() + .insert_tree( + path!("/"), + json!({ "project": { "file.txt": "" }, "other": { "note.txt": "" } }), + ) + .await; + let window = open_test_workspace_paths( + vec![PathBuf::from(path!("/project"))], + app_state.clone(), + cx, + ) + .await + .window; + window + .update(cx, |multi_workspace, window, cx| { + multi_workspace.open_project( + vec![path!("/other").into()], + OpenMode::Add, + window, + cx, + ) + }) + .unwrap() + .await + .unwrap(); + window + .update(cx, |multi_workspace, window, cx| { + let project_workspace = multi_workspace + .workspaces() + .find(|workspace| { + workspace.read(cx).root_paths(cx) + == [Arc::from(Path::new(path!("/project")))] + }) + .unwrap() + .clone(); + multi_workspace.activate(project_workspace, None, window, cx); + }) + .unwrap(); + cx.run_until_parked(); + let project_key = ProjectGroupKey::new(None, PathList::new(&[path!("/project")])); + let other_key = ProjectGroupKey::new(None, PathList::new(&[path!("/other")])); + let sidebar_projects = |cx: &TestAppContext| { + cx.windows() + .into_iter() + .filter_map(|window| window.downcast::()) + .map(|window| { + window + .read_with(cx, |multi_workspace, _| { + multi_workspace.project_group_keys() + }) + .unwrap() + }) + .collect::>() + }; + assert_eq!(sidebar_projects(cx).len(), 1); + assert!(sidebar_projects(cx)[0].contains(&project_key)); + assert!(sidebar_projects(cx)[0].contains(&other_key)); + restart_startup_test_session(&app_state, cx).await; + + let (request, _cli) = terminal_cli_request(&[path!("/other")], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + (vec![PathBuf::from(path!("/other"))], Vec::new()), + (vec![PathBuf::from(path!("/project"))], Vec::new()), + ] + ); + let restored_sidebar = sidebar_projects(cx) + .into_iter() + .find(|projects| projects.contains(&project_key)) + .unwrap(); + assert_eq!(restored_sidebar, vec![project_key]); + } + + #[gpui::test] + async fn test_startup_folder_request_opens_once_a_folder_that_a_saved_window_now_links_to( + cx: &mut TestAppContext, + ) { + let app_state = init_startup_test(cx).await; + let fs = app_state.fs.as_fake(); + fs.insert_tree( + path!("/"), + json!({ "target": { "file.txt": "" }, "old": { "note.txt": "" } }), + ) + .await; + open_test_workspace_paths(vec![PathBuf::from(path!("/target"))], app_state.clone(), cx) + .await; + restart_startup_test_session(&app_state, cx).await; + open_test_workspace_paths(vec![PathBuf::from(path!("/old"))], app_state.clone(), cx).await; + restart_startup_test_session(&app_state, cx).await; + fs.remove_dir( + Path::new(path!("/old")), + fs::RemoveOptions { + recursive: true, + ignore_if_not_exists: false, + }, + ) + .await + .unwrap(); + fs.create_symlink(Path::new(path!("/old")), PathBuf::from(path!("/target"))) + .await + .unwrap(); + + let (request, _cli) = cli_request(&[path!("/target")], cli::OpenBehavior::AlwaysNew); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![(vec![PathBuf::from(path!("/target"))], Vec::new())] + ); + } + + #[gpui::test] + async fn test_startup_folder_request_opens_once_a_folder_that_a_saved_window_now_lies_inside( + cx: &mut TestAppContext, + ) { + let app_state = init_startup_test(cx).await; + let fs = app_state.fs.as_fake(); + fs.insert_tree( + path!("/"), + json!({ + "target": { "file.txt": "", "sub": { "inner.txt": "" } }, + "old": { "note.txt": "" }, + }), + ) + .await; + let target_window = + open_test_workspace_paths(vec![PathBuf::from(path!("/target"))], app_state.clone(), cx) + .await + .window; + add_unsaved_buffer(target_window, "target draft", cx).await; + restart_startup_test_session(&app_state, cx).await; + open_test_workspace_paths( + vec![ + PathBuf::from(path!("/old")), + PathBuf::from(path!("/target/sub")), + ], + app_state.clone(), + cx, + ) + .await; + restart_startup_test_session(&app_state, cx).await; + fs.remove_dir( + Path::new(path!("/old")), + fs::RemoveOptions { + recursive: true, + ignore_if_not_exists: false, + }, + ) + .await + .unwrap(); + fs.create_symlink(Path::new(path!("/old")), PathBuf::from(path!("/target"))) + .await + .unwrap(); + + let (request, _cli) = cli_request(&[path!("/target")], cli::OpenBehavior::AlwaysNew); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![( + vec![PathBuf::from(path!("/target"))], + vec![("target draft".to_owned(), true)] + )] + ); + } + + #[gpui::test] + async fn test_startup_request_opens_without_the_session_when_the_wait_is_over( + cx: &mut TestAppContext, + ) { + let app_state = save_project_and_other_session(cx).await; + let (request, _cli) = + cli_request(&[path!("/project/file.txt")], cli::OpenBehavior::Default); + cx.update(|cx| { + crate::open_startup_request(request, app_state.clone(), futures::future::ready(()), cx) + }) + .await; + cx.run_until_parked(); + + assert_eq!(startup_windows(cx), vec![project_file_window()]); + } + + #[gpui::test] + async fn test_startup_stops_restoring_a_window_that_has_not_opened_when_the_wait_ends( + cx: &mut TestAppContext, + ) { + let app_state = save_session_with_a_project_tab(cx).await; + let outside_window = ( + vec![PathBuf::from(path!("/outside.txt"))], + vec![("outside".to_owned(), false)], + ); + let (end_the_wait, mut wait_ended) = mpsc::unbounded::<()>(); + let _restore_started = cx.update(|cx| { + cx.observe_new::(move |_, _, _| { + end_the_wait.unbounded_send(()).ok(); + }) + }); + let (request, _cli) = cli_request(&[path!("/outside.txt")], cli::OpenBehavior::Default); + cx.update(|cx| { + crate::open_startup_request( + request, + app_state.clone(), + async move { + wait_ended.next().await; + }, + cx, + ) + }) + .await; + cx.run_until_parked(); + assert_eq!(startup_windows(cx), vec![outside_window.clone()]); + + let (request, _cli) = cli_request(&[], cli::OpenBehavior::ExistingWindow); + cx.update(|cx| crate::handle_open_request(request, app_state.clone(), cx)); + cx.run_until_parked(); + assert_eq!( + startup_windows(cx), + vec![ + outside_window, + project_window_with(&[("project file", false)]) + ] + ); + } + + #[gpui::test] + async fn test_startup_finishes_only_the_window_it_is_restoring_when_the_wait_ends( + cx: &mut TestAppContext, + ) { + let app_state = init_startup_test(cx).await; + app_state + .fs + .as_fake() + .insert_tree( + path!("/"), + json!({ + "other": { "note.txt": "note" }, + "project": { "file.txt": "project file" }, + "outside.txt": "outside", + }), + ) + .await; + for (root, file) in [ + (path!("/other"), path!("/other/note.txt")), + (path!("/project"), path!("/project/file.txt")), + ] { + open_test_workspace_paths( + vec![PathBuf::from(root), PathBuf::from(file)], + app_state.clone(), + cx, + ) + .await; + } + restart_startup_test_session(&app_state, cx).await; + + let (end_the_wait, mut wait_ended) = mpsc::unbounded::<()>(); + let _window_opened = cx.update(|cx| { + cx.observe_new::(move |_, _, _| { + end_the_wait.unbounded_send(()).ok(); + }) + }); + let (request, _cli) = cli_request(&[path!("/outside.txt")], cli::OpenBehavior::Default); + cx.update(|cx| { + crate::open_startup_request( + request, + app_state.clone(), + async move { + wait_ended.next().await; + }, + cx, + ) + }) + .await; + let windows = cx.windows(); + assert_eq!(windows.len(), 1); + assert_eq!(cx.read(|cx| cx.active_window()), Some(windows[0])); + let restored_roots = window_contents(windows[0], cx).0; + let restored_tab = if restored_roots == [PathBuf::from(path!("/other"))] { + "note" + } else { + "project file" + }; + + cx.run_until_parked(); + let mut expected_windows = vec![ + (restored_roots, vec![(restored_tab.to_owned(), false)]), + ( + vec![PathBuf::from(path!("/outside.txt"))], + vec![("outside".to_owned(), false)], + ), + ]; + expected_windows.sort(); + assert_eq!(startup_windows(cx), expected_windows); + assert_eq!( + active_window_roots(cx), + vec![PathBuf::from(path!("/outside.txt"))] + ); + } + + #[gpui::test] + async fn test_startup_wait_request_opens_without_the_session(cx: &mut TestAppContext) { + let app_state = save_project_and_other_session(cx).await; + let mut request = cli_open_request( + &[path!("/outside.txt")], + &[], + cli::OpenBehavior::Default, + None, + ); + if let cli::CliRequest::Open { wait, .. } = &mut request { + *wait = true; + } + let (request, _cli) = cli_connection(request); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![( + vec![PathBuf::from(path!("/outside.txt"))], + vec![("outside".to_owned(), false)] + )] + ); + } + + #[gpui::test] + async fn test_startup_request_for_a_linked_worktree_leaves_its_repository_to_the_request( + cx: &mut TestAppContext, + ) { + let app_state = init_startup_test(cx).await; + let fs = app_state.fs.as_fake(); + fs.insert_tree( + path!("/"), + json!({ + "repo": { ".git": {}, "file.txt": "" }, + "other": { "note.txt": "" }, + }), + ) + .await; + fs.add_linked_worktree_for_repo( + Path::new(path!("/repo/.git")), + false, + git::repository::Worktree { + path: PathBuf::from(path!("/repo-wt")), + ref_name: Some("refs/heads/wt".into()), + sha: "aaa".into(), + is_main: false, + is_bare: false, + }, + ) + .await; + for root in [path!("/other"), path!("/repo")] { + open_test_workspace_paths(vec![PathBuf::from(root)], app_state.clone(), cx).await; + } + restart_startup_test_session(&app_state, cx).await; + + let (request, _cli) = + terminal_cli_request(&[path!("/repo-wt")], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + (vec![PathBuf::from(path!("/other"))], Vec::new()), + (vec![PathBuf::from(path!("/repo-wt"))], Vec::new()), + ] + ); + } + + #[gpui::test] + async fn test_startup_request_is_handled_as_before_when_the_wait_ends_before_it_is_prepared( + cx: &mut TestAppContext, + ) { + let app_state = init_startup_test(cx).await; + app_state + .fs + .as_fake() + .insert_tree( + path!("/"), + json!({ "open": { "a.txt": "" }, "outside.txt": "outside" }), + ) + .await; + open_test_workspace_paths(vec![PathBuf::from(path!("/open"))], app_state.clone(), cx).await; + let (request, _cli) = cli_request(&[path!("/outside.txt")], cli::OpenBehavior::Default); + cx.update(|cx| { + crate::open_startup_request(request, app_state.clone(), futures::future::ready(()), cx) + }) + .await; + cx.run_until_parked(); + + assert_eq!( + startup_windows(cx), + vec![( + vec![PathBuf::from(path!("/open"))], + vec![("outside".to_owned(), false)] + )] + ); + } + + #[gpui::test] + async fn test_startup_finishes_a_window_restored_through_a_link_when_the_wait_ends( + cx: &mut TestAppContext, + ) { + let app_state = init_startup_test(cx).await; + let fs = app_state.fs.as_fake(); + fs.insert_tree( + path!("/"), + json!({ + "target": { "file.txt": "target file" }, + "old": { "note.txt": "" }, + "outside.txt": "outside", + }), + ) + .await; + open_test_workspace_paths( + vec![ + PathBuf::from(path!("/target")), + PathBuf::from(path!("/target/file.txt")), + ], + app_state.clone(), + cx, + ) + .await; + restart_startup_test_session(&app_state, cx).await; + open_test_workspace_paths(vec![PathBuf::from(path!("/old"))], app_state.clone(), cx).await; + restart_startup_test_session(&app_state, cx).await; + fs.remove_dir( + Path::new(path!("/old")), + fs::RemoveOptions { + recursive: true, + ignore_if_not_exists: false, + }, + ) + .await + .unwrap(); + fs.create_symlink(Path::new(path!("/old")), PathBuf::from(path!("/target"))) + .await + .unwrap(); + + let (end_the_wait, mut wait_ended) = mpsc::unbounded::<()>(); + let _window_opened = cx.update(|cx| { + cx.observe_new::(move |_, _, _| { + end_the_wait.unbounded_send(()).ok(); + }) + }); + let (request, _cli) = cli_request(&[path!("/outside.txt")], cli::OpenBehavior::Default); + cx.update(|cx| { + crate::open_startup_request( + request, + app_state.clone(), + async move { + wait_ended.next().await; + }, + cx, + ) + }) + .await; + cx.run_until_parked(); + + assert_eq!( + startup_windows(cx), + vec![ + ( + vec![PathBuf::from(path!("/outside.txt"))], + vec![("outside".to_owned(), false)] + ), + ( + vec![PathBuf::from(path!("/target"))], + vec![("target file".to_owned(), false)] + ), + ] + ); + } + + async fn start_with_a_project_window_that_is_still_restoring( + cx: &mut TestAppContext, + ) -> (Arc, WindowHandle) { + let app_state = save_session_with_a_project_tab(cx).await; + let project_window = start_until_the_project_window_is_restoring(&app_state, cx).await; + (app_state, project_window) + } + + async fn start_until_the_project_window_is_restoring( + app_state: &Arc, + cx: &mut TestAppContext, + ) -> WindowHandle { + let project_window = start_until_a_window_is_restoring(app_state, cx).await; + assert_eq!( + window_contents(project_window.into(), cx), + (vec![PathBuf::from(path!("/project"))], Vec::new()) + ); + project_window + } + + async fn start_until_a_window_is_restoring( + app_state: &Arc, + cx: &mut TestAppContext, + ) -> WindowHandle { + let (end_the_wait, mut wait_ended) = mpsc::unbounded::<()>(); + let _window_opened = cx.update(|cx| { + cx.observe_new::(move |_, _, _| { + end_the_wait.unbounded_send(()).ok(); + }) + }); + let (request, _cli) = cli_request(&[path!("/outside.txt")], cli::OpenBehavior::Default); + cx.update(|cx| { + crate::open_startup_request( + request, + app_state.clone(), + async move { + wait_ended.next().await; + }, + cx, + ) + }) + .await; + let windows = cx.windows(); + assert_eq!(windows.len(), 1); + windows[0].downcast::().unwrap() + } + + fn open_tab_with_text( + window: WindowHandle, + text: &str, + cx: &mut TestAppContext, + ) { + window + .update(cx, |multi_workspace, window, cx| { + multi_workspace.workspace().update(cx, |workspace, cx| { + let project = workspace.project().clone(); + let buffer = project.update(cx, |project, cx| { + project.create_local_buffer(text, None, false, cx) + }); + let editor = cx.new(|cx| Editor::for_buffer(buffer, Some(project), window, cx)); + workspace.add_item_to_active_pane(Box::new(editor), None, true, window, cx); + }) + }) + .unwrap(); + } + + fn project_windows(cx: &TestAppContext) -> Vec> { + startup_windows(cx) + .into_iter() + .filter(|(roots, _)| roots == &[PathBuf::from(path!("/project"))]) + .map(|(_, items)| items) + .collect() + } + + #[gpui::test] + async fn test_quitting_while_a_window_is_still_restoring_keeps_it_in_the_session_with_its_tabs( + cx: &mut TestAppContext, + ) { + let (app_state, _) = start_with_a_project_window_that_is_still_restoring(cx).await; + quit_without_finishing_restores(cx).await; + restart_startup_test_session(&app_state, cx).await; + + let (request, _cli) = cli_request(&[], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + assert_eq!( + project_windows(cx), + vec![vec![("project file".to_owned(), false)]] + ); + } + + #[gpui::test] + async fn test_tab_opened_in_a_window_that_is_still_restoring_is_kept(cx: &mut TestAppContext) { + let (_app_state, project_window) = + start_with_a_project_window_that_is_still_restoring(cx).await; + open_tab_with_text(project_window, "opened meanwhile", cx); + cx.run_until_parked(); + + let mut texts = project_windows(cx) + .into_iter() + .flatten() + .map(|(text, _)| text) + .collect::>(); + texts.sort(); + assert_eq!(texts, vec!["opened meanwhile", "project file"]); + } + + #[gpui::test] + async fn test_plain_start_does_not_keep_tabs_opened_while_its_window_is_restoring( + cx: &mut TestAppContext, + ) { + let app_state = save_session_with_a_project_tab(cx).await; + let restore = cx.spawn({ + let app_state = app_state.clone(); + async move |mut cx| crate::restore_or_create_workspace(app_state, &mut cx).await + }); + run_until_a_window_opens(cx); + let project_window = cx.windows()[0].downcast::().unwrap(); + open_tab_with_text(project_window, "opened meanwhile", cx); + restore.await.unwrap(); + cx.run_until_parked(); + + assert_eq!( + project_windows(cx), + vec![vec![("project file".to_owned(), false)]] + ); + } + + #[gpui::test] + async fn test_tab_opened_in_a_window_without_folders_that_is_still_restoring_is_kept( + cx: &mut TestAppContext, + ) { + let app_state = save_session_without_folders(cx).await; + let window = start_until_a_window_is_restoring(&app_state, cx).await; + assert_eq!(window_contents(window.into(), cx), (Vec::new(), Vec::new())); + open_tab_with_text(window, "opened meanwhile", cx); + cx.run_until_parked(); + + let mut texts = window_contents(window.into(), cx) + .1 + .into_iter() + .map(|(text, _)| text) + .collect::>(); + texts.sort(); + assert_eq!(texts, vec!["UNSAVED", "opened meanwhile"]); + } + + #[gpui::test] + async fn test_tab_in_use_in_a_window_that_is_still_restoring_stays_active( + cx: &mut TestAppContext, + ) { + let (_app_state, project_window) = + start_with_a_project_window_that_is_still_restoring(cx).await; + open_tab_with_text(project_window, "in use", cx); + open_tab_with_text(project_window, "opened later", cx); + project_window + .update(cx, |multi_workspace, window, cx| { + let pane = multi_workspace.workspace().read(cx).active_pane().clone(); + pane.update(cx, |pane, cx| pane.activate_item(0, true, true, window, cx)); + }) + .unwrap(); + cx.run_until_parked(); + + let tabs = project_windows(cx) + .into_iter() + .flatten() + .map(|(text, _)| text) + .collect::>(); + assert_eq!(tabs, vec!["in use", "opened later", "project file"]); + let active_tab = project_window + .read_with(cx, |multi_workspace, cx| { + let active_editor = multi_workspace + .workspace() + .read(cx) + .active_item_as::(cx)?; + Some(active_editor.read(cx).text(cx)) + }) + .unwrap(); + assert_eq!(active_tab.as_deref(), Some("in use")); + } + + #[gpui::test(iterations = 10)] + async fn test_file_requested_in_a_window_that_is_still_restoring_gets_one_tab( + cx: &mut TestAppContext, + ) { + let (app_state, _) = start_with_a_project_window_that_is_still_restoring(cx).await; + let (request, _cli) = + cli_request(&[path!("/project/file.txt")], cli::OpenBehavior::Default); + cx.update(|cx| crate::handle_open_request(request, app_state.clone(), cx)); + cx.run_until_parked(); + + assert_eq!( + project_windows(cx), + vec![vec![("project file".to_owned(), false)]] + ); + } + + #[gpui::test] + async fn test_window_whose_restore_was_cancelled_is_saved_as_it_is(cx: &mut TestAppContext) { + let app_state = save_session_with_a_project_tab(cx).await; + let saved = crate::restorable_workspaces(&mut cx.to_async(), &app_state) + .await + .unwrap() + .remove(0) + .active_workspace; + let opening = + cx.update(|cx| workspace::open_saved_workspace(&saved, app_state.clone(), true, cx)); + run_until_a_window_opens(cx); + let window = cx.windows()[0].downcast::().unwrap(); + let is_restoring = |cx: &TestAppContext| { + window + .read_with(cx, |multi_workspace, cx| { + multi_workspace.workspace().read(cx).is_restoring() + }) + .unwrap() + }; + assert!(is_restoring(cx)); + + drop(opening); + cx.run_until_parked(); + assert!(!is_restoring(cx)); + + quit_without_finishing_restores(cx).await; + open_test_workspace_paths( + vec![PathBuf::from(path!("/project"))], + app_state.clone(), + cx, + ) + .await; + assert_eq!(project_windows(cx), vec![Vec::new()]); + } + + #[gpui::test(iterations = 20)] + async fn test_file_requested_in_a_window_that_is_still_restoring_leaves_pinned_tabs_in_place( + cx: &mut TestAppContext, + ) { + let app_state = init_startup_test(cx).await; + app_state + .fs + .as_fake() + .insert_tree( + path!("/"), + json!({ + "project": { "file.txt": "project file", "second.txt": "second" }, + "outside.txt": "outside", + }), + ) + .await; + let window = open_test_workspace_paths( + vec![ + PathBuf::from(path!("/project")), + PathBuf::from(path!("/project/file.txt")), + PathBuf::from(path!("/project/second.txt")), + ], + app_state.clone(), + cx, + ) + .await + .window; + let tabs_and_pinned_count = |window: WindowHandle, cx: &TestAppContext| { + window + .read_with(cx, |multi_workspace, cx| { + let pane = multi_workspace.workspace().read(cx).active_pane().read(cx); + let tabs = pane + .items() + .filter_map(|item| item.downcast::()) + .map(|editor| editor.read(cx).text(cx)) + .collect::>(); + (tabs, pane.pinned_count()) + }) + .unwrap() + }; + window + .update(cx, |multi_workspace, _, cx| { + let pane = multi_workspace.workspace().read(cx).active_pane().clone(); + pane.update(cx, |pane, _| pane.set_pinned_count(1)); + }) + .unwrap(); + cx.run_until_parked(); + let saved_tabs = tabs_and_pinned_count(window, cx); + assert_eq!(saved_tabs.0.len(), 2); + let pinned_file = if saved_tabs.0[0] == "project file" { + path!("/project/file.txt") + } else { + path!("/project/second.txt") + }; + restart_startup_test_session(&app_state, cx).await; + + let project_window = start_until_the_project_window_is_restoring(&app_state, cx).await; + let (request, _cli) = cli_request(&[pinned_file], cli::OpenBehavior::Default); + cx.update(|cx| crate::handle_open_request(request, app_state.clone(), cx)); + cx.run_until_parked(); + + assert_eq!(tabs_and_pinned_count(project_window, cx), saved_tabs); + } + + #[gpui::test] + async fn test_quitting_while_a_window_is_still_restoring_keeps_what_was_made_in_it( + cx: &mut TestAppContext, + ) { + let (app_state, project_window) = + start_with_a_project_window_that_is_still_restoring(cx).await; + project_window + .update(cx, |multi_workspace, window, cx| { + multi_workspace.workspace().update(cx, |workspace, cx| { + let project = workspace.project().clone(); + let buffer = project.update(cx, |project, cx| { + project.create_local_buffer("", None, false, cx) + }); + let editor = cx.new(|cx| Editor::for_buffer(buffer, Some(project), window, cx)); + editor.update(cx, |editor, cx| editor.insert("new draft", window, cx)); + workspace.add_item_to_active_pane(Box::new(editor), None, true, window, cx); + }) + }) + .unwrap(); + quit_without_finishing_restores(cx).await; + restart_startup_test_session(&app_state, cx).await; + + let (request, _cli) = cli_request(&[], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + assert_eq!( + project_windows(cx), + vec![vec![ + ("new draft".to_owned(), true), + ("project file".to_owned(), false) + ]] + ); + } + + #[gpui::test(iterations = 30)] + async fn test_draft_made_in_a_window_that_is_still_restoring_is_kept_without_another_save( + cx: &mut TestAppContext, + ) { + let (app_state, project_window) = + start_with_a_project_window_that_is_still_restoring(cx).await; + project_window + .update(cx, |multi_workspace, window, cx| { + multi_workspace.workspace().update(cx, |workspace, cx| { + let project = workspace.project().clone(); + let buffer = project.update(cx, |project, cx| { + project.create_local_buffer("", None, false, cx) + }); + let editor = cx.new(|cx| Editor::for_buffer(buffer, Some(project), window, cx)); + editor.update(cx, |editor, cx| editor.insert("new draft", window, cx)); + workspace.add_item_to_active_pane(Box::new(editor), None, true, window, cx); + }) + }) + .unwrap(); + cx.run_until_parked(); + for window in cx.windows() { + VisualTestContext::from_window(window, cx).deactivate_window(); + window + .update(cx, |_, window, _| window.remove_window()) + .unwrap(); + } + cx.run_until_parked(); + restart_startup_test_session(&app_state, cx).await; + + let (request, _cli) = cli_request(&[], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + let drafts = project_windows(cx) + .into_iter() + .flatten() + .filter(|(_, is_dirty)| *is_dirty) + .collect::>(); + assert_eq!(drafts, vec![("new draft".to_owned(), true)]); + } + + async fn quit_without_finishing_restores(cx: &mut TestAppContext) { + let mut flushes = Vec::new(); + for window in cx.windows() { + let window = window.downcast::().unwrap(); + flushes.extend( + window + .update(cx, |multi_workspace, window, cx| { + let mut flushes = multi_workspace + .workspaces() + .map(|workspace| { + workspace.update(cx, |workspace, cx| { + workspace.flush_serialization(window, cx) + }) + }) + .collect::>(); + flushes.push(multi_workspace.flush_serialization(cx)); + window.remove_window(); + flushes + }) + .unwrap(), + ); + } + futures::future::join_all(flushes).await; + cx.run_until_parked(); + } + + #[gpui::test] + async fn test_startup_request_for_more_folders_than_a_saved_window_restores_that_window( + cx: &mut TestAppContext, + ) { + let app_state = save_project_and_other_session(cx).await; + let (request, _cli) = cli_request( + &[path!("/new"), path!("/project")], + cli::OpenBehavior::AlwaysNew, + ); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + ( + vec![ + PathBuf::from(path!("/new")), + PathBuf::from(path!("/project")) + ], + Vec::new() + ), + other_window(), + project_window_with(&[("project draft", true)]), + ] + ); + } + + fn project_file_link() -> String { + format!("file://{}", urlencoding::encode(path!("/project/file.txt"))) + } + + fn project_file_window() -> (Vec, Vec<(String, bool)>) { + ( + vec![PathBuf::from(path!("/project/file.txt"))], + vec![("project file".to_owned(), false)], + ) + } + + #[gpui::test] + async fn test_startup_file_request_from_a_terminal_opens_in_its_own_window_with_its_environment( + cx: &mut TestAppContext, + ) { + let app_state = save_project_and_other_session(cx).await; + let (request, _cli) = + terminal_cli_request(&[path!("/project/file.txt")], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![ + other_window(), + project_window_with(&[("project draft", true)]), + project_file_window(), + ] + ); + assert_eq!( + cli_environment_of(path!("/project/file.txt"), cx), + Some("cli".to_owned()) + ); + assert_eq!(cli_environment_of(path!("/project"), cx), None); + assert_eq!( + active_window_roots(cx), + vec![PathBuf::from(path!("/project/file.txt"))] + ); + } + + #[gpui::test] + async fn test_startup_file_request_restores_local_windows_only( + cx: &mut TestAppContext, + server_cx: &mut TestAppContext, + ) { + let app_state = init_startup_test(cx).await; + server_cx.update(|cx| { + release_channel::init(Version::new(0, 0, 0), cx); + HeadlessProject::init(cx); + }); + let remote_fs = FakeFs::new(server_cx.executor()); + remote_fs.insert_tree(path!("/remote"), json!({})).await; + let (connection_options, server_session, connect_guard) = + RemoteClient::fake_server(cx, server_cx); + let _headless = server_cx.new(|cx| { + HeadlessProject::new( + HeadlessAppState { + session: server_session, + fs: remote_fs, + http_client: Arc::new(BlockedHttpClient), + node_runtime: NodeRuntime::unavailable(), + languages: Arc::new(LanguageRegistry::new(cx.background_executor().clone())), + extension_host_proxy: Arc::new(ExtensionHostProxy::new()), + startup_time: std::time::Instant::now(), + }, + false, + cx, + ) + }); + drop(connect_guard); + recent_projects::open_remote_project( + connection_options, + vec![PathBuf::from(path!("/remote"))], + app_state.clone(), + OpenOptions::default(), + &mut cx.to_async(), + ) + .await + .unwrap(); + app_state + .fs + .as_fake() + .insert_tree( + path!("/"), + json!({ "project": { "file.txt": "project file" } }), + ) + .await; + open_test_workspace_paths( + vec![PathBuf::from(path!("/project"))], + app_state.clone(), + cx, + ) + .await; + restart_startup_test_session(&app_state, cx).await; + cx.executor().advance_clock(Duration::from_millis(50)); + cx.run_until_parked(); + let saved = crate::restorable_workspaces(&mut cx.to_async(), &app_state) + .await + .unwrap(); + assert_eq!(saved.len(), 2); + + let (request, _cli) = + cli_request(&[path!("/project/file.txt")], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + + assert_eq!( + startup_windows(cx), + vec![project_window_with(&[("project file", false)])] + ); + assert!(!cx.has_pending_prompt()); + } + + #[gpui::test] + async fn test_startup_stops_holding_later_requests_behind_a_silent_cli( + cx: &mut TestAppContext, + ) { + let app_state = init_startup_test(cx).await; + let (cli_requests, cli_receiver) = mpsc::unbounded::(); + let request = OpenRequest { + kind: Some(OpenRequestKind::CliConnection(( + cli_receiver, + Box::new(IgnoredCliResponses), + ))), + ..OpenRequest::default() + }; + let (end_the_wait, wait_ended) = futures::channel::oneshot::channel::<()>(); + let mut ready = cx.update(|cx| { + crate::open_startup_request( + request, + app_state.clone(), + async move { + wait_ended.await.ok(); + }, + cx, + ) + }); + cx.run_until_parked(); + assert!((&mut ready).now_or_never().is_none()); + + end_the_wait.send(()).unwrap(); + ready.await; + drop(cli_requests); + } + + #[gpui::test] + async fn test_startup_cli_request_that_comes_too_late_opens_without_the_session( + cx: &mut TestAppContext, + ) { + let app_state = save_project_and_other_session(cx).await; + let (cli_requests, cli_receiver) = mpsc::unbounded::(); + let request = OpenRequest { + kind: Some(OpenRequestKind::CliConnection(( + cli_receiver, + Box::new(IgnoredCliResponses), + ))), + ..OpenRequest::default() + }; + cx.update(|cx| { + crate::open_startup_request(request, app_state.clone(), futures::future::ready(()), cx) + }) + .await; + cx.run_until_parked(); + assert_eq!(startup_windows(cx), Vec::new()); + + cli_requests + .unbounded_send(cli_open_request( + &[path!("/outside.txt")], + &[], + cli::OpenBehavior::Default, + None, + )) + .unwrap(); + cx.run_until_parked(); + assert_eq!( + startup_windows(cx), + vec![( + vec![PathBuf::from(path!("/outside.txt"))], + vec![("outside".to_owned(), false)] + )] + ); + } + + #[gpui::test] + async fn test_startup_file_request_outside_restored_projects_opens_in_the_front_window( + cx: &mut TestAppContext, + ) { + let app_state = save_project_and_other_session(cx).await; + let front_window_roots = crate::restorable_workspaces(&mut cx.to_async(), &app_state) + .await + .unwrap() + .last() + .unwrap() + .active_workspace + .paths + .paths() + .to_vec(); + let (request, _cli) = cli_request(&[path!("/outside.txt")], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + + let window_with_the_file = startup_windows(cx) + .into_iter() + .find(|(_, items)| items.contains(&("outside".to_owned(), false))) + .unwrap(); + assert_eq!(window_with_the_file.0, front_window_roots); + assert_eq!(startup_windows(cx).len(), 2); + } + + #[gpui::test] + async fn test_startup_folder_request_opens_after_the_session_is_restored( + cx: &mut TestAppContext, + ) { + let app_state = save_session_with_a_project_tab(cx).await; + let new_window = (vec![PathBuf::from(path!("/new"))], Vec::new()); + let (request, _cli) = cli_request(&[path!("/new")], cli::OpenBehavior::Default); + let mut ready = cx.update(|cx| { + crate::open_startup_request(request, app_state.clone(), futures::future::pending(), cx) + }); + run_until_a_window_opens(cx); + assert!((&mut ready).now_or_never().is_none()); + assert_eq!( + startup_windows(cx) + .into_iter() + .map(|(roots, _)| roots) + .collect::>(), + vec![vec![PathBuf::from(path!("/project"))]] + ); + + ready.await; + assert_eq!( + active_window_roots(cx), + vec![PathBuf::from(path!("/project"))] + ); + cx.run_until_parked(); + assert_eq!( + startup_windows(cx), + vec![new_window, project_window_with(&[("project file", false)])] + ); + assert_eq!(active_window_roots(cx), vec![PathBuf::from(path!("/new"))]); + } + + #[gpui::test] + async fn test_startup_file_request_restores_the_window_it_opens_in_last( + cx: &mut TestAppContext, + ) { + for file in [path!("/other/note.txt"), path!("/project/file.txt")] { + let app_state = save_project_and_other_session(cx).await; + let restored_roots = Rc::new(RefCell::new(Vec::new())); + let _subscription = cx.update(|cx| { + let restored_roots = restored_roots.clone(); + cx.observe_new::(move |multi_workspace, _, cx| { + let roots = multi_workspace.workspace().read(cx).root_paths(cx); + restored_roots.borrow_mut().push(roots); + }) + }); + let (request, _cli) = cli_request(&[file], cli::OpenBehavior::Default); + open_on_startup(request, &app_state, cx).await; + + let restored_roots = restored_roots.borrow(); + assert_eq!(restored_roots.len(), 2); + assert!(Path::new(file).starts_with(&restored_roots[1][0])); + for window in cx.windows() { + cx.update_window(window, |_, window, _| window.remove_window()) + .unwrap(); + } + cx.run_until_parked(); + } + } + fn has_view_item(cx: &mut App, item_name: &str) -> bool { cx.get_menus() .expect("reload_keymaps should populate the menu bar") diff --git a/crates/zed/src/zed/open_listener.rs b/crates/zed/src/zed/open_listener.rs index b89cd2158a3..38360b05867 100644 --- a/crates/zed/src/zed/open_listener.rs +++ b/crates/zed/src/zed/open_listener.rs @@ -21,8 +21,6 @@ use onboarding::show_onboarding_view; use recent_projects::{RemoteSettings, navigate_to_positions, open_remote_project}; use remote::{RemoteConnectionOptions, WslConnectionOptions}; use settings::Settings; -#[cfg(target_os = "windows")] -use std::path::{Component, Prefix}; use std::path::{Path, PathBuf}; use std::sync::Arc; use std::thread; @@ -30,7 +28,7 @@ use std::time::Duration; use ui::SharedString; use util::ResultExt; use util::debug_panic; -use util::paths::PathWithPosition; +use util::paths::{PathStyle, PathWithPosition, url_path_to_path}; use workspace::PathList; use workspace::item::ItemHandle; use workspace::{AppState, MultiWorkspace, OpenOptions, OpenResult, SerializedWorkspaceLocation}; @@ -224,18 +222,8 @@ impl OpenRequest { fn parse_local_file_path(&mut self, file: &str) { if let Some(decoded) = urlencoding::decode(file).log_err() { - // URL paths keep a `/` before a Windows drive letter (`/C:/x`), which Windows cannot open. - #[cfg(target_os = "windows")] - if let Some(path) = decoded.strip_prefix('/') - && matches!( - Path::new(path).components().next(), - Some(Component::Prefix(prefix)) if matches!(prefix.kind(), Prefix::Disk(_)) - ) - { - self.open_paths.push(path.to_owned()); - return; - } - self.open_paths.push(decoded.into_owned()) + self.open_paths + .push(url_path_to_path(&decoded, PathStyle::local()).to_owned()) } } @@ -601,100 +589,127 @@ pub async fn handle_cli_connection( cx: &mut AsyncApp, ) { if let Some(request) = requests.next().await { - match request { - CliRequest::Open { - urls, + handle_cli_request(request, requests, responses, app_state, cx).await; + } +} + +pub async fn handle_cli_request( + request: CliRequest, + mut requests: mpsc::UnboundedReceiver, + responses: Box, + app_state: Arc, + cx: &mut AsyncApp, +) { + match request { + CliRequest::Open { + urls, + paths, + diff_paths, + diff_all, + wait, + wsl, + mut open_behavior, + env, + user_data_dir: _, + dev_container, + cwd, + } => { + if !urls.is_empty() { + cx.update(|cx| { + match OpenRequest::parse( + RawOpenRequest { + urls, + diff_paths, + diff_all, + dev_container, + wsl, + open_behavior: Some(open_behavior), + }, + cx, + ) { + Ok(open_request) => { + cx.activate(true); + handle_open_request(open_request, app_state.clone(), cx); + responses.send(CliResponse::Exit { status: 0 }).log_err(); + } + Err(e) => { + responses + .send(CliResponse::Stderr { + message: format!("{e}"), + }) + .log_err(); + responses.send(CliResponse::Exit { status: 1 }).log_err(); + } + }; + }); + return; + } + + if open_behavior == cli::OpenBehavior::Default { + match resolve_open_behavior( + &paths, + &app_state, + responses.as_ref(), + &mut requests, + cx, + ) + .await + { + Some(settings::CliDefaultOpenBehavior::ExistingWindow) => { + open_behavior = cli::OpenBehavior::ExistingWindow; + } + Some(settings::CliDefaultOpenBehavior::NewWindow) => { + open_behavior = cli::OpenBehavior::PreferNewWindow; + } + None => {} + } + } + + if open_behavior == cli::OpenBehavior::Default { + open_behavior = cx.update(|cx| open_behavior_for_default_setting(cx)); + } + + cx.update(|cx| cx.activate(true)); + + let open_workspace_result = open_workspaces( paths, diff_paths, diff_all, + open_behavior, + responses.as_ref(), wait, - wsl, - mut open_behavior, - env, - user_data_dir: _, dev_container, + app_state.clone(), + env, cwd, - } => { - if !urls.is_empty() { - cx.update(|cx| { - match OpenRequest::parse( - RawOpenRequest { - urls, - diff_paths, - diff_all, - dev_container, - wsl, - open_behavior: Some(open_behavior), - }, - cx, - ) { - Ok(open_request) => { - cx.activate(true); - handle_open_request(open_request, app_state.clone(), cx); - responses.send(CliResponse::Exit { status: 0 }).log_err(); - } - Err(e) => { - responses - .send(CliResponse::Stderr { - message: format!("{e}"), - }) - .log_err(); - responses.send(CliResponse::Exit { status: 1 }).log_err(); - } - }; - }); - return; - } + cx, + ) + .await; - if open_behavior == cli::OpenBehavior::Default { - match resolve_open_behavior( - &paths, - &app_state, - responses.as_ref(), - &mut requests, - cx, - ) - .await - { - Some(settings::CliDefaultOpenBehavior::ExistingWindow) => { - open_behavior = cli::OpenBehavior::ExistingWindow; - } - Some(settings::CliDefaultOpenBehavior::NewWindow) => { - open_behavior = cli::OpenBehavior::PreferNewWindow; - } - None => {} - } - } - - if open_behavior == cli::OpenBehavior::Default { - open_behavior = cx.update(|cx| open_behavior_for_default_setting(cx)); - } - - cx.update(|cx| cx.activate(true)); - - let open_workspace_result = open_workspaces( - paths, - diff_paths, - diff_all, - open_behavior, - responses.as_ref(), - wait, - dev_container, - app_state.clone(), - env, - cwd, - cx, - ) - .await; - - let status = if open_workspace_result.is_err() { 1 } else { 0 }; - responses.send(CliResponse::Exit { status }).log_err(); - } - CliRequest::SetOpenBehavior { .. } => { - // We handle this case in a situation-specific way in - // resolve_open_behavior - debug_panic!("unexpected SetOpenBehavior message"); - } + let status = if open_workspace_result.is_err() { 1 } else { 0 }; + responses.send(CliResponse::Exit { status }).log_err(); + } + CliRequest::SetOpenBehavior { .. } => { + // We handle this case in a situation-specific way in + // resolve_open_behavior + debug_panic!("unexpected SetOpenBehavior message"); + } + CliRequest::DebugState => { + // Deliberately does not activate the app: activation redraws + // windows and would disturb the state being inspected. + let state = cx.update(|cx| cx.debug_state()); + let response = match serde_json::to_string_pretty(&state) { + Ok(message) => CliResponse::Stdout { message }, + Err(error) => CliResponse::Stderr { + message: format!("failed to serialize debug state: {error}"), + }, + }; + let status = match response { + CliResponse::Stdout { .. } => 0, + _ => 1, + }; + responses.send(response).log_err(); + responses.send(CliResponse::Exit { status }).log_err(); } } } @@ -723,19 +738,15 @@ async fn resolve_open_behavior( } if !paths.is_empty() { - let paths_as_pathbufs: Vec = paths.iter().map(PathBuf::from).collect(); let paths_in_existing_workspace = cx.update(|cx| { for window in cx.windows() { - if let Some(multi_workspace) = window.downcast::() { - if let Ok(multi_workspace) = multi_workspace.read(cx) { - for workspace in multi_workspace.workspaces() { - let project = workspace.read(cx).project().read(cx); - if project - .visibility_for_paths(&paths_as_pathbufs, false, cx) - .is_some() - { - return true; - } + if let Some(multi_workspace) = window.downcast::() + && let Ok(multi_workspace) = multi_workspace.read(cx) + { + for workspace in multi_workspace.workspaces() { + let project = workspace.read(cx).project().read(cx); + if project.visibility_for_paths(&paths, false, cx).is_some() { + return true; } } } @@ -746,14 +757,13 @@ async fn resolve_open_behavior( if paths_in_existing_workspace { return None; } - } - if !paths.is_empty() { - let has_directory = - futures::future::join_all(paths.iter().map(|p| app_state.fs.is_dir(Path::new(p)))) - .await - .into_iter() - .any(|is_dir| is_dir); + let has_directory = paths + .iter() + .map(|path| app_state.fs.is_dir(Path::new(path))) + .collect::>() + .any(|is_dir| async move { is_dir }) + .await; if !has_directory { return None; @@ -2297,7 +2307,7 @@ mod tests { // Now test the reuse functionality - should replace the existing workspace let workspace_paths_reuse = vec![file1_path.to_string()]; - let paths: Vec = workspace_paths_reuse.iter().map(PathBuf::from).collect(); + let paths: Vec<_> = workspace_paths_reuse.iter().map(PathBuf::from).collect(); let window_to_replace = workspace::find_existing_workspace( &paths, &workspace::OpenOptions::default(), diff --git a/docs/src/account/zed-hosted-models.md b/docs/src/account/zed-hosted-models.md index a2f1e13a793..c6b058bd7bc 100644 --- a/docs/src/account/zed-hosted-models.md +++ b/docs/src/account/zed-hosted-models.md @@ -1,6 +1,6 @@ --- title: Zed-Hosted Models - Zed -description: AI models available via Zed Pro including Claude Fable 5.1, Claude Opus 5.5, GPT-6.1 Sol, and Gemini 4 Argon. Pricing, context windows, and tool call support. +description: AI models available via Zed Pro including Claude Fable 5.2, Claude Opus 5.5, GPT-6.1 Sol, and Gemini 4 Argon. Pricing, context windows, and tool call support. --- # Zed-Hosted Models @@ -11,6 +11,10 @@ Zed's plans offer hosted versions of major LLMs with higher rate limits than dir | Model | Provider | Token Type | Provider Price per 1M tokens | Zed Price per 1M tokens | | ----------------- | --------- | ------------------- | ---------------------------- | ----------------------- | +| Claude Fable 5.2 | Anthropic | Input | $8.00 | $8.80 | +| | Anthropic | Output | $40.00 | $44.00 | +| | Anthropic | Input - Cache Write | $10.00 | $11.00 | +| | Anthropic | Input - Cache Read | $0.20 | $0.22 | | Claude Fable 5.1 | Anthropic | Input | $10.00 | $11.00 | | | Anthropic | Output | $50.00 | $55.00 | | | Anthropic | Input - Cache Write | $12.50 | $13.75 | @@ -126,7 +130,7 @@ Zed's plans offer hosted versions of major LLMs with higher rate limits than dir | Gemini 3 Flash | Google | Input | $0.50 | $0.55 | | | Google | Output | $3.00 | $3.30 | -> **Warn:** Anthropic retains prompts and outputs sent to Claude Fable 5.1 and Claude Fable 5 for at least 30 days for trust and safety purposes. The no-training commitment still applies, and Zed does not retain your prompts or outputs. See [Provider Safety Retention for Designated Models](../ai/privacy-and-security.md#provider-safety-retention). +> **Warn:** Anthropic retains prompts and outputs sent to Claude Fable 5.2, Claude Fable 5.1, and Claude Fable 5 for at least 30 days for trust and safety purposes. The no-training commitment still applies, and Zed does not retain your prompts or outputs. See [Provider Safety Retention for Designated Models](../ai/privacy-and-security.md#provider-safety-retention). ## Recent Model Retirements {#recent-model-retirements} @@ -145,6 +149,8 @@ Zed no longer offers the models below: Any usage of a Zed-hosted model will be billed at the Zed Price (rightmost column above). See [Plans & Pricing](./plans-and-pricing.md) for details on Zed's plans and limits for use of hosted models. +For Claude Fable 5.2, the cache-write rate above is for the 5-minute cache. The 1-hour cache costs $16.00 per 1M tokens from Anthropic, or $17.60 through Zed. Fast mode doubles all Fable 5.2 token rates, including cache writes and reads. + Gemini 4 Argon bills implicit cache hits at the cached-input rate above. Gemini 3 models do not use Google context caching and are billed only as input and output tokens, which preserves zero-data-retention behavior for those requests. For background, see Google's Vertex AI documentation on [context caching](https://cloud.google.com/vertex-ai/generative-ai/docs/context-cache/context-cache-overview) and [zero data retention](https://cloud.google.com/vertex-ai/generative-ai/docs/vertex-ai-zero-data-retention). > LLMs can enter unproductive loops that require user intervention. Monitor longer-running tasks and interrupt if needed. @@ -155,6 +161,7 @@ A context window is the maximum span of text and code an LLM can consider at onc | Model | Provider | Zed-Hosted Context Window | | ----------------- | --------- | ------------------------- | +| Claude Fable 5.2 | Anthropic | 1M | | Claude Fable 5.1 | Anthropic | 1M | | Claude Fable 5 | Anthropic | 1M | | Claude Opus 5.5 | Anthropic | 1M | diff --git a/docs/src/reference/all-settings.md b/docs/src/reference/all-settings.md index 5de21223ed6..818ddaee97d 100644 --- a/docs/src/reference/all-settings.md +++ b/docs/src/reference/all-settings.md @@ -4695,7 +4695,7 @@ These settings belong inside the `file_finder` object. - Description: Prefill the file finder query with text selected in the focused item, such as an editor or terminal. - Setting: `prefill_query_from_selection` -- Default: `true` +- Default: `false` **Options** @@ -6442,6 +6442,7 @@ Run the {#action theme_selector::Toggle} action in the command palette to see a ```json [settings] { "title_bar": { + "show": "always", "show_branch_status_icon": false, "show_branch_name": true, "show_worktree_name": true, @@ -6459,6 +6460,7 @@ Run the {#action theme_selector::Toggle} action in the command palette to see a **Options** +- `show`: When to show the title bar: `"always"` (default), `"never"`, or `"hide_in_full_screen"`. - `show_branch_status_icon`: Whether to show git status indicators on the branch icon in the titlebar - `show_branch_name`: Whether to show the branch name button in the titlebar - `show_worktree_name`: Whether to show the worktree name button in the titlebar diff --git a/docs/src/visual-customization.md b/docs/src/visual-customization.md index 6253f5d5cf5..c6be9dd5c4f 100644 --- a/docs/src/visual-customization.md +++ b/docs/src/visual-customization.md @@ -142,6 +142,7 @@ To disable this behavior use: ```json [settings] // Control which items are shown/hidden in the title bar "title_bar": { + "show": "always", // When to show: always | never | hide_in_full_screen "show_branch_status_icon": false, // Show git status on branch icon "show_branch_name": true, // Show/hide branch name "show_worktree_name": true, // Show/hide worktree name diff --git a/docs/src/worktree-trust.md b/docs/src/worktree-trust.md index 8a4834e24b6..b5851333a3f 100644 --- a/docs/src/worktree-trust.md +++ b/docs/src/worktree-trust.md @@ -20,7 +20,10 @@ If a worktree is not trusted, Zed will indicate this with an exclamation mark ic Trusting a worktree persists that decision between restarts. You can clear all trusted worktrees with the `workspace::ClearTrustedWorktrees` command. This command will restart Zed, to ensure no untrusted settings, language servers or MCP servers persist. -This feature works locally and on SSH and WSL remote hosts. Zed tracks trust information per host in these cases. +Choosing "Stay in Restricted Mode" also persists between restarts, per worktree path and remote connection, so the security modal does not open automatically for that worktree again. +The title bar icon and the `workspace::ToggleWorktreeSecurity` action still open it, and `workspace::ClearTrustedWorktrees` also clears these choices. + +This feature works locally and on SSH and WSL remote hosts. Zed tracks trust information per remote connection in these cases, so the same host on a different SSH port or with a different user is trusted separately. ## What is restricted diff --git a/script/github-triage-queue-board.py b/script/github-triage-queue-board.py index caebba03bba..4f4f1db2473 100644 --- a/script/github-triage-queue-board.py +++ b/script/github-triage-queue-board.py @@ -1,11 +1,11 @@ #!/usr/bin/env python3 """ -Maintain a GitHub project as a search filter for second-line issue triage. +Maintain a GitHub project as a search filter for the current issue triage shift. -GitHub issue search can't express "created at least one business day ago", so -this script keeps the project's membership equal to the open issues created in -that window, adding issues that have become eligible and removing the ones that -have aged out. +GitHub issue search can't express "created since last Friday 14:00 CET", so +this script keeps the project's membership equal to the open issues created +since then, adding new issues and removing the ones that have been closed or +have aged out at the Monday reset. Requires: requests (pip install requests) @@ -23,44 +23,20 @@ from github_helpers import add_github_project_item, github_graphql, github_rest_ REPO_OWNER = "zed-industries" REPO_NAME = "zed" -# The eligibility window's boundaries are calendar days in this timezone. GitHub -# search interprets bare dates as UTC, so the window is pinned to a fixed zone to -# stay aligned with a consistent business day regardless of where the job runs. -# ZoneInfo (not a fixed offset) so daylight saving is handled automatically. -BUSINESS_DAY_TZ = ZoneInfo("America/Los_Angeles") +TRIAGE_TZ = ZoneInfo("Europe/Berlin") +HANDOFF_HOUR = 14 -def day_start(day): - # First instant of a calendar day in the business-day timezone. - return datetime(day.year, day.month, day.day, 0, 0, 0, tzinfo=BUSINESS_DAY_TZ) +def window_start(now): + # The Friday handoff before this week's Monday. The board resets on Monday + # rather than at the handoff itself so the outgoing shift keeps its leftovers + # through Friday afternoon. + friday = now.date() - timedelta(days=now.isoweekday() + 2) + return datetime(friday.year, friday.month, friday.day, HANDOFF_HOUR, tzinfo=TRIAGE_TZ) -def day_end(day): - # Last instant of a calendar day in the business-day timezone. - return datetime(day.year, day.month, day.day, 23, 59, 59, tzinfo=BUSINESS_DAY_TZ) - - -def eligibility_window(today): - # Returns the inclusive (start, end) day-edge instants bounding the window. - weekday = today.isoweekday() # Monday = 1 - # Nothing advances over the weekend; evaluate as of the preceding Friday. - if weekday >= 6: - today -= timedelta(days=weekday - 5) - weekday = 5 - this_monday = today - timedelta(days=weekday - 1) - # Floored at the prior week's Thursday; the Monday reset drops older issues. - window_start = this_monday - timedelta(days=4) - # Eligible once a full business day has elapsed since creation: two business - # days back from today, so Mon and Tue reach across the weekend. - window_end = today - timedelta(days=4 if weekday <= 2 else 2) - return day_start(window_start), day_end(window_end) - - -def eligible_issues(window_start, window_end): - query = ( - f"repo:{REPO_OWNER}/{REPO_NAME} is:issue is:open " - f"created:{window_start.isoformat()}..{window_end.isoformat()}" - ) +def eligible_issues(start): + query = f"repo:{REPO_OWNER}/{REPO_NAME} is:issue is:open created:>={start.isoformat()}" issues = {} page = 1 while True: @@ -129,11 +105,10 @@ def remove_from_project(project_id, item_id): def sync_project(project_id, dry_run=False): - today = datetime.now(BUSINESS_DAY_TZ).date() - window_start, window_end = eligibility_window(today) - print(f"window: created:{window_start.isoformat()}..{window_end.isoformat()}") + start = window_start(datetime.now(TRIAGE_TZ)) + print(f"window: created:>={start.isoformat()}") - eligible = eligible_issues(window_start, window_end) + eligible = eligible_issues(start) current = list(project_items(project_id)) on_board = {content_id for _, content_id, _ in current} diff --git a/script/linux b/script/linux index df95f90eaf4..e03923cc3d7 100755 --- a/script/linux +++ b/script/linux @@ -19,6 +19,16 @@ EOF # Ubuntu, Debian, Mint, Kali, Pop!_OS, Raspbian, etc. apt=$(command -v apt-get || true) if [[ -n $apt ]]; then + if [[ "${GITHUB_ACTIONS:-}" == "true" ]]; then + # Namespace's Ubuntu sources use these mirror lists; other runners may not. + for mirror_file in /etc/apt/apt-mirrors.txt /etc/apt/apt-security-mirrors.txt; do + if [[ -f "$mirror_file" ]] && ! grep -Fxq 'https://mirror.clarkson.edu/ubuntu/' "$mirror_file"; then + printf '\n%s\n' 'https://mirror.clarkson.edu/ubuntu/' | \ + $maysudo tee -a "$mirror_file" > /dev/null + fi + done + fi + deps=( gcc g++