chore: Prepare for Rust edition bump to 2024 (without autofix) (#27791)

Piotr Osiewicz created

Successor to #27779 - in this PR I've applied changes manually, without
futzing with if let lifetimes at all.

Release Notes:

- N/A

Change summary

Cargo.lock                                                    | 313 +
crates/assistant2/src/active_thread.rs                        |   6 
crates/assistant2/src/assistant_configuration.rs              |   2 
crates/assistant2/src/context_store.rs                        |   6 
crates/assistant2/src/thread.rs                               |   2 
crates/assistant_context_editor/src/context_editor.rs         |   2 
crates/assistant_settings/src/assistant_settings.rs           |   6 
crates/assistant_slash_commands/src/file_command.rs           |   9 
crates/assistant_tools/src/bash_tool.rs                       |   4 
crates/assistant_tools/src/edit_files_tool.rs                 |   6 
crates/audio/src/assets.rs                                    |   2 
crates/aws_http_client/src/aws_http_client.rs                 |   2 
crates/buffer_diff/src/buffer_diff.rs                         | 125 
crates/call/src/call_impl/room.rs                             |   4 
crates/channel/src/channel_chat.rs                            |   4 
crates/channel/src/channel_store.rs                           |   5 
crates/cli/src/main.rs                                        |   8 
crates/client/src/client.rs                                   |  10 
crates/client/src/telemetry.rs                                |   4 
crates/client/src/user.rs                                     |   2 
crates/collab/src/api/billing.rs                              |   4 
crates/collab/src/db.rs                                       |   2 
crates/collab/src/db/tests.rs                                 |   2 
crates/collab/src/env.rs                                      |   2 
crates/collab/src/executor.rs                                 |   2 
crates/collab/src/llm/authorization.rs                        |   4 
crates/collab/src/llm/db/tests.rs                             |   2 
crates/collab/src/rpc.rs                                      |   2 
crates/collab/src/tests/integration_tests.rs                  |   6 
crates/collab/src/tests/random_project_collaboration_tests.rs |  62 
crates/collab_ui/src/chat_panel.rs                            |   2 
crates/command_palette/src/command_palette.rs                 |   2 
crates/component/src/component.rs                             |   2 
crates/component_preview/src/component_preview.rs             |   2 
crates/context_server_settings/src/context_server_settings.rs |   2 
crates/copilot/src/copilot.rs                                 |   5 
crates/debugger_ui/src/debugger_panel.rs                      |   4 
crates/debugger_ui/src/session/running/variable_list.rs       |   4 
crates/editor/src/commit_tooltip.rs                           |   2 
crates/editor/src/display_map.rs                              |   8 
crates/editor/src/display_map/block_map.rs                    |   8 
crates/editor/src/display_map/fold_map.rs                     |   4 
crates/editor/src/display_map/inlay_map.rs                    |   6 
crates/editor/src/display_map/tab_map.rs                      |   2 
crates/editor/src/display_map/wrap_map.rs                     |   2 
crates/editor/src/editor.rs                                   |  10 
crates/editor/src/editor_tests.rs                             |   6 
crates/editor/src/element.rs                                  |  13 
crates/extension/src/extension_builder.rs                     |   7 
crates/extension_api/Cargo.toml                               |   2 
crates/extension_api/src/extension_api.rs                     |   2 
crates/extension_host/src/extension_host.rs                   |   2 
crates/file_finder/src/file_finder_tests.rs                   | 122 
crates/fs/src/fs.rs                                           |   4 
crates/fsevent/src/fsevent.rs                                 |   2 
crates/git_ui/src/git_panel.rs                                |   4 
crates/gpui/Cargo.toml                                        |   2 
crates/gpui/src/action.rs                                     |  22 
crates/gpui/src/app.rs                                        |   2 
crates/gpui/src/app/async_context.rs                          |   6 
crates/gpui/src/app/test_context.rs                           |   5 
crates/gpui/src/arena.rs                                      |   8 
crates/gpui/src/executor.rs                                   |  24 
crates/gpui/src/keymap/context.rs                             |  10 
crates/gpui/src/platform/blade/blade_renderer.rs              |   8 
crates/gpui/src/platform/linux/platform.rs                    |   2 
crates/gpui/src/platform/linux/wayland/clipboard.rs           |   2 
crates/gpui/src/platform/linux/x11/window.rs                  |  25 
crates/gpui/src/platform/mac.rs                               |  14 
crates/gpui/src/platform/mac/display.rs                       |   2 
crates/gpui/src/platform/mac/display_link.rs                  |  54 
crates/gpui/src/platform/mac/events.rs                        | 629 ++--
crates/gpui/src/platform/mac/metal_renderer.rs                |   3 
crates/gpui/src/platform/mac/open_type.rs                     |   2 
crates/gpui/src/platform/mac/platform.rs                      | 560 ++--
crates/gpui/src/platform/mac/screen_capture.rs                |  49 
crates/gpui/src/platform/mac/text_system.rs                   |   8 
crates/gpui/src/platform/mac/window.rs                        | 422 +-
crates/gpui/src/platform/mac/window_appearance.rs             |  32 
crates/gpui/src/platform/test/dispatcher.rs                   |   2 
crates/gpui/src/platform/windows/direct_write.rs              |  96 
crates/gpui/src/shared_string.rs                              |   4 
crates/gpui/src/subscription.rs                               |   7 
crates/gpui/src/text_system/font_features.rs                  |   2 
crates/gpui/src/window.rs                                     |   8 
crates/gpui_macros/src/derive_app_context.rs                  |   4 
crates/gpui_macros/src/derive_into_element.rs                 |   4 
crates/gpui_macros/src/derive_render.rs                       |   4 
crates/gpui_macros/src/derive_visual_context.rs               |   4 
crates/gpui_macros/src/styles.rs                              |  14 
crates/image_viewer/src/image_viewer.rs                       |   4 
crates/language/src/buffer.rs                                 | 196 
crates/language/src/language.rs                               |  14 
crates/language/src/language_registry.rs                      |   2 
crates/language/src/language_settings.rs                      |   2 
crates/language/src/syntax_map/syntax_map_tests.rs            |  86 
crates/language_model/src/rate_limiter.rs                     |   2 
crates/language_models/src/provider/copilot_chat.rs           |  23 
crates/language_models/src/provider/google.rs                 |   3 
crates/language_models/src/provider/lmstudio.rs               |   3 
crates/language_tools/src/key_context_view.rs                 |   2 
crates/languages/src/go.rs                                    |   4 
crates/livekit_client/src/livekit_client/playback.rs          |   4 
crates/livekit_client/src/mock_client.rs                      |   2 
crates/lsp/src/lsp.rs                                         |   8 
crates/markdown_preview/src/markdown_renderer.rs              |   4 
crates/media/Cargo.toml                                       |   2 
crates/media/src/media.rs                                     |  54 
crates/multi_buffer/src/multi_buffer.rs                       | 191 
crates/multi_buffer/src/multi_buffer_tests.rs                 |   2 
crates/outline_panel/src/outline_panel.rs                     |   3 
crates/picker/src/picker.rs                                   |   6 
crates/prettier/src/prettier.rs                               |  17 
crates/project/src/debugger/dap_store.rs                      |   2 
crates/project/src/debugger/locator_store.rs                  |   2 
crates/project/src/environment.rs                             |   4 
crates/project/src/git_store.rs                               |   2 
crates/project/src/lsp_store.rs                               |  27 
crates/project/src/project.rs                                 |   2 
crates/project/src/project_tests.rs                           |  40 
crates/project/src/task_inventory.rs                          |   2 
crates/project_panel/src/project_panel.rs                     |   4 
crates/project_panel/src/project_panel_tests.rs               | 252 +-
crates/prompt_store/src/prompt_store.rs                       |   2 
crates/recent_projects/src/ssh_connections.rs                 |   2 
crates/refineable/derive_refineable/src/derive_refineable.rs  |  10 
crates/remote/src/ssh_session.rs                              |   4 
crates/remote_server/src/unix.rs                              |  16 
crates/repl/src/kernels/mod.rs                                |   2 
crates/repl/src/notebook/notebook_ui.rs                       |   2 
crates/repl/src/outputs.rs                                    |   3 
crates/rope/src/rope.rs                                       |   4 
crates/rpc/src/auth.rs                                        |   2 
crates/rpc/src/peer.rs                                        |  12 
crates/rpc/src/proto_client.rs                                |   2 
crates/search/src/buffer_search.rs                            |   6 
crates/search/src/search.rs                                   |   6 
crates/semantic_index/src/embedding_index.rs                  |   7 
crates/semantic_index/src/summary_index.rs                    |  12 
crates/settings/src/keymap_file.rs                            |  10 
crates/settings/src/settings_store.rs                         |   4 
crates/snippet_provider/src/format.rs                         |   6 
crates/sqlez/src/statement.rs                                 |   3 
crates/sum_tree/src/sum_tree.rs                               |  10 
crates/task/src/debug_format.rs                               |   2 
crates/task/src/task_template.rs                              |  12 
crates/terminal/src/terminal.rs                               |  25 
crates/terminal/src/terminal_settings.rs                      |   2 
crates/terminal_view/src/terminal_view.rs                     |   2 
crates/text/src/text.rs                                       |  17 
crates/theme/src/schema.rs                                    |   2 
crates/theme/src/settings.rs                                  |   2 
crates/ui/src/components/context_menu.rs                      |   2 
crates/ui/src/components/tooltip.rs                           |  18 
crates/util/src/util.rs                                       |   4 
crates/vim/src/motion.rs                                      |   2 
crates/workspace/src/pane.rs                                  |  10 
crates/workspace/src/workspace.rs                             |   4 
crates/worktree/src/worktree.rs                               |  13 
crates/worktree/src/worktree_tests.rs                         |   4 
crates/zed/src/zed.rs                                         |   6 
crates/zlog/src/zlog.rs                                       |   4 
162 files changed, 2,201 insertions(+), 1,905 deletions(-)

Detailed changes

Cargo.lock 🔗

@@ -86,7 +86,7 @@ version = "0.25.1-dev"
 source = "git+https://github.com/zed-industries/alacritty.git?branch=add-hush-login-flag#828457c9ff1f7ea0a0469337cc8a37ee3a1b0590"
 dependencies = [
  "base64 0.22.1",
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "home",
  "libc",
  "log",
@@ -128,7 +128,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "ed7572b7ba83a31e20d1b48970ee402d2e3e0537dcfe0a3ff4d6eb7508617d43"
 dependencies = [
  "alsa-sys",
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "cfg-if",
  "libc",
 ]
@@ -1189,6 +1189,18 @@ dependencies = [
  "util",
 ]
 
+[[package]]
+name = "auditable-serde"
+version = "0.8.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5c7bf8143dfc3c0258df908843e169b5cc5fcf76c7718bd66135ef4a9cd558c5"
+dependencies = [
+ "semver",
+ "serde",
+ "serde_json",
+ "topological-sort",
+]
+
 [[package]]
 name = "auto_update"
 version = "0.1.0"
@@ -1888,7 +1900,7 @@ version = "0.69.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "271383c67ccabffb7381723dea0672a673f292304fcb45c01cc648c7a8d58088"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "cexpr",
  "clang-sys",
  "itertools 0.12.1",
@@ -1911,7 +1923,25 @@ version = "0.70.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "f49d8fed880d473ea71efb9bf597651e77201bdd4893efe54c9e5d65ae04ce6f"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
+ "cexpr",
+ "clang-sys",
+ "itertools 0.12.1",
+ "proc-macro2",
+ "quote",
+ "regex",
+ "rustc-hash 1.1.0",
+ "shlex",
+ "syn 2.0.100",
+]
+
+[[package]]
+name = "bindgen"
+version = "0.71.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "5f58bf3d7db68cfbac37cfc485a8d711e87e064c3d0fe0435b92f7a407f9d6b3"
+dependencies = [
+ "bitflags 2.9.0",
  "cexpr",
  "clang-sys",
  "itertools 0.12.1",
@@ -1920,7 +1950,7 @@ dependencies = [
  "proc-macro2",
  "quote",
  "regex",
- "rustc-hash 1.1.0",
+ "rustc-hash 2.1.1",
  "shlex",
  "syn 2.0.100",
 ]
@@ -1969,9 +1999,9 @@ checksum = "bef38d45163c2f1dde094a7dfd33ccf595c92905c8f8f4fdc18d06fb1037718a"
 
 [[package]]
 name = "bitflags"
-version = "2.8.0"
+version = "2.9.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "8f68f53c83ab957f72c32642f3868eec03eb974d1fb82e453128456482613d36"
+checksum = "5c8214115b7bf84099f1309324e63141d4c5d7cc26862f97a0a857dbefe165bd"
 dependencies = [
  "serde",
 ]
@@ -2001,9 +2031,9 @@ source = "git+https://github.com/kvark/blade?rev=b16f5c7bd873c7126f48c82c39e7ae6
 dependencies = [
  "ash",
  "ash-window",
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "bytemuck",
- "codespan-reporting 0.11.1",
+ "codespan-reporting",
  "glow",
  "gpu-alloc",
  "gpu-alloc-ash",
@@ -2049,9 +2079,9 @@ dependencies = [
 
 [[package]]
 name = "blake3"
-version = "1.6.1"
+version = "1.7.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "675f87afced0413c9bb02843499dbbd3882a237645883f71a2b59644a6d2f753"
+checksum = "b17679a8d69b6d7fd9cd9801a536cec9fa5e5970b69f9d4747f70b39b031f5e7"
 dependencies = [
  "arrayref",
  "arrayvec",
@@ -2289,11 +2319,12 @@ dependencies = [
 
 [[package]]
 name = "bzip2-sys"
-version = "0.1.13+1.0.8"
+version = "0.1.11+1.0.8"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "225bff33b2141874fe80d71e07d6eec4f85c5c216453dd96388240f96e1acc14"
+checksum = "736a955f3fa7875102d57c82b8cac37ec45224a07fd32d58f9f7a186b6cd4cdc"
 dependencies = [
  "cc",
+ "libc",
  "pkg-config",
 ]
 
@@ -2329,7 +2360,7 @@ version = "0.13.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "b99da2f8558ca23c71f4fd15dc57c906239752dd27ff3c00a1d56b685b7cbfec"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "log",
  "polling",
  "rustix",
@@ -2367,7 +2398,7 @@ dependencies = [
  "cap-primitives",
  "cap-std",
  "io-lifetimes",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
 ]
 
 [[package]]
@@ -2395,7 +2426,7 @@ dependencies = [
  "ipnet",
  "maybe-owned",
  "rustix",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
  "winx",
 ]
 
@@ -2844,7 +2875,7 @@ version = "0.26.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "f79398230a6e2c08f5c9760610eb6924b52aa9e7950a619602baba59dcbbdbb2"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "block",
  "cocoa-foundation 0.2.0",
  "core-foundation 0.10.0",
@@ -2874,7 +2905,7 @@ version = "0.2.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "e14045fb83be07b5acf1c0884b2180461635b433455fa35d1cd6f17f1450679d"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "block",
  "core-foundation 0.10.0",
  "core-graphics-types 0.2.0",
@@ -2892,17 +2923,6 @@ dependencies = [
  "unicode-width",
 ]
 
-[[package]]
-name = "codespan-reporting"
-version = "0.12.0"
-source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fe6d2e5af09e8c8ad56c969f2157a3d4238cebc7c55f0a517728c38f7b200f81"
-dependencies = [
- "serde",
- "termcolor",
- "unicode-width",
-]
-
 [[package]]
 name = "collab"
 version = "0.44.0"
@@ -3354,7 +3374,7 @@ version = "0.24.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "fa95a34622365fa5bbf40b20b75dba8dfa8c94c734aea8ac9a5ca38af14316f1"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "core-foundation 0.10.0",
  "core-graphics-types 0.2.0",
  "foreign-types 0.5.0",
@@ -3378,7 +3398,7 @@ version = "0.2.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "3d44a101f213f6c4cdc1853d4b78aef6db6bdfa3468798cc1d9912f4735013eb"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "core-foundation 0.10.0",
  "libc",
 ]
@@ -3389,7 +3409,7 @@ version = "0.4.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "7e4583956b9806b69f73fcb23aee05eb3620efc282972f08f6a6db7504f8334d"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "block",
  "cfg-if",
  "core-foundation 0.10.0",
@@ -3477,7 +3497,7 @@ version = "0.13.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "e418dd4f5128c3e93eab12246391c54a20c496811131f85754dc8152ee207892"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "fontdb 0.16.2",
  "log",
  "rangemap",
@@ -3849,9 +3869,9 @@ checksum = "96a6ac251f4a2aca6b3f91340350eab87ae57c3f127ffeb585e92bd336717991"
 
 [[package]]
 name = "cxx"
-version = "1.0.151"
+version = "1.0.134"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "fdb3e596b379180315d2f934231e233a2fc745041f88231807774093d8de45f2"
+checksum = "a5a32d755fe20281b46118ee4b507233311fb7a48a0cfd42f554b93640521a2f"
 dependencies = [
  "cc",
  "cxxbridge-cmd",
@@ -3863,12 +3883,12 @@ dependencies = [
 
 [[package]]
 name = "cxx-build"
-version = "1.0.151"
+version = "1.0.134"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "3743fae7f47620cd34ec23bab819db9ee52da93166a058f87ab0ad99d777dc9b"
+checksum = "11645536ada5d1c8804312cbffc9ab950f2216154de431de930da47ca6955199"
 dependencies = [
  "cc",
- "codespan-reporting 0.12.0",
+ "codespan-reporting",
  "proc-macro2",
  "quote",
  "scratch",
@@ -3877,12 +3897,12 @@ dependencies = [
 
 [[package]]
 name = "cxxbridge-cmd"
-version = "1.0.151"
+version = "1.0.134"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "aaea0273c049b126a3918df88a1670c9c0168e0738df9370a988ff69070d4fff"
+checksum = "ebcc9c78e3c7289665aab921a2b394eaffe8bdb369aa18d81ffc0f534fd49385"
 dependencies = [
  "clap",
- "codespan-reporting 0.12.0",
+ "codespan-reporting",
  "proc-macro2",
  "quote",
  "syn 2.0.100",
@@ -3890,15 +3910,15 @@ dependencies = [
 
 [[package]]
 name = "cxxbridge-flags"
-version = "1.0.151"
+version = "1.0.134"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "020a9a3d6b792aab7f30f6e323893ad7f45052e572cde5d014c47fe67c89495f"
+checksum = "3a22a87bd9e78d7204d793261470a4c9d585154fddd251828d8aefbb5f74c3bf"
 
 [[package]]
 name = "cxxbridge-macro"
-version = "1.0.151"
+version = "1.0.134"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "ee54cd01f94db0328c4c73036d38bd8c3bb88927e953d05ffefe743edbf4eb68"
+checksum = "1dfdb020ff8787c5daf6e0dca743005cc8782868faeadfbabb8824ede5cb1c72"
 dependencies = [
  "proc-macro2",
  "quote",
@@ -4643,7 +4663,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "33d852cb9b869c2a9b3df2f71a3074817f01e1844f839a144f5fcef059a4eb5d"
 dependencies = [
  "libc",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
 ]
 
 [[package]]
@@ -5076,9 +5096,9 @@ checksum = "0ce7134b9999ecaf8bcd65542e436736ef32ddca1b3e06094cb6ec5755203b80"
 
 [[package]]
 name = "flate2"
-version = "1.0.35"
+version = "1.1.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "c936bfdafb507ebbf50b8074c54fa31c5be9a1e7e5f467dd659697041407d07c"
+checksum = "11faaf5a5236997af9848be0bef4db95824b1d534ebc64d0f0c6cf3e67bd38dc"
 dependencies = [
  "crc32fast",
  "miniz_oxide",
@@ -5131,7 +5151,7 @@ name = "font-kit"
 version = "0.14.1"
 source = "git+https://github.com/zed-industries/font-kit?rev=5474cfad4b719a72ec8ed2cb7327b2b01fd10568#5474cfad4b719a72ec8ed2cb7327b2b01fd10568"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "byteorder",
  "core-foundation 0.10.0",
  "core-graphics 0.24.0",
@@ -5308,7 +5328,7 @@ checksum = "5e2e6123af26f0f2c51cc66869137080199406754903cc926a7690401ce09cb4"
 dependencies = [
  "io-lifetimes",
  "rustix",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
 ]
 
 [[package]]
@@ -5331,7 +5351,7 @@ checksum = "42703706b716c37f96a77aea830392ad231f44c9e9a67872fa5548707e11b11c"
 name = "fsevent"
 version = "0.1.0"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "core-foundation 0.10.0",
  "fsevent-sys 3.1.0",
  "parking_lot",
@@ -5659,7 +5679,7 @@ version = "0.20.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "5220b8ba44c68a9a7f7a7659e864dd73692e417ef0211bea133c7b74e031eeb9"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "libc",
  "libgit2-sys",
  "log",
@@ -5825,7 +5845,7 @@ version = "0.6.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "fbcd2dba93594b227a1f57ee09b8b9da8892c34d55aa332e034a228d0fe6a171"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "gpu-alloc-types",
 ]
 
@@ -5846,7 +5866,7 @@ version = "0.3.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "98ff03b468aa837d70984d55f5d3f846f6ec31fe34bbb97c4f85219caeee1ca4"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
 ]
 
 [[package]]
@@ -5858,7 +5878,7 @@ dependencies = [
  "ashpd",
  "async-task",
  "backtrace",
- "bindgen 0.70.1",
+ "bindgen 0.71.1",
  "blade-graphics",
  "blade-macros",
  "blade-util",
@@ -6159,7 +6179,7 @@ version = "0.21.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "bd54745cfacb7b97dee45e8fdb91814b62bccddb481debb7de0f9ee6b7bf5b43"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "byteorder",
  "heed-traits",
  "heed-types",
@@ -6719,9 +6739,9 @@ dependencies = [
 
 [[package]]
 name = "image"
-version = "0.25.5"
+version = "0.25.6"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "cd6f44aed642f18953a158afeb30206f4d50da59fbc66ecb53c66488de73563b"
+checksum = "db35664ce6b9810857a38a906215e75a9c879f0696556a39f59c62829710251a"
 dependencies = [
  "bytemuck",
  "byteorder-lite",
@@ -6896,7 +6916,7 @@ version = "0.11.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "f37dccff2791ab604f9babef0ba14fbe0be30bd368dc541e2b08d07c8aa908f3"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "inotify-sys",
  "libc",
 ]
@@ -6966,7 +6986,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "2285ddfe3054097ef4b2fe909ef8c3bcd1ea52a8f0d274416caebeef39f04a65"
 dependencies = [
  "io-lifetimes",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
 ]
 
 [[package]]
@@ -7589,6 +7609,12 @@ version = "0.2.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "884e2677b40cc8c339eaefcb701c32ef1fd2493d71118dc0ca4b6a736c93bd67"
 
+[[package]]
+name = "leb128fmt"
+version = "0.1.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "09edd9e8b54e49e587e4f6295a7d29c3ea94d469cb40ab8ca70b288248a81db2"
+
 [[package]]
 name = "lebe"
 version = "0.5.2"
@@ -7640,7 +7666,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "fc2f4eb4bc735547cfed7c0a4922cbd04a4655978c09b54f1f7b228750664c34"
 dependencies = [
  "cfg-if",
- "windows-targets 0.48.5",
+ "windows-targets 0.52.6",
 ]
 
 [[package]]
@@ -7665,7 +7691,7 @@ version = "0.1.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "c0ff37bd590ca25063e35af745c343cb7a0271906fb7b37e4813e8f79f00268d"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "libc",
  "redox_syscall 0.5.8",
 ]
@@ -7718,9 +7744,9 @@ dependencies = [
 
 [[package]]
 name = "link-cplusplus"
-version = "1.0.10"
+version = "1.0.9"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "4a6f6da007f968f9def0d65a05b187e2960183de70c160204ecfccf0ee330212"
+checksum = "9d240c6f7e1ba3a28b0249f774e6a9dd0175054b52dfbb61b16eb8505c3785c9"
 dependencies = [
  "cc",
 ]
@@ -7925,9 +7951,9 @@ dependencies = [
 
 [[package]]
 name = "log"
-version = "0.4.26"
+version = "0.4.27"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "30bde2b3dc3671ae49d8e2e9f044c7c005836e7a023ee57cffa25ab82764bb9e"
+checksum = "13dc2df351e3202783a1fe0d44375f7295ffb4049267b0f3018346dc122a1d94"
 dependencies = [
  "serde",
  "value-bag",
@@ -8230,7 +8256,7 @@ name = "media"
 version = "0.1.0"
 dependencies = [
  "anyhow",
- "bindgen 0.70.1",
+ "bindgen 0.71.1",
  "core-foundation 0.10.0",
  "core-video",
  "ctor",
@@ -8286,7 +8312,7 @@ version = "0.29.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "7ecfd3296f8c56b7c1f6fbac3c71cefa9d78ce009850c45000015f206dc7fa21"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "block",
  "core-graphics-types 0.1.3",
  "foreign-types 0.5.0",
@@ -8342,9 +8368,9 @@ checksum = "68354c5c6bd36d73ff3feceb05efa59b6acb7626617f4962be322a825e61f79a"
 
 [[package]]
 name = "miniz_oxide"
-version = "0.8.0"
+version = "0.8.5"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "e2d80299ef12ff69b16a84bb182e3b9df68b5a91574d3d4fa6e41b65deec4df1"
+checksum = "8e3e04debbb59698c15bacbb6d93584a8c0ca9cc3213cb423d31f760d8843ce5"
 dependencies = [
  "adler2",
  "simd-adler32",
@@ -8437,6 +8463,12 @@ version = "0.8.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "e5ce46fe64a9d73be07dcbe690a38ce1b293be448fd8ce1e6c1b8062c9f72c6a"
 
+[[package]]
+name = "multimap"
+version = "0.10.0"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "defc4c55412d89136f966bbb339008b474350e5e6e78d2714439c386b3137a03"
+
 [[package]]
 name = "naga"
 version = "23.1.0"
@@ -8445,9 +8477,9 @@ checksum = "364f94bc34f61332abebe8cad6f6cd82a5b65cff22c828d05d0968911462ca4f"
 dependencies = [
  "arrayvec",
  "bit-set 0.8.0",
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "cfg_aliases 0.1.1",
- "codespan-reporting 0.11.1",
+ "codespan-reporting",
  "hexf-parse",
  "indexmap",
  "log",
@@ -8514,7 +8546,7 @@ version = "0.8.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "2076a31b7010b17a38c01907c45b945e8f11495ee4dd588309718901b1f7a5b7"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "jni-sys",
  "log",
  "ndk-sys",
@@ -8549,7 +8581,7 @@ version = "0.29.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "71e2746dc3a24dd78b3cfcb7be93368c6de9963d30f43a6a73998a9cf4b17b46"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "cfg-if",
  "cfg_aliases 0.2.1",
  "libc",
@@ -8633,7 +8665,7 @@ version = "8.0.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "2fee8403b3d66ac7b26aee6e40a897d85dc5ce26f44da36b8b73e987cc52e943"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "filetime",
  "fsevent-sys 4.1.0",
  "inotify",
@@ -8651,7 +8683,7 @@ name = "notify"
 version = "8.0.0"
 source = "git+https://github.com/zed-industries/notify.git?rev=bbb9ea5ae52b253e095737847e367c30653a2e96#bbb9ea5ae52b253e095737847e367c30653a2e96"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "filetime",
  "fsevent-sys 4.1.0",
  "inotify",
@@ -8927,7 +8959,7 @@ version = "0.2.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "e4e89ad9e3d7d297152b17d39ed92cd50ca8063a89a9fa569046d41568891eff"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "block2",
  "libc",
  "objc2",
@@ -8943,7 +8975,7 @@ version = "0.2.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "74dd3b56391c7a0596a295029734d3c1c5e7e510a4cb30245f8221ccea96b009"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "block2",
  "objc2",
  "objc2-core-location",
@@ -8967,7 +8999,7 @@ version = "0.2.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "617fbf49e071c178c0b24c080767db52958f716d9eabdf0890523aeae54773ef"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "block2",
  "objc2",
  "objc2-foundation",
@@ -9009,7 +9041,7 @@ version = "0.2.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "0ee638a5da3799329310ad4cfa62fbf045d5f56e3ef5ba4149e7452dcf89d5a8"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "block2",
  "libc",
  "objc2",
@@ -9033,7 +9065,7 @@ version = "0.2.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "dd0cba1276f6023976a406a14ffa85e1fdd19df6b0f737b063b95f6c8c7aadd6"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "block2",
  "objc2",
  "objc2-foundation",
@@ -9045,7 +9077,7 @@ version = "0.2.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "e42bee7bff906b14b167da2bac5efe6b6a07e6f7c0a21a7308d40c960242dc7a"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "block2",
  "objc2",
  "objc2-foundation",
@@ -9068,7 +9100,7 @@ version = "0.2.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "b8bb46798b20cd6b91cbd113524c490f1686f4c4e8f49502431415f3512e2b6f"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "block2",
  "objc2",
  "objc2-cloud-kit",
@@ -9100,7 +9132,7 @@ version = "0.2.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "76cfcbf642358e8689af64cee815d139339f3ed8ad05103ed5eaf73db8d84cb3"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "block2",
  "objc2",
  "objc2-core-location",
@@ -9162,9 +9194,9 @@ checksum = "945462a4b81e43c4e3ba96bd7b49d834c6f61198356aa858733bc4acf3cbe62e"
 
 [[package]]
 name = "oo7"
-version = "0.4.1"
+version = "0.4.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "72c84df357c7049f98c8b157abe71ee751531166c14ba09366e08bc6ab1ea2c9"
+checksum = "6cb23d3ec3527d65a83be1c1795cb883c52cfa57147d42acc797127df56fc489"
 dependencies = [
  "aes",
  "ashpd",
@@ -9243,7 +9275,7 @@ version = "0.10.70"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "61cfb4e166a8bb8c9b55c500bc2308550148ece889be90f609377e58140f42c6"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "cfg-if",
  "foreign-types 0.3.2",
  "libc",
@@ -10755,7 +10787,7 @@ dependencies = [
  "itertools 0.10.5",
  "lazy_static",
  "log",
- "multimap",
+ "multimap 0.8.3",
  "petgraph",
  "prost 0.9.0",
  "prost-types 0.9.0",
@@ -10771,10 +10803,10 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "22505a5c94da8e3b7c2996394d1c933236c4d743e81a410bcca4e6989fc066a4"
 dependencies = [
  "bytes 1.10.1",
- "heck 0.4.1",
+ "heck 0.5.0",
  "itertools 0.12.1",
  "log",
- "multimap",
+ "multimap 0.10.0",
  "once_cell",
  "petgraph",
  "prettyplease",
@@ -10882,7 +10914,7 @@ version = "0.10.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "76979bea66e7875e7509c4ec5300112b316af87fa7a252ca91c448b32dfe3993"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "memchr",
  "pulldown-cmark-escape",
  "unicase",
@@ -10894,7 +10926,7 @@ version = "0.12.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "f86ba2052aebccc42cbbb3ed234b8b13ce76f75c3551a303cb2bcffcff12bb14"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "memchr",
  "unicase",
 ]
@@ -10999,7 +11031,7 @@ dependencies = [
  "once_cell",
  "socket2",
  "tracing",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
 ]
 
 [[package]]
@@ -11275,7 +11307,7 @@ version = "0.5.8"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "03a862b389f93e68874fbf580b9de08dd02facb9a788ebadaf4a3fd33cf58834"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
 ]
 
 [[package]]
@@ -11919,13 +11951,13 @@ version = "0.38.42"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "f93dc38ecbab2eb790ff964bb77fa94faf256fd3e73285fd7ba0903b76bedb85"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "errno 0.3.10",
  "itoa",
  "libc",
  "linux-raw-sys",
  "once_cell",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
 ]
 
 [[package]]
@@ -12036,7 +12068,7 @@ dependencies = [
  "security-framework 3.0.1",
  "security-framework-sys",
  "webpki-root-certs",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
 ]
 
 [[package]]
@@ -12079,7 +12111,7 @@ version = "0.14.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "cfb9cf8877777222e4a3bc7eb247e398b56baba500c38c1c46842431adc8b55c"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "bytemuck",
  "libm",
  "smallvec",
@@ -12096,7 +12128,7 @@ version = "0.20.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "fd3c7c96f8a08ee34eff8857b11b49b07d71d1c3f4e88f8a88d4c9e9f90b1702"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "bytemuck",
  "core_maths",
  "log",
@@ -12193,9 +12225,9 @@ checksum = "94143f37725109f92c262ed2cf5e59bce7498c01bcc1502d7b9afe439a4e9f49"
 
 [[package]]
 name = "scratch"
-version = "1.0.8"
+version = "1.0.7"
 source = "registry+https://github.com/rust-lang/crates.io-index"
-checksum = "9f6280af86e5f559536da57a45ebc84948833b3bee313a7dd25232e09c878a52"
+checksum = "a3cf7c11c38cb994f3d40e8a8cde3bbd1f72a435e4c49e85d6553d8312306152"
 
 [[package]]
 name = "scrypt"
@@ -12319,7 +12351,7 @@ version = "0.1.0"
 dependencies = [
  "any_vec",
  "anyhow",
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "client",
  "collections",
  "editor",
@@ -12361,7 +12393,7 @@ version = "2.11.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "897b2245f0b511c87893af39b033e5ca9cce68824c4d7e7630b5a1d339658d02"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "core-foundation 0.9.4",
  "core-foundation-sys",
  "libc",
@@ -12374,7 +12406,7 @@ version = "3.0.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "e1415a607e92bec364ea2cf9264646dcce0f91e6d65281bd6f2819cca3bf39c8"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "core-foundation 0.10.0",
  "core-foundation-sys",
  "libc",
@@ -12974,7 +13006,7 @@ version = "0.3.0+sdk-1.3.268.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "eda41003dc44290527a59b13432d4a0379379fa074b70174882adfbdfd917844"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
 ]
 
 [[package]]
@@ -13141,7 +13173,7 @@ dependencies = [
  "atoi",
  "base64 0.22.1",
  "bigdecimal",
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "byteorder",
  "bytes 1.10.1",
  "chrono",
@@ -13188,7 +13220,7 @@ dependencies = [
  "atoi",
  "base64 0.22.1",
  "bigdecimal",
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "byteorder",
  "chrono",
  "crc",
@@ -13651,7 +13683,7 @@ version = "0.6.1"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "3c879d448e9d986b661742763247d3693ed13609438cf3d006f51f5368a5ba6b"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "core-foundation 0.9.4",
  "system-configuration-sys 0.6.0",
 ]
@@ -13695,13 +13727,13 @@ version = "0.27.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "cc4592f674ce18521c2a81483873a49596655b179f71c5e05d10c1fe66c78745"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "cap-fs-ext",
  "cap-std",
  "fd-lock",
  "io-lifetimes",
  "rustix",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
  "winx",
 ]
 
@@ -13843,7 +13875,7 @@ dependencies = [
  "getrandom 0.3.1",
  "once_cell",
  "rustix",
- "windows-sys 0.52.0",
+ "windows-sys 0.59.0",
 ]
 
 [[package]]
@@ -14525,7 +14557,7 @@ version = "0.4.4"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "61c5bb1d698276a2443e5ecfabc1008bf15a36c12e6a7176e7bf089ea9131140"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "bytes 1.10.1",
  "futures-core",
  "futures-util",
@@ -15456,7 +15488,7 @@ source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "a5924018406ce0063cd67f8e008104968b74b563ee1b85dde3ed1f7cb87d3dbd"
 dependencies = [
  "arrayvec",
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "cursor-icon",
  "log",
  "memchr",
@@ -15629,6 +15661,16 @@ dependencies = [
  "wasmparser 0.221.3",
 ]
 
+[[package]]
+name = "wasm-encoder"
+version = "0.227.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "80bb72f02e7fbf07183443b27b0f3d4144abf8c114189f2e088ed95b696a7822"
+dependencies = [
+ "leb128fmt",
+ "wasmparser 0.227.1",
+]
+
 [[package]]
 name = "wasm-metadata"
 version = "0.201.0"
@@ -15661,6 +15703,25 @@ dependencies = [
  "wasmparser 0.221.3",
 ]
 
+[[package]]
+name = "wasm-metadata"
+version = "0.227.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "ce1ef0faabbbba6674e97a56bee857ccddf942785a336c8b47b42373c922a91d"
+dependencies = [
+ "anyhow",
+ "auditable-serde",
+ "flate2",
+ "indexmap",
+ "serde",
+ "serde_derive",
+ "serde_json",
+ "spdx",
+ "url",
+ "wasm-encoder 0.227.1",
+ "wasmparser 0.227.1",
+]
+
 [[package]]
 name = "wasm-streams"
 version = "0.4.2"
@@ -15680,7 +15741,7 @@ version = "0.201.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "84e5df6dba6c0d7fafc63a450f1738451ed7a0b52295d83e868218fa286bf708"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "indexmap",
  "semver",
 ]
@@ -15691,13 +15752,25 @@ version = "0.221.3"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "d06bfa36ab3ac2be0dee563380147a5b81ba10dd8885d7fbbc9eb574be67d185"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "hashbrown 0.15.2",
  "indexmap",
  "semver",
  "serde",
 ]
 
+[[package]]
+name = "wasmparser"
+version = "0.227.1"
+source = "registry+https://github.com/rust-lang/crates.io-index"
+checksum = "0f51cad774fb3c9461ab9bccc9c62dfb7388397b5deda31bf40e8108ccd678b2"
+dependencies = [
+ "bitflags 2.9.0",
+ "hashbrown 0.15.2",
+ "indexmap",
+ "semver",
+]
+
 [[package]]
 name = "wasmprinter"
 version = "0.221.3"
@@ -15717,7 +15790,7 @@ checksum = "11976a250672556d1c4c04c6d5d7656ac9192ac9edc42a4587d6c21460010e69"
 dependencies = [
  "anyhow",
  "async-trait",
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "bumpalo",
  "cc",
  "cfg-if",
@@ -15923,7 +15996,7 @@ checksum = "8d1be69bfcab1bdac74daa7a1f9695ab992b9c8e21b9b061e7d66434097e0ca4"
 dependencies = [
  "anyhow",
  "async-trait",
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "bytes 1.10.1",
  "cap-fs-ext",
  "cap-net-ext",
@@ -16004,7 +16077,7 @@ version = "0.31.8"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "c2120de3d33638aaef5b9f4472bff75f07c56379cf76ea320bd3a3d65ecaf73f"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "rustix",
  "wayland-backend",
  "wayland-scanner",
@@ -16027,7 +16100,7 @@ version = "0.31.2"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "8f81f365b8b4a97f422ac0e8737c438024b5951734506b0e1d775c73030561f4"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "wayland-backend",
  "wayland-client",
  "wayland-scanner",
@@ -16039,7 +16112,7 @@ version = "0.2.0"
 source = "registry+https://github.com/rust-lang/crates.io-index"
 checksum = "23803551115ff9ea9bce586860c5c5a971e360825a0309264102a9495a5ff479"
 dependencies = [
- "bitflags 2.8.0",
+ "bitflags 2.9.0",
  "wayland-backend",
  "wayland-client",
  "wayland-protocols",

crates/assistant2/src/active_thread.rs 🔗

@@ -1412,7 +1412,11 @@ impl ActiveThread {
         )
     }
 
-    fn render_tool_use(&self, tool_use: ToolUse, cx: &mut Context<Self>) -> impl IntoElement {
+    fn render_tool_use(
+        &self,
+        tool_use: ToolUse,
+        cx: &mut Context<Self>,
+    ) -> impl IntoElement + use<> {
         let is_open = self
             .expanded_tool_uses
             .get(&tool_use.id)

crates/assistant2/src/assistant_configuration.rs 🔗

@@ -105,7 +105,7 @@ impl AssistantConfiguration {
         &mut self,
         provider: &Arc<dyn LanguageModelProvider>,
         cx: &mut Context<Self>,
-    ) -> impl IntoElement {
+    ) -> impl IntoElement + use<> {
         let provider_id = provider.id().0.clone();
         let provider_name = provider.name().0.clone();
         let configuration_view = self

crates/assistant2/src/context_store.rs 🔗

@@ -687,7 +687,7 @@ pub fn refresh_context_store_text(
     context_store: Entity<ContextStore>,
     changed_buffers: &HashSet<Entity<Buffer>>,
     cx: &App,
-) -> impl Future<Output = Vec<ContextId>> {
+) -> impl Future<Output = Vec<ContextId>> + use<> {
     let mut tasks = Vec::new();
 
     for context in &context_store.read(cx).context {
@@ -855,7 +855,7 @@ fn refresh_thread_text(
 fn refresh_context_buffer(
     context_buffer: &ContextBuffer,
     cx: &App,
-) -> Option<impl Future<Output = ContextBuffer>> {
+) -> Option<impl Future<Output = ContextBuffer> + use<>> {
     let buffer = context_buffer.buffer.read(cx);
     let path = buffer_path_log_err(buffer)?;
     if buffer.version.changed_since(&context_buffer.version) {
@@ -875,7 +875,7 @@ fn refresh_context_buffer(
 fn refresh_context_symbol(
     context_symbol: &ContextSymbol,
     cx: &App,
-) -> Option<impl Future<Output = ContextSymbol>> {
+) -> Option<impl Future<Output = ContextSymbol> + use<>> {
     let buffer = context_symbol.buffer.read(cx);
     let path = buffer_path_log_err(buffer)?;
     let project_path = buffer.project_path(cx)?;

crates/assistant2/src/thread.rs 🔗

@@ -1192,7 +1192,7 @@ impl Thread {
     pub fn use_pending_tools(
         &mut self,
         cx: &mut Context<Self>,
-    ) -> impl IntoIterator<Item = PendingToolUse> {
+    ) -> impl IntoIterator<Item = PendingToolUse> + use<> {
         let request = self.to_completion_request(RequestKind::Chat, cx);
         let messages = Arc::new(request.messages);
         let pending_tool_uses = self

crates/assistant_context_editor/src/context_editor.rs 🔗

@@ -3413,7 +3413,7 @@ impl ContextEditorToolbarItem {
 pub fn render_remaining_tokens(
     context_editor: &Entity<ContextEditor>,
     cx: &App,
-) -> Option<impl IntoElement> {
+) -> Option<impl IntoElement + use<>> {
     let context = &context_editor.read(cx).context;
 
     let (token_count_color, token_count, max_token_count, tooltip) = match token_state(context, cx)?

crates/assistant_settings/src/assistant_settings.rs 🔗

@@ -105,8 +105,8 @@ impl JsonSchema for AssistantSettingsContent {
         VersionedAssistantSettingsContent::schema_name()
     }
 
-    fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> Schema {
-        VersionedAssistantSettingsContent::json_schema(gen)
+    fn json_schema(r#gen: &mut schemars::r#gen::SchemaGenerator) -> Schema {
+        VersionedAssistantSettingsContent::json_schema(r#gen)
     }
 
     fn is_referenceable() -> bool {
@@ -416,7 +416,7 @@ pub struct LanguageModelSelection {
     pub model: String,
 }
 
-fn providers_schema(_: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
+fn providers_schema(_: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
     schemars::schema::SchemaObject {
         enum_values: Some(vec![
             "anthropic".into(),

crates/assistant_slash_commands/src/file_command.rs 🔗

@@ -221,7 +221,7 @@ fn collect_files(
     project: Entity<Project>,
     glob_inputs: &[String],
     cx: &mut App,
-) -> impl Stream<Item = Result<SlashCommandEvent>> {
+) -> impl Stream<Item = Result<SlashCommandEvent>> + use<> {
     let Ok(matchers) = glob_inputs
         .into_iter()
         .map(|glob_input| {
@@ -782,7 +782,12 @@ mod test {
         assert_eq!(result.sections[6].label, "summercamp");
         assert_eq!(result.sections[7].label, separator!("zed/assets/themes"));
 
-        assert_eq!(result.text, separator!("zed/assets/themes\n```zed/assets/themes/LICENSE\n1\n```\n\nsummercamp\n```zed/assets/themes/summercamp/LICENSE\n1\n```\n\nsubdir\n```zed/assets/themes/summercamp/subdir/LICENSE\n1\n```\n\nsubsubdir\n```zed/assets/themes/summercamp/subdir/subsubdir/LICENSE\n3\n```\n\n"));
+        assert_eq!(
+            result.text,
+            separator!(
+                "zed/assets/themes\n```zed/assets/themes/LICENSE\n1\n```\n\nsummercamp\n```zed/assets/themes/summercamp/LICENSE\n1\n```\n\nsubdir\n```zed/assets/themes/summercamp/subdir/LICENSE\n1\n```\n\nsubsubdir\n```zed/assets/themes/summercamp/subdir/subsubdir/LICENSE\n3\n```\n\n"
+            )
+        );
 
         // Ensure that the project lasts until after the last await
         drop(project);

crates/assistant_tools/src/bash_tool.rs 🔗

@@ -81,7 +81,9 @@ impl Tool for BashTool {
             };
 
             if worktrees.next().is_some() {
-                return Task::ready(Err(anyhow!("'.' is ambiguous in multi-root workspaces. Please specify a root directory explicitly.")));
+                return Task::ready(Err(anyhow!(
+                    "'.' is ambiguous in multi-root workspaces. Please specify a root directory explicitly."
+                )));
             }
 
             only_worktree.read(cx).abs_path()

crates/assistant_tools/src/edit_files_tool.rs 🔗

@@ -526,7 +526,8 @@ impl EditToolRequest {
                         }
                     }
 
-                    write!(&mut output,
+                    write!(
+                        &mut output,
                         "The SEARCH section must exactly match an existing block of lines including all white \
                         space, comments, indentation, docstrings, etc."
                     )?;
@@ -545,7 +546,8 @@ impl EditToolRequest {
                 }
 
                 if has_errors {
-                    writeln!(&mut output,
+                    writeln!(
+                        &mut output,
                         "\n\nYou can fix errors by running the tool again. You can include instructions, \
                         but errors are part of the conversation so you don't need to repeat them.",
                     )?;

crates/audio/src/assets.rs 🔗

@@ -35,7 +35,7 @@ impl SoundRegistry {
         cx.set_global(GlobalSoundRegistry(SoundRegistry::new(source)));
     }
 
-    pub fn get(&self, name: &str) -> Result<impl Source<Item = f32>> {
+    pub fn get(&self, name: &str) -> Result<impl Source<Item = f32> + use<>> {
         if let Some(wav) = self.cache.lock().get(name) {
             return Ok(wav.clone());
         }

crates/aws_http_client/src/aws_http_client.rs 🔗

@@ -32,7 +32,7 @@ impl AwsConnector for AwsHttpConnector {
         let req = match request.try_into_http1x() {
             Ok(req) => req,
             Err(err) => {
-                return HttpConnectorFuture::ready(Err(ConnectorError::other(err.into(), None)))
+                return HttpConnectorFuture::ready(Err(ConnectorError::other(err.into(), None)));
             }
         };
 

crates/buffer_diff/src/buffer_diff.rs 🔗

@@ -433,79 +433,82 @@ impl BufferDiffInner {
 
         let max_point = buffer.max_point();
         let mut summaries = buffer.summaries_for_anchors_with_payload::<Point, _, _>(anchor_iter);
-        iter::from_fn(move || loop {
-            let (start_point, (start_anchor, start_base)) = summaries.next()?;
-            let (mut end_point, (mut end_anchor, end_base)) = summaries.next()?;
-
-            if !start_anchor.is_valid(buffer) {
-                continue;
-            }
-
-            if end_point.column > 0 && end_point < max_point {
-                end_point.row += 1;
-                end_point.column = 0;
-                end_anchor = buffer.anchor_before(end_point);
-            }
-
-            let mut secondary_status = DiffHunkSecondaryStatus::NoSecondaryHunk;
-
-            let mut has_pending = false;
-            if start_anchor
-                .cmp(&pending_hunks_cursor.start().buffer_range.start, buffer)
-                .is_gt()
-            {
-                pending_hunks_cursor.seek_forward(&start_anchor, Bias::Left, buffer);
-            }
+        iter::from_fn(move || {
+            loop {
+                let (start_point, (start_anchor, start_base)) = summaries.next()?;
+                let (mut end_point, (mut end_anchor, end_base)) = summaries.next()?;
 
-            if let Some(pending_hunk) = pending_hunks_cursor.item() {
-                let mut pending_range = pending_hunk.buffer_range.to_point(buffer);
-                if pending_range.end.column > 0 {
-                    pending_range.end.row += 1;
-                    pending_range.end.column = 0;
+                if !start_anchor.is_valid(buffer) {
+                    continue;
                 }
 
-                if pending_range == (start_point..end_point) {
-                    if !buffer.has_edits_since_in_range(
-                        &pending_hunk.buffer_version,
-                        start_anchor..end_anchor,
-                    ) {
-                        has_pending = true;
-                        secondary_status = pending_hunk.new_status;
-                    }
+                if end_point.column > 0 && end_point < max_point {
+                    end_point.row += 1;
+                    end_point.column = 0;
+                    end_anchor = buffer.anchor_before(end_point);
                 }
-            }
 
-            if let (Some(secondary_cursor), false) = (secondary_cursor.as_mut(), has_pending) {
+                let mut secondary_status = DiffHunkSecondaryStatus::NoSecondaryHunk;
+
+                let mut has_pending = false;
                 if start_anchor
-                    .cmp(&secondary_cursor.start().buffer_range.start, buffer)
+                    .cmp(&pending_hunks_cursor.start().buffer_range.start, buffer)
                     .is_gt()
                 {
-                    secondary_cursor.seek_forward(&start_anchor, Bias::Left, buffer);
+                    pending_hunks_cursor.seek_forward(&start_anchor, Bias::Left, buffer);
                 }
 
-                if let Some(secondary_hunk) = secondary_cursor.item() {
-                    let mut secondary_range = secondary_hunk.buffer_range.to_point(buffer);
-                    if secondary_range.end.column > 0 {
-                        secondary_range.end.row += 1;
-                        secondary_range.end.column = 0;
+                if let Some(pending_hunk) = pending_hunks_cursor.item() {
+                    let mut pending_range = pending_hunk.buffer_range.to_point(buffer);
+                    if pending_range.end.column > 0 {
+                        pending_range.end.row += 1;
+                        pending_range.end.column = 0;
+                    }
+
+                    if pending_range == (start_point..end_point) {
+                        if !buffer.has_edits_since_in_range(
+                            &pending_hunk.buffer_version,
+                            start_anchor..end_anchor,
+                        ) {
+                            has_pending = true;
+                            secondary_status = pending_hunk.new_status;
+                        }
                     }
-                    if secondary_range.is_empty() && secondary_hunk.diff_base_byte_range.is_empty()
+                }
+
+                if let (Some(secondary_cursor), false) = (secondary_cursor.as_mut(), has_pending) {
+                    if start_anchor
+                        .cmp(&secondary_cursor.start().buffer_range.start, buffer)
+                        .is_gt()
                     {
-                        // ignore
-                    } else if secondary_range == (start_point..end_point) {
-                        secondary_status = DiffHunkSecondaryStatus::HasSecondaryHunk;
-                    } else if secondary_range.start <= end_point {
-                        secondary_status = DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk;
+                        secondary_cursor.seek_forward(&start_anchor, Bias::Left, buffer);
+                    }
+
+                    if let Some(secondary_hunk) = secondary_cursor.item() {
+                        let mut secondary_range = secondary_hunk.buffer_range.to_point(buffer);
+                        if secondary_range.end.column > 0 {
+                            secondary_range.end.row += 1;
+                            secondary_range.end.column = 0;
+                        }
+                        if secondary_range.is_empty()
+                            && secondary_hunk.diff_base_byte_range.is_empty()
+                        {
+                            // ignore
+                        } else if secondary_range == (start_point..end_point) {
+                            secondary_status = DiffHunkSecondaryStatus::HasSecondaryHunk;
+                        } else if secondary_range.start <= end_point {
+                            secondary_status = DiffHunkSecondaryStatus::OverlapsWithSecondaryHunk;
+                        }
                     }
                 }
-            }
 
-            return Some(DiffHunk {
-                range: start_point..end_point,
-                diff_base_byte_range: start_base..end_base,
-                buffer_range: start_anchor..end_anchor,
-                secondary_status,
-            });
+                return Some(DiffHunk {
+                    range: start_point..end_point,
+                    diff_base_byte_range: start_base..end_base,
+                    buffer_range: start_anchor..end_anchor,
+                    secondary_status,
+                });
+            }
         })
     }
 
@@ -776,7 +779,7 @@ impl BufferDiff {
         language: Option<Arc<Language>>,
         language_registry: Option<Arc<LanguageRegistry>>,
         cx: &mut App,
-    ) -> impl Future<Output = BufferDiffInner> {
+    ) -> impl Future<Output = BufferDiffInner> + use<> {
         let base_text_pair;
         let base_text_exists;
         let base_text_snapshot;
@@ -818,7 +821,7 @@ impl BufferDiff {
         base_text: Option<Arc<String>>,
         base_text_snapshot: language::BufferSnapshot,
         cx: &App,
-    ) -> impl Future<Output = BufferDiffInner> {
+    ) -> impl Future<Output = BufferDiffInner> + use<> {
         let base_text_exists = base_text.is_some();
         let base_text_pair = base_text.map(|text| (text, base_text_snapshot.as_rope().clone()));
         cx.background_spawn(async move {
@@ -2071,7 +2074,7 @@ mod tests {
             )
         });
         let working_copy = working_copy.read_with(cx, |working_copy, _| working_copy.snapshot());
-        let mut index_text = if rng.gen() {
+        let mut index_text = if rng.r#gen() {
             Rope::from(head_text.as_str())
         } else {
             working_copy.as_rope().clone()

crates/call/src/call_impl/room.rs 🔗

@@ -243,7 +243,7 @@ impl Room {
         }
     }
 
-    fn app_will_quit(&mut self, cx: &mut Context<Self>) -> impl Future<Output = ()> {
+    fn app_will_quit(&mut self, cx: &mut Context<Self>) -> impl Future<Output = ()> + use<> {
         let task = if self.status.is_online() {
             let leave = self.leave_internal(cx);
             Some(cx.background_spawn(async move {
@@ -665,7 +665,7 @@ impl Room {
         Ok(())
     }
 
-    pub fn room_update_completed(&mut self) -> impl Future<Output = ()> {
+    pub fn room_update_completed(&mut self) -> impl Future<Output = ()> + use<> {
         let mut done_rx = self.room_update_completed_rx.clone();
         async move {
             while let Some(result) = done_rx.next().await {

crates/channel/src/channel_chat.rs 🔗

@@ -183,7 +183,7 @@ impl ChannelChat {
 
         let channel_id = self.channel_id;
         let pending_id = ChannelMessageId::Pending(post_inc(&mut self.next_pending_message_id));
-        let nonce = self.rng.gen();
+        let nonce = self.rng.r#gen();
         self.insert_messages(
             SumTree::from_item(
                 ChannelMessage {
@@ -257,7 +257,7 @@ impl ChannelChat {
             cx,
         );
 
-        let nonce: u128 = self.rng.gen();
+        let nonce: u128 = self.rng.r#gen();
 
         let request = self.rpc.request(proto::UpdateChannelMessage {
             channel_id: self.channel_id.0,

crates/channel/src/channel_store.rs 🔗

@@ -824,7 +824,10 @@ impl ChannelStore {
         })
     }
 
-    pub fn remove_channel(&self, channel_id: ChannelId) -> impl Future<Output = Result<()>> {
+    pub fn remove_channel(
+        &self,
+        channel_id: ChannelId,
+    ) -> impl Future<Output = Result<()>> + use<> {
         let client = self.client.clone();
         async move {
             client

crates/cli/src/main.rs 🔗

@@ -465,7 +465,7 @@ mod linux {
             match fork::fork() {
                 Ok(Fork::Parent(_)) => Ok(()),
                 Ok(Fork::Child) => {
-                    std::env::set_var(FORCE_CLI_MODE_ENV_VAR_NAME, "");
+                    unsafe { std::env::set_var(FORCE_CLI_MODE_ENV_VAR_NAME, "") };
                     if let Err(_) = fork::setsid() {
                         eprintln!("failed to setsid: {}", std::io::Error::last_os_error());
                         process::exit(1);
@@ -521,7 +521,7 @@ mod flatpak {
             paths.push(extra_path.into());
         }
 
-        env::set_var("LD_LIBRARY_PATH", env::join_paths(paths).unwrap());
+        unsafe { env::set_var("LD_LIBRARY_PATH", env::join_paths(paths).unwrap()) };
     }
 
     /// Restarts outside of the sandbox if currently running within it
@@ -562,7 +562,9 @@ mod flatpak {
         {
             if args.zed.is_none() {
                 args.zed = Some("/app/libexec/zed-editor".into());
-                env::set_var("ZED_UPDATE_EXPLANATION", "Please use flatpak to update zed");
+                unsafe {
+                    env::set_var("ZED_UPDATE_EXPLANATION", "Please use flatpak to update zed")
+                };
             }
         }
         args

crates/client/src/client.rs 🔗

@@ -817,7 +817,7 @@ impl Client {
             | Status::Reauthenticating { .. }
             | Status::ReconnectionError { .. } => false,
             Status::Connected { .. } | Status::Connecting { .. } | Status::Reconnecting { .. } => {
-                return Ok(())
+                return Ok(());
             }
             Status::UpgradeRequired => return Err(EstablishConnectionError::UpgradeRequired)?,
         };
@@ -1024,7 +1024,7 @@ impl Client {
         &self,
         http: Arc<HttpClientWithUrl>,
         release_channel: Option<ReleaseChannel>,
-    ) -> impl Future<Output = Result<url::Url>> {
+    ) -> impl Future<Output = Result<url::Url>> + use<> {
         #[cfg(any(test, feature = "test-support"))]
         let url_override = self.rpc_url.read().clone();
 
@@ -1444,7 +1444,7 @@ impl Client {
     pub fn request<T: RequestMessage>(
         &self,
         request: T,
-    ) -> impl Future<Output = Result<T::Response>> {
+    ) -> impl Future<Output = Result<T::Response>> + use<T> {
         self.request_envelope(request)
             .map_ok(|envelope| envelope.payload)
     }
@@ -1476,7 +1476,7 @@ impl Client {
     pub fn request_envelope<T: RequestMessage>(
         &self,
         request: T,
-    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> {
+    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> + use<T> {
         let client_id = self.id();
         log::debug!(
             "rpc request start. client_id:{}. name:{}",
@@ -1501,7 +1501,7 @@ impl Client {
         &self,
         envelope: proto::Envelope,
         request_type: &'static str,
-    ) -> impl Future<Output = Result<proto::Envelope>> {
+    ) -> impl Future<Output = Result<proto::Envelope>> + use<> {
         let client_id = self.id();
         log::debug!(
             "rpc request start. client_id:{}. name:{}",

crates/client/src/telemetry.rs 🔗

@@ -273,14 +273,14 @@ impl Telemetry {
     }
 
     #[cfg(any(test, feature = "test-support"))]
-    fn shutdown_telemetry(self: &Arc<Self>) -> impl Future<Output = ()> {
+    fn shutdown_telemetry(self: &Arc<Self>) -> impl Future<Output = ()> + use<> {
         Task::ready(())
     }
 
     // Skip calling this function in tests.
     // TestAppContext ends up calling this function on shutdown and it panics when trying to find the TelemetrySettings
     #[cfg(not(any(test, feature = "test-support")))]
-    fn shutdown_telemetry(self: &Arc<Self>) -> impl Future<Output = ()> {
+    fn shutdown_telemetry(self: &Arc<Self>) -> impl Future<Output = ()> + use<> {
         telemetry::event!("App Closed");
         // TODO: close final edit period and make sure it's sent
         Task::ready(())

crates/client/src/user.rs 🔗

@@ -581,7 +581,7 @@ impl UserStore {
         })
     }
 
-    pub fn clear_contacts(&self) -> impl Future<Output = ()> {
+    pub fn clear_contacts(&self) -> impl Future<Output = ()> + use<> {
         let (tx, mut rx) = postage::barrier::channel();
         self.update_contacts_tx
             .unbounded_send(UpdateContacts::Clear(tx))

crates/collab/src/api/billing.rs 🔗

@@ -534,7 +534,9 @@ async fn poll_stripe_events(
         if event_pages.page.has_more {
             if pages_of_already_processed_events >= NUMBER_OF_ALREADY_PROCESSED_PAGES_BEFORE_WE_STOP
             {
-                log::info!("Stripe events: stopping, saw {pages_of_already_processed_events} pages of already-processed events");
+                log::info!(
+                    "Stripe events: stopping, saw {pages_of_already_processed_events} pages of already-processed events"
+                );
                 break;
             } else {
                 log::info!("Stripe events: retrieving next page");

crates/collab/src/db.rs 🔗

@@ -853,7 +853,7 @@ fn db_status_to_proto(
             _ => {
                 return Err(anyhow!(
                     "Unexpected combination of status fields: {entry:?}"
-                ))
+                ));
             }
         };
     Ok(proto::StatusEntry {

crates/collab/src/db/tests.rs 🔗

@@ -74,7 +74,7 @@ impl TestDb {
         let mut rng = StdRng::from_entropy();
         let url = format!(
             "postgres://postgres@localhost/zed-test-{}",
-            rng.gen::<u128>()
+            rng.r#gen::<u128>()
         );
         let runtime = tokio::runtime::Builder::new_current_thread()
             .enable_io()

crates/collab/src/env.rs 🔗

@@ -20,7 +20,7 @@ pub fn get_dotenv_vars(current_dir: impl AsRef<Path>) -> Result<Vec<(String, Str
 
 pub fn load_dotenv() -> Result<()> {
     for (key, value) in get_dotenv_vars("./crates/collab")? {
-        std::env::set_var(key, value);
+        unsafe { std::env::set_var(key, value) };
     }
     Ok(())
 }

crates/collab/src/executor.rs 🔗

@@ -26,7 +26,7 @@ impl Executor {
         }
     }
 
-    pub fn sleep(&self, duration: Duration) -> impl Future<Output = ()> {
+    pub fn sleep(&self, duration: Duration) -> impl Future<Output = ()> + use<> {
         let this = self.clone();
         async move {
             match this {

crates/collab/src/llm/authorization.rs 🔗

@@ -193,7 +193,9 @@ mod tests {
                 .to_vec();
             assert_eq!(
                 String::from_utf8(response_body).unwrap(),
-                format!("access to {provider:?} models is not available in your region ({country_code})")
+                format!(
+                    "access to {provider:?} models is not available in your region ({country_code})"
+                )
             );
         }
     }

crates/collab/src/llm/db/tests.rs 🔗

@@ -26,7 +26,7 @@ impl TestLlmDb {
         let mut rng = StdRng::from_entropy();
         let url = format!(
             "postgres://postgres@localhost/zed-llm-test-{}",
-            rng.gen::<u128>()
+            rng.r#gen::<u128>()
         );
         let runtime = tokio::runtime::Builder::new_current_thread()
             .enable_io()

crates/collab/src/rpc.rs 🔗

@@ -724,7 +724,7 @@ impl Server {
         system_id: Option<String>,
         send_connection_id: Option<oneshot::Sender<ConnectionId>>,
         executor: Executor,
-    ) -> impl Future<Output = ()> {
+    ) -> impl Future<Output = ()> + use<> {
         let this = self.clone();
         let span = info_span!("handle connection", %address,
             connection_id=field::Empty,

crates/collab/src/tests/integration_tests.rs 🔗

@@ -5103,7 +5103,9 @@ async fn test_project_search(
                 results.entry(buffer).or_insert(ranges);
             }
             SearchResult::LimitReached => {
-                panic!("Unexpectedly reached search limit in tests. If you do want to assert limit-reached, change this panic call.")
+                panic!(
+                    "Unexpectedly reached search limit in tests. If you do want to assert limit-reached, change this panic call."
+                )
             }
         };
     }
@@ -5602,7 +5604,7 @@ async fn test_open_buffer_while_getting_definition_pointing_to_it(
 
     let definitions;
     let buffer_b2;
-    if rng.gen() {
+    if rng.r#gen() {
         definitions = project_b.update(cx_b, |p, cx| p.definition(&buffer_b1, 23, cx));
         (buffer_b2, _) = project_b
             .update(cx_b, |p, cx| {

crates/collab/src/tests/random_project_collaboration_tests.rs 🔗

@@ -279,7 +279,7 @@ impl RandomizedTest for ProjectCollaborationTest {
                             let project_root_name = root_name_for_project(&project, cx);
                             let mut paths = client.fs().paths(false);
                             paths.remove(0);
-                            let new_root_path = if paths.is_empty() || rng.gen() {
+                            let new_root_path = if paths.is_empty() || rng.r#gen() {
                                 Path::new(path!("/")).join(plan.next_root_dir_name())
                             } else {
                                 paths.choose(rng).unwrap().clone()
@@ -309,7 +309,7 @@ impl RandomizedTest for ProjectCollaborationTest {
                                     .choose(rng)
                             });
                             let Some(worktree) = worktree else { continue };
-                            let is_dir = rng.gen::<bool>();
+                            let is_dir = rng.r#gen::<bool>();
                             let mut full_path =
                                 worktree.read_with(cx, |w, _| PathBuf::from(w.root_name()));
                             full_path.push(gen_file_name(rng));
@@ -387,7 +387,7 @@ impl RandomizedTest for ProjectCollaborationTest {
                                             language::Bias::Left,
                                         )
                                     });
-                                    let detach = rng.gen();
+                                    let detach = rng.r#gen();
                                     break ClientOperation::RequestLspDataInBuffer {
                                         project_root_name,
                                         full_path,
@@ -460,7 +460,7 @@ impl RandomizedTest for ProjectCollaborationTest {
 
                 // Create or update a file or directory
                 96.. => {
-                    let is_dir = rng.gen::<bool>();
+                    let is_dir = rng.r#gen::<bool>();
                     let content;
                     let mut path;
                     let dir_paths = client.fs().directories(false);
@@ -1315,7 +1315,9 @@ impl RandomizedTest for ProjectCollaborationTest {
                     match (host_file, guest_file) {
                         (Some(host_file), Some(guest_file)) => {
                             assert_eq!(guest_file.path(), host_file.path());
-                            assert_eq!(guest_file.disk_state(), host_file.disk_state(),
+                            assert_eq!(
+                                guest_file.disk_state(),
+                                host_file.disk_state(),
                                 "guest {} disk_state does not match host {} for path {:?} in project {}",
                                 guest_user_id,
                                 host_user_id,
@@ -1347,52 +1349,54 @@ impl RandomizedTest for ProjectCollaborationTest {
                             .base_text_string()
                     });
                     assert_eq!(
-                            guest_diff_base, host_diff_base,
-                            "guest {} diff base does not match host's for path {path:?} in project {project_id}",
-                            client.username
-                        );
+                        guest_diff_base, host_diff_base,
+                        "guest {} diff base does not match host's for path {path:?} in project {project_id}",
+                        client.username
+                    );
 
                     let host_saved_version =
                         host_buffer.read_with(host_cx, |b, _| b.saved_version().clone());
                     let guest_saved_version =
                         guest_buffer.read_with(client_cx, |b, _| b.saved_version().clone());
                     assert_eq!(
-                            guest_saved_version, host_saved_version,
-                            "guest {} saved version does not match host's for path {path:?} in project {project_id}",
-                            client.username
-                        );
+                        guest_saved_version, host_saved_version,
+                        "guest {} saved version does not match host's for path {path:?} in project {project_id}",
+                        client.username
+                    );
 
                     let host_is_dirty = host_buffer.read_with(host_cx, |b, _| b.is_dirty());
                     let guest_is_dirty = guest_buffer.read_with(client_cx, |b, _| b.is_dirty());
                     assert_eq!(
-                            guest_is_dirty, host_is_dirty,
-                            "guest {} dirty state does not match host's for path {path:?} in project {project_id}",
-                            client.username
-                        );
+                        guest_is_dirty, host_is_dirty,
+                        "guest {} dirty state does not match host's for path {path:?} in project {project_id}",
+                        client.username
+                    );
 
                     let host_saved_mtime = host_buffer.read_with(host_cx, |b, _| b.saved_mtime());
                     let guest_saved_mtime =
                         guest_buffer.read_with(client_cx, |b, _| b.saved_mtime());
                     assert_eq!(
-                            guest_saved_mtime, host_saved_mtime,
-                            "guest {} saved mtime does not match host's for path {path:?} in project {project_id}",
-                            client.username
-                        );
+                        guest_saved_mtime, host_saved_mtime,
+                        "guest {} saved mtime does not match host's for path {path:?} in project {project_id}",
+                        client.username
+                    );
 
                     let host_is_dirty = host_buffer.read_with(host_cx, |b, _| b.is_dirty());
                     let guest_is_dirty = guest_buffer.read_with(client_cx, |b, _| b.is_dirty());
-                    assert_eq!(guest_is_dirty, host_is_dirty,
-                            "guest {} dirty status does not match host's for path {path:?} in project {project_id}",
-                            client.username
-                        );
+                    assert_eq!(
+                        guest_is_dirty, host_is_dirty,
+                        "guest {} dirty status does not match host's for path {path:?} in project {project_id}",
+                        client.username
+                    );
 
                     let host_has_conflict = host_buffer.read_with(host_cx, |b, _| b.has_conflict());
                     let guest_has_conflict =
                         guest_buffer.read_with(client_cx, |b, _| b.has_conflict());
-                    assert_eq!(guest_has_conflict, host_has_conflict,
-                            "guest {} conflict status does not match host's for path {path:?} in project {project_id}",
-                            client.username
-                        );
+                    assert_eq!(
+                        guest_has_conflict, host_has_conflict,
+                        "guest {} conflict status does not match host's for path {path:?} in project {project_id}",
+                        client.username
+                    );
                 }
             }
         }

crates/command_palette/src/command_palette.rs 🔗

@@ -46,7 +46,7 @@ fn normalize_query(input: &str) -> String {
         match (last_char, char) {
             (Some(':'), ':') => continue,
             (Some(last_char), char) if last_char.is_whitespace() && char.is_whitespace() => {
-                continue
+                continue;
             }
             _ => {
                 last_char = Some(char);

crates/component/src/component.rs 🔗

@@ -158,7 +158,7 @@ pub fn components() -> AllComponents {
     let data = COMPONENT_DATA.read();
     let mut all_components = AllComponents::new();
 
-    for (ref scope, name, description) in &data.components {
+    for (scope, name, description) in &data.components {
         let preview = data.previews.get(name).cloned();
         let component_name = SharedString::new_static(name);
         let id = ComponentId(name);

crates/component_preview/src/component_preview.rs 🔗

@@ -244,7 +244,7 @@ impl ComponentPreview {
         ix: usize,
         entry: &PreviewEntry,
         cx: &Context<Self>,
-    ) -> impl IntoElement {
+    ) -> impl IntoElement + use<> {
         match entry {
             PreviewEntry::Component(component_metadata) => {
                 let id = component_metadata.id();

crates/context_server_settings/src/context_server_settings.rs 🔗

@@ -2,7 +2,7 @@ use std::sync::Arc;
 
 use collections::HashMap;
 use gpui::App;
-use schemars::gen::SchemaGenerator;
+use schemars::r#gen::SchemaGenerator;
 use schemars::schema::{InstanceType, Schema, SchemaObject};
 use schemars::JsonSchema;
 use serde::{Deserialize, Serialize};

crates/copilot/src/copilot.rs 🔗

@@ -348,7 +348,10 @@ impl Copilot {
         this
     }
 
-    fn shutdown_language_server(&mut self, _cx: &mut Context<Self>) -> impl Future<Output = ()> {
+    fn shutdown_language_server(
+        &mut self,
+        _cx: &mut Context<Self>,
+    ) -> impl Future<Output = ()> + use<> {
         let shutdown = match mem::replace(&mut self.server, CopilotServer::Disabled) {
             CopilotServer::Running(server) => Some(Box::pin(async move { server.lsp.shutdown() })),
             _ => None,

crates/debugger_ui/src/debugger_panel.rs 🔗

@@ -296,7 +296,9 @@ impl DebugPanel {
         match event {
             dap_store::DapStoreEvent::DebugClientStarted(session_id) => {
                 let Some(session) = dap_store.read(cx).session_by_id(session_id) else {
-                    return log::error!("Couldn't get session with id: {session_id:?} from DebugClientStarted event");
+                    return log::error!(
+                        "Couldn't get session with id: {session_id:?} from DebugClientStarted event"
+                    );
                 };
 
                 let Some(project) = self.project.upgrade() else {

crates/debugger_ui/src/session/running/variable_list.rs 🔗

@@ -437,7 +437,9 @@ impl VariableList {
         });
 
         if res.is_none() {
-            log::error!("Couldn't confirm variable edit because variable doesn't have a leaf name or a parent reference id");
+            log::error!(
+                "Couldn't confirm variable edit because variable doesn't have a leaf name or a parent reference id"
+            );
         }
     }
 

crates/editor/src/commit_tooltip.rs 🔗

@@ -49,7 +49,7 @@ impl<'a> CommitAvatar<'a> {
         &'a self,
         window: &mut Window,
         cx: &mut Context<CommitTooltip>,
-    ) -> Option<impl IntoElement> {
+    ) -> Option<impl IntoElement + use<>> {
         let remote = self
             .commit
             .message

crates/editor/src/display_map.rs 🔗

@@ -1464,7 +1464,7 @@ pub mod tests {
         });
 
         let buffer = cx.update(|cx| {
-            if rng.gen() {
+            if rng.r#gen() {
                 let len = rng.gen_range(0..10);
                 let text = util::RandomCharIter::new(&mut rng)
                     .take(len)
@@ -1526,7 +1526,7 @@ pub mod tests {
                 }
                 30..=44 => {
                     map.update(cx, |map, cx| {
-                        if rng.gen() || blocks.is_empty() {
+                        if rng.r#gen() || blocks.is_empty() {
                             let buffer = map.snapshot(cx).buffer_snapshot;
                             let block_properties = (0..rng.gen_range(1..=1))
                                 .map(|_| {
@@ -1536,7 +1536,7 @@ pub mod tests {
                                             Bias::Left,
                                         ));
 
-                                    let placement = if rng.gen() {
+                                    let placement = if rng.r#gen() {
                                         BlockPlacement::Above(position)
                                     } else {
                                         BlockPlacement::Below(position)
@@ -1580,7 +1580,7 @@ pub mod tests {
                         });
                     }
 
-                    if rng.gen() && fold_count > 0 {
+                    if rng.r#gen() && fold_count > 0 {
                         log::info!("unfolding ranges: {:?}", ranges);
                         map.update(cx, |map, cx| {
                             map.unfold_intersecting(ranges, true, cx);

crates/editor/src/display_map/block_map.rs 🔗

@@ -1370,7 +1370,7 @@ impl BlockSnapshot {
         while let Some(transform) = cursor.item() {
             match &transform.block {
                 Some(Block::ExcerptBoundary { excerpt, .. }) => {
-                    return Some(StickyHeaderExcerpt { excerpt })
+                    return Some(StickyHeaderExcerpt { excerpt });
                 }
                 Some(block) if block.is_buffer_header() => return None,
                 _ => {
@@ -2913,7 +2913,7 @@ mod tests {
 
         log::info!("Wrap width: {:?}", wrap_width);
         log::info!("Excerpt Header Height: {:?}", excerpt_header_height);
-        let is_singleton = rng.gen();
+        let is_singleton = rng.r#gen();
         let buffer = if is_singleton {
             let len = rng.gen_range(0..10);
             let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
@@ -3077,7 +3077,9 @@ mod tests {
                     let fold = !unfolded_buffers.is_empty() && rng.gen_bool(0.5);
                     let unfold = !folded_buffers.is_empty() && rng.gen_bool(0.5);
                     if !fold && !unfold {
-                        log::info!("Noop fold/unfold operation. Unfolded buffers: {unfolded_count}, folded buffers: {folded_count}");
+                        log::info!(
+                            "Noop fold/unfold operation. Unfolded buffers: {unfolded_count}, folded buffers: {folded_count}"
+                        );
                         continue;
                     }
 

crates/editor/src/display_map/fold_map.rs 🔗

@@ -1616,7 +1616,7 @@ mod tests {
 
         let len = rng.gen_range(0..10);
         let text = RandomCharIter::new(&mut rng).take(len).collect::<String>();
-        let buffer = if rng.gen() {
+        let buffer = if rng.r#gen() {
             MultiBuffer::build_simple(&text, cx)
         } else {
             MultiBuffer::build_random(&mut rng, cx)
@@ -1962,7 +1962,7 @@ mod tests {
                         let start = buffer.clip_offset(rng.gen_range(0..=end), Left);
                         to_unfold.push(start..end);
                     }
-                    let inclusive = rng.gen();
+                    let inclusive = rng.r#gen();
                     log::info!("unfolding {:?} (inclusive: {})", to_unfold, inclusive);
                     let (mut writer, snapshot, edits) = self.write(inlay_snapshot, vec![]);
                     snapshot_edits.push((snapshot, edits));

crates/editor/src/display_map/inlay_map.rs 🔗

@@ -610,9 +610,9 @@ impl InlayMap {
         let mut to_insert = Vec::new();
         let snapshot = &mut self.snapshot;
         for i in 0..rng.gen_range(1..=5) {
-            if self.inlays.is_empty() || rng.gen() {
+            if self.inlays.is_empty() || rng.r#gen() {
                 let position = snapshot.buffer.random_byte_range(0, rng).start;
-                let bias = if rng.gen() { Bias::Left } else { Bias::Right };
+                let bias = if rng.r#gen() { Bias::Left } else { Bias::Right };
                 let len = if rng.gen_bool(0.01) {
                     0
                 } else {
@@ -1500,7 +1500,7 @@ mod tests {
             .unwrap_or(10);
 
         let len = rng.gen_range(0..30);
-        let buffer = if rng.gen() {
+        let buffer = if rng.r#gen() {
             let text = util::RandomCharIter::new(&mut rng)
                 .take(len)
                 .collect::<String>();

crates/editor/src/display_map/tab_map.rs 🔗

@@ -738,7 +738,7 @@ mod tests {
     fn test_random_tabs(cx: &mut gpui::App, mut rng: StdRng) {
         let tab_size = NonZeroU32::new(rng.gen_range(1..=4)).unwrap();
         let len = rng.gen_range(0..30);
-        let buffer = if rng.gen() {
+        let buffer = if rng.r#gen() {
             let text = util::RandomCharIter::new(&mut rng)
                 .take(len)
                 .collect::<String>();

crates/editor/src/display_map/wrap_map.rs 🔗

@@ -1207,7 +1207,7 @@ mod tests {
         log::info!("Wrap width: {:?}", wrap_width);
 
         let buffer = cx.update(|cx| {
-            if rng.gen() {
+            if rng.r#gen() {
                 MultiBuffer::build_random(&mut rng, cx)
             } else {
                 let len = rng.gen_range(0..10);

crates/editor/src/editor.rs 🔗

@@ -2428,7 +2428,11 @@ impl Editor {
             background_executor.timer(SERIALIZATION_THROTTLE_TIME).await;
             DB.save_editor_folds(editor_id, workspace_id, db_folds)
                 .await
-                .with_context(|| format!("persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"))
+                .with_context(|| {
+                    format!(
+                        "persisting editor folds for editor {editor_id}, workspace {workspace_id:?}"
+                    )
+                })
                 .log_err();
         });
     }
@@ -6200,7 +6204,9 @@ impl Editor {
     fn insert_tasks(&mut self, key: (BufferId, BufferRow), value: RunnableTasks) {
         if self.tasks.insert(key, value).is_some() {
             // This case should hopefully be rare, but just in case...
-            log::error!("multiple different run targets found on a single line, only the last target will be rendered")
+            log::error!(
+                "multiple different run targets found on a single line, only the last target will be rendered"
+            )
         }
     }
 

crates/editor/src/editor_tests.rs 🔗

@@ -7985,7 +7985,9 @@ async fn test_multibuffer_format_during_save(cx: &mut TestAppContext) {
     assert!(cx.read(|cx| !multi_buffer_editor.is_dirty(cx)));
     assert_eq!(
         multi_buffer_editor.update(cx, |editor, cx| editor.text(cx)),
-        uri!("a|o[file:///a/main.rs formatted]bbbb\ncccc\n\nffff\ngggg\n\njjjj\n\nlll[file:///a/other.rs formatted]mmmm\nnnnn|four|five|six|\nr\n\nuuuu\n\nvvvv\nwwww\nxxxx\n\n{{{{\n||||\n\n\u{7f}\u{7f}\u{7f}\u{7f}"),
+        uri!(
+            "a|o[file:///a/main.rs formatted]bbbb\ncccc\n\nffff\ngggg\n\njjjj\n\nlll[file:///a/other.rs formatted]mmmm\nnnnn|four|five|six|\nr\n\nuuuu\n\nvvvv\nwwww\nxxxx\n\n{{{{\n||||\n\n\u{7f}\u{7f}\u{7f}\u{7f}"
+        ),
     );
     buffer_1.update(cx, |buffer, _| {
         assert!(!buffer.is_dirty());
@@ -18669,7 +18671,7 @@ fn assert_selection_ranges(marked_text: &str, editor: &mut Editor, cx: &mut Cont
 pub fn handle_signature_help_request(
     cx: &mut EditorLspTestContext,
     mocked_response: lsp::SignatureHelp,
-) -> impl Future<Output = ()> {
+) -> impl Future<Output = ()> + use<> {
     let mut request =
         cx.set_request_handler::<lsp::request::SignatureHelpRequest, _, _>(move |_, _, _| {
             let mocked_response = mocked_response.clone();

crates/editor/src/element.rs 🔗

@@ -4190,8 +4190,7 @@ impl EditorElement {
                     None;
                 for (&new_row, &new_background) in &layout.highlighted_rows {
                     match &mut current_paint {
-                        Some((current_background, current_range, mut edges)) => {
-                            let current_background = *current_background;
+                        &mut Some((current_background, ref mut current_range, mut edges)) => {
                             let new_range_started = current_background != new_background
                                 || current_range.end.next_row() != new_row;
                             if new_range_started {
@@ -8793,8 +8792,10 @@ mod tests {
                     px(500.0),
                     show_line_numbers,
                 );
-                assert!(invisibles.is_empty(),
-                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}");
+                assert!(
+                    invisibles.is_empty(),
+                    "For editor mode {editor_mode_without_invisibles:?} no invisibles was expected but got {invisibles:?}"
+                );
             }
         }
     }
@@ -8872,7 +8873,9 @@ mod tests {
                             (Invisible::Whitespace { .. }, Invisible::Whitespace { .. })
                             | (Invisible::Tab { .. }, Invisible::Tab { .. }) => {}
                             _ => {
-                                panic!("At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}")
+                                panic!(
+                                    "At index {i}, expected invisible {expected_invisible:?} does not match actual {actual_invisible:?} by kind. Actual invisibles: {actual_invisibles:?}"
+                                )
                             }
                         },
                         None => {

crates/extension/src/extension_builder.rs 🔗

@@ -26,8 +26,7 @@ use wit_component::ComponentEncoder;
 /// Once Rust 1.78 is released, there will be a `wasm32-wasip2` target available, so we will
 /// not need the adapter anymore.
 const RUST_TARGET: &str = "wasm32-wasip1";
-const WASI_ADAPTER_URL: &str =
-    "https://github.com/bytecodealliance/wasmtime/releases/download/v18.0.2/wasi_snapshot_preview1.reactor.wasm";
+const WASI_ADAPTER_URL: &str = "https://github.com/bytecodealliance/wasmtime/releases/download/v18.0.2/wasi_snapshot_preview1.reactor.wasm";
 
 /// Compiling Tree-sitter parsers from C to WASM requires Clang 17, and a WASM build of libc
 /// and clang's runtime library. The `wasi-sdk` provides these binaries.
@@ -100,7 +99,9 @@ impl ExtensionBuilder {
         for (grammar_name, grammar_metadata) in &extension_manifest.grammars {
             let snake_cased_grammar_name = grammar_name.to_case(Case::Snake);
             if grammar_name.as_ref() != snake_cased_grammar_name.as_str() {
-                bail!("grammar name '{grammar_name}' must be written in snake_case: {snake_cased_grammar_name}");
+                bail!(
+                    "grammar name '{grammar_name}' must be written in snake_case: {snake_cased_grammar_name}"
+                );
             }
 
             log::info!(

crates/extension_api/Cargo.toml 🔗

@@ -19,7 +19,7 @@ path = "src/extension_api.rs"
 [dependencies]
 serde = { version = "1.0", features = ["derive"] }
 serde_json = "1.0"
-wit-bindgen = "0.22"
+wit-bindgen = "0.41"
 
 [package.metadata.component]
 target = { path = "wit" }

crates/extension_api/src/extension_api.rs 🔗

@@ -185,7 +185,7 @@ pub trait Extension: Send + Sync {
 #[macro_export]
 macro_rules! register_extension {
     ($extension_type:ty) => {
-        #[export_name = "init-extension"]
+        #[unsafe(export_name = "init-extension")]
         pub extern "C" fn __init_extension() {
             std::env::set_current_dir(std::env::var("PWD").unwrap()).unwrap();
             zed_extension_api::register_extension(|| {

crates/extension_host/src/extension_host.rs 🔗

@@ -398,7 +398,7 @@ impl ExtensionStore {
         &mut self,
         modified_extension: Option<Arc<str>>,
         cx: &mut Context<Self>,
-    ) -> impl Future<Output = ()> {
+    ) -> impl Future<Output = ()> + use<> {
         let (tx, rx) = oneshot::channel();
         self.reload_complete_senders.push(tx);
         self.reload_tx

crates/file_finder/src/file_finder_tests.rs 🔗

@@ -839,64 +839,64 @@ async fn test_query_history(cx: &mut gpui::TestAppContext) {
     let history_after_third =
         open_close_queried_buffer("sec", 1, "second.rs", &workspace, cx).await;
     assert_eq!(
-                history_after_third,
-                vec![
-                    FoundPath::new(
-                        ProjectPath {
-                            worktree_id,
-                            path: Arc::from(Path::new("test/third.rs")),
-                        },
-                        Some(PathBuf::from(path!("/src/test/third.rs")))
-                    ),
-                    FoundPath::new(
-                        ProjectPath {
-                            worktree_id,
-                            path: Arc::from(Path::new("test/second.rs")),
-                        },
-                        Some(PathBuf::from(path!("/src/test/second.rs")))
-                    ),
-                    FoundPath::new(
-                        ProjectPath {
-                            worktree_id,
-                            path: Arc::from(Path::new("test/first.rs")),
-                        },
-                        Some(PathBuf::from(path!("/src/test/first.rs")))
-                    ),
-                ],
-                "Should show 1st, 2nd and 3rd opened items in the history when opening the 2nd item again. \
+        history_after_third,
+        vec![
+            FoundPath::new(
+                ProjectPath {
+                    worktree_id,
+                    path: Arc::from(Path::new("test/third.rs")),
+                },
+                Some(PathBuf::from(path!("/src/test/third.rs")))
+            ),
+            FoundPath::new(
+                ProjectPath {
+                    worktree_id,
+                    path: Arc::from(Path::new("test/second.rs")),
+                },
+                Some(PathBuf::from(path!("/src/test/second.rs")))
+            ),
+            FoundPath::new(
+                ProjectPath {
+                    worktree_id,
+                    path: Arc::from(Path::new("test/first.rs")),
+                },
+                Some(PathBuf::from(path!("/src/test/first.rs")))
+            ),
+        ],
+        "Should show 1st, 2nd and 3rd opened items in the history when opening the 2nd item again. \
     3rd item should be the first in the history, as the last opened."
-            );
+    );
 
     let history_after_second_again =
         open_close_queried_buffer("thi", 1, "third.rs", &workspace, cx).await;
     assert_eq!(
-                history_after_second_again,
-                vec![
-                    FoundPath::new(
-                        ProjectPath {
-                            worktree_id,
-                            path: Arc::from(Path::new("test/second.rs")),
-                        },
-                        Some(PathBuf::from(path!("/src/test/second.rs")))
-                    ),
-                    FoundPath::new(
-                        ProjectPath {
-                            worktree_id,
-                            path: Arc::from(Path::new("test/third.rs")),
-                        },
-                        Some(PathBuf::from(path!("/src/test/third.rs")))
-                    ),
-                    FoundPath::new(
-                        ProjectPath {
-                            worktree_id,
-                            path: Arc::from(Path::new("test/first.rs")),
-                        },
-                        Some(PathBuf::from(path!("/src/test/first.rs")))
-                    ),
-                ],
-                "Should show 1st, 2nd and 3rd opened items in the history when opening the 3rd item again. \
+        history_after_second_again,
+        vec![
+            FoundPath::new(
+                ProjectPath {
+                    worktree_id,
+                    path: Arc::from(Path::new("test/second.rs")),
+                },
+                Some(PathBuf::from(path!("/src/test/second.rs")))
+            ),
+            FoundPath::new(
+                ProjectPath {
+                    worktree_id,
+                    path: Arc::from(Path::new("test/third.rs")),
+                },
+                Some(PathBuf::from(path!("/src/test/third.rs")))
+            ),
+            FoundPath::new(
+                ProjectPath {
+                    worktree_id,
+                    path: Arc::from(Path::new("test/first.rs")),
+                },
+                Some(PathBuf::from(path!("/src/test/first.rs")))
+            ),
+        ],
+        "Should show 1st, 2nd and 3rd opened items in the history when opening the 3rd item again. \
     2nd item, as the last opened, 3rd item should go next as it was opened right before."
-            );
+    );
 }
 
 #[gpui::test]
@@ -1656,15 +1656,15 @@ async fn test_nonexistent_history_items_not_shown(cx: &mut gpui::TestAppContext)
     cx.simulate_input("rs");
 
     picker.update(cx, |picker, _| {
-            assert_eq!(
-                collect_search_matches(picker).history,
-                vec![
-                    PathBuf::from("test/first.rs"),
-                    PathBuf::from("test/third.rs"),
-                ],
-                "Should have all opened files in the history, except the ones that do not exist on disk"
-            );
-        });
+        assert_eq!(
+            collect_search_matches(picker).history,
+            vec![
+                PathBuf::from("test/first.rs"),
+                PathBuf::from("test/third.rs"),
+            ],
+            "Should have all opened files in the history, except the ones that do not exist on disk"
+        );
+    });
 }
 
 #[gpui::test]

crates/fs/src/fs.rs 🔗

@@ -430,7 +430,7 @@ impl Fs for RealFs {
 
         unsafe {
             unsafe fn ns_string(string: &str) -> id {
-                NSString::alloc(nil).init_str(string).autorelease()
+                unsafe { NSString::alloc(nil).init_str(string).autorelease() }
             }
 
             let url: id = msg_send![class!(NSURL), fileURLWithPath: ns_string(path.to_string_lossy().as_ref())];
@@ -591,7 +591,7 @@ impl Fs for RealFs {
                     (io::ErrorKind::NotFound, _) => Ok(None),
                     (io::ErrorKind::Other, Some(libc::ENOTDIR)) => Ok(None),
                     _ => Err(anyhow::Error::new(err)),
-                }
+                };
             }
         };
 

crates/fsevent/src/fsevent.rs 🔗

@@ -365,7 +365,7 @@ impl std::fmt::Display for StreamFlags {
 }
 
 #[link(name = "CoreServices", kind = "framework")]
-extern "C" {
+unsafe extern "C" {
     pub fn FSEventsGetCurrentEventId() -> u64;
 }
 

crates/git_ui/src/git_panel.rs 🔗

@@ -1548,7 +1548,7 @@ impl GitPanel {
         &mut self,
         window: &mut Window,
         cx: &mut Context<Self>,
-    ) -> impl Future<Output = Result<bool, anyhow::Error>> {
+    ) -> impl Future<Output = Result<bool, anyhow::Error>> + use<> {
         let repo = self.active_repository.clone();
         let mut cx = window.to_async(cx);
 
@@ -2007,7 +2007,7 @@ impl GitPanel {
         &mut self,
         window: &mut Window,
         cx: &mut Context<Self>,
-    ) -> impl Future<Output = anyhow::Result<Option<Remote>>> {
+    ) -> impl Future<Output = anyhow::Result<Option<Remote>>> + use<> {
         let repo = self.active_repository.clone();
         let workspace = self.workspace.clone();
         let mut cx = window.to_async(cx);

crates/gpui/Cargo.toml 🔗

@@ -226,7 +226,7 @@ embed-resource = "3.0"
 naga.workspace = true
 
 [target.'cfg(target_os = "macos")'.build-dependencies]
-bindgen = "0.70.0"
+bindgen = "0.71"
 cbindgen = { version = "0.28.0", default-features = false }
 naga.workspace = true
 

crates/gpui/src/action.rs 🔗

@@ -68,7 +68,7 @@ pub trait Action: 'static + Send {
 
     /// Optional JSON schema for the action's input data.
     fn action_json_schema(
-        _: &mut schemars::gen::SchemaGenerator,
+        _: &mut schemars::r#gen::SchemaGenerator,
     ) -> Option<schemars::schema::Schema>
     where
         Self: Sized,
@@ -167,7 +167,7 @@ impl Default for ActionRegistry {
 
 struct ActionData {
     pub build: ActionBuilder,
-    pub json_schema: fn(&mut schemars::gen::SchemaGenerator) -> Option<schemars::schema::Schema>,
+    pub json_schema: fn(&mut schemars::r#gen::SchemaGenerator) -> Option<schemars::schema::Schema>,
 }
 
 /// This type must be public so that our macros can build it in other crates.
@@ -183,7 +183,7 @@ pub struct MacroActionData {
     pub aliases: &'static [&'static str],
     pub type_id: TypeId,
     pub build: ActionBuilder,
-    pub json_schema: fn(&mut schemars::gen::SchemaGenerator) -> Option<schemars::schema::Schema>,
+    pub json_schema: fn(&mut schemars::r#gen::SchemaGenerator) -> Option<schemars::schema::Schema>,
 }
 
 inventory::collect!(MacroActionBuilder);
@@ -271,7 +271,7 @@ impl ActionRegistry {
 
     pub fn action_schemas(
         &self,
-        generator: &mut schemars::gen::SchemaGenerator,
+        generator: &mut schemars::r#gen::SchemaGenerator,
     ) -> Vec<(SharedString, Option<schemars::schema::Schema>)> {
         // Use the order from all_names so that the resulting schema has sensible order.
         self.all_names
@@ -310,7 +310,7 @@ macro_rules! actions {
                     Ok(Box::new(Self))
                 },
                 fn action_json_schema(
-                    _: &mut gpui::private::schemars::gen::SchemaGenerator,
+                    _: &mut gpui::private::schemars::r#gen::SchemaGenerator,
                 ) -> Option<gpui::private::schemars::schema::Schema> {
                     None
                 }
@@ -347,7 +347,7 @@ macro_rules! action_as {
                 Ok(Box::new(Self))
             },
             fn action_json_schema(
-                generator: &mut gpui::private::schemars::gen::SchemaGenerator,
+                generator: &mut gpui::private::schemars::r#gen::SchemaGenerator,
             ) -> Option<gpui::private::schemars::schema::Schema> {
                 None
             }
@@ -381,7 +381,7 @@ macro_rules! action_with_deprecated_aliases {
             },
 
             fn action_json_schema(
-                generator: &mut gpui::private::schemars::gen::SchemaGenerator,
+                generator: &mut gpui::private::schemars::r#gen::SchemaGenerator,
             ) -> Option<gpui::private::schemars::schema::Schema> {
                 None
             },
@@ -412,7 +412,7 @@ macro_rules! impl_action_with_deprecated_aliases {
             },
 
             fn action_json_schema(
-                generator: &mut gpui::private::schemars::gen::SchemaGenerator,
+                generator: &mut gpui::private::schemars::r#gen::SchemaGenerator,
             ) -> Option<gpui::private::schemars::schema::Schema> {
                 Some(<Self as gpui::private::schemars::JsonSchema>::json_schema(
                     generator,
@@ -446,7 +446,7 @@ macro_rules! impl_actions {
                     Ok(std::boxed::Box::new(gpui::private::serde_json::from_value::<Self>(value)?))
                 },
                 fn action_json_schema(
-                    generator: &mut gpui::private::schemars::gen::SchemaGenerator,
+                    generator: &mut gpui::private::schemars::r#gen::SchemaGenerator,
                 ) -> Option<gpui::private::schemars::schema::Schema> {
                     Some(<Self as gpui::private::schemars::JsonSchema>::json_schema(
                         generator,
@@ -479,7 +479,7 @@ macro_rules! impl_internal_actions {
                         )))
                 },
                 fn action_json_schema(
-                    generator: &mut gpui::private::schemars::gen::SchemaGenerator,
+                    generator: &mut gpui::private::schemars::r#gen::SchemaGenerator,
                 ) -> Option<gpui::private::schemars::schema::Schema> {
                     None
                 }
@@ -509,7 +509,7 @@ macro_rules! impl_action_as {
                 ))
             },
             fn action_json_schema(
-                generator: &mut gpui::private::schemars::gen::SchemaGenerator,
+                generator: &mut gpui::private::schemars::r#gen::SchemaGenerator,
             ) -> Option<gpui::private::schemars::schema::Schema> {
                 Some(<Self as gpui::private::schemars::JsonSchema>::json_schema(
                     generator,

crates/gpui/src/app.rs 🔗

@@ -1347,7 +1347,7 @@ impl App {
     /// Get all non-internal actions that have been registered, along with their schemas.
     pub fn action_schemas(
         &self,
-        generator: &mut schemars::gen::SchemaGenerator,
+        generator: &mut schemars::r#gen::SchemaGenerator,
     ) -> Vec<(SharedString, Option<schemars::schema::Schema>)> {
         self.actions.action_schemas(generator)
     }

crates/gpui/src/app/async_context.rs 🔗

@@ -234,11 +234,11 @@ impl AsyncApp {
     }
 
     /// Run something using this entity and cx, when the returned struct is dropped
-    pub fn on_drop<T: 'static>(
+    pub fn on_drop<T: 'static, Callback: FnOnce(&mut T, &mut Context<T>) + 'static>(
         &self,
         entity: &WeakEntity<T>,
-        f: impl FnOnce(&mut T, &mut Context<T>) + 'static,
-    ) -> util::Deferred<impl FnOnce()> {
+        f: Callback,
+    ) -> util::Deferred<impl FnOnce() + use<T, Callback>> {
         let entity = entity.clone();
         let mut cx = self.clone();
         util::defer(move || {

crates/gpui/src/app/test_context.rs 🔗

@@ -448,7 +448,10 @@ impl TestAppContext {
     }
 
     /// Returns a stream of notifications whenever the Entity is updated.
-    pub fn notifications<T: 'static>(&mut self, entity: &Entity<T>) -> impl Stream<Item = ()> {
+    pub fn notifications<T: 'static>(
+        &mut self,
+        entity: &Entity<T>,
+    ) -> impl Stream<Item = ()> + use<T> {
         let (tx, rx) = futures::channel::mpsc::unbounded();
         self.update(|cx| {
             cx.observe(entity, {

crates/gpui/src/arena.rs 🔗

@@ -66,11 +66,15 @@ impl Arena {
         where
             F: FnOnce() -> T,
         {
-            ptr::write(ptr, f());
+            unsafe {
+                ptr::write(ptr, f());
+            }
         }
 
         unsafe fn drop<T>(ptr: *mut u8) {
-            std::ptr::drop_in_place(ptr.cast::<T>());
+            unsafe {
+                std::ptr::drop_in_place(ptr.cast::<T>());
+            }
         }
 
         unsafe {

crates/gpui/src/executor.rs 🔗

@@ -196,12 +196,12 @@ impl BackgroundExecutor {
     }
 
     #[cfg(not(any(test, feature = "test-support")))]
-    pub(crate) fn block_internal<R>(
+    pub(crate) fn block_internal<Fut: Future>(
         &self,
         _background_only: bool,
-        future: impl Future<Output = R>,
+        future: Fut,
         timeout: Option<Duration>,
-    ) -> Result<R, impl Future<Output = R>> {
+    ) -> Result<Fut::Output, impl Future<Output = Fut::Output> + use<Fut>> {
         use std::time::Instant;
 
         let mut future = Box::pin(future);
@@ -234,12 +234,12 @@ impl BackgroundExecutor {
 
     #[cfg(any(test, feature = "test-support"))]
     #[track_caller]
-    pub(crate) fn block_internal<R>(
+    pub(crate) fn block_internal<Fut: Future>(
         &self,
         background_only: bool,
-        future: impl Future<Output = R>,
+        future: Fut,
         timeout: Option<Duration>,
-    ) -> Result<R, impl Future<Output = R>> {
+    ) -> Result<Fut::Output, impl Future<Output = Fut::Output> + use<Fut>> {
         use std::sync::atomic::AtomicBool;
 
         let mut future = Box::pin(future);
@@ -291,8 +291,8 @@ impl BackgroundExecutor {
                                 waiting_message = format!("\n  waiting on: {}\n", waiting_hint);
                             }
                             panic!(
-                                    "parked with nothing left to run{waiting_message}{backtrace_message}",
-                                )
+                                "parked with nothing left to run{waiting_message}{backtrace_message}",
+                            )
                         }
                         self.dispatcher.park(None);
                     }
@@ -303,11 +303,11 @@ impl BackgroundExecutor {
 
     /// Block the current thread until the given future resolves
     /// or `duration` has elapsed.
-    pub fn block_with_timeout<R>(
+    pub fn block_with_timeout<Fut: Future>(
         &self,
         duration: Duration,
-        future: impl Future<Output = R>,
-    ) -> Result<R, impl Future<Output = R>> {
+        future: Fut,
+    ) -> Result<Fut::Output, impl Future<Output = Fut::Output> + use<Fut>> {
         self.block_internal(true, future, Some(duration))
     }
 
@@ -365,7 +365,7 @@ impl BackgroundExecutor {
 
     /// in tests, run an arbitrary number of tasks (determined by the SEED environment variable)
     #[cfg(any(test, feature = "test-support"))]
-    pub fn simulate_random_delay(&self) -> impl Future<Output = ()> {
+    pub fn simulate_random_delay(&self) -> impl Future<Output = ()> + use<> {
         self.dispatcher.as_test().unwrap().simulate_random_delay()
     }
 

crates/gpui/src/keymap/context.rs 🔗

@@ -438,14 +438,8 @@ mod tests {
             actions!(
                 test,
                 [
-                A,
-                B,
-                C,
-                D,
-                E,
-                F,
-                G, // Don't wrap, test the trailing comma
-            ]
+                    A, B, C, D, E, F, G, // Don't wrap, test the trailing comma
+                ]
             );
         }
     }

crates/gpui/src/platform/blade/blade_renderer.rs 🔗

@@ -398,8 +398,12 @@ impl BladeRenderer {
                 log::error!("GPU hung");
                 #[cfg(target_os = "linux")]
                 if self.gpu.device_information().driver_name == "radv" {
-                    log::error!("there's a known bug with amdgpu/radv, try setting ZED_PATH_SAMPLE_COUNT=0 as a workaround");
-                    log::error!("if that helps you're running into https://github.com/zed-industries/zed/issues/26143");
+                    log::error!(
+                        "there's a known bug with amdgpu/radv, try setting ZED_PATH_SAMPLE_COUNT=0 as a workaround"
+                    );
+                    log::error!(
+                        "if that helps you're running into https://github.com/zed-industries/zed/issues/26143"
+                    );
                 }
                 log::error!(
                     "your device information is: {:?}",

crates/gpui/src/platform/linux/platform.rs 🔗

@@ -632,7 +632,7 @@ pub(super) fn get_xkb_compose_state(cx: &xkb::Context) -> Option<xkb::compose::S
 
 #[cfg(any(feature = "wayland", feature = "x11"))]
 pub(super) unsafe fn read_fd(mut fd: filedescriptor::FileDescriptor) -> Result<Vec<u8>> {
-    let mut file = File::from_raw_fd(fd.as_raw_fd());
+    let mut file = unsafe { File::from_raw_fd(fd.as_raw_fd()) };
     let mut buffer = Vec::new();
     file.read_to_end(&mut buffer)?;
     Ok(buffer)

crates/gpui/src/platform/linux/wayland/clipboard.rs 🔗

@@ -256,7 +256,7 @@ impl Clipboard {
                             }
                             Ok(n) => written += n,
                             Err(err) if err.kind() == ErrorKind::WouldBlock => {
-                                break Ok(PostAction::Continue)
+                                break Ok(PostAction::Continue);
                             }
                             Err(_) => break Ok(PostAction::Remove),
                         }

crates/gpui/src/platform/linux/x11/window.rs 🔗

@@ -186,12 +186,15 @@ fn find_visuals(xcb: &XCBConnection, screen_index: usize) -> VisualSet {
                 colormap: 0,
                 depth: depth_info.depth,
             };
-            log::debug!("Visual id: {}, class: {:?}, depth: {}, bits_per_value: {}, masks: 0x{:x} 0x{:x} 0x{:x}",
+            log::debug!(
+                "Visual id: {}, class: {:?}, depth: {}, bits_per_value: {}, masks: 0x{:x} 0x{:x} 0x{:x}",
                 visual_type.visual_id,
                 visual_type.class,
                 depth_info.depth,
                 visual_type.bits_per_rgb_value,
-                visual_type.red_mask, visual_type.green_mask, visual_type.blue_mask,
+                visual_type.red_mask,
+                visual_type.green_mask,
+                visual_type.blue_mask,
             );
 
             if (
@@ -409,15 +412,27 @@ impl X11WindowState {
 
         let mut bounds = params.bounds.to_device_pixels(scale_factor);
         if bounds.size.width.0 == 0 || bounds.size.height.0 == 0 {
-            log::warn!("Window bounds contain a zero value. height={}, width={}. Falling back to defaults.", bounds.size.height.0, bounds.size.width.0);
+            log::warn!(
+                "Window bounds contain a zero value. height={}, width={}. Falling back to defaults.",
+                bounds.size.height.0,
+                bounds.size.width.0
+            );
             bounds.size.width = 800.into();
             bounds.size.height = 600.into();
         }
 
         check_reply(
             || {
-                format!("X11 CreateWindow failed. depth: {}, x_window: {}, visual_set.root: {}, bounds.origin.x.0: {}, bounds.origin.y.0: {}, bounds.size.width.0: {}, bounds.size.height.0: {}",
-                                visual.depth, x_window, visual_set.root, bounds.origin.x.0 + 2, bounds.origin.y.0, bounds.size.width.0, bounds.size.height.0)
+                format!(
+                    "X11 CreateWindow failed. depth: {}, x_window: {}, visual_set.root: {}, bounds.origin.x.0: {}, bounds.origin.y.0: {}, bounds.size.width.0: {}, bounds.size.height.0: {}",
+                    visual.depth,
+                    x_window,
+                    visual_set.root,
+                    bounds.origin.x.0 + 2,
+                    bounds.origin.y.0,
+                    bounds.size.width.0,
+                    bounds.size.height.0
+                )
             },
             xcb.create_window(
                 visual.depth,

crates/gpui/src/platform/mac.rs 🔗

@@ -74,11 +74,13 @@ trait NSStringExt {
 
 impl NSStringExt for id {
     unsafe fn to_str(&self) -> &str {
-        let cstr = self.UTF8String();
-        if cstr.is_null() {
-            ""
-        } else {
-            CStr::from_ptr(cstr as *mut c_char).to_str().unwrap()
+        unsafe {
+            let cstr = self.UTF8String();
+            if cstr.is_null() {
+                ""
+            } else {
+                CStr::from_ptr(cstr as *mut c_char).to_str().unwrap()
+            }
         }
     }
 }
@@ -134,7 +136,7 @@ unsafe impl objc::Encode for NSRange {
 }
 
 unsafe fn ns_string(string: &str) -> id {
-    NSString::alloc(nil).init_str(string).autorelease()
+    unsafe { NSString::alloc(nil).init_str(string).autorelease() }
 }
 
 impl From<NSSize> for Size<Pixels> {

crates/gpui/src/platform/mac/display.rs 🔗

@@ -65,7 +65,7 @@ impl MacDisplay {
 }
 
 #[link(name = "ApplicationServices", kind = "framework")]
-extern "C" {
+unsafe extern "C" {
     fn CGDisplayCreateUUIDFromDisplayID(display: CGDirectDisplayID) -> CFUUIDRef;
 }
 

crates/gpui/src/platform/mac/display_link.rs 🔗

@@ -30,9 +30,11 @@ impl DisplayLink {
             _flags_out: *mut i64,
             frame_requests: *mut c_void,
         ) -> i32 {
-            let frame_requests = frame_requests as dispatch_source_t;
-            dispatch_source_merge_data(frame_requests, 1);
-            0
+            unsafe {
+                let frame_requests = frame_requests as dispatch_source_t;
+                dispatch_source_merge_data(frame_requests, 1);
+                0
+            }
         }
 
         unsafe {
@@ -202,7 +204,7 @@ mod sys {
     #[link(name = "CoreFoundation", kind = "framework")]
     #[link(name = "CoreVideo", kind = "framework")]
     #[allow(improper_ctypes, unknown_lints, clippy::duplicated_attributes)]
-    extern "C" {
+    unsafe extern "C" {
         pub fn CVDisplayLinkCreateWithActiveCGDisplays(
             display_link_out: *mut *mut CVDisplayLink,
         ) -> i32;
@@ -228,40 +230,46 @@ mod sys {
             callback: CVDisplayLinkOutputCallback,
             user_info: *mut c_void,
         ) -> Result<Self> {
-            let mut display_link: *mut CVDisplayLink = 0 as _;
+            unsafe {
+                let mut display_link: *mut CVDisplayLink = 0 as _;
 
-            let code = CVDisplayLinkCreateWithActiveCGDisplays(&mut display_link);
-            anyhow::ensure!(code == 0, "could not create display link, code: {}", code);
+                let code = CVDisplayLinkCreateWithActiveCGDisplays(&mut display_link);
+                anyhow::ensure!(code == 0, "could not create display link, code: {}", code);
 
-            let mut display_link = DisplayLink::from_ptr(display_link);
+                let mut display_link = DisplayLink::from_ptr(display_link);
 
-            let code = CVDisplayLinkSetOutputCallback(&mut display_link, callback, user_info);
-            anyhow::ensure!(code == 0, "could not set output callback, code: {}", code);
+                let code = CVDisplayLinkSetOutputCallback(&mut display_link, callback, user_info);
+                anyhow::ensure!(code == 0, "could not set output callback, code: {}", code);
 
-            let code = CVDisplayLinkSetCurrentCGDisplay(&mut display_link, display_id);
-            anyhow::ensure!(
-                code == 0,
-                "could not assign display to display link, code: {}",
-                code
-            );
+                let code = CVDisplayLinkSetCurrentCGDisplay(&mut display_link, display_id);
+                anyhow::ensure!(
+                    code == 0,
+                    "could not assign display to display link, code: {}",
+                    code
+                );
 
-            Ok(display_link)
+                Ok(display_link)
+            }
         }
     }
 
     impl DisplayLinkRef {
         /// Apple docs: [CVDisplayLinkStart](https://developer.apple.com/documentation/corevideo/1457193-cvdisplaylinkstart?language=objc)
         pub unsafe fn start(&mut self) -> Result<()> {
-            let code = CVDisplayLinkStart(self);
-            anyhow::ensure!(code == 0, "could not start display link, code: {}", code);
-            Ok(())
+            unsafe {
+                let code = CVDisplayLinkStart(self);
+                anyhow::ensure!(code == 0, "could not start display link, code: {}", code);
+                Ok(())
+            }
         }
 
         /// Apple docs: [CVDisplayLinkStop](https://developer.apple.com/documentation/corevideo/1457281-cvdisplaylinkstop?language=objc)
         pub unsafe fn stop(&mut self) -> Result<()> {
-            let code = CVDisplayLinkStop(self);
-            anyhow::ensure!(code == 0, "could not stop display link, code: {}", code);
-            Ok(())
+            unsafe {
+                let code = CVDisplayLinkStop(self);
+                anyhow::ensure!(code == 0, "could not stop display link, code: {}", code);
+                Ok(())
+            }
         }
     }
 }

crates/gpui/src/platform/mac/events.rs 🔗

@@ -80,19 +80,21 @@ pub fn key_to_native(key: &str) -> Cow<str> {
 }
 
 unsafe fn read_modifiers(native_event: id) -> Modifiers {
-    let modifiers = native_event.modifierFlags();
-    let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
-    let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
-    let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
-    let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
-    let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
-
-    Modifiers {
-        control,
-        alt,
-        shift,
-        platform: command,
-        function,
+    unsafe {
+        let modifiers = native_event.modifierFlags();
+        let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
+        let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
+        let shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
+        let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
+        let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask);
+
+        Modifiers {
+            control,
+            alt,
+            shift,
+            platform: command,
+            function,
+        }
     }
 }
 
@@ -101,344 +103,351 @@ impl PlatformInput {
         native_event: id,
         window_height: Option<Pixels>,
     ) -> Option<Self> {
-        let event_type = native_event.eventType();
+        unsafe {
+            let event_type = native_event.eventType();
 
-        // Filter out event types that aren't in the NSEventType enum.
-        // See https://github.com/servo/cocoa-rs/issues/155#issuecomment-323482792 for details.
-        match event_type as u64 {
-            0 | 21 | 32 | 33 | 35 | 36 | 37 => {
-                return None;
+            // Filter out event types that aren't in the NSEventType enum.
+            // See https://github.com/servo/cocoa-rs/issues/155#issuecomment-323482792 for details.
+            match event_type as u64 {
+                0 | 21 | 32 | 33 | 35 | 36 | 37 => {
+                    return None;
+                }
+                _ => {}
             }
-            _ => {}
-        }
 
-        match event_type {
-            NSEventType::NSFlagsChanged => Some(Self::ModifiersChanged(ModifiersChangedEvent {
-                modifiers: read_modifiers(native_event),
-            })),
-            NSEventType::NSKeyDown => Some(Self::KeyDown(KeyDownEvent {
-                keystroke: parse_keystroke(native_event),
-                is_held: native_event.isARepeat() == YES,
-            })),
-            NSEventType::NSKeyUp => Some(Self::KeyUp(KeyUpEvent {
-                keystroke: parse_keystroke(native_event),
-            })),
-            NSEventType::NSLeftMouseDown
-            | NSEventType::NSRightMouseDown
-            | NSEventType::NSOtherMouseDown => {
-                let button = match native_event.buttonNumber() {
-                    0 => MouseButton::Left,
-                    1 => MouseButton::Right,
-                    2 => MouseButton::Middle,
-                    3 => MouseButton::Navigate(NavigationDirection::Back),
-                    4 => MouseButton::Navigate(NavigationDirection::Forward),
-                    // Other mouse buttons aren't tracked currently
-                    _ => return None,
-                };
-                window_height.map(|window_height| {
-                    Self::MouseDown(MouseDownEvent {
-                        button,
-                        position: point(
-                            px(native_event.locationInWindow().x as f32),
-                            // MacOS screen coordinates are relative to bottom left
-                            window_height - px(native_event.locationInWindow().y as f32),
-                        ),
+            match event_type {
+                NSEventType::NSFlagsChanged => {
+                    Some(Self::ModifiersChanged(ModifiersChangedEvent {
                         modifiers: read_modifiers(native_event),
-                        click_count: native_event.clickCount() as usize,
-                        first_mouse: false,
+                    }))
+                }
+                NSEventType::NSKeyDown => Some(Self::KeyDown(KeyDownEvent {
+                    keystroke: parse_keystroke(native_event),
+                    is_held: native_event.isARepeat() == YES,
+                })),
+                NSEventType::NSKeyUp => Some(Self::KeyUp(KeyUpEvent {
+                    keystroke: parse_keystroke(native_event),
+                })),
+                NSEventType::NSLeftMouseDown
+                | NSEventType::NSRightMouseDown
+                | NSEventType::NSOtherMouseDown => {
+                    let button = match native_event.buttonNumber() {
+                        0 => MouseButton::Left,
+                        1 => MouseButton::Right,
+                        2 => MouseButton::Middle,
+                        3 => MouseButton::Navigate(NavigationDirection::Back),
+                        4 => MouseButton::Navigate(NavigationDirection::Forward),
+                        // Other mouse buttons aren't tracked currently
+                        _ => return None,
+                    };
+                    window_height.map(|window_height| {
+                        Self::MouseDown(MouseDownEvent {
+                            button,
+                            position: point(
+                                px(native_event.locationInWindow().x as f32),
+                                // MacOS screen coordinates are relative to bottom left
+                                window_height - px(native_event.locationInWindow().y as f32),
+                            ),
+                            modifiers: read_modifiers(native_event),
+                            click_count: native_event.clickCount() as usize,
+                            first_mouse: false,
+                        })
                     })
-                })
-            }
-            NSEventType::NSLeftMouseUp
-            | NSEventType::NSRightMouseUp
-            | NSEventType::NSOtherMouseUp => {
-                let button = match native_event.buttonNumber() {
-                    0 => MouseButton::Left,
-                    1 => MouseButton::Right,
-                    2 => MouseButton::Middle,
-                    3 => MouseButton::Navigate(NavigationDirection::Back),
-                    4 => MouseButton::Navigate(NavigationDirection::Forward),
-                    // Other mouse buttons aren't tracked currently
-                    _ => return None,
-                };
+                }
+                NSEventType::NSLeftMouseUp
+                | NSEventType::NSRightMouseUp
+                | NSEventType::NSOtherMouseUp => {
+                    let button = match native_event.buttonNumber() {
+                        0 => MouseButton::Left,
+                        1 => MouseButton::Right,
+                        2 => MouseButton::Middle,
+                        3 => MouseButton::Navigate(NavigationDirection::Back),
+                        4 => MouseButton::Navigate(NavigationDirection::Forward),
+                        // Other mouse buttons aren't tracked currently
+                        _ => return None,
+                    };
 
-                window_height.map(|window_height| {
-                    Self::MouseUp(MouseUpEvent {
-                        button,
+                    window_height.map(|window_height| {
+                        Self::MouseUp(MouseUpEvent {
+                            button,
+                            position: point(
+                                px(native_event.locationInWindow().x as f32),
+                                window_height - px(native_event.locationInWindow().y as f32),
+                            ),
+                            modifiers: read_modifiers(native_event),
+                            click_count: native_event.clickCount() as usize,
+                        })
+                    })
+                }
+                // Some mice (like Logitech MX Master) send navigation buttons as swipe events
+                NSEventType::NSEventTypeSwipe => {
+                    let navigation_direction = match native_event.phase() {
+                        NSEventPhase::NSEventPhaseEnded => match native_event.deltaX() {
+                            x if x > 0.0 => Some(NavigationDirection::Back),
+                            x if x < 0.0 => Some(NavigationDirection::Forward),
+                            _ => return None,
+                        },
+                        _ => return None,
+                    };
+
+                    match navigation_direction {
+                        Some(direction) => window_height.map(|window_height| {
+                            Self::MouseDown(MouseDownEvent {
+                                button: MouseButton::Navigate(direction),
+                                position: point(
+                                    px(native_event.locationInWindow().x as f32),
+                                    window_height - px(native_event.locationInWindow().y as f32),
+                                ),
+                                modifiers: read_modifiers(native_event),
+                                click_count: 1,
+                                first_mouse: false,
+                            })
+                        }),
+                        _ => None,
+                    }
+                }
+                NSEventType::NSScrollWheel => window_height.map(|window_height| {
+                    let phase = match native_event.phase() {
+                        NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => {
+                            TouchPhase::Started
+                        }
+                        NSEventPhase::NSEventPhaseEnded => TouchPhase::Ended,
+                        _ => TouchPhase::Moved,
+                    };
+
+                    let raw_data = point(
+                        native_event.scrollingDeltaX() as f32,
+                        native_event.scrollingDeltaY() as f32,
+                    );
+
+                    let delta = if native_event.hasPreciseScrollingDeltas() == YES {
+                        ScrollDelta::Pixels(raw_data.map(px))
+                    } else {
+                        ScrollDelta::Lines(raw_data)
+                    };
+
+                    Self::ScrollWheel(ScrollWheelEvent {
                         position: point(
                             px(native_event.locationInWindow().x as f32),
                             window_height - px(native_event.locationInWindow().y as f32),
                         ),
+                        delta,
+                        touch_phase: phase,
                         modifiers: read_modifiers(native_event),
-                        click_count: native_event.clickCount() as usize,
                     })
-                })
-            }
-            // Some mice (like Logitech MX Master) send navigation buttons as swipe events
-            NSEventType::NSEventTypeSwipe => {
-                let navigation_direction = match native_event.phase() {
-                    NSEventPhase::NSEventPhaseEnded => match native_event.deltaX() {
-                        x if x > 0.0 => Some(NavigationDirection::Back),
-                        x if x < 0.0 => Some(NavigationDirection::Forward),
+                }),
+                NSEventType::NSLeftMouseDragged
+                | NSEventType::NSRightMouseDragged
+                | NSEventType::NSOtherMouseDragged => {
+                    let pressed_button = match native_event.buttonNumber() {
+                        0 => MouseButton::Left,
+                        1 => MouseButton::Right,
+                        2 => MouseButton::Middle,
+                        3 => MouseButton::Navigate(NavigationDirection::Back),
+                        4 => MouseButton::Navigate(NavigationDirection::Forward),
+                        // Other mouse buttons aren't tracked currently
                         _ => return None,
-                    },
-                    _ => return None,
-                };
+                    };
 
-                match navigation_direction {
-                    Some(direction) => window_height.map(|window_height| {
-                        Self::MouseDown(MouseDownEvent {
-                            button: MouseButton::Navigate(direction),
+                    window_height.map(|window_height| {
+                        Self::MouseMove(MouseMoveEvent {
+                            pressed_button: Some(pressed_button),
                             position: point(
                                 px(native_event.locationInWindow().x as f32),
                                 window_height - px(native_event.locationInWindow().y as f32),
                             ),
                             modifiers: read_modifiers(native_event),
-                            click_count: 1,
-                            first_mouse: false,
                         })
-                    }),
-                    _ => None,
+                    })
                 }
-            }
-            NSEventType::NSScrollWheel => window_height.map(|window_height| {
-                let phase = match native_event.phase() {
-                    NSEventPhase::NSEventPhaseMayBegin | NSEventPhase::NSEventPhaseBegan => {
-                        TouchPhase::Started
-                    }
-                    NSEventPhase::NSEventPhaseEnded => TouchPhase::Ended,
-                    _ => TouchPhase::Moved,
-                };
-
-                let raw_data = point(
-                    native_event.scrollingDeltaX() as f32,
-                    native_event.scrollingDeltaY() as f32,
-                );
-
-                let delta = if native_event.hasPreciseScrollingDeltas() == YES {
-                    ScrollDelta::Pixels(raw_data.map(px))
-                } else {
-                    ScrollDelta::Lines(raw_data)
-                };
-
-                Self::ScrollWheel(ScrollWheelEvent {
-                    position: point(
-                        px(native_event.locationInWindow().x as f32),
-                        window_height - px(native_event.locationInWindow().y as f32),
-                    ),
-                    delta,
-                    touch_phase: phase,
-                    modifiers: read_modifiers(native_event),
-                })
-            }),
-            NSEventType::NSLeftMouseDragged
-            | NSEventType::NSRightMouseDragged
-            | NSEventType::NSOtherMouseDragged => {
-                let pressed_button = match native_event.buttonNumber() {
-                    0 => MouseButton::Left,
-                    1 => MouseButton::Right,
-                    2 => MouseButton::Middle,
-                    3 => MouseButton::Navigate(NavigationDirection::Back),
-                    4 => MouseButton::Navigate(NavigationDirection::Forward),
-                    // Other mouse buttons aren't tracked currently
-                    _ => return None,
-                };
-
-                window_height.map(|window_height| {
+                NSEventType::NSMouseMoved => window_height.map(|window_height| {
                     Self::MouseMove(MouseMoveEvent {
-                        pressed_button: Some(pressed_button),
                         position: point(
                             px(native_event.locationInWindow().x as f32),
                             window_height - px(native_event.locationInWindow().y as f32),
                         ),
+                        pressed_button: None,
                         modifiers: read_modifiers(native_event),
                     })
-                })
+                }),
+                NSEventType::NSMouseExited => window_height.map(|window_height| {
+                    Self::MouseExited(MouseExitEvent {
+                        position: point(
+                            px(native_event.locationInWindow().x as f32),
+                            window_height - px(native_event.locationInWindow().y as f32),
+                        ),
+
+                        pressed_button: None,
+                        modifiers: read_modifiers(native_event),
+                    })
+                }),
+                _ => None,
             }
-            NSEventType::NSMouseMoved => window_height.map(|window_height| {
-                Self::MouseMove(MouseMoveEvent {
-                    position: point(
-                        px(native_event.locationInWindow().x as f32),
-                        window_height - px(native_event.locationInWindow().y as f32),
-                    ),
-                    pressed_button: None,
-                    modifiers: read_modifiers(native_event),
-                })
-            }),
-            NSEventType::NSMouseExited => window_height.map(|window_height| {
-                Self::MouseExited(MouseExitEvent {
-                    position: point(
-                        px(native_event.locationInWindow().x as f32),
-                        window_height - px(native_event.locationInWindow().y as f32),
-                    ),
-
-                    pressed_button: None,
-                    modifiers: read_modifiers(native_event),
-                })
-            }),
-            _ => None,
         }
     }
 }
 
 unsafe fn parse_keystroke(native_event: id) -> Keystroke {
-    use cocoa::appkit::*;
+    unsafe {
+        use cocoa::appkit::*;
+
+        let mut characters = native_event
+            .charactersIgnoringModifiers()
+            .to_str()
+            .to_string();
+        let mut key_char = None;
+        let first_char = characters.chars().next().map(|ch| ch as u16);
+        let modifiers = native_event.modifierFlags();
+
+        let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
+        let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
+        let mut shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
+        let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
+        let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask)
+            && first_char.map_or(true, |ch| {
+                !(NSUpArrowFunctionKey..=NSModeSwitchFunctionKey).contains(&ch)
+            });
+
+        #[allow(non_upper_case_globals)]
+        let key = match first_char {
+            Some(SPACE_KEY) => {
+                key_char = Some(" ".to_string());
+                "space".to_string()
+            }
+            Some(TAB_KEY) => {
+                key_char = Some("\t".to_string());
+                "tab".to_string()
+            }
+            Some(ENTER_KEY) | Some(NUMPAD_ENTER_KEY) => {
+                key_char = Some("\n".to_string());
+                "enter".to_string()
+            }
+            Some(BACKSPACE_KEY) => "backspace".to_string(),
+            Some(ESCAPE_KEY) => "escape".to_string(),
+            Some(SHIFT_TAB_KEY) => "tab".to_string(),
+            Some(NSUpArrowFunctionKey) => "up".to_string(),
+            Some(NSDownArrowFunctionKey) => "down".to_string(),
+            Some(NSLeftArrowFunctionKey) => "left".to_string(),
+            Some(NSRightArrowFunctionKey) => "right".to_string(),
+            Some(NSPageUpFunctionKey) => "pageup".to_string(),
+            Some(NSPageDownFunctionKey) => "pagedown".to_string(),
+            Some(NSHomeFunctionKey) => "home".to_string(),
+            Some(NSEndFunctionKey) => "end".to_string(),
+            Some(NSDeleteFunctionKey) => "delete".to_string(),
+            // Observed Insert==NSHelpFunctionKey not NSInsertFunctionKey.
+            Some(NSHelpFunctionKey) => "insert".to_string(),
+            Some(NSF1FunctionKey) => "f1".to_string(),
+            Some(NSF2FunctionKey) => "f2".to_string(),
+            Some(NSF3FunctionKey) => "f3".to_string(),
+            Some(NSF4FunctionKey) => "f4".to_string(),
+            Some(NSF5FunctionKey) => "f5".to_string(),
+            Some(NSF6FunctionKey) => "f6".to_string(),
+            Some(NSF7FunctionKey) => "f7".to_string(),
+            Some(NSF8FunctionKey) => "f8".to_string(),
+            Some(NSF9FunctionKey) => "f9".to_string(),
+            Some(NSF10FunctionKey) => "f10".to_string(),
+            Some(NSF11FunctionKey) => "f11".to_string(),
+            Some(NSF12FunctionKey) => "f12".to_string(),
+            Some(NSF13FunctionKey) => "f13".to_string(),
+            Some(NSF14FunctionKey) => "f14".to_string(),
+            Some(NSF15FunctionKey) => "f15".to_string(),
+            Some(NSF16FunctionKey) => "f16".to_string(),
+            Some(NSF17FunctionKey) => "f17".to_string(),
+            Some(NSF18FunctionKey) => "f18".to_string(),
+            Some(NSF19FunctionKey) => "f19".to_string(),
+            Some(NSF20FunctionKey) => "f20".to_string(),
+            Some(NSF21FunctionKey) => "f21".to_string(),
+            Some(NSF22FunctionKey) => "f22".to_string(),
+            Some(NSF23FunctionKey) => "f23".to_string(),
+            Some(NSF24FunctionKey) => "f24".to_string(),
+            Some(NSF25FunctionKey) => "f25".to_string(),
+            Some(NSF26FunctionKey) => "f26".to_string(),
+            Some(NSF27FunctionKey) => "f27".to_string(),
+            Some(NSF28FunctionKey) => "f28".to_string(),
+            Some(NSF29FunctionKey) => "f29".to_string(),
+            Some(NSF30FunctionKey) => "f30".to_string(),
+            Some(NSF31FunctionKey) => "f31".to_string(),
+            Some(NSF32FunctionKey) => "f32".to_string(),
+            Some(NSF33FunctionKey) => "f33".to_string(),
+            Some(NSF34FunctionKey) => "f34".to_string(),
+            Some(NSF35FunctionKey) => "f35".to_string(),
+            _ => {
+                // Cases to test when modifying this:
+                //
+                //           qwerty key | none | cmd   | cmd-shift
+                // * Armenian         s | ս    | cmd-s | cmd-shift-s  (layout is non-ASCII, so we use cmd layout)
+                // * Dvorak+QWERTY    s | o    | cmd-s | cmd-shift-s  (layout switches on cmd)
+                // * Ukrainian+QWERTY s | с    | cmd-s | cmd-shift-s  (macOS reports cmd-s instead of cmd-S)
+                // * Czech            7 | ý    | cmd-ý | cmd-7        (layout has shifted numbers)
+                // * Norwegian        7 | 7    | cmd-7 | cmd-/        (macOS reports cmd-shift-7 instead of cmd-/)
+                // * Russian          7 | 7    | cmd-7 | cmd-&        (shift-7 is . but when cmd is down, should use cmd layout)
+                // * German QWERTZ    ; | ö    | cmd-ö | cmd-Ö        (Zed's shift special case only applies to a-z)
+                //
+                let mut chars_ignoring_modifiers =
+                    chars_for_modified_key(native_event.keyCode(), NO_MOD);
+                let mut chars_with_shift =
+                    chars_for_modified_key(native_event.keyCode(), SHIFT_MOD);
+                let always_use_cmd_layout = always_use_command_layout();
+
+                // Handle Dvorak+QWERTY / Russian / Armenian
+                if command || always_use_cmd_layout {
+                    let chars_with_cmd = chars_for_modified_key(native_event.keyCode(), CMD_MOD);
+                    let chars_with_both =
+                        chars_for_modified_key(native_event.keyCode(), CMD_MOD | SHIFT_MOD);
+
+                    // We don't do this in the case that the shifted command key generates
+                    // the same character as the unshifted command key (Norwegian, e.g.)
+                    if chars_with_both != chars_with_cmd {
+                        chars_with_shift = chars_with_both;
+
+                    // Handle edge-case where cmd-shift-s reports cmd-s instead of
+                    // cmd-shift-s (Ukrainian, etc.)
+                    } else if chars_with_cmd.to_ascii_uppercase() != chars_with_cmd {
+                        chars_with_shift = chars_with_cmd.to_ascii_uppercase();
+                    }
+                    chars_ignoring_modifiers = chars_with_cmd;
+                }
 
-    let mut characters = native_event
-        .charactersIgnoringModifiers()
-        .to_str()
-        .to_string();
-    let mut key_char = None;
-    let first_char = characters.chars().next().map(|ch| ch as u16);
-    let modifiers = native_event.modifierFlags();
-
-    let control = modifiers.contains(NSEventModifierFlags::NSControlKeyMask);
-    let alt = modifiers.contains(NSEventModifierFlags::NSAlternateKeyMask);
-    let mut shift = modifiers.contains(NSEventModifierFlags::NSShiftKeyMask);
-    let command = modifiers.contains(NSEventModifierFlags::NSCommandKeyMask);
-    let function = modifiers.contains(NSEventModifierFlags::NSFunctionKeyMask)
-        && first_char.map_or(true, |ch| {
-            !(NSUpArrowFunctionKey..=NSModeSwitchFunctionKey).contains(&ch)
-        });
+                if !control && !command && !function {
+                    let mut mods = NO_MOD;
+                    if shift {
+                        mods |= SHIFT_MOD;
+                    }
+                    if alt {
+                        mods |= OPTION_MOD;
+                    }
 
-    #[allow(non_upper_case_globals)]
-    let key = match first_char {
-        Some(SPACE_KEY) => {
-            key_char = Some(" ".to_string());
-            "space".to_string()
-        }
-        Some(TAB_KEY) => {
-            key_char = Some("\t".to_string());
-            "tab".to_string()
-        }
-        Some(ENTER_KEY) | Some(NUMPAD_ENTER_KEY) => {
-            key_char = Some("\n".to_string());
-            "enter".to_string()
-        }
-        Some(BACKSPACE_KEY) => "backspace".to_string(),
-        Some(ESCAPE_KEY) => "escape".to_string(),
-        Some(SHIFT_TAB_KEY) => "tab".to_string(),
-        Some(NSUpArrowFunctionKey) => "up".to_string(),
-        Some(NSDownArrowFunctionKey) => "down".to_string(),
-        Some(NSLeftArrowFunctionKey) => "left".to_string(),
-        Some(NSRightArrowFunctionKey) => "right".to_string(),
-        Some(NSPageUpFunctionKey) => "pageup".to_string(),
-        Some(NSPageDownFunctionKey) => "pagedown".to_string(),
-        Some(NSHomeFunctionKey) => "home".to_string(),
-        Some(NSEndFunctionKey) => "end".to_string(),
-        Some(NSDeleteFunctionKey) => "delete".to_string(),
-        // Observed Insert==NSHelpFunctionKey not NSInsertFunctionKey.
-        Some(NSHelpFunctionKey) => "insert".to_string(),
-        Some(NSF1FunctionKey) => "f1".to_string(),
-        Some(NSF2FunctionKey) => "f2".to_string(),
-        Some(NSF3FunctionKey) => "f3".to_string(),
-        Some(NSF4FunctionKey) => "f4".to_string(),
-        Some(NSF5FunctionKey) => "f5".to_string(),
-        Some(NSF6FunctionKey) => "f6".to_string(),
-        Some(NSF7FunctionKey) => "f7".to_string(),
-        Some(NSF8FunctionKey) => "f8".to_string(),
-        Some(NSF9FunctionKey) => "f9".to_string(),
-        Some(NSF10FunctionKey) => "f10".to_string(),
-        Some(NSF11FunctionKey) => "f11".to_string(),
-        Some(NSF12FunctionKey) => "f12".to_string(),
-        Some(NSF13FunctionKey) => "f13".to_string(),
-        Some(NSF14FunctionKey) => "f14".to_string(),
-        Some(NSF15FunctionKey) => "f15".to_string(),
-        Some(NSF16FunctionKey) => "f16".to_string(),
-        Some(NSF17FunctionKey) => "f17".to_string(),
-        Some(NSF18FunctionKey) => "f18".to_string(),
-        Some(NSF19FunctionKey) => "f19".to_string(),
-        Some(NSF20FunctionKey) => "f20".to_string(),
-        Some(NSF21FunctionKey) => "f21".to_string(),
-        Some(NSF22FunctionKey) => "f22".to_string(),
-        Some(NSF23FunctionKey) => "f23".to_string(),
-        Some(NSF24FunctionKey) => "f24".to_string(),
-        Some(NSF25FunctionKey) => "f25".to_string(),
-        Some(NSF26FunctionKey) => "f26".to_string(),
-        Some(NSF27FunctionKey) => "f27".to_string(),
-        Some(NSF28FunctionKey) => "f28".to_string(),
-        Some(NSF29FunctionKey) => "f29".to_string(),
-        Some(NSF30FunctionKey) => "f30".to_string(),
-        Some(NSF31FunctionKey) => "f31".to_string(),
-        Some(NSF32FunctionKey) => "f32".to_string(),
-        Some(NSF33FunctionKey) => "f33".to_string(),
-        Some(NSF34FunctionKey) => "f34".to_string(),
-        Some(NSF35FunctionKey) => "f35".to_string(),
-        _ => {
-            // Cases to test when modifying this:
-            //
-            //           qwerty key | none | cmd   | cmd-shift
-            // * Armenian         s | ս    | cmd-s | cmd-shift-s  (layout is non-ASCII, so we use cmd layout)
-            // * Dvorak+QWERTY    s | o    | cmd-s | cmd-shift-s  (layout switches on cmd)
-            // * Ukrainian+QWERTY s | с    | cmd-s | cmd-shift-s  (macOS reports cmd-s instead of cmd-S)
-            // * Czech            7 | ý    | cmd-ý | cmd-7        (layout has shifted numbers)
-            // * Norwegian        7 | 7    | cmd-7 | cmd-/        (macOS reports cmd-shift-7 instead of cmd-/)
-            // * Russian          7 | 7    | cmd-7 | cmd-&        (shift-7 is . but when cmd is down, should use cmd layout)
-            // * German QWERTZ    ; | ö    | cmd-ö | cmd-Ö        (Zed's shift special case only applies to a-z)
-            //
-            let mut chars_ignoring_modifiers =
-                chars_for_modified_key(native_event.keyCode(), NO_MOD);
-            let mut chars_with_shift = chars_for_modified_key(native_event.keyCode(), SHIFT_MOD);
-            let always_use_cmd_layout = always_use_command_layout();
-
-            // Handle Dvorak+QWERTY / Russian / Armenian
-            if command || always_use_cmd_layout {
-                let chars_with_cmd = chars_for_modified_key(native_event.keyCode(), CMD_MOD);
-                let chars_with_both =
-                    chars_for_modified_key(native_event.keyCode(), CMD_MOD | SHIFT_MOD);
-
-                // We don't do this in the case that the shifted command key generates
-                // the same character as the unshifted command key (Norwegian, e.g.)
-                if chars_with_both != chars_with_cmd {
-                    chars_with_shift = chars_with_both;
-
-                // Handle edge-case where cmd-shift-s reports cmd-s instead of
-                // cmd-shift-s (Ukrainian, etc.)
-                } else if chars_with_cmd.to_ascii_uppercase() != chars_with_cmd {
-                    chars_with_shift = chars_with_cmd.to_ascii_uppercase();
+                    key_char = Some(chars_for_modified_key(native_event.keyCode(), mods));
                 }
-                chars_ignoring_modifiers = chars_with_cmd;
-            }
 
-            if !control && !command && !function {
-                let mut mods = NO_MOD;
-                if shift {
-                    mods |= SHIFT_MOD;
-                }
-                if alt {
-                    mods |= OPTION_MOD;
-                }
+                let mut key = if shift
+                    && chars_ignoring_modifiers
+                        .chars()
+                        .all(|c| c.is_ascii_lowercase())
+                {
+                    chars_ignoring_modifiers
+                } else if shift {
+                    shift = false;
+                    chars_with_shift
+                } else {
+                    chars_ignoring_modifiers
+                };
 
-                key_char = Some(chars_for_modified_key(native_event.keyCode(), mods));
+                key
             }
-
-            let mut key = if shift
-                && chars_ignoring_modifiers
-                    .chars()
-                    .all(|c| c.is_ascii_lowercase())
-            {
-                chars_ignoring_modifiers
-            } else if shift {
-                shift = false;
-                chars_with_shift
-            } else {
-                chars_ignoring_modifiers
-            };
-
-            key
+        };
+
+        Keystroke {
+            modifiers: Modifiers {
+                control,
+                alt,
+                shift,
+                platform: command,
+                function,
+            },
+            key,
+            key_char,
         }
-    };
-
-    Keystroke {
-        modifiers: Modifiers {
-            control,
-            alt,
-            shift,
-            platform: command,
-            function,
-        },
-        key,
-        key_char,
     }
 }
 

crates/gpui/src/platform/mac/metal_renderer.rs 🔗

@@ -471,7 +471,8 @@ impl MetalRenderer {
 
             if !ok {
                 command_encoder.end_encoding();
-                return Err(anyhow!("scene too large: {} paths, {} shadows, {} quads, {} underlines, {} mono, {} poly, {} surfaces",
+                return Err(anyhow!(
+                    "scene too large: {} paths, {} shadows, {} quads, {} underlines, {} mono, {} poly, {} surfaces",
                     scene.paths.len(),
                     scene.shadows.len(),
                     scene.quads.len(),

crates/gpui/src/platform/mac/open_type.rs 🔗

@@ -132,7 +132,7 @@ fn append_system_fallbacks(fallback_array: CFMutableArrayRef, font_ref: CTFontRe
 }
 
 #[link(name = "CoreText", kind = "framework")]
-extern "C" {
+unsafe extern "C" {
     static kCTFontOpenTypeFeatureTag: CFStringRef;
     static kCTFontOpenTypeFeatureValue: CFStringRef;
 

crates/gpui/src/platform/mac/platform.rs 🔗

@@ -68,79 +68,82 @@ static mut APP_DELEGATE_CLASS: *const Class = ptr::null();
 
 #[ctor]
 unsafe fn build_classes() {
-    APP_CLASS = {
-        let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
-        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
-        decl.register()
+    unsafe {
+        APP_CLASS = {
+            let mut decl = ClassDecl::new("GPUIApplication", class!(NSApplication)).unwrap();
+            decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
+            decl.register()
+        }
     };
+    unsafe {
+        APP_DELEGATE_CLASS = unsafe {
+            let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
+            decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
+            decl.add_method(
+                sel!(applicationDidFinishLaunching:),
+                did_finish_launching as extern "C" fn(&mut Object, Sel, id),
+            );
+            decl.add_method(
+                sel!(applicationShouldHandleReopen:hasVisibleWindows:),
+                should_handle_reopen as extern "C" fn(&mut Object, Sel, id, bool),
+            );
+            decl.add_method(
+                sel!(applicationWillTerminate:),
+                will_terminate as extern "C" fn(&mut Object, Sel, id),
+            );
+            decl.add_method(
+                sel!(handleGPUIMenuItem:),
+                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
+            );
+            // Add menu item handlers so that OS save panels have the correct key commands
+            decl.add_method(
+                sel!(cut:),
+                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
+            );
+            decl.add_method(
+                sel!(copy:),
+                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
+            );
+            decl.add_method(
+                sel!(paste:),
+                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
+            );
+            decl.add_method(
+                sel!(selectAll:),
+                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
+            );
+            decl.add_method(
+                sel!(undo:),
+                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
+            );
+            decl.add_method(
+                sel!(redo:),
+                handle_menu_item as extern "C" fn(&mut Object, Sel, id),
+            );
+            decl.add_method(
+                sel!(validateMenuItem:),
+                validate_menu_item as extern "C" fn(&mut Object, Sel, id) -> bool,
+            );
+            decl.add_method(
+                sel!(menuWillOpen:),
+                menu_will_open as extern "C" fn(&mut Object, Sel, id),
+            );
+            decl.add_method(
+                sel!(applicationDockMenu:),
+                handle_dock_menu as extern "C" fn(&mut Object, Sel, id) -> id,
+            );
+            decl.add_method(
+                sel!(application:openURLs:),
+                open_urls as extern "C" fn(&mut Object, Sel, id, id),
+            );
 
-    APP_DELEGATE_CLASS = {
-        let mut decl = ClassDecl::new("GPUIApplicationDelegate", class!(NSResponder)).unwrap();
-        decl.add_ivar::<*mut c_void>(MAC_PLATFORM_IVAR);
-        decl.add_method(
-            sel!(applicationDidFinishLaunching:),
-            did_finish_launching as extern "C" fn(&mut Object, Sel, id),
-        );
-        decl.add_method(
-            sel!(applicationShouldHandleReopen:hasVisibleWindows:),
-            should_handle_reopen as extern "C" fn(&mut Object, Sel, id, bool),
-        );
-        decl.add_method(
-            sel!(applicationWillTerminate:),
-            will_terminate as extern "C" fn(&mut Object, Sel, id),
-        );
-        decl.add_method(
-            sel!(handleGPUIMenuItem:),
-            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
-        );
-        // Add menu item handlers so that OS save panels have the correct key commands
-        decl.add_method(
-            sel!(cut:),
-            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
-        );
-        decl.add_method(
-            sel!(copy:),
-            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
-        );
-        decl.add_method(
-            sel!(paste:),
-            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
-        );
-        decl.add_method(
-            sel!(selectAll:),
-            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
-        );
-        decl.add_method(
-            sel!(undo:),
-            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
-        );
-        decl.add_method(
-            sel!(redo:),
-            handle_menu_item as extern "C" fn(&mut Object, Sel, id),
-        );
-        decl.add_method(
-            sel!(validateMenuItem:),
-            validate_menu_item as extern "C" fn(&mut Object, Sel, id) -> bool,
-        );
-        decl.add_method(
-            sel!(menuWillOpen:),
-            menu_will_open as extern "C" fn(&mut Object, Sel, id),
-        );
-        decl.add_method(
-            sel!(applicationDockMenu:),
-            handle_dock_menu as extern "C" fn(&mut Object, Sel, id) -> id,
-        );
-        decl.add_method(
-            sel!(application:openURLs:),
-            open_urls as extern "C" fn(&mut Object, Sel, id, id),
-        );
-
-        decl.add_method(
-            sel!(onKeyboardLayoutChange:),
-            on_keyboard_layout_change as extern "C" fn(&mut Object, Sel, id),
-        );
+            decl.add_method(
+                sel!(onKeyboardLayoutChange:),
+                on_keyboard_layout_change as extern "C" fn(&mut Object, Sel, id),
+            );
 
-        decl.register()
+            decl.register()
+        }
     }
 }
 
@@ -206,14 +209,16 @@ impl MacPlatform {
     }
 
     unsafe fn read_from_pasteboard(&self, pasteboard: *mut Object, kind: id) -> Option<&[u8]> {
-        let data = pasteboard.dataForType(kind);
-        if data == nil {
-            None
-        } else {
-            Some(slice::from_raw_parts(
-                data.bytes() as *mut u8,
-                data.length() as usize,
-            ))
+        unsafe {
+            let data = pasteboard.dataForType(kind);
+            if data == nil {
+                None
+            } else {
+                Some(slice::from_raw_parts(
+                    data.bytes() as *mut u8,
+                    data.length() as usize,
+                ))
+            }
         }
     }
 
@@ -224,36 +229,38 @@ impl MacPlatform {
         actions: &mut Vec<Box<dyn Action>>,
         keymap: &Keymap,
     ) -> id {
-        let application_menu = NSMenu::new(nil).autorelease();
-        application_menu.setDelegate_(delegate);
+        unsafe {
+            let application_menu = NSMenu::new(nil).autorelease();
+            application_menu.setDelegate_(delegate);
+
+            for menu_config in menus {
+                let menu = NSMenu::new(nil).autorelease();
+                let menu_title = ns_string(&menu_config.name);
+                menu.setTitle_(menu_title);
+                menu.setDelegate_(delegate);
+
+                for item_config in menu_config.items {
+                    menu.addItem_(Self::create_menu_item(
+                        item_config,
+                        delegate,
+                        actions,
+                        keymap,
+                    ));
+                }
 
-        for menu_config in menus {
-            let menu = NSMenu::new(nil).autorelease();
-            let menu_title = ns_string(&menu_config.name);
-            menu.setTitle_(menu_title);
-            menu.setDelegate_(delegate);
+                let menu_item = NSMenuItem::new(nil).autorelease();
+                menu_item.setTitle_(menu_title);
+                menu_item.setSubmenu_(menu);
+                application_menu.addItem_(menu_item);
 
-            for item_config in menu_config.items {
-                menu.addItem_(Self::create_menu_item(
-                    item_config,
-                    delegate,
-                    actions,
-                    keymap,
-                ));
+                if menu_config.name == "Window" {
+                    let app: id = msg_send![APP_CLASS, sharedApplication];
+                    app.setWindowsMenu_(menu);
+                }
             }
 
-            let menu_item = NSMenuItem::new(nil).autorelease();
-            menu_item.setTitle_(menu_title);
-            menu_item.setSubmenu_(menu);
-            application_menu.addItem_(menu_item);
-
-            if menu_config.name == "Window" {
-                let app: id = msg_send![APP_CLASS, sharedApplication];
-                app.setWindowsMenu_(menu);
-            }
+            application_menu
         }
-
-        application_menu
     }
 
     unsafe fn create_dock_menu(
@@ -263,18 +270,20 @@ impl MacPlatform {
         actions: &mut Vec<Box<dyn Action>>,
         keymap: &Keymap,
     ) -> id {
-        let dock_menu = NSMenu::new(nil);
-        dock_menu.setDelegate_(delegate);
-        for item_config in menu_items {
-            dock_menu.addItem_(Self::create_menu_item(
-                item_config,
-                delegate,
-                actions,
-                keymap,
-            ));
-        }
+        unsafe {
+            let dock_menu = NSMenu::new(nil);
+            dock_menu.setDelegate_(delegate);
+            for item_config in menu_items {
+                dock_menu.addItem_(Self::create_menu_item(
+                    item_config,
+                    delegate,
+                    actions,
+                    keymap,
+                ));
+            }
 
-        dock_menu
+            dock_menu
+        }
     }
 
     unsafe fn create_menu_item(
@@ -283,70 +292,80 @@ impl MacPlatform {
         actions: &mut Vec<Box<dyn Action>>,
         keymap: &Keymap,
     ) -> id {
-        match item {
-            MenuItem::Separator => NSMenuItem::separatorItem(nil),
-            MenuItem::Action {
-                name,
-                action,
-                os_action,
-            } => {
-                let keystrokes = crate::Keymap::binding_to_display_from_bindings_iterator(
-                    keymap.bindings_for_action(action.as_ref()),
-                )
-                .map(|binding| binding.keystrokes());
-
-                let selector = match os_action {
-                    Some(crate::OsAction::Cut) => selector("cut:"),
-                    Some(crate::OsAction::Copy) => selector("copy:"),
-                    Some(crate::OsAction::Paste) => selector("paste:"),
-                    Some(crate::OsAction::SelectAll) => selector("selectAll:"),
-                    // "undo:" and "redo:" are always disabled in our case, as
-                    // we don't have a NSTextView/NSTextField to enable them on.
-                    Some(crate::OsAction::Undo) => selector("handleGPUIMenuItem:"),
-                    Some(crate::OsAction::Redo) => selector("handleGPUIMenuItem:"),
-                    None => selector("handleGPUIMenuItem:"),
-                };
-
-                let item;
-                if let Some(keystrokes) = keystrokes {
-                    if keystrokes.len() == 1 {
-                        let keystroke = &keystrokes[0];
-                        let mut mask = NSEventModifierFlags::empty();
-                        for (modifier, flag) in &[
-                            (
-                                keystroke.modifiers.platform,
-                                NSEventModifierFlags::NSCommandKeyMask,
-                            ),
-                            (
-                                keystroke.modifiers.control,
-                                NSEventModifierFlags::NSControlKeyMask,
-                            ),
-                            (
-                                keystroke.modifiers.alt,
-                                NSEventModifierFlags::NSAlternateKeyMask,
-                            ),
-                            (
-                                keystroke.modifiers.shift,
-                                NSEventModifierFlags::NSShiftKeyMask,
-                            ),
-                        ] {
-                            if *modifier {
-                                mask |= *flag;
+        unsafe {
+            match item {
+                MenuItem::Separator => NSMenuItem::separatorItem(nil),
+                MenuItem::Action {
+                    name,
+                    action,
+                    os_action,
+                } => {
+                    let keystrokes = crate::Keymap::binding_to_display_from_bindings_iterator(
+                        keymap.bindings_for_action(action.as_ref()),
+                    )
+                    .map(|binding| binding.keystrokes());
+
+                    let selector = match os_action {
+                        Some(crate::OsAction::Cut) => selector("cut:"),
+                        Some(crate::OsAction::Copy) => selector("copy:"),
+                        Some(crate::OsAction::Paste) => selector("paste:"),
+                        Some(crate::OsAction::SelectAll) => selector("selectAll:"),
+                        // "undo:" and "redo:" are always disabled in our case, as
+                        // we don't have a NSTextView/NSTextField to enable them on.
+                        Some(crate::OsAction::Undo) => selector("handleGPUIMenuItem:"),
+                        Some(crate::OsAction::Redo) => selector("handleGPUIMenuItem:"),
+                        None => selector("handleGPUIMenuItem:"),
+                    };
+
+                    let item;
+                    if let Some(keystrokes) = keystrokes {
+                        if keystrokes.len() == 1 {
+                            let keystroke = &keystrokes[0];
+                            let mut mask = NSEventModifierFlags::empty();
+                            for (modifier, flag) in &[
+                                (
+                                    keystroke.modifiers.platform,
+                                    NSEventModifierFlags::NSCommandKeyMask,
+                                ),
+                                (
+                                    keystroke.modifiers.control,
+                                    NSEventModifierFlags::NSControlKeyMask,
+                                ),
+                                (
+                                    keystroke.modifiers.alt,
+                                    NSEventModifierFlags::NSAlternateKeyMask,
+                                ),
+                                (
+                                    keystroke.modifiers.shift,
+                                    NSEventModifierFlags::NSShiftKeyMask,
+                                ),
+                            ] {
+                                if *modifier {
+                                    mask |= *flag;
+                                }
                             }
-                        }
 
-                        item = NSMenuItem::alloc(nil)
-                            .initWithTitle_action_keyEquivalent_(
-                                ns_string(&name),
-                                selector,
-                                ns_string(key_to_native(&keystroke.key).as_ref()),
-                            )
-                            .autorelease();
-                        if MacPlatform::os_version().unwrap() >= SemanticVersion::new(12, 0, 0) {
-                            let _: () =
-                                msg_send![item, setAllowsAutomaticKeyEquivalentLocalization: NO];
+                            item = NSMenuItem::alloc(nil)
+                                .initWithTitle_action_keyEquivalent_(
+                                    ns_string(&name),
+                                    selector,
+                                    ns_string(key_to_native(&keystroke.key).as_ref()),
+                                )
+                                .autorelease();
+                            if MacPlatform::os_version().unwrap() >= SemanticVersion::new(12, 0, 0)
+                            {
+                                let _: () = msg_send![item, setAllowsAutomaticKeyEquivalentLocalization: NO];
+                            }
+                            item.setKeyEquivalentModifierMask_(mask);
+                        } else {
+                            item = NSMenuItem::alloc(nil)
+                                .initWithTitle_action_keyEquivalent_(
+                                    ns_string(&name),
+                                    selector,
+                                    ns_string(""),
+                                )
+                                .autorelease();
                         }
-                        item.setKeyEquivalentModifierMask_(mask);
                     } else {
                         item = NSMenuItem::alloc(nil)
                             .initWithTitle_action_keyEquivalent_(
@@ -356,36 +375,28 @@ impl MacPlatform {
                             )
                             .autorelease();
                     }
-                } else {
-                    item = NSMenuItem::alloc(nil)
-                        .initWithTitle_action_keyEquivalent_(
-                            ns_string(&name),
-                            selector,
-                            ns_string(""),
-                        )
-                        .autorelease();
-                }
 
-                let tag = actions.len() as NSInteger;
-                let _: () = msg_send![item, setTag: tag];
-                actions.push(action);
-                item
-            }
-            MenuItem::Submenu(Menu { name, items }) => {
-                let item = NSMenuItem::new(nil).autorelease();
-                let submenu = NSMenu::new(nil).autorelease();
-                submenu.setDelegate_(delegate);
-                for item in items {
-                    submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
-                }
-                item.setSubmenu_(submenu);
-                item.setTitle_(ns_string(&name));
-                if name == "Services" {
-                    let app: id = msg_send![APP_CLASS, sharedApplication];
-                    app.setServicesMenu_(item);
+                    let tag = actions.len() as NSInteger;
+                    let _: () = msg_send![item, setTag: tag];
+                    actions.push(action);
+                    item
                 }
+                MenuItem::Submenu(Menu { name, items }) => {
+                    let item = NSMenuItem::new(nil).autorelease();
+                    let submenu = NSMenu::new(nil).autorelease();
+                    submenu.setDelegate_(delegate);
+                    for item in items {
+                        submenu.addItem_(Self::create_menu_item(item, delegate, actions, keymap));
+                    }
+                    item.setSubmenu_(submenu);
+                    item.setTitle_(ns_string(&name));
+                    if name == "Services" {
+                        let app: id = msg_send![APP_CLASS, sharedApplication];
+                        app.setServicesMenu_(item);
+                    }
 
-                item
+                    item
+                }
             }
         }
     }
@@ -460,8 +471,10 @@ impl Platform for MacPlatform {
         }
 
         unsafe extern "C" fn quit(_: *mut c_void) {
-            let app = NSApplication::sharedApplication(nil);
-            let _: () = msg_send![app, terminate: nil];
+            unsafe {
+                let app = NSApplication::sharedApplication(nil);
+                let _: () = msg_send![app, terminate: nil];
+            }
         }
     }
 
@@ -1180,75 +1193,81 @@ impl MacPlatform {
         state: &MacPlatformState,
         text_bytes: &[u8],
     ) -> ClipboardItem {
-        let text = String::from_utf8_lossy(text_bytes).to_string();
-        let metadata = self
-            .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
-            .and_then(|hash_bytes| {
-                let hash_bytes = hash_bytes.try_into().ok()?;
-                let hash = u64::from_be_bytes(hash_bytes);
-                let metadata =
-                    self.read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)?;
-
-                if hash == ClipboardString::text_hash(&text) {
-                    String::from_utf8(metadata.to_vec()).ok()
-                } else {
-                    None
-                }
-            });
+        unsafe {
+            let text = String::from_utf8_lossy(text_bytes).to_string();
+            let metadata = self
+                .read_from_pasteboard(state.pasteboard, state.text_hash_pasteboard_type)
+                .and_then(|hash_bytes| {
+                    let hash_bytes = hash_bytes.try_into().ok()?;
+                    let hash = u64::from_be_bytes(hash_bytes);
+                    let metadata = self
+                        .read_from_pasteboard(state.pasteboard, state.metadata_pasteboard_type)?;
+
+                    if hash == ClipboardString::text_hash(&text) {
+                        String::from_utf8(metadata.to_vec()).ok()
+                    } else {
+                        None
+                    }
+                });
 
-        ClipboardItem {
-            entries: vec![ClipboardEntry::String(ClipboardString { text, metadata })],
+            ClipboardItem {
+                entries: vec![ClipboardEntry::String(ClipboardString { text, metadata })],
+            }
         }
     }
 
     unsafe fn write_plaintext_to_clipboard(&self, string: &ClipboardString) {
-        let state = self.0.lock();
-        state.pasteboard.clearContents();
-
-        let text_bytes = NSData::dataWithBytes_length_(
-            nil,
-            string.text.as_ptr() as *const c_void,
-            string.text.len() as u64,
-        );
-        state
-            .pasteboard
-            .setData_forType(text_bytes, NSPasteboardTypeString);
+        unsafe {
+            let state = self.0.lock();
+            state.pasteboard.clearContents();
 
-        if let Some(metadata) = string.metadata.as_ref() {
-            let hash_bytes = ClipboardString::text_hash(&string.text).to_be_bytes();
-            let hash_bytes = NSData::dataWithBytes_length_(
+            let text_bytes = NSData::dataWithBytes_length_(
                 nil,
-                hash_bytes.as_ptr() as *const c_void,
-                hash_bytes.len() as u64,
+                string.text.as_ptr() as *const c_void,
+                string.text.len() as u64,
             );
             state
                 .pasteboard
-                .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
+                .setData_forType(text_bytes, NSPasteboardTypeString);
+
+            if let Some(metadata) = string.metadata.as_ref() {
+                let hash_bytes = ClipboardString::text_hash(&string.text).to_be_bytes();
+                let hash_bytes = NSData::dataWithBytes_length_(
+                    nil,
+                    hash_bytes.as_ptr() as *const c_void,
+                    hash_bytes.len() as u64,
+                );
+                state
+                    .pasteboard
+                    .setData_forType(hash_bytes, state.text_hash_pasteboard_type);
 
-            let metadata_bytes = NSData::dataWithBytes_length_(
-                nil,
-                metadata.as_ptr() as *const c_void,
-                metadata.len() as u64,
-            );
-            state
-                .pasteboard
-                .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
+                let metadata_bytes = NSData::dataWithBytes_length_(
+                    nil,
+                    metadata.as_ptr() as *const c_void,
+                    metadata.len() as u64,
+                );
+                state
+                    .pasteboard
+                    .setData_forType(metadata_bytes, state.metadata_pasteboard_type);
+            }
         }
     }
 
     unsafe fn write_image_to_clipboard(&self, image: &Image) {
-        let state = self.0.lock();
-        state.pasteboard.clearContents();
+        unsafe {
+            let state = self.0.lock();
+            state.pasteboard.clearContents();
 
-        let bytes = NSData::dataWithBytes_length_(
-            nil,
-            image.bytes.as_ptr() as *const c_void,
-            image.bytes.len() as u64,
-        );
+            let bytes = NSData::dataWithBytes_length_(
+                nil,
+                image.bytes.as_ptr() as *const c_void,
+                image.bytes.len() as u64,
+            );
 
-        state
-            .pasteboard
-            .setData_forType(bytes, Into::<UTType>::into(image.format).inner_mut());
+            state
+                .pasteboard
+                .setData_forType(bytes, Into::<UTType>::into(image.format).inner_mut());
+        }
     }
 }
 
@@ -1280,15 +1299,17 @@ fn try_clipboard_image(pasteboard: id, format: ImageFormat) -> Option<ClipboardI
 
 unsafe fn path_from_objc(path: id) -> PathBuf {
     let len = msg_send![path, lengthOfBytesUsingEncoding: NSUTF8StringEncoding];
-    let bytes = path.UTF8String() as *const u8;
-    let path = str::from_utf8(slice::from_raw_parts(bytes, len)).unwrap();
+    let bytes = unsafe { path.UTF8String() as *const u8 };
+    let path = str::from_utf8(unsafe { slice::from_raw_parts(bytes, len) }).unwrap();
     PathBuf::from(path)
 }
 
 unsafe fn get_mac_platform(object: &mut Object) -> &MacPlatform {
-    let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
-    assert!(!platform_ptr.is_null());
-    &*(platform_ptr as *const MacPlatform)
+    unsafe {
+        let platform_ptr: *mut c_void = *object.get_ivar(MAC_PLATFORM_IVAR);
+        assert!(!platform_ptr.is_null());
+        &*(platform_ptr as *const MacPlatform)
+    }
 }
 
 extern "C" fn did_finish_launching(this: &mut Object, _: Sel, _: id) {
@@ -1438,25 +1459,24 @@ extern "C" fn handle_dock_menu(this: &mut Object, _: Sel, _: id) -> id {
 }
 
 unsafe fn ns_string(string: &str) -> id {
-    NSString::alloc(nil).init_str(string).autorelease()
+    unsafe { NSString::alloc(nil).init_str(string).autorelease() }
 }
 
 unsafe fn ns_url_to_path(url: id) -> Result<PathBuf> {
     let path: *mut c_char = msg_send![url, fileSystemRepresentation];
     if path.is_null() {
-        Err(anyhow!(
-            "url is not a file path: {}",
+        Err(anyhow!("url is not a file path: {}", unsafe {
             CStr::from_ptr(url.absoluteString().UTF8String()).to_string_lossy()
-        ))
+        }))
     } else {
-        Ok(PathBuf::from(OsStr::from_bytes(
-            CStr::from_ptr(path).to_bytes(),
-        )))
+        Ok(PathBuf::from(OsStr::from_bytes(unsafe {
+            CStr::from_ptr(path).to_bytes()
+        })))
     }
 }
 
 #[link(name = "Carbon", kind = "framework")]
-extern "C" {
+unsafe extern "C" {
     pub(super) fn TISCopyCurrentKeyboardLayoutInputSource() -> *mut Object;
     pub(super) fn TISGetInputSourceProperty(
         inputSource: *mut Object,
@@ -1485,7 +1505,7 @@ mod security {
     use super::*;
 
     #[link(name = "Security", kind = "framework")]
-    extern "C" {
+    unsafe extern "C" {
         pub static kSecClass: CFStringRef;
         pub static kSecClassInternetPassword: CFStringRef;
         pub static kSecAttrServer: CFStringRef;

crates/gpui/src/platform/mac/screen_capture.rs 🔗

@@ -37,7 +37,7 @@ pub struct MacScreenCaptureStream {
 }
 
 #[link(name = "ScreenCaptureKit", kind = "framework")]
-extern "C" {}
+unsafe extern "C" {}
 
 static mut DELEGATE_CLASS: *const Class = ptr::null();
 static mut OUTPUT_CLASS: *const Class = ptr::null();
@@ -200,28 +200,31 @@ pub(crate) fn get_sources() -> oneshot::Receiver<Result<Vec<Box<dyn ScreenCaptur
 #[ctor]
 unsafe fn build_classes() {
     let mut decl = ClassDecl::new("GPUIStreamDelegate", class!(NSObject)).unwrap();
-    decl.add_method(
-        sel!(outputVideoEffectDidStartForStream:),
-        output_video_effect_did_start_for_stream as extern "C" fn(&Object, Sel, id),
-    );
-    decl.add_method(
-        sel!(outputVideoEffectDidStopForStream:),
-        output_video_effect_did_stop_for_stream as extern "C" fn(&Object, Sel, id),
-    );
-    decl.add_method(
-        sel!(stream:didStopWithError:),
-        stream_did_stop_with_error as extern "C" fn(&Object, Sel, id, id),
-    );
-    DELEGATE_CLASS = decl.register();
-
-    let mut decl = ClassDecl::new("GPUIStreamOutput", class!(NSObject)).unwrap();
-    decl.add_method(
-        sel!(stream:didOutputSampleBuffer:ofType:),
-        stream_did_output_sample_buffer_of_type as extern "C" fn(&Object, Sel, id, id, NSInteger),
-    );
-    decl.add_ivar::<*mut c_void>(FRAME_CALLBACK_IVAR);
-
-    OUTPUT_CLASS = decl.register();
+    unsafe {
+        decl.add_method(
+            sel!(outputVideoEffectDidStartForStream:),
+            output_video_effect_did_start_for_stream as extern "C" fn(&Object, Sel, id),
+        );
+        decl.add_method(
+            sel!(outputVideoEffectDidStopForStream:),
+            output_video_effect_did_stop_for_stream as extern "C" fn(&Object, Sel, id),
+        );
+        decl.add_method(
+            sel!(stream:didStopWithError:),
+            stream_did_stop_with_error as extern "C" fn(&Object, Sel, id, id),
+        );
+        DELEGATE_CLASS = decl.register();
+
+        let mut decl = ClassDecl::new("GPUIStreamOutput", class!(NSObject)).unwrap();
+        decl.add_method(
+            sel!(stream:didOutputSampleBuffer:ofType:),
+            stream_did_output_sample_buffer_of_type
+                as extern "C" fn(&Object, Sel, id, id, NSInteger),
+        );
+        decl.add_ivar::<*mut c_void>(FRAME_CALLBACK_IVAR);
+
+        OUTPUT_CLASS = decl.register();
+    }
 }
 
 extern "C" fn output_video_effect_did_start_for_stream(_this: &Object, _: Sel, _stream: id) {}

crates/gpui/src/platform/mac/text_system.rs 🔗

@@ -664,9 +664,11 @@ mod lenient_font_attributes {
     }
 
     unsafe fn wrap_under_get_rule(reference: CFStringRef) -> CFString {
-        assert!(!reference.is_null(), "Attempted to create a NULL object.");
-        let reference = CFRetain(reference as *const ::std::os::raw::c_void) as CFStringRef;
-        TCFType::wrap_under_create_rule(reference)
+        unsafe {
+            assert!(!reference.is_null(), "Attempted to create a NULL object.");
+            let reference = CFRetain(reference as *const ::std::os::raw::c_void) as CFStringRef;
+            TCFType::wrap_under_create_rule(reference)
+        }
     }
 }
 

crates/gpui/src/platform/mac/window.rs 🔗

@@ -80,7 +80,7 @@ const NSDragOperationNone: NSDragOperation = 0;
 const NSDragOperationCopy: NSDragOperation = 1;
 
 #[link(name = "CoreGraphics", kind = "framework")]
-extern "C" {
+unsafe extern "C" {
     // Widely used private APIs; Apple uses them for their Terminal.app.
     fn CGSMainConnectionID() -> id;
     fn CGSSetWindowBackgroundBlurRadius(
@@ -92,235 +92,241 @@ extern "C" {
 
 #[ctor]
 unsafe fn build_classes() {
-    WINDOW_CLASS = build_window_class("GPUIWindow", class!(NSWindow));
-    PANEL_CLASS = build_window_class("GPUIPanel", class!(NSPanel));
-    VIEW_CLASS = {
-        let mut decl = ClassDecl::new("GPUIView", class!(NSView)).unwrap();
-        decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
+    unsafe {
+        WINDOW_CLASS = build_window_class("GPUIWindow", class!(NSWindow));
+        PANEL_CLASS = build_window_class("GPUIPanel", class!(NSPanel));
+        VIEW_CLASS = {
+            let mut decl = ClassDecl::new("GPUIView", class!(NSView)).unwrap();
+            decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
+            unsafe {
+                decl.add_method(sel!(dealloc), dealloc_view as extern "C" fn(&Object, Sel));
+
+                decl.add_method(
+                    sel!(performKeyEquivalent:),
+                    handle_key_equivalent as extern "C" fn(&Object, Sel, id) -> BOOL,
+                );
+                decl.add_method(
+                    sel!(keyDown:),
+                    handle_key_down as extern "C" fn(&Object, Sel, id),
+                );
+                decl.add_method(
+                    sel!(keyUp:),
+                    handle_key_up as extern "C" fn(&Object, Sel, id),
+                );
+                decl.add_method(
+                    sel!(mouseDown:),
+                    handle_view_event as extern "C" fn(&Object, Sel, id),
+                );
+                decl.add_method(
+                    sel!(mouseUp:),
+                    handle_view_event as extern "C" fn(&Object, Sel, id),
+                );
+                decl.add_method(
+                    sel!(rightMouseDown:),
+                    handle_view_event as extern "C" fn(&Object, Sel, id),
+                );
+                decl.add_method(
+                    sel!(rightMouseUp:),
+                    handle_view_event as extern "C" fn(&Object, Sel, id),
+                );
+                decl.add_method(
+                    sel!(otherMouseDown:),
+                    handle_view_event as extern "C" fn(&Object, Sel, id),
+                );
+                decl.add_method(
+                    sel!(otherMouseUp:),
+                    handle_view_event as extern "C" fn(&Object, Sel, id),
+                );
+                decl.add_method(
+                    sel!(mouseMoved:),
+                    handle_view_event as extern "C" fn(&Object, Sel, id),
+                );
+                decl.add_method(
+                    sel!(mouseExited:),
+                    handle_view_event as extern "C" fn(&Object, Sel, id),
+                );
+                decl.add_method(
+                    sel!(mouseDragged:),
+                    handle_view_event as extern "C" fn(&Object, Sel, id),
+                );
+                decl.add_method(
+                    sel!(scrollWheel:),
+                    handle_view_event as extern "C" fn(&Object, Sel, id),
+                );
+                decl.add_method(
+                    sel!(swipeWithEvent:),
+                    handle_view_event as extern "C" fn(&Object, Sel, id),
+                );
+                decl.add_method(
+                    sel!(flagsChanged:),
+                    handle_view_event as extern "C" fn(&Object, Sel, id),
+                );
 
-        decl.add_method(sel!(dealloc), dealloc_view as extern "C" fn(&Object, Sel));
+                decl.add_method(
+                    sel!(makeBackingLayer),
+                    make_backing_layer as extern "C" fn(&Object, Sel) -> id,
+                );
+
+                decl.add_protocol(Protocol::get("CALayerDelegate").unwrap());
+                decl.add_method(
+                    sel!(viewDidChangeBackingProperties),
+                    view_did_change_backing_properties as extern "C" fn(&Object, Sel),
+                );
+                decl.add_method(
+                    sel!(setFrameSize:),
+                    set_frame_size as extern "C" fn(&Object, Sel, NSSize),
+                );
+                decl.add_method(
+                    sel!(displayLayer:),
+                    display_layer as extern "C" fn(&Object, Sel, id),
+                );
+
+                decl.add_protocol(Protocol::get("NSTextInputClient").unwrap());
+                decl.add_method(
+                    sel!(validAttributesForMarkedText),
+                    valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id,
+                );
+                decl.add_method(
+                    sel!(hasMarkedText),
+                    has_marked_text as extern "C" fn(&Object, Sel) -> BOOL,
+                );
+                decl.add_method(
+                    sel!(markedRange),
+                    marked_range as extern "C" fn(&Object, Sel) -> NSRange,
+                );
+                decl.add_method(
+                    sel!(selectedRange),
+                    selected_range as extern "C" fn(&Object, Sel) -> NSRange,
+                );
+                decl.add_method(
+                    sel!(firstRectForCharacterRange:actualRange:),
+                    first_rect_for_character_range
+                        as extern "C" fn(&Object, Sel, NSRange, id) -> NSRect,
+                );
+                decl.add_method(
+                    sel!(insertText:replacementRange:),
+                    insert_text as extern "C" fn(&Object, Sel, id, NSRange),
+                );
+                decl.add_method(
+                    sel!(setMarkedText:selectedRange:replacementRange:),
+                    set_marked_text as extern "C" fn(&Object, Sel, id, NSRange, NSRange),
+                );
+                decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel));
+                decl.add_method(
+                    sel!(attributedSubstringForProposedRange:actualRange:),
+                    attributed_substring_for_proposed_range
+                        as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
+                );
+                decl.add_method(
+                    sel!(viewDidChangeEffectiveAppearance),
+                    view_did_change_effective_appearance as extern "C" fn(&Object, Sel),
+                );
+
+                // Suppress beep on keystrokes with modifier keys.
+                decl.add_method(
+                    sel!(doCommandBySelector:),
+                    do_command_by_selector as extern "C" fn(&Object, Sel, Sel),
+                );
+
+                decl.add_method(
+                    sel!(acceptsFirstMouse:),
+                    accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL,
+                );
+
+                decl.add_method(
+                    sel!(characterIndexForPoint:),
+                    character_index_for_point as extern "C" fn(&Object, Sel, NSPoint) -> u64,
+                );
+            }
+            decl.register()
+        };
+    }
+}
+
+pub(crate) fn convert_mouse_position(position: NSPoint, window_height: Pixels) -> Point<Pixels> {
+    point(
+        px(position.x as f32),
+        // macOS screen coordinates are relative to bottom left
+        window_height - px(position.y as f32),
+    )
+}
+
+unsafe fn build_window_class(name: &'static str, superclass: &Class) -> *const Class {
+    unsafe {
+        let mut decl = ClassDecl::new(name, superclass).unwrap();
+        decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
+        decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(&Object, Sel));
 
         decl.add_method(
-            sel!(performKeyEquivalent:),
-            handle_key_equivalent as extern "C" fn(&Object, Sel, id) -> BOOL,
-        );
-        decl.add_method(
-            sel!(keyDown:),
-            handle_key_down as extern "C" fn(&Object, Sel, id),
-        );
-        decl.add_method(
-            sel!(keyUp:),
-            handle_key_up as extern "C" fn(&Object, Sel, id),
-        );
-        decl.add_method(
-            sel!(mouseDown:),
-            handle_view_event as extern "C" fn(&Object, Sel, id),
-        );
-        decl.add_method(
-            sel!(mouseUp:),
-            handle_view_event as extern "C" fn(&Object, Sel, id),
-        );
-        decl.add_method(
-            sel!(rightMouseDown:),
-            handle_view_event as extern "C" fn(&Object, Sel, id),
+            sel!(canBecomeMainWindow),
+            yes as extern "C" fn(&Object, Sel) -> BOOL,
         );
         decl.add_method(
-            sel!(rightMouseUp:),
-            handle_view_event as extern "C" fn(&Object, Sel, id),
+            sel!(canBecomeKeyWindow),
+            yes as extern "C" fn(&Object, Sel) -> BOOL,
         );
         decl.add_method(
-            sel!(otherMouseDown:),
-            handle_view_event as extern "C" fn(&Object, Sel, id),
+            sel!(windowDidResize:),
+            window_did_resize as extern "C" fn(&Object, Sel, id),
         );
         decl.add_method(
-            sel!(otherMouseUp:),
-            handle_view_event as extern "C" fn(&Object, Sel, id),
+            sel!(windowDidChangeOcclusionState:),
+            window_did_change_occlusion_state as extern "C" fn(&Object, Sel, id),
         );
         decl.add_method(
-            sel!(mouseMoved:),
-            handle_view_event as extern "C" fn(&Object, Sel, id),
+            sel!(windowWillEnterFullScreen:),
+            window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id),
         );
         decl.add_method(
-            sel!(mouseExited:),
-            handle_view_event as extern "C" fn(&Object, Sel, id),
+            sel!(windowWillExitFullScreen:),
+            window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id),
         );
         decl.add_method(
-            sel!(mouseDragged:),
-            handle_view_event as extern "C" fn(&Object, Sel, id),
+            sel!(windowDidMove:),
+            window_did_move as extern "C" fn(&Object, Sel, id),
         );
         decl.add_method(
-            sel!(scrollWheel:),
-            handle_view_event as extern "C" fn(&Object, Sel, id),
+            sel!(windowDidChangeScreen:),
+            window_did_change_screen as extern "C" fn(&Object, Sel, id),
         );
         decl.add_method(
-            sel!(swipeWithEvent:),
-            handle_view_event as extern "C" fn(&Object, Sel, id),
+            sel!(windowDidBecomeKey:),
+            window_did_change_key_status as extern "C" fn(&Object, Sel, id),
         );
         decl.add_method(
-            sel!(flagsChanged:),
-            handle_view_event as extern "C" fn(&Object, Sel, id),
+            sel!(windowDidResignKey:),
+            window_did_change_key_status as extern "C" fn(&Object, Sel, id),
         );
-
         decl.add_method(
-            sel!(makeBackingLayer),
-            make_backing_layer as extern "C" fn(&Object, Sel) -> id,
+            sel!(windowShouldClose:),
+            window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
         );
 
-        decl.add_protocol(Protocol::get("CALayerDelegate").unwrap());
-        decl.add_method(
-            sel!(viewDidChangeBackingProperties),
-            view_did_change_backing_properties as extern "C" fn(&Object, Sel),
-        );
-        decl.add_method(
-            sel!(setFrameSize:),
-            set_frame_size as extern "C" fn(&Object, Sel, NSSize),
-        );
-        decl.add_method(
-            sel!(displayLayer:),
-            display_layer as extern "C" fn(&Object, Sel, id),
-        );
+        decl.add_method(sel!(close), close_window as extern "C" fn(&Object, Sel));
 
-        decl.add_protocol(Protocol::get("NSTextInputClient").unwrap());
-        decl.add_method(
-            sel!(validAttributesForMarkedText),
-            valid_attributes_for_marked_text as extern "C" fn(&Object, Sel) -> id,
-        );
-        decl.add_method(
-            sel!(hasMarkedText),
-            has_marked_text as extern "C" fn(&Object, Sel) -> BOOL,
-        );
-        decl.add_method(
-            sel!(markedRange),
-            marked_range as extern "C" fn(&Object, Sel) -> NSRange,
-        );
-        decl.add_method(
-            sel!(selectedRange),
-            selected_range as extern "C" fn(&Object, Sel) -> NSRange,
-        );
-        decl.add_method(
-            sel!(firstRectForCharacterRange:actualRange:),
-            first_rect_for_character_range as extern "C" fn(&Object, Sel, NSRange, id) -> NSRect,
-        );
-        decl.add_method(
-            sel!(insertText:replacementRange:),
-            insert_text as extern "C" fn(&Object, Sel, id, NSRange),
-        );
-        decl.add_method(
-            sel!(setMarkedText:selectedRange:replacementRange:),
-            set_marked_text as extern "C" fn(&Object, Sel, id, NSRange, NSRange),
-        );
-        decl.add_method(sel!(unmarkText), unmark_text as extern "C" fn(&Object, Sel));
         decl.add_method(
-            sel!(attributedSubstringForProposedRange:actualRange:),
-            attributed_substring_for_proposed_range
-                as extern "C" fn(&Object, Sel, NSRange, *mut c_void) -> id,
+            sel!(draggingEntered:),
+            dragging_entered as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
         );
         decl.add_method(
-            sel!(viewDidChangeEffectiveAppearance),
-            view_did_change_effective_appearance as extern "C" fn(&Object, Sel),
+            sel!(draggingUpdated:),
+            dragging_updated as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
         );
-
-        // Suppress beep on keystrokes with modifier keys.
         decl.add_method(
-            sel!(doCommandBySelector:),
-            do_command_by_selector as extern "C" fn(&Object, Sel, Sel),
+            sel!(draggingExited:),
+            dragging_exited as extern "C" fn(&Object, Sel, id),
         );
-
         decl.add_method(
-            sel!(acceptsFirstMouse:),
-            accepts_first_mouse as extern "C" fn(&Object, Sel, id) -> BOOL,
+            sel!(performDragOperation:),
+            perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL,
         );
-
         decl.add_method(
-            sel!(characterIndexForPoint:),
-            character_index_for_point as extern "C" fn(&Object, Sel, NSPoint) -> u64,
+            sel!(concludeDragOperation:),
+            conclude_drag_operation as extern "C" fn(&Object, Sel, id),
         );
 
         decl.register()
-    };
-}
-
-pub(crate) fn convert_mouse_position(position: NSPoint, window_height: Pixels) -> Point<Pixels> {
-    point(
-        px(position.x as f32),
-        // macOS screen coordinates are relative to bottom left
-        window_height - px(position.y as f32),
-    )
-}
-
-unsafe fn build_window_class(name: &'static str, superclass: &Class) -> *const Class {
-    let mut decl = ClassDecl::new(name, superclass).unwrap();
-    decl.add_ivar::<*mut c_void>(WINDOW_STATE_IVAR);
-    decl.add_method(sel!(dealloc), dealloc_window as extern "C" fn(&Object, Sel));
-    decl.add_method(
-        sel!(canBecomeMainWindow),
-        yes as extern "C" fn(&Object, Sel) -> BOOL,
-    );
-    decl.add_method(
-        sel!(canBecomeKeyWindow),
-        yes as extern "C" fn(&Object, Sel) -> BOOL,
-    );
-    decl.add_method(
-        sel!(windowDidResize:),
-        window_did_resize as extern "C" fn(&Object, Sel, id),
-    );
-    decl.add_method(
-        sel!(windowDidChangeOcclusionState:),
-        window_did_change_occlusion_state as extern "C" fn(&Object, Sel, id),
-    );
-    decl.add_method(
-        sel!(windowWillEnterFullScreen:),
-        window_will_enter_fullscreen as extern "C" fn(&Object, Sel, id),
-    );
-    decl.add_method(
-        sel!(windowWillExitFullScreen:),
-        window_will_exit_fullscreen as extern "C" fn(&Object, Sel, id),
-    );
-    decl.add_method(
-        sel!(windowDidMove:),
-        window_did_move as extern "C" fn(&Object, Sel, id),
-    );
-    decl.add_method(
-        sel!(windowDidChangeScreen:),
-        window_did_change_screen as extern "C" fn(&Object, Sel, id),
-    );
-    decl.add_method(
-        sel!(windowDidBecomeKey:),
-        window_did_change_key_status as extern "C" fn(&Object, Sel, id),
-    );
-    decl.add_method(
-        sel!(windowDidResignKey:),
-        window_did_change_key_status as extern "C" fn(&Object, Sel, id),
-    );
-    decl.add_method(
-        sel!(windowShouldClose:),
-        window_should_close as extern "C" fn(&Object, Sel, id) -> BOOL,
-    );
-
-    decl.add_method(sel!(close), close_window as extern "C" fn(&Object, Sel));
-
-    decl.add_method(
-        sel!(draggingEntered:),
-        dragging_entered as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
-    );
-    decl.add_method(
-        sel!(draggingUpdated:),
-        dragging_updated as extern "C" fn(&Object, Sel, id) -> NSDragOperation,
-    );
-    decl.add_method(
-        sel!(draggingExited:),
-        dragging_exited as extern "C" fn(&Object, Sel, id),
-    );
-    decl.add_method(
-        sel!(performDragOperation:),
-        perform_drag_operation as extern "C" fn(&Object, Sel, id) -> BOOL,
-    );
-    decl.add_method(
-        sel!(concludeDragOperation:),
-        conclude_drag_operation as extern "C" fn(&Object, Sel, id),
-    );
-
-    decl.register()
+    }
 }
 
 struct MacWindowState {
@@ -913,7 +919,7 @@ impl PlatformWindow for MacWindow {
             .iter()
             .enumerate()
             .rev()
-            .find(|(_, &label)| label != "Cancel")
+            .find(|(_, label)| **label != "Cancel")
             .filter(|&(label_index, _)| label_index > 0);
 
         unsafe {
@@ -1200,16 +1206,20 @@ fn get_scale_factor(native_window: id) -> f32 {
 }
 
 unsafe fn get_window_state(object: &Object) -> Arc<Mutex<MacWindowState>> {
-    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
-    let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
-    let rc2 = rc1.clone();
-    mem::forget(rc1);
-    rc2
+    unsafe {
+        let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
+        let rc1 = Arc::from_raw(raw as *mut Mutex<MacWindowState>);
+        let rc2 = rc1.clone();
+        mem::forget(rc1);
+        rc2
+    }
 }
 
 unsafe fn drop_window_state(object: &Object) {
-    let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
-    Arc::from_raw(raw as *mut Mutex<MacWindowState>);
+    unsafe {
+        let raw: *mut c_void = *object.get_ivar(WINDOW_STATE_IVAR);
+        Arc::from_raw(raw as *mut Mutex<MacWindowState>);
+    }
 }
 
 extern "C" fn yes(_: &Object, _: Sel) -> BOOL {
@@ -2069,9 +2079,11 @@ where
 }
 
 unsafe fn display_id_for_screen(screen: id) -> CGDirectDisplayID {
-    let device_description = NSScreen::deviceDescription(screen);
-    let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
-    let screen_number = device_description.objectForKey_(screen_number_key);
-    let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
-    screen_number as CGDirectDisplayID
+    unsafe {
+        let device_description = NSScreen::deviceDescription(screen);
+        let screen_number_key: id = NSString::alloc(nil).init_str("NSScreenNumber");
+        let screen_number = device_description.objectForKey_(screen_number_key);
+        let screen_number: NSUInteger = msg_send![screen_number, unsignedIntegerValue];
+        screen_number as CGDirectDisplayID
+    }
 }

crates/gpui/src/platform/mac/window_appearance.rs 🔗

@@ -10,26 +10,28 @@ use std::ffi::CStr;
 impl WindowAppearance {
     pub(crate) unsafe fn from_native(appearance: id) -> Self {
         let name: id = msg_send![appearance, name];
-        if name == NSAppearanceNameVibrantLight {
-            Self::VibrantLight
-        } else if name == NSAppearanceNameVibrantDark {
-            Self::VibrantDark
-        } else if name == NSAppearanceNameAqua {
-            Self::Light
-        } else if name == NSAppearanceNameDarkAqua {
-            Self::Dark
-        } else {
-            println!(
-                "unknown appearance: {:?}",
-                CStr::from_ptr(name.UTF8String())
-            );
-            Self::Light
+        unsafe {
+            if name == NSAppearanceNameVibrantLight {
+                Self::VibrantLight
+            } else if name == NSAppearanceNameVibrantDark {
+                Self::VibrantDark
+            } else if name == NSAppearanceNameAqua {
+                Self::Light
+            } else if name == NSAppearanceNameDarkAqua {
+                Self::Dark
+            } else {
+                println!(
+                    "unknown appearance: {:?}",
+                    CStr::from_ptr(name.UTF8String())
+                );
+                Self::Light
+            }
         }
     }
 }
 
 #[link(name = "AppKit", kind = "framework")]
-extern "C" {
+unsafe extern "C" {
     pub static NSAppearanceNameAqua: id;
     pub static NSAppearanceNameDarkAqua: id;
 }

crates/gpui/src/platform/test/dispatcher.rs 🔗

@@ -89,7 +89,7 @@ impl TestDispatcher {
         self.state.lock().time = new_now;
     }
 
-    pub fn simulate_random_delay(&self) -> impl 'static + Send + Future<Output = ()> {
+    pub fn simulate_random_delay(&self) -> impl 'static + Send + Future<Output = ()> + use<> {
         struct YieldNow {
             pub(crate) count: usize,
         }

crates/gpui/src/platform/windows/direct_write.rs 🔗

@@ -333,7 +333,7 @@ impl DirectWriteState {
         &self,
         font_features: &FontFeatures,
     ) -> Result<IDWriteTypography> {
-        let direct_write_features = self.components.factory.CreateTypography()?;
+        let direct_write_features = unsafe { self.components.factory.CreateTypography()? };
         apply_font_features(&direct_write_features, font_features)?;
         Ok(direct_write_features)
     }
@@ -352,28 +352,32 @@ impl DirectWriteState {
         } else {
             &self.custom_font_collection
         };
-        let fontset = collection.GetFontSet().log_err()?;
-        let font = fontset
-            .GetMatchingFonts(
-                &HSTRING::from(family_name),
-                font_weight.into(),
-                DWRITE_FONT_STRETCH_NORMAL,
-                font_style.into(),
-            )
-            .log_err()?;
-        let total_number = font.GetFontCount();
+        let fontset = unsafe { collection.GetFontSet().log_err()? };
+        let font = unsafe {
+            fontset
+                .GetMatchingFonts(
+                    &HSTRING::from(family_name),
+                    font_weight.into(),
+                    DWRITE_FONT_STRETCH_NORMAL,
+                    font_style.into(),
+                )
+                .log_err()?
+        };
+        let total_number = unsafe { font.GetFontCount() };
         for index in 0..total_number {
-            let Some(font_face_ref) = font.GetFontFaceReference(index).log_err() else {
+            let Some(font_face_ref) = (unsafe { font.GetFontFaceReference(index).log_err() })
+            else {
                 continue;
             };
-            let Some(font_face) = font_face_ref.CreateFontFace().log_err() else {
+            let Some(font_face) = (unsafe { font_face_ref.CreateFontFace().log_err() }) else {
                 continue;
             };
             let Some(identifier) = get_font_identifier(&font_face, &self.components.locale) else {
                 continue;
             };
-            let is_emoji = font_face.IsColorFont().as_bool();
-            let Some(direct_write_features) = self.generate_font_features(font_features).log_err()
+            let is_emoji = unsafe { font_face.IsColorFont().as_bool() };
+            let Some(direct_write_features) =
+                (unsafe { self.generate_font_features(font_features).log_err() })
             else {
                 continue;
             };
@@ -396,14 +400,14 @@ impl DirectWriteState {
     }
 
     unsafe fn update_system_font_collection(&mut self) {
-        let mut collection = std::mem::zeroed();
-        if self
-            .components
-            .factory
-            .GetSystemFontCollection(false, &mut collection, true)
-            .log_err()
-            .is_some()
-        {
+        let mut collection = unsafe { std::mem::zeroed() };
+        if unsafe {
+            self.components
+                .factory
+                .GetSystemFontCollection(false, &mut collection, true)
+                .log_err()
+                .is_some()
+        } {
             self.system_font_collection = collection.unwrap();
         }
     }
@@ -461,35 +465,37 @@ impl DirectWriteState {
         fallbacks: Option<&FontFallbacks>,
     ) -> Option<FontId> {
         // try to find target font in custom font collection first
-        self.get_font_id_from_font_collection(
-            family_name,
-            weight,
-            style,
-            features,
-            fallbacks,
-            false,
-        )
-        .or_else(|| {
-            self.get_font_id_from_font_collection(
-                family_name,
-                weight,
-                style,
-                features,
-                fallbacks,
-                true,
-            )
-        })
-        .or_else(|| {
-            self.update_system_font_collection();
+        unsafe {
             self.get_font_id_from_font_collection(
                 family_name,
                 weight,
                 style,
                 features,
                 fallbacks,
-                true,
+                false,
             )
-        })
+            .or_else(|| {
+                self.get_font_id_from_font_collection(
+                    family_name,
+                    weight,
+                    style,
+                    features,
+                    fallbacks,
+                    true,
+                )
+            })
+            .or_else(|| {
+                self.update_system_font_collection();
+                self.get_font_id_from_font_collection(
+                    family_name,
+                    weight,
+                    style,
+                    features,
+                    fallbacks,
+                    true,
+                )
+            })
+        }
     }
 
     fn layout_line(

crates/gpui/src/shared_string.rs 🔗

@@ -27,8 +27,8 @@ impl JsonSchema for SharedString {
         String::schema_name()
     }
 
-    fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
-        String::json_schema(gen)
+    fn json_schema(r#gen: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
+        String::json_schema(r#gen)
     }
 }
 

crates/gpui/src/subscription.rs 🔗

@@ -45,7 +45,7 @@ where
         &self,
         emitter_key: EmitterKey,
         callback: Callback,
-    ) -> (Subscription, impl FnOnce()) {
+    ) -> (Subscription, impl FnOnce() + use<EmitterKey, Callback>) {
         let active = Rc::new(Cell::new(false));
         let mut lock = self.0.lock();
         let subscriber_id = post_inc(&mut lock.next_subscriber_id);
@@ -88,7 +88,10 @@ where
         (subscription, move || active.set(true))
     }
 
-    pub fn remove(&self, emitter: &EmitterKey) -> impl IntoIterator<Item = Callback> {
+    pub fn remove(
+        &self,
+        emitter: &EmitterKey,
+    ) -> impl IntoIterator<Item = Callback> + use<EmitterKey, Callback> {
         let subscribers = self.0.lock().subscribers.remove(emitter);
         subscribers
             .unwrap_or_default()

crates/gpui/src/text_system/font_features.rs 🔗

@@ -133,7 +133,7 @@ impl schemars::JsonSchema for FontFeatures {
         "FontFeatures".into()
     }
 
-    fn json_schema(_: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
+    fn json_schema(_: &mut schemars::r#gen::SchemaGenerator) -> schemars::schema::Schema {
         let mut schema = SchemaObject::default();
         schema.instance_type = Some(schemars::schema::SingleOrVec::Single(Box::new(
             InstanceType::Object,

crates/gpui/src/window.rs 🔗

@@ -936,7 +936,7 @@ impl Window {
     pub(crate) fn new_focus_listener(
         &self,
         value: AnyWindowFocusListener,
-    ) -> (Subscription, impl FnOnce()) {
+    ) -> (Subscription, impl FnOnce() + use<>) {
         self.focus_listeners.insert((), value)
     }
 }
@@ -3719,11 +3719,11 @@ impl Window {
     }
 
     /// Returns a generic handler that invokes the given handler with the view and context associated with the given view handle.
-    pub fn handler_for<V: Render>(
+    pub fn handler_for<V: Render, Callback: Fn(&mut V, &mut Window, &mut Context<V>) + 'static>(
         &self,
         view: &Entity<V>,
-        f: impl Fn(&mut V, &mut Window, &mut Context<V>) + 'static,
-    ) -> impl Fn(&mut Window, &mut App) {
+        f: Callback,
+    ) -> impl Fn(&mut Window, &mut App) + use<V, Callback> {
         let view = view.downgrade();
         move |window: &mut Window, cx: &mut App| {
             view.update(cx, |view, cx| f(view, window, cx)).ok();

crates/gpui_macros/src/derive_app_context.rs 🔗

@@ -17,7 +17,7 @@ pub fn derive_app_context(input: TokenStream) -> TokenStream {
     let type_name = &ast.ident;
     let (impl_generics, type_generics, where_clause) = ast.generics.split_for_impl();
 
-    let gen = quote! {
+    let r#gen = quote! {
         impl #impl_generics gpui::AppContext for #type_name #type_generics
         #where_clause
         {
@@ -98,5 +98,5 @@ pub fn derive_app_context(input: TokenStream) -> TokenStream {
         }
     };
 
-    gen.into()
+    r#gen.into()
 }

crates/gpui_macros/src/derive_into_element.rs 🔗

@@ -7,7 +7,7 @@ pub fn derive_into_element(input: TokenStream) -> TokenStream {
     let type_name = &ast.ident;
     let (impl_generics, type_generics, where_clause) = ast.generics.split_for_impl();
 
-    let gen = quote! {
+    let r#gen = quote! {
         impl #impl_generics gpui::IntoElement for #type_name #type_generics
         #where_clause
         {
@@ -19,5 +19,5 @@ pub fn derive_into_element(input: TokenStream) -> TokenStream {
         }
     };
 
-    gen.into()
+    r#gen.into()
 }

crates/gpui_macros/src/derive_render.rs 🔗

@@ -7,7 +7,7 @@ pub fn derive_render(input: TokenStream) -> TokenStream {
     let type_name = &ast.ident;
     let (impl_generics, type_generics, where_clause) = ast.generics.split_for_impl();
 
-    let gen = quote! {
+    let r#gen = quote! {
         impl #impl_generics gpui::Render for #type_name #type_generics
         #where_clause
         {
@@ -17,5 +17,5 @@ pub fn derive_render(input: TokenStream) -> TokenStream {
         }
     };
 
-    gen.into()
+    r#gen.into()
 }

crates/gpui_macros/src/derive_visual_context.rs 🔗

@@ -24,7 +24,7 @@ pub fn derive_visual_context(input: TokenStream) -> TokenStream {
     let type_name = &ast.ident;
     let (impl_generics, type_generics, where_clause) = ast.generics.split_for_impl();
 
-    let gen = quote! {
+    let r#gen = quote! {
         impl #impl_generics gpui::VisualContext for #type_name #type_generics
         #where_clause
         {
@@ -67,5 +67,5 @@ pub fn derive_visual_context(input: TokenStream) -> TokenStream {
         }
     };
 
-    gen.into()
+    r#gen.into()
 }

crates/gpui_macros/src/styles.rs 🔗

@@ -1292,27 +1292,27 @@ fn border_prefixes() -> Vec<BorderStylePrefix> {
                 quote! { border_widths.bottom },
                 quote! { border_widths.left },
             ],
-            doc_string_prefix: "Sets the border width of the element. [Docs](https://tailwindcss.com/docs/border-width)"
+            doc_string_prefix: "Sets the border width of the element. [Docs](https://tailwindcss.com/docs/border-width)",
         },
         BorderStylePrefix {
             prefix: "border_t",
             fields: vec![quote! { border_widths.top }],
-            doc_string_prefix: "Sets the border width of the top side of the element. [Docs](https://tailwindcss.com/docs/border-width#individual-sides)"
+            doc_string_prefix: "Sets the border width of the top side of the element. [Docs](https://tailwindcss.com/docs/border-width#individual-sides)",
         },
         BorderStylePrefix {
             prefix: "border_b",
             fields: vec![quote! { border_widths.bottom }],
-            doc_string_prefix: "Sets the border width of the bottom side of the element. [Docs](https://tailwindcss.com/docs/border-width#individual-sides)"
+            doc_string_prefix: "Sets the border width of the bottom side of the element. [Docs](https://tailwindcss.com/docs/border-width#individual-sides)",
         },
         BorderStylePrefix {
             prefix: "border_r",
             fields: vec![quote! { border_widths.right }],
-            doc_string_prefix: "Sets the border width of the right side of the element. [Docs](https://tailwindcss.com/docs/border-width#individual-sides)"
+            doc_string_prefix: "Sets the border width of the right side of the element. [Docs](https://tailwindcss.com/docs/border-width#individual-sides)",
         },
         BorderStylePrefix {
             prefix: "border_l",
             fields: vec![quote! { border_widths.left }],
-            doc_string_prefix: "Sets the border width of the left side of the element. [Docs](https://tailwindcss.com/docs/border-width#individual-sides)"
+            doc_string_prefix: "Sets the border width of the left side of the element. [Docs](https://tailwindcss.com/docs/border-width#individual-sides)",
         },
         BorderStylePrefix {
             prefix: "border_x",
@@ -1320,7 +1320,7 @@ fn border_prefixes() -> Vec<BorderStylePrefix> {
                 quote! { border_widths.left },
                 quote! { border_widths.right },
             ],
-            doc_string_prefix: "Sets the border width of the vertical sides of the element. [Docs](https://tailwindcss.com/docs/border-width#horizontal-and-vertical-sides)"
+            doc_string_prefix: "Sets the border width of the vertical sides of the element. [Docs](https://tailwindcss.com/docs/border-width#horizontal-and-vertical-sides)",
         },
         BorderStylePrefix {
             prefix: "border_y",
@@ -1328,7 +1328,7 @@ fn border_prefixes() -> Vec<BorderStylePrefix> {
                 quote! { border_widths.top },
                 quote! { border_widths.bottom },
             ],
-            doc_string_prefix: "Sets the border width of the horizontal sides of the element. [Docs](https://tailwindcss.com/docs/border-width#horizontal-and-vertical-sides)"
+            doc_string_prefix: "Sets the border width of the horizontal sides of the element. [Docs](https://tailwindcss.com/docs/border-width#horizontal-and-vertical-sides)",
         },
     ]
 }

crates/image_viewer/src/image_viewer.rs 🔗

@@ -441,7 +441,9 @@ mod persistence {
                 .collect::<Vec<&str>>()
                 .join(", ");
 
-            let query = format!("DELETE FROM image_viewers WHERE workspace_id = ? AND item_id NOT IN ({placeholders})");
+            let query = format!(
+                "DELETE FROM image_viewers WHERE workspace_id = ? AND item_id NOT IN ({placeholders})"
+            );
 
             self.write(move |conn| {
                 let mut statement = Statement::prepare(conn, query)?;

crates/language/src/buffer.rs 🔗

@@ -989,7 +989,7 @@ impl Buffer {
         language: Option<Arc<Language>>,
         language_registry: Option<Arc<LanguageRegistry>>,
         cx: &mut App,
-    ) -> impl Future<Output = BufferSnapshot> {
+    ) -> impl Future<Output = BufferSnapshot> + use<> {
         let entity_id = cx.reserve_entity::<Self>().entity_id();
         let buffer_id = entity_id.as_non_zero_u64().into();
         async move {
@@ -1587,7 +1587,9 @@ impl Buffer {
         }
     }
 
-    fn compute_autoindents(&self) -> Option<impl Future<Output = BTreeMap<u32, IndentSize>>> {
+    fn compute_autoindents(
+        &self,
+    ) -> Option<impl Future<Output = BTreeMap<u32, IndentSize>> + use<>> {
         let max_rows_between_yields = 100;
         let snapshot = self.snapshot();
         if snapshot.syntax.is_empty() || self.autoindent_requests.is_empty() {
@@ -2082,23 +2084,26 @@ impl Buffer {
     }
 
     /// Waits for the buffer to receive operations with the given timestamps.
-    pub fn wait_for_edits(
+    pub fn wait_for_edits<It: IntoIterator<Item = clock::Lamport>>(
         &mut self,
-        edit_ids: impl IntoIterator<Item = clock::Lamport>,
-    ) -> impl Future<Output = Result<()>> {
+        edit_ids: It,
+    ) -> impl Future<Output = Result<()>> + use<It> {
         self.text.wait_for_edits(edit_ids)
     }
 
     /// Waits for the buffer to receive the operations necessary for resolving the given anchors.
-    pub fn wait_for_anchors(
+    pub fn wait_for_anchors<It: IntoIterator<Item = Anchor>>(
         &mut self,
-        anchors: impl IntoIterator<Item = Anchor>,
-    ) -> impl 'static + Future<Output = Result<()>> {
+        anchors: It,
+    ) -> impl 'static + Future<Output = Result<()>> + use<It> {
         self.text.wait_for_anchors(anchors)
     }
 
     /// Waits for the buffer to receive operations up to the given version.
-    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = Result<()>> {
+    pub fn wait_for_version(
+        &mut self,
+        version: clock::Global,
+    ) -> impl Future<Output = Result<()>> + use<> {
         self.text.wait_for_version(version)
     }
 
@@ -3916,91 +3921,93 @@ impl BufferSnapshot {
             .map(|grammar| grammar.runnable_config.as_ref())
             .collect::<Vec<_>>();
 
-        iter::from_fn(move || loop {
-            let mat = syntax_matches.peek()?;
-
-            let test_range = test_configs[mat.grammar_index].and_then(|test_configs| {
-                let mut run_range = None;
-                let full_range = mat.captures.iter().fold(
-                    Range {
-                        start: usize::MAX,
-                        end: 0,
-                    },
-                    |mut acc, next| {
-                        let byte_range = next.node.byte_range();
-                        if acc.start > byte_range.start {
-                            acc.start = byte_range.start;
-                        }
-                        if acc.end < byte_range.end {
-                            acc.end = byte_range.end;
-                        }
-                        acc
-                    },
-                );
-                if full_range.start > full_range.end {
-                    // We did not find a full spanning range of this match.
-                    return None;
-                }
-                let extra_captures: SmallVec<[_; 1]> =
-                    SmallVec::from_iter(mat.captures.iter().filter_map(|capture| {
-                        test_configs
-                            .extra_captures
-                            .get(capture.index as usize)
-                            .cloned()
-                            .and_then(|tag_name| match tag_name {
-                                RunnableCapture::Named(name) => {
-                                    Some((capture.node.byte_range(), name))
-                                }
-                                RunnableCapture::Run => {
-                                    let _ = run_range.insert(capture.node.byte_range());
-                                    None
-                                }
-                            })
-                    }));
-                let run_range = run_range?;
-                let tags = test_configs
-                    .query
-                    .property_settings(mat.pattern_index)
-                    .iter()
-                    .filter_map(|property| {
-                        if *property.key == *"tag" {
-                            property
-                                .value
-                                .as_ref()
-                                .map(|value| RunnableTag(value.to_string().into()))
-                        } else {
-                            None
-                        }
-                    })
-                    .collect();
-                let extra_captures = extra_captures
-                    .into_iter()
-                    .map(|(range, name)| {
-                        (
-                            name.to_string(),
-                            self.text_for_range(range.clone()).collect::<String>(),
-                        )
+        iter::from_fn(move || {
+            loop {
+                let mat = syntax_matches.peek()?;
+
+                let test_range = test_configs[mat.grammar_index].and_then(|test_configs| {
+                    let mut run_range = None;
+                    let full_range = mat.captures.iter().fold(
+                        Range {
+                            start: usize::MAX,
+                            end: 0,
+                        },
+                        |mut acc, next| {
+                            let byte_range = next.node.byte_range();
+                            if acc.start > byte_range.start {
+                                acc.start = byte_range.start;
+                            }
+                            if acc.end < byte_range.end {
+                                acc.end = byte_range.end;
+                            }
+                            acc
+                        },
+                    );
+                    if full_range.start > full_range.end {
+                        // We did not find a full spanning range of this match.
+                        return None;
+                    }
+                    let extra_captures: SmallVec<[_; 1]> =
+                        SmallVec::from_iter(mat.captures.iter().filter_map(|capture| {
+                            test_configs
+                                .extra_captures
+                                .get(capture.index as usize)
+                                .cloned()
+                                .and_then(|tag_name| match tag_name {
+                                    RunnableCapture::Named(name) => {
+                                        Some((capture.node.byte_range(), name))
+                                    }
+                                    RunnableCapture::Run => {
+                                        let _ = run_range.insert(capture.node.byte_range());
+                                        None
+                                    }
+                                })
+                        }));
+                    let run_range = run_range?;
+                    let tags = test_configs
+                        .query
+                        .property_settings(mat.pattern_index)
+                        .iter()
+                        .filter_map(|property| {
+                            if *property.key == *"tag" {
+                                property
+                                    .value
+                                    .as_ref()
+                                    .map(|value| RunnableTag(value.to_string().into()))
+                            } else {
+                                None
+                            }
+                        })
+                        .collect();
+                    let extra_captures = extra_captures
+                        .into_iter()
+                        .map(|(range, name)| {
+                            (
+                                name.to_string(),
+                                self.text_for_range(range.clone()).collect::<String>(),
+                            )
+                        })
+                        .collect();
+                    // All tags should have the same range.
+                    Some(RunnableRange {
+                        run_range,
+                        full_range,
+                        runnable: Runnable {
+                            tags,
+                            language: mat.language,
+                            buffer: self.remote_id(),
+                        },
+                        extra_captures,
+                        buffer_id: self.remote_id(),
                     })
-                    .collect();
-                // All tags should have the same range.
-                Some(RunnableRange {
-                    run_range,
-                    full_range,
-                    runnable: Runnable {
-                        tags,
-                        language: mat.language,
-                        buffer: self.remote_id(),
-                    },
-                    extra_captures,
-                    buffer_id: self.remote_id(),
-                })
-            });
+                });
 
-            syntax_matches.advance();
-            if test_range.is_some() {
-                // It's fine for us to short-circuit on .peek()? returning None. We don't want to return None from this iter if we
-                // had a capture that did not contain a run marker, hence we'll just loop around for the next capture.
-                return test_range;
+                syntax_matches.advance();
+                if test_range.is_some() {
+                    // It's fine for us to short-circuit on .peek()? returning None. We don't want to return None from this iter if we
+                    // had a capture that did not contain a run marker, hence we'll just loop around for the next capture.
+                    return test_range;
+                }
             }
         })
     }
@@ -4352,7 +4359,10 @@ impl<'a> BufferChunks<'a> {
             } else {
                 // We cannot obtain new highlights for a language-aware buffer iterator, as we don't have a buffer snapshot.
                 // Seeking such BufferChunks is not supported.
-                debug_assert!(false, "Attempted to seek on a language-aware buffer iterator without associated buffer snapshot");
+                debug_assert!(
+                    false,
+                    "Attempted to seek on a language-aware buffer iterator without associated buffer snapshot"
+                );
             }
 
             highlights.captures.set_byte_range(self.range.clone());

crates/language/src/language.rs 🔗

@@ -38,7 +38,7 @@ pub use manifest::{ManifestName, ManifestProvider, ManifestQuery};
 use parking_lot::Mutex;
 use regex::Regex;
 use schemars::{
-    gen::SchemaGenerator,
+    r#gen::SchemaGenerator,
     schema::{InstanceType, Schema, SchemaObject},
     JsonSchema,
 };
@@ -598,7 +598,9 @@ pub trait LspAdapter: 'static + Send + Sync {
     /// Should not be called unless the callee is sure that
     /// `Self::is_primary_zed_json_schema_adapter` returns `true`
     async fn clear_zed_json_schema_cache(&self) {
-        unreachable!("Not implemented for this adapter. This method should only be called on the default JSON language server adapter");
+        unreachable!(
+            "Not implemented for this adapter. This method should only be called on the default JSON language server adapter"
+        );
     }
 }
 
@@ -931,8 +933,8 @@ impl BracketPairConfig {
     }
 }
 
-fn bracket_pair_config_json_schema(gen: &mut SchemaGenerator) -> Schema {
-    Option::<Vec<BracketPairContent>>::json_schema(gen)
+fn bracket_pair_config_json_schema(r#gen: &mut SchemaGenerator) -> Schema {
+    Option::<Vec<BracketPairContent>>::json_schema(r#gen)
 }
 
 #[derive(Deserialize, JsonSchema)]
@@ -1532,7 +1534,9 @@ impl Language {
                     .scope_opt_in_language_servers
                     .contains(server_name)
                 {
-                    util::debug_panic!("Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server");
+                    util::debug_panic!(
+                        "Server {server_name:?} has been opted-in by scope {name:?} but has not been marked as an opt-in server"
+                    );
                 }
             }
 

crates/language/src/language_registry.rs 🔗

@@ -597,7 +597,7 @@ impl LanguageRegistry {
     pub fn language_for_name(
         self: &Arc<Self>,
         name: &str,
-    ) -> impl Future<Output = Result<Arc<Language>>> {
+    ) -> impl Future<Output = Result<Arc<Language>>> + use<> {
         let name = UniCase::new(name);
         let rx = self.get_or_load_language(|language_name, _| {
             if UniCase::new(&language_name.0) == name {

crates/language/src/language_settings.rs 🔗

@@ -1300,7 +1300,7 @@ impl settings::Settings for AllLanguageSettings {
     }
 
     fn json_schema(
-        generator: &mut schemars::gen::SchemaGenerator,
+        generator: &mut schemars::r#gen::SchemaGenerator,
         params: &settings::SettingsJsonSchemaParams,
         _: &App,
     ) -> schemars::schema::RootSchema {

crates/language/src/syntax_map/syntax_map_tests.rs 🔗

@@ -153,14 +153,14 @@ fn test_syntax_map_layers_for_range(cx: &mut App) {
     syntax_map.reparse(language.clone(), &buffer);
 
     assert_layers_for_range(
-            &syntax_map,
-            &buffer,
-            Point::new(2, 14)..Point::new(2, 16),
-            &[
-                "...(function_item ...",
-                "...(tuple_expression (call_expression ... arguments: (arguments (reference_expression value: (array_expression...",
-            ],
-        );
+        &syntax_map,
+        &buffer,
+        Point::new(2, 14)..Point::new(2, 16),
+        &[
+            "...(function_item ...",
+            "...(tuple_expression (call_expression ... arguments: (arguments (reference_expression value: (array_expression...",
+        ],
+    );
 
     // Put the vec! macro back, adding back the syntactic layer.
     buffer.undo();
@@ -207,15 +207,15 @@ fn test_dynamic_language_injection(cx: &mut App) {
     syntax_map.reparse(markdown.clone(), &buffer);
     syntax_map.reparse(markdown_inline.clone(), &buffer);
     assert_layers_for_range(
-            &syntax_map,
-            &buffer,
-            Point::new(3, 0)..Point::new(3, 0),
-            &[
-                "(document (section (paragraph (inline)) (fenced_code_block (fenced_code_block_delimiter) (info_string (language)) (block_continuation) (code_fence_content (block_continuation)) (fenced_code_block_delimiter))))",
-                "(inline (code_span (code_span_delimiter) (code_span_delimiter)))",
-                "...(function_item name: (identifier) parameters: (parameters) body: (block)...",
-            ],
-        );
+        &syntax_map,
+        &buffer,
+        Point::new(3, 0)..Point::new(3, 0),
+        &[
+            "(document (section (paragraph (inline)) (fenced_code_block (fenced_code_block_delimiter) (info_string (language)) (block_continuation) (code_fence_content (block_continuation)) (fenced_code_block_delimiter))))",
+            "(inline (code_span (code_span_delimiter) (code_span_delimiter)))",
+            "...(function_item name: (identifier) parameters: (parameters) body: (block)...",
+        ],
+    );
 
     // Replace `rs` with a path to ending in `.rb` in code block.
     let macro_name_range = range_for_text(&buffer, "rs");
@@ -224,15 +224,15 @@ fn test_dynamic_language_injection(cx: &mut App) {
     syntax_map.reparse(markdown.clone(), &buffer);
     syntax_map.reparse(markdown_inline.clone(), &buffer);
     assert_layers_for_range(
-            &syntax_map,
-            &buffer,
-            Point::new(3, 0)..Point::new(3, 0),
-            &[
-                "(document (section (paragraph (inline)) (fenced_code_block (fenced_code_block_delimiter) (info_string (language)) (block_continuation) (code_fence_content (block_continuation)) (fenced_code_block_delimiter))))",
-                "(inline (code_span (code_span_delimiter) (code_span_delimiter)))",
-                "...(call method: (identifier) arguments: (argument_list (call method: (identifier) arguments: (argument_list) block: (block)...",
-            ],
-        );
+        &syntax_map,
+        &buffer,
+        Point::new(3, 0)..Point::new(3, 0),
+        &[
+            "(document (section (paragraph (inline)) (fenced_code_block (fenced_code_block_delimiter) (info_string (language)) (block_continuation) (code_fence_content (block_continuation)) (fenced_code_block_delimiter))))",
+            "(inline (code_span (code_span_delimiter) (code_span_delimiter)))",
+            "...(call method: (identifier) arguments: (argument_list (call method: (identifier) arguments: (argument_list) block: (block)...",
+        ],
+    );
 
     // Replace Ruby with a language that hasn't been loaded yet.
     let macro_name_range = range_for_text(&buffer, "foo/bar/baz.rb");
@@ -241,29 +241,29 @@ fn test_dynamic_language_injection(cx: &mut App) {
     syntax_map.reparse(markdown.clone(), &buffer);
     syntax_map.reparse(markdown_inline.clone(), &buffer);
     assert_layers_for_range(
-            &syntax_map,
-            &buffer,
-            Point::new(3, 0)..Point::new(3, 0),
-            &[
-                "(document (section (paragraph (inline)) (fenced_code_block (fenced_code_block_delimiter) (info_string (language)) (block_continuation) (code_fence_content (block_continuation)) (fenced_code_block_delimiter))))",
-                "(inline (code_span (code_span_delimiter) (code_span_delimiter)))",
-            ],
-        );
+        &syntax_map,
+        &buffer,
+        Point::new(3, 0)..Point::new(3, 0),
+        &[
+            "(document (section (paragraph (inline)) (fenced_code_block (fenced_code_block_delimiter) (info_string (language)) (block_continuation) (code_fence_content (block_continuation)) (fenced_code_block_delimiter))))",
+            "(inline (code_span (code_span_delimiter) (code_span_delimiter)))",
+        ],
+    );
     assert!(syntax_map.contains_unknown_injections());
 
     registry.add(Arc::new(html_lang()));
     syntax_map.reparse(markdown.clone(), &buffer);
     syntax_map.reparse(markdown_inline.clone(), &buffer);
     assert_layers_for_range(
-            &syntax_map,
-            &buffer,
-            Point::new(3, 0)..Point::new(3, 0),
-            &[
-                "(document (section (paragraph (inline)) (fenced_code_block (fenced_code_block_delimiter) (info_string (language)) (block_continuation) (code_fence_content (block_continuation)) (fenced_code_block_delimiter))))",
-                "(inline (code_span (code_span_delimiter) (code_span_delimiter)))",
-                "(document (text))",
-            ],
-        );
+        &syntax_map,
+        &buffer,
+        Point::new(3, 0)..Point::new(3, 0),
+        &[
+            "(document (section (paragraph (inline)) (fenced_code_block (fenced_code_block_delimiter) (info_string (language)) (block_continuation) (code_fence_content (block_continuation)) (fenced_code_block_delimiter))))",
+            "(inline (code_span (code_span_delimiter) (code_span_delimiter)))",
+            "(document (text))",
+        ],
+    );
     assert!(!syntax_map.contains_unknown_injections());
 }
 

crates/language_model/src/rate_limiter.rs 🔗

@@ -52,7 +52,7 @@ impl RateLimiter {
     pub fn stream<'a, Fut, T>(
         &self,
         future: Fut,
-    ) -> impl 'a + Future<Output = Result<impl Stream<Item = T::Item>>>
+    ) -> impl 'a + Future<Output = Result<impl Stream<Item = T::Item> + use<Fut, T>>>
     where
         Fut: 'a + Future<Output = Result<T>>,
         T: Stream,

crates/language_models/src/provider/copilot_chat.rs 🔗

@@ -125,11 +125,21 @@ impl LanguageModelProvider for CopilotChatLanguageModelProvider {
 
         let err = match copilot.read(cx).status() {
             Status::Authorized => return Task::ready(Ok(())),
-            Status::Disabled => anyhow!("Copilot must be enabled for Copilot Chat to work. Please enable Copilot and try again."),
-            Status::Error(err) => anyhow!(format!("Received the following error while signing into Copilot: {err}")),
-            Status::Starting { task: _ } => anyhow!("Copilot is still starting, please wait for Copilot to start then try again"),
-            Status::Unauthorized => anyhow!("Unable to authorize with Copilot. Please make sure that you have an active Copilot and Copilot Chat subscription."),
-            Status::SignedOut {..} => anyhow!("You have signed out of Copilot. Please sign in to Copilot and try again."),
+            Status::Disabled => anyhow!(
+                "Copilot must be enabled for Copilot Chat to work. Please enable Copilot and try again."
+            ),
+            Status::Error(err) => anyhow!(format!(
+                "Received the following error while signing into Copilot: {err}"
+            )),
+            Status::Starting { task: _ } => anyhow!(
+                "Copilot is still starting, please wait for Copilot to start then try again"
+            ),
+            Status::Unauthorized => anyhow!(
+                "Unable to authorize with Copilot. Please make sure that you have an active Copilot and Copilot Chat subscription."
+            ),
+            Status::SignedOut { .. } => {
+                anyhow!("You have signed out of Copilot. Please sign in to Copilot and try again.")
+            }
             Status::SigningIn { prompt: _ } => anyhow!("Still signing into Copilot..."),
         };
 
@@ -398,8 +408,7 @@ impl Render for ConfigurationView {
                             .child(svg().size_8().path(IconName::CopilotError.path()))
                     }
                     _ => {
-                        const LABEL: &str =
-                    "To use Zed's assistant with GitHub Copilot, you need to be logged in to GitHub. Note that your GitHub account must have an active Copilot Chat subscription.";
+                        const LABEL: &str = "To use Zed's assistant with GitHub Copilot, you need to be logged in to GitHub. Note that your GitHub account must have an active Copilot Chat subscription.";
                         v_flex().gap_6().child(Label::new(LABEL)).child(
                             v_flex()
                                 .gap_2()

crates/language_models/src/provider/google.rs 🔗

@@ -2,8 +2,7 @@ use anyhow::{anyhow, Context as _, Result};
 use collections::BTreeMap;
 use credentials_provider::CredentialsProvider;
 use editor::{Editor, EditorElement, EditorStyle};
-use futures::Stream;
-use futures::{future::BoxFuture, FutureExt, StreamExt};
+use futures::{future::BoxFuture, FutureExt, Stream, StreamExt};
 use google_ai::{FunctionDeclaration, GenerateContentResponse, Part, UsageMetadata};
 use gpui::{
     AnyView, App, AsyncApp, Context, Entity, FontStyle, Subscription, Task, TextStyle, WhiteSpace,

crates/language_models/src/provider/lmstudio.rs 🔗

@@ -415,8 +415,7 @@ impl Render for ConfigurationView {
         let is_authenticated = self.state.read(cx).is_authenticated();
 
         let lmstudio_intro = "Run local LLMs like Llama, Phi, and Qwen.";
-        let lmstudio_reqs =
-            "To use LM Studio as a provider for Zed assistant, it needs to be running with at least one model downloaded.";
+        let lmstudio_reqs = "To use LM Studio as a provider for Zed assistant, it needs to be running with at least one model downloaded.";
 
         let inline_code_bg = cx.theme().colors().editor_foreground.opacity(0.05);
 

crates/language_tools/src/key_context_view.rs 🔗

@@ -239,7 +239,7 @@ impl Render for KeyContextView {
                     .mt_8(),
             )
             .children({
-                window.context_stack().iter().enumerate().map(|(i, context)| {
+                window.context_stack().into_iter().enumerate().map(|(i, context)| {
                     let primary = context.primary().map(|e| e.key.clone()).unwrap_or_default();
                     let secondary = context
                         .secondary()

crates/languages/src/go.rs 🔗

@@ -168,7 +168,9 @@ impl super::LspAdapter for GoLspAdapter {
                 String::from_utf8_lossy(&install_output.stderr)
             );
 
-            return Err(anyhow!("failed to install gopls with `go install`. Is `go` installed and in the PATH? Check logs for more information."));
+            return Err(anyhow!(
+                "failed to install gopls with `go install`. Is `go` installed and in the PATH? Check logs for more information."
+            ));
         }
 
         let installed_binary_path = gobin_dir.join(BINARY);

crates/livekit_client/src/livekit_client/playback.rs 🔗

@@ -427,7 +427,7 @@ impl libwebrtc::native::audio_mixer::AudioMixerSource for AudioMixerSource {
 
 pub fn play_remote_video_track(
     track: &crate::RemoteVideoTrack,
-) -> impl Stream<Item = RemoteVideoFrame> {
+) -> impl Stream<Item = RemoteVideoFrame> + use<> {
     #[cfg(target_os = "macos")]
     {
         let mut pool = None;
@@ -660,7 +660,7 @@ mod macos {
         callback: *mut ::std::os::raw::c_void,
     ) -> OSStatus {
         let wrapper = callback as *mut PropertyListenerCallbackWrapper;
-        (*wrapper).0();
+        unsafe { (*wrapper).0() };
         0
     }
 

crates/livekit_client/src/mock_client.rs 🔗

@@ -33,6 +33,6 @@ impl Into<gpui::SurfaceSource> for RemoteVideoFrame {
 }
 pub(crate) fn play_remote_video_track(
     _track: &crate::RemoteVideoTrack,
-) -> impl futures::Stream<Item = RemoteVideoFrame> {
+) -> impl futures::Stream<Item = RemoteVideoFrame> + use<> {
     futures::stream::pending()
 }

crates/lsp/src/lsp.rs 🔗

@@ -11,7 +11,7 @@ use notification::DidChangeWorkspaceFolders;
 use parking_lot::{Mutex, RwLock};
 use postage::{barrier, prelude::Stream};
 use schemars::{
-    gen::SchemaGenerator,
+    r#gen::SchemaGenerator,
     schema::{InstanceType, Schema, SchemaObject},
     JsonSchema,
 };
@@ -830,7 +830,7 @@ impl LanguageServer {
     }
 
     /// Sends a shutdown request to the language server process and prepares the [`LanguageServer`] to be dropped.
-    pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>>> {
+    pub fn shutdown(&self) -> Option<impl 'static + Send + Future<Output = Option<()>> + use<>> {
         if let Some(tasks) = self.io_tasks.lock().take() {
             let response_handlers = self.response_handlers.clone();
             let next_id = AtomicI32::new(self.next_id.load(SeqCst));
@@ -1077,7 +1077,7 @@ impl LanguageServer {
     pub fn request<T: request::Request>(
         &self,
         params: T::Params,
-    ) -> impl LspRequestFuture<Result<T::Result>>
+    ) -> impl LspRequestFuture<Result<T::Result>> + use<T>
     where
         T::Result: 'static + Send,
     {
@@ -1096,7 +1096,7 @@ impl LanguageServer {
         outbound_tx: &channel::Sender<String>,
         executor: &BackgroundExecutor,
         params: T::Params,
-    ) -> impl LspRequestFuture<Result<T::Result>>
+    ) -> impl LspRequestFuture<Result<T::Result>> + use<T>
     where
         T::Result: 'static + Send,
     {

crates/markdown_preview/src/markdown_renderer.rs 🔗

@@ -526,9 +526,7 @@ fn render_markdown_text(parsed_new: &MarkdownParagraph, cx: &mut RenderContext)
                             .max_w_full()
                             .with_fallback({
                                 let alt_text = image.alt_text.clone();
-                                {
-                                    move || div().children(alt_text.clone()).into_any_element()
-                                }
+                                move || div().children(alt_text.clone()).into_any_element()
                             }),
                     )
                     .tooltip({

crates/media/Cargo.toml 🔗

@@ -24,4 +24,4 @@ core-video.workspace = true
 objc = "0.2"
 
 [build-dependencies]
-bindgen = "0.70.0"
+bindgen = "0.71"

crates/media/src/media.rs 🔗

@@ -96,7 +96,7 @@ pub mod core_media {
     }
 
     #[link(name = "CoreMedia", kind = "framework")]
-    extern "C" {
+    unsafe extern "C" {
         fn CMSampleBufferGetTypeID() -> CFTypeID;
         fn CMSampleBufferGetSampleAttachmentsArray(
             buffer: CMSampleBufferRef,
@@ -163,7 +163,7 @@ pub mod core_media {
     }
 
     #[link(name = "CoreMedia", kind = "framework")]
-    extern "C" {
+    unsafe extern "C" {
         fn CMFormatDescriptionGetTypeID() -> CFTypeID;
         fn CMVideoFormatDescriptionGetH264ParameterSetAtIndex(
             video_desc: CMFormatDescriptionRef,
@@ -202,7 +202,7 @@ pub mod core_media {
     }
 
     #[link(name = "CoreMedia", kind = "framework")]
-    extern "C" {
+    unsafe extern "C" {
         fn CMBlockBufferGetTypeID() -> CFTypeID;
         fn CMBlockBufferGetDataPointer(
             buffer: CMBlockBufferRef,
@@ -258,15 +258,17 @@ pub mod core_video {
         /// metal_device must be valid according to CVMetalTextureCacheCreate
         pub unsafe fn new(metal_device: *mut MTLDevice) -> Result<Self> {
             let mut this = ptr::null();
-            let result = CVMetalTextureCacheCreate(
-                kCFAllocatorDefault,
-                ptr::null(),
-                metal_device,
-                ptr::null(),
-                &mut this,
-            );
+            let result = unsafe {
+                CVMetalTextureCacheCreate(
+                    kCFAllocatorDefault,
+                    ptr::null(),
+                    metal_device,
+                    ptr::null(),
+                    &mut this,
+                )
+            };
             if result == kCVReturnSuccess {
-                Ok(CVMetalTextureCache::wrap_under_create_rule(this))
+                unsafe { Ok(CVMetalTextureCache::wrap_under_create_rule(this)) }
             } else {
                 Err(anyhow!("could not create texture cache, code: {}", result))
             }
@@ -285,19 +287,21 @@ pub mod core_video {
             plane_index: usize,
         ) -> Result<CVMetalTexture> {
             let mut this = ptr::null();
-            let result = CVMetalTextureCacheCreateTextureFromImage(
-                kCFAllocatorDefault,
-                self.as_concrete_TypeRef(),
-                source,
-                texture_attributes,
-                pixel_format,
-                width,
-                height,
-                plane_index,
-                &mut this,
-            );
+            let result = unsafe {
+                CVMetalTextureCacheCreateTextureFromImage(
+                    kCFAllocatorDefault,
+                    self.as_concrete_TypeRef(),
+                    source,
+                    texture_attributes,
+                    pixel_format,
+                    width,
+                    height,
+                    plane_index,
+                    &mut this,
+                )
+            };
             if result == kCVReturnSuccess {
-                Ok(CVMetalTexture::wrap_under_create_rule(this))
+                unsafe { Ok(CVMetalTexture::wrap_under_create_rule(this)) }
             } else {
                 Err(anyhow!("could not create texture, code: {}", result))
             }
@@ -305,7 +309,7 @@ pub mod core_video {
     }
 
     #[link(name = "CoreVideo", kind = "framework")]
-    extern "C" {
+    unsafe extern "C" {
         fn CVMetalTextureCacheGetTypeID() -> CFTypeID;
         fn CVMetalTextureCacheCreate(
             allocator: CFAllocatorRef,
@@ -345,7 +349,7 @@ pub mod core_video {
     }
 
     #[link(name = "CoreVideo", kind = "framework")]
-    extern "C" {
+    unsafe extern "C" {
         fn CVMetalTextureGetTypeID() -> CFTypeID;
         fn CVMetalTextureGetTexture(texture: CVMetalTextureRef) -> *mut c_void;
     }

crates/multi_buffer/src/multi_buffer.rs 🔗

@@ -2271,11 +2271,11 @@ impl MultiBuffer {
         cx.notify();
     }
 
-    pub fn wait_for_anchors<'a>(
+    pub fn wait_for_anchors<'a, Anchors: 'a + Iterator<Item = Anchor>>(
         &self,
-        anchors: impl 'a + Iterator<Item = Anchor>,
+        anchors: Anchors,
         cx: &mut Context<Self>,
-    ) -> impl 'static + Future<Output = Result<()>> {
+    ) -> impl 'static + Future<Output = Result<()>> + use<Anchors> {
         let borrow = self.buffers.borrow();
         let mut error = None;
         let mut futures = Vec::new();
@@ -3494,8 +3494,8 @@ impl MultiBuffer {
             }
 
             let excerpt_ids = self.excerpt_ids();
-            if excerpt_ids.is_empty() || (rng.gen() && excerpt_ids.len() < max_excerpts) {
-                let buffer_handle = if rng.gen() || self.buffers.borrow().is_empty() {
+            if excerpt_ids.is_empty() || (rng.r#gen() && excerpt_ids.len() < max_excerpts) {
+                let buffer_handle = if rng.r#gen() || self.buffers.borrow().is_empty() {
                     let text = RandomCharIter::new(&mut *rng).take(10).collect::<String>();
                     buffers.push(cx.new(|cx| Buffer::local(text, cx)));
                     let buffer = buffers.last().unwrap().read(cx);
@@ -3573,7 +3573,7 @@ impl MultiBuffer {
 
             if let Some(buffer) = buffer {
                 buffer.update(cx, |buffer, cx| {
-                    if rng.gen() {
+                    if rng.r#gen() {
                         buffer.randomly_edit(rng, mutation_count, cx);
                     } else {
                         buffer.randomly_undo_redo(rng, cx);
@@ -3873,108 +3873,114 @@ impl MultiBufferSnapshot {
             }
         }
 
-        iter::from_fn(move || loop {
-            let excerpt = cursor.excerpt()?;
+        iter::from_fn(move || {
+            loop {
+                let excerpt = cursor.excerpt()?;
 
-            // If we have already retrieved metadata for this excerpt, continue to use it.
-            let metadata_iter = if let Some((_, metadata)) = current_excerpt_metadata
-                .as_mut()
-                .filter(|(excerpt_id, _)| *excerpt_id == excerpt.id)
-            {
-                Some(metadata)
-            }
-            // Otherwise, compute the intersection of the input range with the excerpt's range,
-            // and retrieve the metadata for the resulting range.
-            else {
-                let region = cursor.region()?;
-                let mut buffer_start;
-                if region.is_main_buffer {
-                    buffer_start = region.buffer_range.start;
-                    if query_range.start > region.range.start {
-                        let overshoot = query_range.start - region.range.start;
-                        buffer_start.add_assign(&overshoot);
+                // If we have already retrieved metadata for this excerpt, continue to use it.
+                let metadata_iter = if let Some((_, metadata)) = current_excerpt_metadata
+                    .as_mut()
+                    .filter(|(excerpt_id, _)| *excerpt_id == excerpt.id)
+                {
+                    Some(metadata)
+                }
+                // Otherwise, compute the intersection of the input range with the excerpt's range,
+                // and retrieve the metadata for the resulting range.
+                else {
+                    let region = cursor.region()?;
+                    let mut buffer_start;
+                    if region.is_main_buffer {
+                        buffer_start = region.buffer_range.start;
+                        if query_range.start > region.range.start {
+                            let overshoot = query_range.start - region.range.start;
+                            buffer_start.add_assign(&overshoot);
+                        }
+                        buffer_start = buffer_start.min(region.buffer_range.end);
+                    } else {
+                        buffer_start = cursor.main_buffer_position()?;
+                    };
+                    let mut buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
+                    if let Some((end_excerpt_id, end_buffer_offset)) = range_end {
+                        if excerpt.id == end_excerpt_id {
+                            buffer_end = buffer_end.min(end_buffer_offset);
+                        }
                     }
-                    buffer_start = buffer_start.min(region.buffer_range.end);
-                } else {
-                    buffer_start = cursor.main_buffer_position()?;
-                };
-                let mut buffer_end = excerpt.range.context.end.summary::<D>(&excerpt.buffer);
-                if let Some((end_excerpt_id, end_buffer_offset)) = range_end {
-                    if excerpt.id == end_excerpt_id {
-                        buffer_end = buffer_end.min(end_buffer_offset);
+
+                    if let Some(iterator) =
+                        get_buffer_metadata(&excerpt.buffer, buffer_start..buffer_end)
+                    {
+                        Some(&mut current_excerpt_metadata.insert((excerpt.id, iterator)).1)
+                    } else {
+                        None
                     }
-                }
+                };
 
-                if let Some(iterator) =
-                    get_buffer_metadata(&excerpt.buffer, buffer_start..buffer_end)
+                // Visit each metadata item.
+                if let Some((metadata_buffer_range, metadata)) =
+                    metadata_iter.and_then(Iterator::next)
                 {
-                    Some(&mut current_excerpt_metadata.insert((excerpt.id, iterator)).1)
-                } else {
-                    None
-                }
-            };
-
-            // Visit each metadata item.
-            if let Some((metadata_buffer_range, metadata)) = metadata_iter.and_then(Iterator::next)
-            {
-                // Find the multibuffer regions that contain the start and end of
-                // the metadata item's range.
-                if metadata_buffer_range.start > D::default() {
+                    // Find the multibuffer regions that contain the start and end of
+                    // the metadata item's range.
+                    if metadata_buffer_range.start > D::default() {
+                        while let Some(region) = cursor.region() {
+                            if region.is_main_buffer
+                                && (region.buffer_range.end >= metadata_buffer_range.start
+                                    || cursor.is_at_end_of_excerpt())
+                            {
+                                break;
+                            }
+                            cursor.next();
+                        }
+                    }
+                    let start_region = cursor.region()?;
                     while let Some(region) = cursor.region() {
                         if region.is_main_buffer
-                            && (region.buffer_range.end >= metadata_buffer_range.start
+                            && (region.buffer_range.end > metadata_buffer_range.end
                                 || cursor.is_at_end_of_excerpt())
                         {
                             break;
                         }
                         cursor.next();
                     }
-                }
-                let start_region = cursor.region()?;
-                while let Some(region) = cursor.region() {
-                    if region.is_main_buffer
-                        && (region.buffer_range.end > metadata_buffer_range.end
-                            || cursor.is_at_end_of_excerpt())
+                    let end_region = cursor.region();
+
+                    // Convert the metadata item's range into multibuffer coordinates.
+                    let mut start_position = start_region.range.start;
+                    let region_buffer_start = start_region.buffer_range.start;
+                    if start_region.is_main_buffer
+                        && metadata_buffer_range.start > region_buffer_start
                     {
-                        break;
+                        start_position
+                            .add_assign(&(metadata_buffer_range.start - region_buffer_start));
+                        start_position = start_position.min(start_region.range.end);
                     }
-                    cursor.next();
-                }
-                let end_region = cursor.region();
-
-                // Convert the metadata item's range into multibuffer coordinates.
-                let mut start_position = start_region.range.start;
-                let region_buffer_start = start_region.buffer_range.start;
-                if start_region.is_main_buffer && metadata_buffer_range.start > region_buffer_start
-                {
-                    start_position.add_assign(&(metadata_buffer_range.start - region_buffer_start));
-                    start_position = start_position.min(start_region.range.end);
-                }
 
-                let mut end_position = max_position;
-                if let Some(end_region) = &end_region {
-                    end_position = end_region.range.start;
-                    debug_assert!(end_region.is_main_buffer);
-                    let region_buffer_start = end_region.buffer_range.start;
-                    if metadata_buffer_range.end > region_buffer_start {
-                        end_position.add_assign(&(metadata_buffer_range.end - region_buffer_start));
+                    let mut end_position = max_position;
+                    if let Some(end_region) = &end_region {
+                        end_position = end_region.range.start;
+                        debug_assert!(end_region.is_main_buffer);
+                        let region_buffer_start = end_region.buffer_range.start;
+                        if metadata_buffer_range.end > region_buffer_start {
+                            end_position
+                                .add_assign(&(metadata_buffer_range.end - region_buffer_start));
+                        }
+                        end_position = end_position.min(end_region.range.end);
                     }
-                    end_position = end_position.min(end_region.range.end);
-                }
 
-                if start_position <= query_range.end && end_position >= query_range.start {
-                    return Some((start_position..end_position, metadata, excerpt));
+                    if start_position <= query_range.end && end_position >= query_range.start {
+                        return Some((start_position..end_position, metadata, excerpt));
+                    }
                 }
-            }
-            // When there are no more metadata items for this excerpt, move to the next excerpt.
-            else {
-                current_excerpt_metadata.take();
-                if let Some((end_excerpt_id, _)) = range_end {
-                    if excerpt.id == end_excerpt_id {
-                        return None;
+                // When there are no more metadata items for this excerpt, move to the next excerpt.
+                else {
+                    current_excerpt_metadata.take();
+                    if let Some((end_excerpt_id, _)) = range_end {
+                        if excerpt.id == end_excerpt_id {
+                            return None;
+                        }
                     }
+                    cursor.next_excerpt();
                 }
-                cursor.next_excerpt();
             }
         })
     }
@@ -6197,7 +6203,8 @@ impl MultiBufferSnapshot {
                     if *inserted_hunk_info == *prev_inserted_hunk_info {
                         panic!(
                             "multiple adjacent buffer content transforms with is_inserted_hunk = {inserted_hunk_info:?}. transforms: {:+?}",
-                            self.diff_transforms.items(&()));
+                            self.diff_transforms.items(&())
+                        );
                     }
                 }
                 if summary.len == 0 && !self.is_empty() {
@@ -6842,14 +6849,18 @@ impl<'a> MultiBufferExcerpt<'a> {
     /// Map a range within the [`Buffer`] to a range within the [`MultiBuffer`]
     pub fn map_range_from_buffer(&mut self, buffer_range: Range<usize>) -> Range<usize> {
         if buffer_range.start < self.buffer_offset {
-            log::warn!("Attempting to map a range from a buffer offset that starts before the current buffer offset");
+            log::warn!(
+                "Attempting to map a range from a buffer offset that starts before the current buffer offset"
+            );
             return buffer_range;
         }
         let overshoot = buffer_range.start - self.buffer_offset;
         let excerpt_offset = ExcerptDimension(self.excerpt_offset.0 + overshoot);
         self.diff_transforms.seek(&excerpt_offset, Bias::Right, &());
         if excerpt_offset.0 < self.diff_transforms.start().1 .0 {
-            log::warn!("Attempting to map a range from a buffer offset that starts before the current buffer offset");
+            log::warn!(
+                "Attempting to map a range from a buffer offset that starts before the current buffer offset"
+            );
             return buffer_range;
         }
         let overshoot = excerpt_offset.0 - self.diff_transforms.start().1 .0;

crates/multi_buffer/src/multi_buffer_tests.rs 🔗

@@ -2536,7 +2536,7 @@ async fn test_random_multibuffer(cx: &mut TestAppContext, mut rng: StdRng) {
                     multibuffer.read_with(cx, |multibuffer, cx| multibuffer.snapshot(cx));
                 let offset =
                     multibuffer.clip_offset(rng.gen_range(0..=multibuffer.len()), Bias::Left);
-                let bias = if rng.gen() { Bias::Left } else { Bias::Right };
+                let bias = if rng.r#gen() { Bias::Left } else { Bias::Right };
                 log::info!("Creating anchor at {} with bias {:?}", offset, bias);
                 anchors.push(multibuffer.anchor_at(offset, bias));
                 anchors.sort_by(|a, b| a.cmp(b, &multibuffer));

crates/outline_panel/src/outline_panel.rs 🔗

@@ -5694,8 +5694,7 @@ mod tests {
         outline_panel.update_in(cx, |outline_panel, window, cx| {
             outline_panel.select_next(&SelectNext, window, cx);
         });
-        let next_navigated_outline_selection =
-            "search: InlayHintsConfig { param_names_for_lifetime_elision_hints: true, ..TEST_CONFIG },";
+        let next_navigated_outline_selection = "search: InlayHintsConfig { param_names_for_lifetime_elision_hints: true, ..TEST_CONFIG },";
         outline_panel.update(cx, |outline_panel, cx| {
             assert_eq!(
                 display_entries(

crates/picker/src/picker.rs 🔗

@@ -526,7 +526,7 @@ impl<D: PickerDelegate> Picker<D> {
         window: &mut Window,
         cx: &mut Context<Self>,
     ) {
-        let Head::Editor(ref editor) = &self.head else {
+        let Head::Editor(editor) = &self.head else {
             panic!("unexpected call");
         };
         match event {
@@ -617,7 +617,7 @@ impl<D: PickerDelegate> Picker<D> {
     }
 
     pub fn set_query(&self, query: impl Into<Arc<str>>, window: &mut Window, cx: &mut App) {
-        if let Head::Editor(ref editor) = &self.head {
+        if let Head::Editor(editor) = &self.head {
             editor.update(cx, |editor, cx| {
                 editor.set_text(query, window, cx);
                 let editor_offset = editor.buffer().read(cx).len(cx);
@@ -642,7 +642,7 @@ impl<D: PickerDelegate> Picker<D> {
         window: &mut Window,
         cx: &mut Context<Self>,
         ix: usize,
-    ) -> impl IntoElement {
+    ) -> impl IntoElement + use<D> {
         div()
             .id(("item", ix))
             .cursor_pointer()

crates/prettier/src/prettier.rs 🔗

@@ -119,9 +119,13 @@ impl Prettier {
                                     } else {
                                         log::warn!("Skipping path {path_to_check:?} workspace root with workspaces {workspaces:?} that have no prettier installed");
                                     }
-                                },
-                                Some(unknown) => log::error!("Failed to parse workspaces for {path_to_check:?} from package.json, got {unknown:?}. Skipping."),
-                                None => log::warn!("Skipping path {path_to_check:?} that has no prettier dependency and no workspaces section in its package.json"),
+                                }
+                                Some(unknown) => log::error!(
+                                    "Failed to parse workspaces for {path_to_check:?} from package.json, got {unknown:?}. Skipping."
+                                ),
+                                None => log::warn!(
+                                    "Skipping path {path_to_check:?} that has no prettier dependency and no workspaces section in its package.json"
+                                ),
                             }
                         }
                     }
@@ -213,7 +217,9 @@ impl Prettier {
                                 let workspace_ignore = path_to_check.join(".prettierignore");
                                 if let Some(metadata) = fs.metadata(&workspace_ignore).await? {
                                     if !metadata.is_dir {
-                                        log::info!("Found prettier ignore at workspace root {workspace_ignore:?}");
+                                        log::info!(
+                                            "Found prettier ignore at workspace root {workspace_ignore:?}"
+                                        );
                                         return Ok(ControlFlow::Continue(Some(path_to_check)));
                                     }
                                 }
@@ -646,7 +652,8 @@ mod tests {
                 &HashSet::default(),
                 Path::new("/root/work/project/src/index.js")
             )
-            .await.unwrap(),
+            .await
+            .unwrap(),
             ControlFlow::Continue(Some(PathBuf::from("/root/work/project"))),
             "Should successfully find a prettier for path hierarchy that has node_modules with prettier, but no package.json mentions of it"
         );

crates/project/src/debugger/locator_store.rs 🔗

@@ -25,7 +25,7 @@ impl LocatorStore {
         &self,
         debug_config: &mut DebugAdapterConfig,
     ) -> Result<()> {
-        let Some(ref locator_name) = &debug_config.locator else {
+        let Some(locator_name) = &debug_config.locator else {
             log::debug!("Attempted to resolve debug config without a locator field");
             return Ok(());
         };

crates/project/src/environment.rs 🔗

@@ -342,7 +342,9 @@ async fn load_shell_environment(
         .await
         .log_err()
     else {
-        return message("Failed to spawn login shell to source login environment variables. See logs for details");
+        return message(
+            "Failed to spawn login shell to source login environment variables. See logs for details",
+        );
     };
 
     if !output.status.success() {

crates/project/src/git_store.rs 🔗

@@ -1136,7 +1136,7 @@ impl GitStore {
         &mut self,
         buffers: Vec<Entity<Buffer>>,
         cx: &mut Context<Self>,
-    ) -> impl Future<Output = ()> {
+    ) -> impl Future<Output = ()> + use<> {
         let mut futures = Vec::new();
         for buffer in buffers {
             if let Some(diff_state) = self.diffs.get_mut(&buffer.read(cx).remote_id()) {

crates/project/src/lsp_store.rs 🔗

@@ -974,7 +974,7 @@ impl LocalLspStore {
     fn shutdown_language_servers(
         &mut self,
         _cx: &mut Context<LspStore>,
-    ) -> impl Future<Output = ()> {
+    ) -> impl Future<Output = ()> + use<> {
         let shutdown_futures = self
             .language_servers
             .drain()
@@ -2564,7 +2564,10 @@ impl LocalLspStore {
                         }
                     })?;
                 } else {
-                    log::warn!("Cannot execute a command {} not listed in the language server capabilities", command.command)
+                    log::warn!(
+                        "Cannot execute a command {} not listed in the language server capabilities",
+                        command.command
+                    )
                 }
             }
         }
@@ -3230,16 +3233,16 @@ impl LocalLspStore {
 
         if registrations.remove(registration_id).is_some() {
             log::info!(
-                    "language server {}: unregistered workspace/DidChangeWatchedFiles capability with id {}",
-                    language_server_id,
-                    registration_id
-                );
+                "language server {}: unregistered workspace/DidChangeWatchedFiles capability with id {}",
+                language_server_id,
+                registration_id
+            );
         } else {
             log::warn!(
-                    "language server {}: failed to unregister workspace/DidChangeWatchedFiles capability with id {}. not registered.",
-                    language_server_id,
-                    registration_id
-                );
+                "language server {}: failed to unregister workspace/DidChangeWatchedFiles capability with id {}. not registered.",
+                language_server_id,
+                registration_id
+            );
         }
 
         self.rebuild_watched_paths(language_server_id, cx);
@@ -3558,7 +3561,7 @@ impl LspStore {
             toolchain_store: Some(toolchain_store),
             languages: languages.clone(),
             language_server_statuses: Default::default(),
-            nonce: StdRng::from_entropy().gen(),
+            nonce: StdRng::from_entropy().r#gen(),
             diagnostic_summaries: Default::default(),
             active_entry: None,
 
@@ -3614,7 +3617,7 @@ impl LspStore {
             worktree_store,
             languages: languages.clone(),
             language_server_statuses: Default::default(),
-            nonce: StdRng::from_entropy().gen(),
+            nonce: StdRng::from_entropy().r#gen(),
             diagnostic_summaries: Default::default(),
             active_entry: None,
             toolchain_store,

crates/project/src/project.rs 🔗

@@ -4595,7 +4595,7 @@ impl Project {
             ProjectClientState::Shared { .. } | ProjectClientState::Local => {
                 return Task::ready(Err(anyhow!(
                     "can't synchronize remote buffers on a local project"
-                )))
+                )));
             }
         };
 

crates/project/src/project_tests.rs 🔗

@@ -4772,12 +4772,11 @@ async fn test_search_with_inclusions(cx: &mut gpui::TestAppContext) {
                 false,
                 true,
                 false,
-
-                    PathMatcher::new(&["*.ts".to_owned(), "*.odd".to_owned()]).unwrap(),
-
+                PathMatcher::new(&["*.ts".to_owned(), "*.odd".to_owned()]).unwrap(),
                 Default::default(),
                 None,
-            ).unwrap(),
+            )
+            .unwrap(),
             cx
         )
         .await
@@ -4797,12 +4796,12 @@ async fn test_search_with_inclusions(cx: &mut gpui::TestAppContext) {
                 false,
                 true,
                 false,
-
-                    PathMatcher::new(&["*.rs".to_owned(), "*.ts".to_owned(), "*.odd".to_owned()]).unwrap(),
-
-               Default::default(),
-               None,
-            ).unwrap(),
+                PathMatcher::new(&["*.rs".to_owned(), "*.ts".to_owned(), "*.odd".to_owned()])
+                    .unwrap(),
+                Default::default(),
+                None,
+            )
+            .unwrap(),
             cx
         )
         .await
@@ -4897,7 +4896,8 @@ async fn test_search_with_exclusions(cx: &mut gpui::TestAppContext) {
                 Default::default(),
                 PathMatcher::new(&["*.ts".to_owned(), "*.odd".to_owned()]).unwrap(),
                 None,
-            ).unwrap(),
+            )
+            .unwrap(),
             cx
         )
         .await
@@ -4917,16 +4917,17 @@ async fn test_search_with_exclusions(cx: &mut gpui::TestAppContext) {
                 false,
                 true,
                 false,
-                 Default::default(),
-
-                    PathMatcher::new(&["*.rs".to_owned(), "*.ts".to_owned(), "*.odd".to_owned()]).unwrap(),
-                    None,
-
-            ).unwrap(),
+                Default::default(),
+                PathMatcher::new(&["*.rs".to_owned(), "*.ts".to_owned(), "*.odd".to_owned()])
+                    .unwrap(),
+                None,
+            )
+            .unwrap(),
             cx
         )
         .await
-        .unwrap().is_empty(),
+        .unwrap()
+        .is_empty(),
         "Rust and typescript exclusion should give no files, even if other exclusions don't match anything"
     );
 }
@@ -4982,7 +4983,8 @@ async fn test_search_with_exclusions_and_inclusions(cx: &mut gpui::TestAppContex
                 PathMatcher::new(&["*.ts".to_owned()]).unwrap(),
                 PathMatcher::new(&["*.ts".to_owned()]).unwrap(),
                 None,
-            ).unwrap(),
+            )
+            .unwrap(),
             cx
         )
         .await

crates/project/src/task_inventory.rs 🔗

@@ -392,7 +392,7 @@ impl Inventory {
                         }
                     },
                     message: format!("Failed to parse tasks file content as a JSON array: {e}"),
-                })
+                });
             }
         };
         let new_templates = raw_tasks

crates/project_panel/src/project_panel.rs 🔗

@@ -1493,7 +1493,9 @@ impl ProjectPanel {
                         } else if dirty_buffers == 1 {
                             "\n\n1 of these has unsaved changes, which will be lost.".to_string()
                         } else {
-                            format!("\n\n{dirty_buffers} of these have unsaved changes, which will be lost.")
+                            format!(
+                                "\n\n{dirty_buffers} of these have unsaved changes, which will be lost."
+                            )
                         };
 
                         format!(

crates/project_panel/src/project_panel_tests.rs 🔗

@@ -1582,24 +1582,24 @@ async fn test_copy_paste_directory_with_sibling_file(cx: &mut gpui::TestAppConte
     cx.executor().run_until_parked();
 
     assert_eq!(
-            visible_entries_as_strings(&panel, 0..15, cx),
-            &[
-                "v test",
-                "    v dir1  <== marked",
-                "          a.txt",
-                "          b.txt",
-                "    v dir2",
-                "        v dir1",
-                "              a.txt",
-                "              b.txt",
-                "        > dir1 copy  <== selected",
-                "          c.txt",
-                "          c copy.txt",
-                "      c.txt  <== marked",
-                "      d.txt",
-            ],
-            "Should copy dir1 as well as c.txt into dir2 and disambiguate them without opening the rename editor"
-        );
+        visible_entries_as_strings(&panel, 0..15, cx),
+        &[
+            "v test",
+            "    v dir1  <== marked",
+            "          a.txt",
+            "          b.txt",
+            "    v dir2",
+            "        v dir1",
+            "              a.txt",
+            "              b.txt",
+            "        > dir1 copy  <== selected",
+            "          c.txt",
+            "          c copy.txt",
+            "      c.txt  <== marked",
+            "      d.txt",
+        ],
+        "Should copy dir1 as well as c.txt into dir2 and disambiguate them without opening the rename editor"
+    );
 }
 
 #[gpui::test]
@@ -2909,16 +2909,16 @@ async fn test_autoreveal_and_gitignored_files(cx: &mut gpui::TestAppContext) {
         });
         cx.run_until_parked();
         assert_eq!(
-                visible_entries_as_strings(&panel, 0..20, cx),
-                &[
-                    "v project_root",
-                    "    > .git",
-                    "    > dir_1  <== selected",
-                    "    > dir_2",
-                    "      .gitignore",
-                ],
-                "When no auto reveal is enabled, the selected entry should not be revealed in the project panel"
-            );
+            visible_entries_as_strings(&panel, 0..20, cx),
+            &[
+                "v project_root",
+                "    > .git",
+                "    > dir_1  <== selected",
+                "    > dir_2",
+                "      .gitignore",
+            ],
+            "When no auto reveal is enabled, the selected entry should not be revealed in the project panel"
+        );
     }
 
     cx.update(|_, cx| {
@@ -2985,23 +2985,23 @@ async fn test_autoreveal_and_gitignored_files(cx: &mut gpui::TestAppContext) {
     });
     cx.run_until_parked();
     assert_eq!(
-            visible_entries_as_strings(&panel, 0..20, cx),
-            &[
-                "v project_root",
-                "    > .git",
-                "    v dir_1",
-                "        > gitignored_dir",
-                "          file_1.py",
-                "          file_2.py",
-                "          file_3.py",
-                "    v dir_2",
-                "          file_1.py  <== selected  <== marked",
-                "          file_2.py",
-                "          file_3.py",
-                "      .gitignore",
-            ],
-            "When auto reveal is enabled, a gitignored selected entry should not be revealed in the project panel"
-        );
+        visible_entries_as_strings(&panel, 0..20, cx),
+        &[
+            "v project_root",
+            "    > .git",
+            "    v dir_1",
+            "        > gitignored_dir",
+            "          file_1.py",
+            "          file_2.py",
+            "          file_3.py",
+            "    v dir_2",
+            "          file_1.py  <== selected  <== marked",
+            "          file_2.py",
+            "          file_3.py",
+            "      .gitignore",
+        ],
+        "When auto reveal is enabled, a gitignored selected entry should not be revealed in the project panel"
+    );
 
     panel.update(cx, |panel, cx| {
         panel.project.update(cx, |_, cx| {
@@ -3128,24 +3128,24 @@ async fn test_gitignored_and_always_included(cx: &mut gpui::TestAppContext) {
     cx.run_until_parked();
 
     assert_eq!(
-            visible_entries_as_strings(&panel, 0..20, cx),
-            &[
-                "v project_root",
-                "    > .git",
-                "    v always_included_but_ignored_dir",
-                "          file_a.py  <== selected  <== marked",
-                "          file_b.py",
-                "          file_c.py",
-                "    v dir_1",
-                "        > gitignored_dir",
-                "          file_1.py",
-                "          file_2.py",
-                "          file_3.py",
-                "    > dir_2",
-                "      .gitignore",
-            ],
-            "When auto reveal is enabled, a gitignored but always included selected entry should be revealed in the project panel"
-        );
+        visible_entries_as_strings(&panel, 0..20, cx),
+        &[
+            "v project_root",
+            "    > .git",
+            "    v always_included_but_ignored_dir",
+            "          file_a.py  <== selected  <== marked",
+            "          file_b.py",
+            "          file_c.py",
+            "    v dir_1",
+            "        > gitignored_dir",
+            "          file_1.py",
+            "          file_2.py",
+            "          file_3.py",
+            "    > dir_2",
+            "      .gitignore",
+        ],
+        "When auto reveal is enabled, a gitignored but always included selected entry should be revealed in the project panel"
+    );
 }
 
 #[gpui::test]
@@ -3261,16 +3261,16 @@ async fn test_explicit_reveal(cx: &mut gpui::TestAppContext) {
         });
         cx.run_until_parked();
         assert_eq!(
-                visible_entries_as_strings(&panel, 0..20, cx),
-                &[
-                    "v project_root",
-                    "    > .git",
-                    "    > dir_1  <== selected",
-                    "    > dir_2",
-                    "      .gitignore",
-                ],
-                "When no auto reveal is enabled, the selected entry should not be revealed in the project panel"
-            );
+            visible_entries_as_strings(&panel, 0..20, cx),
+            &[
+                "v project_root",
+                "    > .git",
+                "    > dir_1  <== selected",
+                "    > dir_2",
+                "      .gitignore",
+            ],
+            "When no auto reveal is enabled, the selected entry should not be revealed in the project panel"
+        );
     }
 
     panel.update(cx, |panel, cx| {
@@ -3327,26 +3327,26 @@ async fn test_explicit_reveal(cx: &mut gpui::TestAppContext) {
     });
     cx.run_until_parked();
     assert_eq!(
-            visible_entries_as_strings(&panel, 0..20, cx),
-            &[
-                "v project_root",
-                "    > .git",
-                "    v dir_1",
-                "        v gitignored_dir",
-                "              file_a.py  <== selected  <== marked",
-                "              file_b.py",
-                "              file_c.py",
-                "          file_1.py",
-                "          file_2.py",
-                "          file_3.py",
-                "    v dir_2",
-                "          file_1.py",
-                "          file_2.py",
-                "          file_3.py",
-                "      .gitignore",
-            ],
-            "With no auto reveal, explicit reveal should show the gitignored entry in the project panel"
-        );
+        visible_entries_as_strings(&panel, 0..20, cx),
+        &[
+            "v project_root",
+            "    > .git",
+            "    v dir_1",
+            "        v gitignored_dir",
+            "              file_a.py  <== selected  <== marked",
+            "              file_b.py",
+            "              file_c.py",
+            "          file_1.py",
+            "          file_2.py",
+            "          file_3.py",
+            "    v dir_2",
+            "          file_1.py",
+            "          file_2.py",
+            "          file_3.py",
+            "      .gitignore",
+        ],
+        "With no auto reveal, explicit reveal should show the gitignored entry in the project panel"
+    );
 }
 
 #[gpui::test]
@@ -3475,10 +3475,10 @@ async fn test_creating_excluded_entries(cx: &mut gpui::TestAppContext) {
         .unwrap();
 
     assert_eq!(
-            visible_entries_as_strings(&panel, 0..13, cx),
-            &["v root1", "      .dockerignore"],
-            "Should not change the project panel after trying to create an excluded directorya directory with the same name as the excluded file"
-        );
+        visible_entries_as_strings(&panel, 0..13, cx),
+        &["v root1", "      .dockerignore"],
+        "Should not change the project panel after trying to create an excluded directorya directory with the same name as the excluded file"
+    );
     panel.update_in(cx, |panel, window, cx| {
         assert!(
             !panel.filename_editor.read(cx).is_focused(window),
@@ -4571,23 +4571,23 @@ async fn test_expand_all_for_entry(cx: &mut gpui::TestAppContext) {
     cx.run_until_parked();
 
     assert_eq!(
-            visible_entries_as_strings(&panel, 0..20, cx),
-            &[
-                separator!("v root"),
-                separator!("    v dir1  <== selected"),
-                separator!("        v empty1"),
-                separator!("            v empty2"),
-                separator!("                v empty3"),
-                separator!("                      file.txt"),
-                separator!("        > ignored_dir"),
-                separator!("        v subdir1"),
-                separator!("            > ignored_nested"),
-                separator!("              file1.txt"),
-                separator!("              file2.txt"),
-                separator!("      .gitignore"),
-            ],
-            "After expand_all with auto-fold: should not expand ignored_dir, should expand folded dirs, and should not expand ignored_nested"
-        );
+        visible_entries_as_strings(&panel, 0..20, cx),
+        &[
+            separator!("v root"),
+            separator!("    v dir1  <== selected"),
+            separator!("        v empty1"),
+            separator!("            v empty2"),
+            separator!("                v empty3"),
+            separator!("                      file.txt"),
+            separator!("        > ignored_dir"),
+            separator!("        v subdir1"),
+            separator!("            > ignored_nested"),
+            separator!("              file1.txt"),
+            separator!("              file2.txt"),
+            separator!("      .gitignore"),
+        ],
+        "After expand_all with auto-fold: should not expand ignored_dir, should expand folded dirs, and should not expand ignored_nested"
+    );
 
     // Test 2: When auto-fold is disabled
     cx.update(|_, cx| {
@@ -5095,18 +5095,18 @@ fn ensure_no_open_items_and_panes(workspace: &WindowHandle<Workspace>, cx: &mut
         "Should have no prompts after deletion operation closes the file"
     );
     workspace
-            .read_with(cx, |workspace, cx| {
-                let open_project_paths = workspace
-                    .panes()
-                    .iter()
-                    .filter_map(|pane| pane.read(cx).active_item()?.project_path(cx))
-                    .collect::<Vec<_>>();
-                assert!(
-                    open_project_paths.is_empty(),
-                    "Deleted file's buffer should be closed, but got open files: {open_project_paths:?}"
-                );
-            })
-            .unwrap();
+        .read_with(cx, |workspace, cx| {
+            let open_project_paths = workspace
+                .panes()
+                .iter()
+                .filter_map(|pane| pane.read(cx).active_item()?.project_path(cx))
+                .collect::<Vec<_>>();
+            assert!(
+                open_project_paths.is_empty(),
+                "Deleted file's buffer should be closed, but got open files: {open_project_paths:?}"
+            );
+        })
+        .unwrap();
 }
 
 struct TestProjectItemView {

crates/prompt_store/src/prompt_store.rs 🔗

@@ -117,7 +117,7 @@ impl MetadataCache {
 }
 
 impl PromptStore {
-    pub fn global(cx: &App) -> impl Future<Output = Result<Arc<Self>>> {
+    pub fn global(cx: &App) -> impl Future<Output = Result<Arc<Self>>> + use<> {
         let store = GlobalPromptStore::global(cx).0.clone();
         async move { store.await.map_err(|err| anyhow!(err)) }
     }

crates/recent_projects/src/ssh_connections.rs 🔗

@@ -33,7 +33,7 @@ pub struct SshSettings {
 }
 
 impl SshSettings {
-    pub fn ssh_connections(&self) -> impl Iterator<Item = SshConnection> {
+    pub fn ssh_connections(&self) -> impl Iterator<Item = SshConnection> + use<> {
         self.ssh_connections.clone().into_iter().flatten()
     }
 

crates/refineable/derive_refineable/src/derive_refineable.rs 🔗

@@ -100,13 +100,13 @@ pub fn derive_refineable(input: TokenStream) -> TokenStream {
                 }
             } else if is_optional {
                 quote! {
-                    if let Some(ref value) = &refinement.#name {
+                    if let Some(value) = &refinement.#name {
                         self.#name = Some(value.clone());
                     }
                 }
             } else {
                 quote! {
-                    if let Some(ref value) = &refinement.#name {
+                    if let Some(value) = &refinement.#name {
                         self.#name = value.clone();
                     }
                 }
@@ -153,7 +153,7 @@ pub fn derive_refineable(input: TokenStream) -> TokenStream {
                 }
             } else {
                 quote! {
-                    if let Some(ref value) = &refinement.#name {
+                    if let Some(value) = &refinement.#name {
                         self.#name = Some(value.clone());
                     }
                 }
@@ -244,7 +244,7 @@ pub fn derive_refineable(input: TokenStream) -> TokenStream {
         derive_stream.extend(quote! { #[derive(#trait_to_derive)] })
     }
 
-    let gen = quote! {
+    let r#gen = quote! {
         /// A refinable version of [`#ident`], see that documentation for details.
         #[derive(Clone)]
         #derive_stream
@@ -321,7 +321,7 @@ pub fn derive_refineable(input: TokenStream) -> TokenStream {
 
         #debug_impl
     };
-    gen.into()
+    r#gen.into()
 }
 
 fn is_refineable_field(f: &Field) -> bool {

crates/remote/src/ssh_session.rs 🔗

@@ -682,7 +682,7 @@ impl SshRemoteClient {
     pub fn shutdown_processes<T: RequestMessage>(
         &self,
         shutdown_request: Option<T>,
-    ) -> Option<impl Future<Output = ()>> {
+    ) -> Option<impl Future<Output = ()> + use<T>> {
         let state = self.state.lock().take()?;
         log::info!("shutting down ssh processes");
 
@@ -1423,7 +1423,7 @@ impl RemoteConnection for SshRemoteConnection {
         {
             Ok(process) => process,
             Err(error) => {
-                return Task::ready(Err(anyhow!("failed to spawn remote server: {}", error)))
+                return Task::ready(Err(anyhow!("failed to spawn remote server: {}", error)));
             }
         };
 

crates/remote_server/src/unix.rs 🔗

@@ -547,7 +547,10 @@ pub fn execute_proxy(identifier: String, is_reconnecting: bool) -> Result<()> {
         }
     } else {
         if let Some(pid) = server_pid {
-            log::info!("proxy found server already running with PID {}. Killing process and cleaning up files...", pid);
+            log::info!(
+                "proxy found server already running with PID {}. Killing process and cleaning up files...",
+                pid
+            );
             kill_running_server(pid, &server_paths)?;
         }
 
@@ -692,7 +695,10 @@ fn check_pid_file(path: &Path) -> Result<Option<u32>> {
         .output()
     {
         Ok(output) if output.status.success() => {
-            log::debug!("Process with PID {} exists. NOT spawning new server, but attaching to existing one.", pid);
+            log::debug!(
+                "Process with PID {} exists. NOT spawning new server, but attaching to existing one.",
+                pid
+            );
             Ok(Some(pid))
         }
         _ => {
@@ -878,11 +884,11 @@ fn daemonize() -> Result<ControlFlow<()>> {
 }
 
 unsafe fn redirect_standard_streams() -> Result<()> {
-    let devnull_fd = libc::open(b"/dev/null\0" as *const [u8; 10] as _, libc::O_RDWR);
+    let devnull_fd = unsafe { libc::open(b"/dev/null\0" as *const [u8; 10] as _, libc::O_RDWR) };
     anyhow::ensure!(devnull_fd != -1, "failed to open /dev/null");
 
     let process_stdio = |name, fd| {
-        let reopened_fd = libc::dup2(devnull_fd, fd);
+        let reopened_fd = unsafe { libc::dup2(devnull_fd, fd) };
         anyhow::ensure!(
             reopened_fd != -1,
             format!("failed to redirect {} to /dev/null", name)
@@ -895,7 +901,7 @@ unsafe fn redirect_standard_streams() -> Result<()> {
     process_stdio("stderr", libc::STDERR_FILENO)?;
 
     anyhow::ensure!(
-        libc::close(devnull_fd) != -1,
+        unsafe { libc::close(devnull_fd) != -1 },
         "failed to close /dev/null fd after redirecting"
     );
 

crates/repl/src/kernels/mod.rs 🔗

@@ -79,7 +79,7 @@ pub fn python_env_kernel_specifications(
     project: &Entity<Project>,
     worktree_id: WorktreeId,
     cx: &mut App,
-) -> impl Future<Output = Result<Vec<KernelSpecification>>> {
+) -> impl Future<Output = Result<Vec<KernelSpecification>>> + use<> {
     let python_language = LanguageName::new("Python");
     let toolchains = project.read(cx).available_toolchains(
         ProjectPath {

crates/repl/src/notebook/notebook_ui.rs 🔗

@@ -642,7 +642,7 @@ impl NotebookItem {
                 .and_then(|spec| spec.language.clone()))
     }
 
-    pub fn notebook_language(&self) -> impl Future<Output = Option<Arc<Language>>> {
+    pub fn notebook_language(&self) -> impl Future<Output = Option<Arc<Language>>> + use<> {
         let language_name = self.language_name();
         let languages = self.languages.clone();
 

crates/repl/src/outputs.rs 🔗

@@ -205,11 +205,10 @@ impl Output {
 
     pub fn render(
         &self,
-
         workspace: WeakEntity<Workspace>,
         window: &mut Window,
         cx: &mut Context<ExecutionView>,
-    ) -> impl IntoElement {
+    ) -> impl IntoElement + use<> {
         let content = match self {
             Self::Plain { content, .. } => Some(content.clone().into_any_element()),
             Self::Markdown { content, .. } => Some(content.clone().into_any_element()),

crates/rope/src/rope.rs 🔗

@@ -1674,7 +1674,7 @@ mod tests {
                 chunks.seek(offset);
 
                 for _ in 0..5 {
-                    if rng.gen() {
+                    if rng.r#gen() {
                         let expected_next_line_start = expected[offset..end_ix]
                             .find('\n')
                             .map(|newline_ix| offset + newline_ix + 1);
@@ -1763,7 +1763,7 @@ mod tests {
                     }
 
                     assert!((start_ix..=end_ix).contains(&chunks.offset()));
-                    if rng.gen() {
+                    if rng.r#gen() {
                         offset = rng.gen_range(start_ix..=end_ix);
                         while !expected.is_char_boundary(offset) {
                             offset -= 1;

crates/rpc/src/auth.rs 🔗

@@ -43,7 +43,7 @@ pub fn random_token() -> String {
     let mut rng = thread_rng();
     let mut token_bytes = [0; 48];
     for byte in token_bytes.iter_mut() {
-        *byte = rng.gen();
+        *byte = rng.r#gen();
     }
     BASE64_URL_SAFE.encode(token_bytes)
 }

crates/rpc/src/peer.rs 🔗

@@ -116,7 +116,7 @@ impl Peer {
         create_timer: F,
     ) -> (
         ConnectionId,
-        impl Future<Output = anyhow::Result<()>> + Send,
+        impl Future<Output = anyhow::Result<()>> + Send + use<F, Fut, Out>,
         BoxStream<'static, Box<dyn AnyTypedEnvelope>>,
     )
     where
@@ -377,7 +377,7 @@ impl Peer {
         executor: gpui::BackgroundExecutor,
     ) -> (
         ConnectionId,
-        impl Future<Output = anyhow::Result<()>> + Send,
+        impl Future<Output = anyhow::Result<()>> + Send + use<>,
         BoxStream<'static, Box<dyn AnyTypedEnvelope>>,
     ) {
         let executor = executor.clone();
@@ -403,7 +403,7 @@ impl Peer {
         &self,
         receiver_id: ConnectionId,
         request: T,
-    ) -> impl Future<Output = Result<T::Response>> {
+    ) -> impl Future<Output = Result<T::Response>> + use<T> {
         self.request_internal(None, receiver_id, request)
             .map_ok(|envelope| envelope.payload)
     }
@@ -412,7 +412,7 @@ impl Peer {
         &self,
         receiver_id: ConnectionId,
         request: T,
-    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> {
+    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> + use<T> {
         self.request_internal(None, receiver_id, request)
     }
 
@@ -431,7 +431,7 @@ impl Peer {
         original_sender_id: Option<ConnectionId>,
         receiver_id: ConnectionId,
         request: T,
-    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> {
+    ) -> impl Future<Output = Result<TypedEnvelope<T::Response>>> + use<T> {
         let envelope = request.into_envelope(0, None, original_sender_id.map(Into::into));
         let response = self.request_dynamic(receiver_id, envelope, T::NAME);
         async move {
@@ -457,7 +457,7 @@ impl Peer {
         receiver_id: ConnectionId,
         mut envelope: proto::Envelope,
         type_name: &'static str,
-    ) -> impl Future<Output = Result<(proto::Envelope, Instant)>> {
+    ) -> impl Future<Output = Result<(proto::Envelope, Instant)>> + use<> {
         let (tx, rx) = oneshot::channel();
         let send = self.connection_state(receiver_id).and_then(|connection| {
             envelope.id = connection.next_message_id.fetch_add(1, SeqCst);

crates/rpc/src/proto_client.rs 🔗

@@ -185,7 +185,7 @@ impl AnyProtoClient {
     pub fn request<T: RequestMessage>(
         &self,
         request: T,
-    ) -> impl Future<Output = anyhow::Result<T::Response>> {
+    ) -> impl Future<Output = anyhow::Result<T::Response>> + use<T> {
         let envelope = request.into_envelope(0, None, None);
         let response = self.0.request(envelope, T::NAME);
         async move {

crates/search/src/buffer_search.rs 🔗

@@ -936,12 +936,12 @@ impl BufferSearchBar {
         self.update_matches(!updated, window, cx)
     }
 
-    fn render_search_option_button(
+    fn render_search_option_button<Action: Fn(&ClickEvent, &mut Window, &mut App) + 'static>(
         &self,
         option: SearchOptions,
         focus_handle: FocusHandle,
-        action: impl Fn(&ClickEvent, &mut Window, &mut App) + 'static,
-    ) -> impl IntoElement {
+        action: Action,
+    ) -> impl IntoElement + use<Action> {
         let is_active = self.search_options.contains(option);
         option.as_button(is_active, focus_handle, action)
     }

crates/search/src/search.rs 🔗

@@ -105,12 +105,12 @@ impl SearchOptions {
         options
     }
 
-    pub fn as_button(
+    pub fn as_button<Action: Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static>(
         &self,
         active: bool,
         focus_handle: FocusHandle,
-        action: impl Fn(&gpui::ClickEvent, &mut Window, &mut App) + 'static,
-    ) -> impl IntoElement {
+        action: Action,
+    ) -> impl IntoElement + use<Action> {
         IconButton::new(self.label(), self.icon())
             .on_click(action)
             .style(ButtonStyle::Subtle)

crates/semantic_index/src/embedding_index.rs 🔗

@@ -56,7 +56,10 @@ impl EmbeddingIndex {
         &self.db
     }
 
-    pub fn index_entries_changed_on_disk(&self, cx: &App) -> impl Future<Output = Result<()>> {
+    pub fn index_entries_changed_on_disk(
+        &self,
+        cx: &App,
+    ) -> impl Future<Output = Result<()>> + use<> {
         if !cx.is_staff() {
             return async move { Ok(()) }.boxed();
         }
@@ -78,7 +81,7 @@ impl EmbeddingIndex {
         &self,
         updated_entries: UpdatedEntriesSet,
         cx: &App,
-    ) -> impl Future<Output = Result<()>> {
+    ) -> impl Future<Output = Result<()>> + use<> {
         if !cx.is_staff() {
             return async move { Ok(()) }.boxed();
         }

crates/semantic_index/src/summary_index.rs 🔗

@@ -130,7 +130,7 @@ impl SummaryIndex {
         &self,
         is_auto_available: bool,
         cx: &App,
-    ) -> impl Future<Output = Result<()>> {
+    ) -> impl Future<Output = Result<()>> + use<> {
         let start = Instant::now();
         let backlogged;
         let digest;
@@ -193,7 +193,7 @@ impl SummaryIndex {
         updated_entries: UpdatedEntriesSet,
         is_auto_available: bool,
         cx: &App,
-    ) -> impl Future<Output = Result<()>> {
+    ) -> impl Future<Output = Result<()>> + use<> {
         let start = Instant::now();
         let backlogged;
         let digest;
@@ -528,7 +528,11 @@ impl SummaryIndex {
         }
     }
 
-    fn summarize_code(code: &str, path: &Path, cx: &App) -> impl Future<Output = Result<String>> {
+    fn summarize_code(
+        code: &str,
+        path: &Path,
+        cx: &App,
+    ) -> impl Future<Output = Result<String>> + use<> {
         let start = Instant::now();
         let (summary_model_id, use_cache): (LanguageModelId, bool) = (
             "Qwen/Qwen2-7B-Instruct".to_string().into(), // TODO read this from the user's settings.
@@ -639,7 +643,7 @@ impl SummaryIndex {
         &self,
         worktree_abs_path: Arc<Path>,
         cx: &App,
-    ) -> impl Future<Output = Result<()>> {
+    ) -> impl Future<Output = Result<()>> + use<> {
         let start = Instant::now();
         let backlogged = {
             let (tx, rx) = channel::bounded(512);

crates/settings/src/keymap_file.rs 🔗

@@ -6,7 +6,7 @@ use gpui::{
     NoAction, SharedString, KEYSTROKE_PARSE_EXPECTED_MESSAGE,
 };
 use schemars::{
-    gen::{SchemaGenerator, SchemaSettings},
+    r#gen::{SchemaGenerator, SchemaSettings},
     schema::{ArrayValidation, InstanceType, Schema, SchemaObject, SubschemaValidation},
     JsonSchema,
 };
@@ -363,7 +363,7 @@ impl KeymapFile {
                 return Err(format!(
                     "didn't find an action named {}.",
                     inline_code_string(&name)
-                ))
+                ));
             }
             Err(ActionBuildError::BuildError { name, error }) => match action_input_string {
                 Some(action_input_string) => {
@@ -372,14 +372,14 @@ impl KeymapFile {
                         inline_code_string(&name),
                         MarkdownString::inline_code(&action_input_string),
                         MarkdownString::escape(&error.to_string())
-                    ))
+                    ));
                 }
                 None => {
                     return Err(format!(
                         "can't build {} action - it requires input data via [name, input]: {}",
                         inline_code_string(&name),
                         MarkdownString::escape(&error.to_string())
-                    ))
+                    ));
                 }
             },
         };
@@ -391,7 +391,7 @@ impl KeymapFile {
                     "invalid keystroke {}. {}",
                     inline_code_string(&keystroke),
                     KEYSTROKE_PARSE_EXPECTED_MESSAGE
-                ))
+                ));
             }
         };
 

crates/settings/src/settings_store.rs 🔗

@@ -8,7 +8,7 @@ use gpui::{App, AsyncApp, BorrowAppContext, Global, Task, UpdateGlobal};
 use paths::{
     debug_task_file_name, local_settings_file_relative_path, task_file_name, EDITORCONFIG_NAME,
 };
-use schemars::{gen::SchemaGenerator, schema::RootSchema, JsonSchema};
+use schemars::{r#gen::SchemaGenerator, schema::RootSchema, JsonSchema};
 use serde::{de::DeserializeOwned, Deserialize, Serialize};
 use smallvec::SmallVec;
 use std::{
@@ -760,7 +760,7 @@ impl SettingsStore {
         cx: &App,
     ) -> serde_json::Value {
         use schemars::{
-            gen::SchemaSettings,
+            r#gen::SchemaSettings,
             schema::{Schema, SchemaObject},
         };
 

crates/snippet_provider/src/format.rs 🔗

@@ -1,6 +1,6 @@
 use collections::HashMap;
 use schemars::{
-    gen::SchemaSettings,
+    r#gen::SchemaSettings,
     schema::{ObjectValidation, Schema, SchemaObject},
     JsonSchema,
 };
@@ -29,10 +29,10 @@ impl JsonSchema for VSSnippetsFile {
         "VSSnippetsFile".into()
     }
 
-    fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> Schema {
+    fn json_schema(r#gen: &mut schemars::r#gen::SchemaGenerator) -> Schema {
         SchemaObject {
             object: Some(Box::new(ObjectValidation {
-                additional_properties: Some(Box::new(gen.subschema_for::<VSCodeSnippet>())),
+                additional_properties: Some(Box::new(r#gen.subschema_for::<VSCodeSnippet>())),
                 ..Default::default()
             })),
             ..Default::default()

crates/sqlez/src/statement.rs 🔗

@@ -76,7 +76,8 @@ impl<'a> Statement<'a> {
 
                     bail!(
                         "Write statement prepared with connection that is not write capable. SQL:\n{} ",
-                        sql.to_str()?)
+                        sql.to_str()?
+                    )
                 }
             }
         }

crates/sum_tree/src/sum_tree.rs 🔗

@@ -1038,7 +1038,7 @@ mod tests {
             let rng = &mut rng;
             let mut tree = SumTree::<u8>::default();
             let count = rng.gen_range(0..10);
-            if rng.gen() {
+            if rng.r#gen() {
                 tree.extend(rng.sample_iter(distributions::Standard).take(count), &());
             } else {
                 let items = rng
@@ -1064,7 +1064,7 @@ mod tests {
                 tree = {
                     let mut cursor = tree.cursor::<Count>(&());
                     let mut new_tree = cursor.slice(&Count(splice_start), Bias::Right, &());
-                    if rng.gen() {
+                    if rng.r#gen() {
                         new_tree.extend(new_items, &());
                     } else {
                         new_tree.par_extend(new_items, &());
@@ -1091,7 +1091,7 @@ mod tests {
                     .filter(|(_, item)| (item & 1) == 0)
                     .collect::<Vec<_>>();
 
-                let mut item_ix = if rng.gen() {
+                let mut item_ix = if rng.r#gen() {
                     filter_cursor.next(&());
                     0
                 } else {
@@ -1172,8 +1172,8 @@ mod tests {
             for _ in 0..10 {
                 let end = rng.gen_range(0..tree.extent::<Count>(&()).0 + 1);
                 let start = rng.gen_range(0..end + 1);
-                let start_bias = if rng.gen() { Bias::Left } else { Bias::Right };
-                let end_bias = if rng.gen() { Bias::Left } else { Bias::Right };
+                let start_bias = if rng.r#gen() { Bias::Left } else { Bias::Right };
+                let end_bias = if rng.r#gen() { Bias::Left } else { Bias::Right };
 
                 let mut cursor = tree.cursor::<Count>(&());
                 cursor.seek(&Count(start), start_bias, &());

crates/task/src/debug_format.rs 🔗

@@ -1,5 +1,5 @@
 use dap_types::StartDebuggingRequestArguments;
-use schemars::{gen::SchemaSettings, JsonSchema};
+use schemars::{r#gen::SchemaSettings, JsonSchema};
 use serde::{Deserialize, Serialize};
 use std::net::Ipv4Addr;
 use std::path::PathBuf;

crates/task/src/task_template.rs 🔗

@@ -3,7 +3,7 @@ use util::serde::default_true;
 
 use anyhow::{bail, Context};
 use collections::{HashMap, HashSet};
-use schemars::{gen::SchemaSettings, JsonSchema};
+use schemars::{r#gen::SchemaSettings, JsonSchema};
 use serde::{Deserialize, Serialize};
 use sha2::{Digest, Sha256};
 use util::{truncate_and_remove_front, ResultExt};
@@ -649,7 +649,10 @@ mod tests {
             );
             assert_eq!(
                 spawn_in_terminal.command_label,
-                format!("{} arg1 test_selected_text arg2 5678 arg3 {long_value}", spawn_in_terminal.command),
+                format!(
+                    "{} arg1 test_selected_text arg2 5678 arg3 {long_value}",
+                    spawn_in_terminal.command
+                ),
                 "Command label args should be substituted with variables and those should not be shortened"
             );
 
@@ -686,7 +689,10 @@ mod tests {
                     project_env: HashMap::default(),
                 },
             );
-            assert_eq!(resolved_task_attempt, None, "If any of the Zed task variables is not substituted, the task should not be resolved, but got some resolution without the variable {removed_variable:?} (index {i})");
+            assert_eq!(
+                resolved_task_attempt, None,
+                "If any of the Zed task variables is not substituted, the task should not be resolved, but got some resolution without the variable {removed_variable:?} (index {i})"
+            );
         }
     }
 

crates/terminal/src/terminal.rs 🔗

@@ -782,7 +782,7 @@ impl Terminal {
         cx: &mut Context<Self>,
     ) {
         match event {
-            InternalEvent::Resize(mut new_bounds) => {
+            &InternalEvent::Resize(mut new_bounds) => {
                 new_bounds.bounds.size.height =
                     cmp::max(new_bounds.line_height, new_bounds.height());
                 new_bounds.bounds.size.width = cmp::max(new_bounds.cell_width, new_bounds.width());
@@ -1943,15 +1943,20 @@ const TASK_DELIMITER: &str = "⏵ ";
 fn task_summary(task: &TaskState, error_code: Option<i32>) -> (bool, String, String) {
     let escaped_full_label = task.full_label.replace("\r\n", "\r").replace('\n', "\r");
     let (success, task_line) = match error_code {
-        Some(0) => {
-            (true, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"))
-        }
-        Some(error_code) => {
-            (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"))
-        }
-        None => {
-            (false, format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"))
-        }
+        Some(0) => (
+            true,
+            format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished successfully"),
+        ),
+        Some(error_code) => (
+            false,
+            format!(
+                "{TASK_DELIMITER}Task `{escaped_full_label}` finished with non-zero error code: {error_code}"
+            ),
+        ),
+        None => (
+            false,
+            format!("{TASK_DELIMITER}Task `{escaped_full_label}` finished"),
+        ),
     };
     let escaped_command_label = task.command_label.replace("\r\n", "\r").replace('\n', "\r");
     let command_line = format!("{TASK_DELIMITER}Command: {escaped_command_label}");

crates/terminal/src/terminal_settings.rs 🔗

@@ -5,7 +5,7 @@ use collections::HashMap;
 use gpui::{
     px, AbsoluteLength, App, FontFallbacks, FontFeatures, FontWeight, Pixels, SharedString,
 };
-use schemars::{gen::SchemaGenerator, schema::RootSchema, JsonSchema};
+use schemars::{r#gen::SchemaGenerator, schema::RootSchema, JsonSchema};
 use serde_derive::{Deserialize, Serialize};
 use settings::{add_references_to_properties, SettingsJsonSchemaParams, SettingsSources};
 use std::path::PathBuf;

crates/terminal_view/src/terminal_view.rs 🔗

@@ -1089,7 +1089,7 @@ fn possible_open_target(
                         return Task::ready(Some(OpenTarget::Worktree(
                             root_path_with_posiition,
                             root_entry.clone(),
-                        )))
+                        )));
                     }
                     None => paths_to_check.push(root_path_with_posiition),
                 }

crates/text/src/text.rs 🔗

@@ -1561,10 +1561,10 @@ impl Buffer {
         self.subscriptions.subscribe()
     }
 
-    pub fn wait_for_edits(
+    pub fn wait_for_edits<It: IntoIterator<Item = clock::Lamport>>(
         &mut self,
-        edit_ids: impl IntoIterator<Item = clock::Lamport>,
-    ) -> impl 'static + Future<Output = Result<()>> {
+        edit_ids: It,
+    ) -> impl 'static + Future<Output = Result<()>> + use<It> {
         let mut futures = Vec::new();
         for edit_id in edit_ids {
             if !self.version.observed(edit_id) {
@@ -1584,10 +1584,10 @@ impl Buffer {
         }
     }
 
-    pub fn wait_for_anchors(
+    pub fn wait_for_anchors<It: IntoIterator<Item = Anchor>>(
         &mut self,
-        anchors: impl IntoIterator<Item = Anchor>,
-    ) -> impl 'static + Future<Output = Result<()>> {
+        anchors: It,
+    ) -> impl 'static + Future<Output = Result<()>> + use<It> {
         let mut futures = Vec::new();
         for anchor in anchors {
             if !self.version.observed(anchor.timestamp)
@@ -1613,7 +1613,10 @@ impl Buffer {
         }
     }
 
-    pub fn wait_for_version(&mut self, version: clock::Global) -> impl Future<Output = Result<()>> {
+    pub fn wait_for_version(
+        &mut self,
+        version: clock::Global,
+    ) -> impl Future<Output = Result<()>> + use<> {
         let mut rx = None;
         if !self.snapshot.version.observed_all(&version) {
             let channel = oneshot::channel();

crates/theme/src/schema.rs 🔗

@@ -4,7 +4,7 @@ use anyhow::Result;
 use gpui::{FontStyle, FontWeight, HighlightStyle, Hsla, WindowBackgroundAppearance};
 use indexmap::IndexMap;
 use palette::FromColor;
-use schemars::gen::SchemaGenerator;
+use schemars::r#gen::SchemaGenerator;
 use schemars::schema::{Schema, SchemaObject};
 use schemars::JsonSchema;
 use serde::{Deserialize, Deserializer, Serialize};

crates/theme/src/settings.rs 🔗

@@ -11,7 +11,7 @@ use gpui::{
 };
 use refineable::Refineable;
 use schemars::{
-    gen::SchemaGenerator,
+    r#gen::SchemaGenerator,
     schema::{InstanceType, Schema, SchemaObject},
     JsonSchema,
 };

crates/ui/src/components/context_menu.rs 🔗

@@ -585,7 +585,7 @@ impl ContextMenu {
         item: &ContextMenuItem,
         window: &mut Window,
         cx: &mut Context<Self>,
-    ) -> impl IntoElement {
+    ) -> impl IntoElement + use<> {
         match item {
             ContextMenuItem::Separator => ListSeparator.into_any_element(),
             ContextMenuItem::Header(header) => ListSubHeader::new(header.clone())

crates/ui/src/components/tooltip.rs 🔗

@@ -34,10 +34,10 @@ impl Tooltip {
         }
     }
 
-    pub fn for_action_title(
-        title: impl Into<SharedString>,
+    pub fn for_action_title<Title: Into<SharedString>>(
+        title: Title,
         action: &dyn Action,
-    ) -> impl Fn(&mut Window, &mut App) -> AnyView {
+    ) -> impl Fn(&mut Window, &mut App) -> AnyView + use<Title> {
         let title = title.into();
         let action = action.boxed_clone();
         move |window, cx| {
@@ -50,11 +50,11 @@ impl Tooltip {
         }
     }
 
-    pub fn for_action_title_in(
-        title: impl Into<SharedString>,
+    pub fn for_action_title_in<Str: Into<SharedString>>(
+        title: Str,
         action: &dyn Action,
         focus_handle: &FocusHandle,
-    ) -> impl Fn(&mut Window, &mut App) -> AnyView {
+    ) -> impl Fn(&mut Window, &mut App) -> AnyView + use<Str> {
         let title = title.into();
         let action = action.boxed_clone();
         let focus_handle = focus_handle.clone();
@@ -166,11 +166,11 @@ impl Render for Tooltip {
     }
 }
 
-pub fn tooltip_container<V>(
+pub fn tooltip_container<V, ContentsBuilder: FnOnce(Div, &mut Window, &mut Context<V>) -> Div>(
     window: &mut Window,
     cx: &mut Context<V>,
-    f: impl FnOnce(Div, &mut Window, &mut Context<V>) -> Div,
-) -> impl IntoElement {
+    f: ContentsBuilder,
+) -> impl IntoElement + use<V, ContentsBuilder> {
     let ui_font = ThemeSettings::get_global(cx).ui_font.clone();
 
     // padding to avoid tooltip appearing right below the mouse cursor

crates/util/src/util.rs 🔗

@@ -239,7 +239,7 @@ pub fn load_shell_from_passwd() -> Result<()> {
             "updating SHELL environment variable to value from passwd entry: {:?}",
             shell,
         );
-        env::set_var("SHELL", shell);
+        unsafe { env::set_var("SHELL", shell) };
     }
 
     Ok(())
@@ -285,7 +285,7 @@ pub fn load_login_shell_environment() -> Result<()> {
     if let Some(env_output_start) = stdout.find(marker) {
         let env_output = &stdout[env_output_start + marker.len()..];
 
-        parse_env_output(env_output, |key, value| env::set_var(key, value));
+        parse_env_output(env_output, |key, value| unsafe { env::set_var(key, value) });
 
         log::info!(
             "set environment variables from shell:{}, path:{}",

crates/vim/src/motion.rs 🔗

@@ -878,7 +878,7 @@ impl Motion {
                 smartcase,
             } => {
                 return find_forward(map, point, *before, *char, times, *mode, *smartcase)
-                    .map(|new_point| (new_point, SelectionGoal::None))
+                    .map(|new_point| (new_point, SelectionGoal::None));
             }
             // T F
             FindBackward {

crates/workspace/src/pane.rs 🔗

@@ -1814,11 +1814,9 @@ impl Pane {
         save_intent: SaveIntent,
         cx: &mut AsyncWindowContext,
     ) -> Result<bool> {
-        const CONFLICT_MESSAGE: &str =
-                "This file has changed on disk since you started editing it. Do you want to overwrite it?";
+        const CONFLICT_MESSAGE: &str = "This file has changed on disk since you started editing it. Do you want to overwrite it?";
 
-        const DELETED_MESSAGE: &str =
-                        "This file has been deleted on disk since you started editing it. Do you want to recreate it?";
+        const DELETED_MESSAGE: &str = "This file has been deleted on disk since you started editing it. Do you want to recreate it?";
 
         if save_intent == SaveIntent::Skip {
             return Ok(true);
@@ -2208,7 +2206,7 @@ impl Pane {
         focus_handle: &FocusHandle,
         window: &mut Window,
         cx: &mut Context<Pane>,
-    ) -> impl IntoElement {
+    ) -> impl IntoElement + use<> {
         let is_active = ix == self.active_item_index;
         let is_preview = self
             .preview_item_id
@@ -3499,7 +3497,7 @@ impl NavHistory {
         let mut state = self.0.lock();
         let entry = match mode {
             NavigationMode::Normal | NavigationMode::Disabled | NavigationMode::ClosingItem => {
-                return None
+                return None;
             }
             NavigationMode::GoingBack => &mut state.backward_stack,
             NavigationMode::GoingForward => &mut state.forward_stack,

crates/workspace/src/workspace.rs 🔗

@@ -1832,7 +1832,7 @@ impl Workspace {
     }
 
     #[cfg(any(test, feature = "test-support"))]
-    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static {
+    pub fn worktree_scans_complete(&self, cx: &App) -> impl Future<Output = ()> + 'static + use<> {
         let futures = self
             .worktrees(cx)
             .filter_map(|worktree| worktree.read(cx).as_local())
@@ -5253,7 +5253,7 @@ fn open_items(
     mut project_paths_to_open: Vec<(PathBuf, Option<ProjectPath>)>,
     window: &mut Window,
     cx: &mut Context<Workspace>,
-) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> {
+) -> impl 'static + Future<Output = Result<Vec<Option<Result<Box<dyn ItemHandle>>>>>> + use<> {
     let restored_items = serialized_workspace.map(|serialized_workspace| {
         Workspace::load_workspace(
             serialized_workspace,

crates/worktree/src/worktree.rs 🔗

@@ -1162,9 +1162,9 @@ impl Worktree {
             Worktree::Remote(this) => this.delete_entry(entry_id, trash, cx),
         }?;
 
-        let entry = match self {
-            Worktree::Local(ref this) => this.entry_for_id(entry_id),
-            Worktree::Remote(ref this) => this.entry_for_id(entry_id),
+        let entry = match &*self {
+            Worktree::Local(this) => this.entry_for_id(entry_id),
+            Worktree::Remote(this) => this.entry_for_id(entry_id),
         }?;
 
         let mut ids = vec![entry_id];
@@ -1674,7 +1674,7 @@ impl LocalWorktree {
         changes.into()
     }
 
-    pub fn scan_complete(&self) -> impl Future<Output = ()> {
+    pub fn scan_complete(&self) -> impl Future<Output = ()> + use<> {
         let mut is_scanning_rx = self.is_scanning.1.clone();
         async move {
             let mut is_scanning = *is_scanning_rx.borrow();
@@ -2407,7 +2407,10 @@ impl RemoteWorktree {
         self.completed_scan_id >= scan_id
     }
 
-    pub fn wait_for_snapshot(&mut self, scan_id: usize) -> impl Future<Output = Result<()>> {
+    pub fn wait_for_snapshot(
+        &mut self,
+        scan_id: usize,
+    ) -> impl Future<Output = Result<()>> + use<> {
         let (tx, rx) = oneshot::channel();
         if self.observed_snapshot(scan_id) {
             let _ = tx.send(());

crates/worktree/src/worktree_tests.rs 🔗

@@ -1958,7 +1958,7 @@ async fn randomly_mutate_fs(
         let path = dirs.choose(rng).unwrap();
         let new_path = path.join(random_filename(rng));
 
-        if rng.gen() {
+        if rng.r#gen() {
             log::info!(
                 "creating dir {:?}",
                 new_path.strip_prefix(root_path).unwrap()
@@ -2026,7 +2026,7 @@ async fn randomly_mutate_fs(
             file_path.into_iter().chain(dir_path).choose(rng).unwrap()
         };
 
-        let is_rename = rng.gen();
+        let is_rename = rng.r#gen();
         if is_rename {
             let new_path_parent = dirs
                 .iter()

crates/zed/src/zed.rs 🔗

@@ -2874,9 +2874,9 @@ mod tests {
 
         let entries = cx.read(|cx| workspace.file_project_paths(cx));
         assert_eq!(
-                initial_entries, entries,
-                "Workspace entries should not change after opening excluded files and directories paths"
-            );
+            initial_entries, entries,
+            "Workspace entries should not change after opening excluded files and directories paths"
+        );
 
         cx.read(|cx| {
                 let pane = workspace.read(cx).active_pane().read(cx);

crates/zlog/src/zlog.rs 🔗

@@ -371,7 +371,9 @@ pub mod scope_map {
             "warn" => log_impl::Level::Warn,
             "error" => log_impl::Level::Error,
             "off" | "disable" | "no" | "none" | "disabled" => {
-                crate::warn!("Invalid log level \"{level_str}\", set to error to disable non-error logging. Defaulting to error");
+                crate::warn!(
+                    "Invalid log level \"{level_str}\", set to error to disable non-error logging. Defaulting to error"
+                );
                 log_impl::Level::Error
             }
             _ => {