Visual Studio Code, rebuilt in Rust
Rust
refactor: land the six M27 architecture deepening candidates (#72)
Artur Rok4fc0cf39e4eb
diff --git a/ARCHITECTURE.md b/ARCHITECTURE.mdindex c13177108a1..788d4448e2a 100644--- a/ARCHITECTURE.md+++ b/ARCHITECTURE.md@@ -22,7 +22,7 @@ One app process owns every window. `app/src/main.rs::main` is the entry point ofEach window has its own child processes:-- The extension host: one Bun process per window (Node with `--node`). A thread named `exthost-session` owns the connection (`app/src/main.rs::run_extension_host`). See "Extension host bridge".+- The extension host: one Bun process per window (Node with `--node`). A thread named `exthost-session` owns the connection (`app/src/extension_host_start.rs::run_extension_host`). See "Extension host bridge".- Terminals: one shell per terminal behind a pty (`app/src/terminal/pty.rs::Pty`, ConPTY in `app/src/terminal/pty/conpty.rs`). Two threads per terminal read the pty and wait for the exit.- Search: one ripgrep process per search (`search/src/ripgrep.rs::run`).- Webviews: a native web view inside the app window. The OS web engine runs its own content processes.@@ -122,7 +122,7 @@ The host is upstream's extension host code, bundled by `port/tools/build-exthost- Connection. `exthost/src/lib.rs::ExtensionHost` starts the process and listens on a Unix socket (a named pipe on Windows, `exthost/src/pipe.rs`). Frames are upstream's `PersistentProtocol` (`exthost/src/frame.rs`). Messages are upstream's `rpcProtocol.ts` (`exthost/src/rpc.rs`). Proxy ids come from `exthost/src/proxy_ids.rs`, which `port/tools/gen-proxy-ids.ts` generates from the upstream protocol file.- Session. `exthost/src/session.rs::Session` runs on the `exthost-session` thread. It answers the MainThread calls that need no window by itself: files, configuration, storage, secrets, workspace search.-- Calls that need the workbench take one of two paths. A forwarded call goes to the main thread as a `exthost/src/session.rs::ForwardedRequest`, and `app/src/main_thread_commands.rs::handle_host_request` answers it later. A call that must see current document state goes through `app/src/main_thread.rs::WorkbenchMainThread` while the session thread waits.+- Calls that need the workbench take one of two paths, and `app/src/main_thread_commands.rs::route` names the path and the handler of each. A forwarded call goes to the main thread as a `exthost/src/session.rs::ForwardedRequest`, and `app/src/main_thread_commands.rs::handle_host_request` answers it later. A call that must see current document state goes through `app/src/main_thread.rs::WorkbenchMainThread` while the session thread waits.- Workbench to host. `app/src/host_sync.rs::HostSync` queues what the workbench tells the host (documents, editors, tabs, events) and its requests (`call`). The session thread sends the queue in order before each reply, so the host sees edits before answers that depend on them.**Invariant:** the order of messages to the host is the order in which the workbench made them. Do not send to the host from a second place.diff --git a/README.md b/README.mdindex f717acf62c6..7e703a65caf 100644--- a/README.md+++ b/README.md@@ -44,13 +44,13 @@ Release builds of both with default settings and the same built-in extensions, A## Coverage<!-- coverage:start -->-**465 of 550 items done (84%).** 435 of the 435 parts of VS Code 1.148.0 the port covers match upstream 1:1. 85 work items are still open: 7 for Linux, 35 for Windows, 43 for the VS Code 1.148.0 uplift. 155 more parts are left out on purpose. A part is one upstream folder: a feature, a service or a built-in extension; a work item is one row of a milestone's work (Linux, Windows, the uplift). Both are counted from [port/ledger.md](port/ledger.md).+**463 of 550 items done (84%).** 433 of the 435 parts of VS Code 1.148.0 the port covers match upstream 1:1. The other 2 work, with open gaps listed below. 85 work items are still open: 7 for Linux, 35 for Windows, 43 for the VS Code 1.148.0 uplift. 155 more parts are left out on purpose. A part is one upstream folder: a feature, a service or a built-in extension; a work item is one row of a milestone's work (Linux, Windows, the uplift). Both are counted from [port/ledger.md](port/ledger.md).```mermaid%%{init: {"theme": "base", "themeVariables": {"pie1": "#2da44e", "pie2": "#d4a72c", "pie3": "#cf222e", "pie4": "#8c959f", "pieStrokeColor": "#ffffff", "pieOuterStrokeColor": "#ffffff", "pieSectionTextColor": "#ffffff", "pieLegendTextColor": "#8c959f", "pieTitleTextColor": "#8c959f"}}}%%pie showData- "Matches VS Code 1:1" : 435- "Works, with open gaps" : 0+ "Matches VS Code 1:1" : 433+ "Works, with open gaps" : 2"Work items still open" : 85"Left out on purpose" : 155```@@ -63,17 +63,19 @@ pie showData| Workbench features: debug, Git, terminal, search, settings, extensions view | 71 | 0 | 33 | `████████████████████` 100% || Workbench services: editors, views, layout, themes, storage | 65 | 0 | 30 | `████████████████████` 100% || Built-in extensions: languages, themes, Git, Markdown, npm | 89 | 0 | 6 | `████████████████████` 100% |-| Extension API: the calls extensions make into the editor | 59 | 0 | 31 | `████████████████████` 100% |+| Extension API: the calls extensions make into the editor | 58 | 1 | 31 | `███████████████████░` 98% || Editor features: find, folding, suggest, hover, multi-cursor | 55 | 0 | 3 | `████████████████████` 100% || Window parts: title bar, activity bar, side bar, panel, status bar | 12 | 0 | 2 | `████████████████████` 100% || Extension host: runs unmodified VS Code extensions | 7 | 0 | 0 | `████████████████████` 100% || Base library | 0 | 0 | 5 | all left out || Whole-app checks: look, memory, no telemetry, Open VSX gallery | 5 | 0 | 0 | `████████████████████` 100% |-| Text editor core: model, view, cursor | 2 | 0 | 2 | `████████████████████` 100% |+| Text editor core: model, view, cursor | 1 | 1 | 2 | `██████████░░░░░░░░░░` 50% || Port-only features: settings import from VS Code | 1 | 0 | 0 | `████████████████████` 100% |-| **All** | **435** | **0** | **155** | `████████████████████` 100% |+| **All** | **433** | **2** | **155** | `███████████████████░` 99% |-"Matches 1:1" means upstream's tests or a named check against VS Code pass. No part works with open gaps.+"Matches 1:1" means upstream's tests or a named check against VS Code pass. Parts that work with open gaps, by gap count:++`editor/common` 1, `mainthread/MainThreadTextEditors` 1.| Milestone work | Done | Open | Progress ||---|---:|---:|---|diff --git a/docs/editor.md b/docs/editor.mdindex 509ef5da234..1cd39af9d42 100644--- a/docs/editor.md+++ b/docs/editor.md@@ -14,7 +14,7 @@ Three types in `app/src/editor.rs` carry the state:**Invariant:** text changes go through the edit functions of `app/src/editor/edit.rs` (`execute_edits`, `execute_commands`). They update the version id, the undo stack, the tokens and the edit log, and they return a `app/src/editor/edit.rs::ContentChanged`. Code that writes `lines` directly leaves all of those stale.-**Invariant:** the caller of an edit sends the returned `ContentChanged` to the extension host (`app/src/host_sync.rs::send_content_change`). An edit the host does not see breaks every language feature of the document.+**Invariant:** the caller of an edit hands the returned `ContentChanged` to `app/src/workbench/model_events.rs::model_content_changed`, and a cursor move without an edit goes to `app/src/workbench/model_events.rs::cursor_position_changed`. The host hears the change first, then the listeners of the model and of the active code editor run. An edit the host does not see breaks every language feature of the document.An editor that shares its model with another editor follows the other's edits from the model's edit log: `app/src/editor/edit.rs::sync_with_model` moves its cursors and folds to the new version.diff --git a/docs/extension-host.md b/docs/extension-host.mdindex d7d20593f0d..2408f68dfc8 100644--- a/docs/extension-host.md+++ b/docs/extension-host.md@@ -27,20 +27,22 @@ The handshake is in `exthost/src/lib.rs::start`: the host sends Ready, the parenTwo threads share the work for one window:-- The `exthost-session` thread runs `app/src/main.rs::run_extension_host`. It owns the `exthost/src/session.rs::Session` and blocks in `exthost/src/session.rs::pump` on the host's next message.+- The `exthost-session` thread runs `app/src/extension_host_start.rs::run_extension_host`. It owns the `exthost/src/session.rs::Session` and blocks in `exthost/src/session.rs::pump` on the host's next message.- The GPUI main thread owns the `Workbench`.Anything else that has work for the session (the workbench, a file watcher, a search) queues it and wakes the session with an `exthost/src/lib.rs::Waker`.## Host calls the port answers-A request from the host for `MainThreadX.$method` takes one of three paths:+A request from the host for `MainThreadX.$method` takes one of three paths. `app/src/main_thread_commands.rs::route` names the path and the handler of every call the workbench serves; `exthost/src/session.rs::Session::forward` reads the path through `app/src/main_thread_commands.rs::path`, and a call without one stays with the session:1. The session answers it on its own thread. This is for state that needs no window: the disk and file watchers (`exthost/src/main_thread_files.rs`), settings (`exthost/src/main_thread_configuration.rs`), extension storage (`exthost/src/main_thread_storage.rs`), secrets (`exthost/src/main_thread_secret_state.rs`), workspace search (`exthost/src/main_thread_workspace.rs`).-2. The workbench answers it while the session thread waits. This is for calls whose answer depends on the document state at that moment: `app/src/workbench/host_requests.rs::HOST_REQUESTS` lists them (open a document, apply an edit, set selections, the clipboard). They cross through `app/src/main_thread.rs::WorkbenchMainThread`.-3. The session forwards it and goes on. The proxies named in the `forward` call of `run_extension_host` go to the main thread as `exthost/src/session.rs::ForwardedRequest`, and `app/src/main_thread_commands.rs::handle_host_request` answers them later with `exthost/src/session.rs::reply`. Most of the API is here: commands, languages, webviews, debug, SCM, terminals, tree views.+2. The workbench answers it while the session thread waits. This is for calls whose answer depends on the document state at that moment: `Path::Blocking` in `route` (open a document, apply an edit, set selections, the clipboard). They cross through `app/src/main_thread.rs::WorkbenchMainThread`.+3. The session forwards it and goes on. The calls `route` gives `Path::Forwarded` go to the main thread as `exthost/src/session.rs::ForwardedRequest`, and `app/src/main_thread_commands.rs::handle_host_request` answers them later with `exthost/src/session.rs::reply`. Most of the API is here: commands, languages, webviews, debug, SCM, terminals, tree views.-A method that no path implements answers `undefined`, as a missing optional feature does upstream. The ledger row of the main thread class lists each such method that an extension can observe.+A `Path::Observed` call takes path 1 and the workbench gets a copy (the Window log of console lines and errors).++A method of a proxy `route` claims whole and that has no arm answers `Unknown method $bar on actor MainThreadFoo`, as rpcProtocol.ts `_doInvokeHandler` does. An upstream method the port does not implement yet answers `undefined` through `route`'s `not_ported`, and the ledger row of its main thread class lists it. A call the session serves and does not know answers `undefined` too.**Trap:** on path 2 the session thread blocks until the main thread answers (`app/src/main_thread.rs::ask`). A handler there must be short and must not wait for an answer from the host: the thread that reads the host is the one that waits. A save is the one exception. It runs format on save and dialogs, so it uses `app/src/main_thread.rs::ask_while_pumping`, which keeps the session sending and reading.@@ -48,7 +50,7 @@ A method that no path implements answers `undefined`, as a missing optional feat`app/src/host_sync.rs::HostSync` is the workbench's only door to the host.-- State: `send_changes`, `send_tabs`, `send_content_change` and their siblings tell the host about documents, editors and tabs, as `mainThreadDocumentsAndEditors.ts` does.+- State: `send_changes`, `send_tabs`, `send_model_change` and their siblings tell the host about documents, editors and tabs, as `mainThreadDocumentsAndEditors.ts` does.- Requests: `app/src/host_sync.rs::call` returns a receiver for the answer. `app/src/host_sync.rs::call_cancellable` cancels the request in the host when the receiver is dropped.- Activation: `app/src/host_sync.rs::activate_by_event` sends one `$activateByEvent` per event and shares its answer.diff --git a/native/crates/app/src/editor.rs b/native/crates/app/src/editor.rsindex 6c0f80de1d7..8a09ac4a63e 100644--- a/native/crates/app/src/editor.rs+++ b/native/crates/app/src/editor.rs@@ -1381,20 +1381,31 @@ impl EditorGroup {/// The model of `scheme`/`path`, in an editor of any group or not; the active group's editor first.pub fn model(&self, scheme: &str, path: &Path) -> Option<&OpenEditor> {- let others = self.other_groups.iter().flat_map(|group| &group.editors);- self.editors.iter().chain(&self.models).chain(others).find(|editor| editor.document().is(scheme, path))+ self.all_editors().find(|editor| editor.document().is(scheme, path))}pub fn model_mut(&mut self, scheme: &str, path: &Path) -> Option<&mut OpenEditor> {- let others = self.other_groups.iter_mut().flat_map(|group| &mut group.editors);- self.editors.iter_mut().chain(&mut self.models).chain(others).find(|editor| editor.document().is(scheme, path))+ self.all_editors_mut().find(|editor| editor.document().is(scheme, path))+ }++ /// The tabs of every group, the active group's first; `editors` holds the active group's alone.+ pub fn all_tabs(&self) -> impl Iterator<Item = &OpenEditor> {+ self.editors.iter().chain(self.other_groups.iter().flat_map(|group| &group.editors))}- /// Every editor of every group and every model without an editor.+ pub fn all_tabs_mut(&mut self) -> impl Iterator<Item = &mut OpenEditor> {+ self.editors.iter_mut().chain(self.other_groups.iter_mut().flat_map(|group| &mut group.editors))+ }++ /// The tabs of every group and the models without a tab, in the same order as `all_editors_mut`.pub fn all_editors(&self) -> impl Iterator<Item = &OpenEditor> {self.editors.iter().chain(&self.models).chain(self.other_groups.iter().flat_map(|group| &group.editors))}+ pub fn all_editors_mut(&mut self) -> impl Iterator<Item = &mut OpenEditor> {+ self.editors.iter_mut().chain(&mut self.models).chain(self.other_groups.iter_mut().flat_map(|group| &mut group.editors))+ }+/// The editor groups, most recently active first; the panel's group is not one.pub fn group_ids_mru(&self) -> Vec<u32> {std::iter::once(self.id).chain(self.group_mru.iter().copied()).filter(|id| !is_panel_group(*id) && !self.is_side_group(*id)).collect()@@ -1780,8 +1791,7 @@ impl EditorGroup {pub fn set_previews_disabled(&mut self, disabled: bool) {self.previews_disabled = disabled;if disabled {- let groups = self.other_groups.iter_mut().map(|group| &mut group.editors);- for editor in std::iter::once(&mut self.editors).chain(groups).flatten() {+ for editor in self.all_tabs_mut() {editor.preview = false;}}diff --git a/native/crates/app/src/editor/edit.rs b/native/crates/app/src/editor/edit.rsindex 574543fbf65..54bee35f089 100644--- a/native/crates/app/src/editor/edit.rs+++ b/native/crates/app/src/editor/edit.rs@@ -9,7 +9,7 @@ use super::auto_indent::{AutoIndent, Model};use super::cursor::{self, Position, Selection};use super::word_operations::{self, AutoClosing, DeleteWordContext, WordClassifier, WordDelete, WordDeleteKind, WordNavigation};use super::edit_stack::{AppliedEdit, SingleModelEditStackElement, UndoElement};-use super::{OpenEditor, anchor_select, clipboard, folding, indent_guides};+use super::{OpenEditor, SharedModel, anchor_select, clipboard, folding, indent_guides};use crate::undo_redo::{Direction, Next};/// `EditOperationType`: what the last edit was, which decides where undo stops go.@@ -80,8 +80,9 @@ pub struct ContentChange {}/// One model content change event, as `$acceptModelChanged` carries it.-#[derive(Debug)]pub struct ContentChanged {+ /// The model that changed (`IModelContentChangedEvent` of one `ITextModel`).+ pub model: SharedModel,pub changes: Vec<ContentChange>,pub version_id: u32,pub is_undoing: bool,@@ -834,7 +835,7 @@ impl OpenEditor {// cursor.ts: a model change the cursor did not make resets the previous edit type.self.text_model_mut().history.last_kind = EditKind::Other;self.after_text_change(selections);- ContentChanged { changes, version_id: self.text_model().version_id, is_undoing, is_redoing: !is_undoing, reason: EditReason::ApplyEdits, was_dirty }+ ContentChanged { model: self.model.clone(), changes, version_id: self.text_model().version_id, is_undoing, is_redoing: !is_undoing, reason: EditReason::ApplyEdits, was_dirty }}/// The document as saving writes it: its EOL, in its encoding, with the BOM that encoding takes.@@ -860,7 +861,7 @@ impl OpenEditor {};self.push_edit_operation(Vec::new(), version_id, selections, before_eol);self.seen_version = version_id;- Some(ContentChanged { changes: Vec::new(), version_id, is_undoing: false, is_redoing: false, reason: EditReason::EolChange, was_dirty })+ Some(ContentChanged { model: self.model.clone(), changes: Vec::new(), version_id, is_undoing: false, is_redoing: false, reason: EditReason::EolChange, was_dirty })}pub fn mark_saved(&mut self) {@@ -1103,7 +1104,7 @@ impl OpenEditor {self.push_edit_operation(edits, version_id, selections_before, eol);// Editing a preview editor pins it (editorGroupView.ts pins a preview editor once it is dirty).self.preview = false;- Some(ContentChanged { changes, version_id, is_undoing: false, is_redoing: false, reason, was_dirty })+ Some(ContentChanged { model: self.model.clone(), changes, version_id, is_undoing: false, is_redoing: false, reason, was_dirty })}/// `EditStack.pushEditOperation`: the edits join the model's open element on the undo/redo service, or a newdiff --git a/native/crates/app/src/extension_host_start.rs b/native/crates/app/src/extension_host_start.rsnew file mode 100644index 00000000000..a4fdb3434cc--- /dev/null+++ b/native/crates/app/src/extension_host_start.rs@@ -0,0 +1,272 @@+//! One extension host start per window: the channels, the `HostSync` the workbench queues on, the `exthost-session`+//! thread and the loops of the window's thread that serve it. main.rs `open_window` starts a window's first host,+//! `workbench/extension_host_restart.rs` every later one.++use std::path::{Path, PathBuf};+use std::sync::atomic::{AtomicBool, Ordering};+use std::sync::mpsc::{Receiver, channel};+use std::sync::{Arc, Mutex};++use config::configuration::Overrides;+use config::service::Settings;+use config::workspace::Workspace;+use exthost::extension_development::{ExtensionDevelopment, ExtensionHostDebug};+use exthost::extension_management::WindowExtensions;+use exthost::main_thread_configuration::MainThreadConfiguration;+use exthost::main_thread_files::MainThreadFiles;+use exthost::main_thread_secret_state::MainThreadSecretState;+use exthost::main_thread_storage::MainThreadStorage;+use exthost::main_thread_workspace::MainThreadWorkspace;+use exthost::rpc::Arg;+use exthost::scan::ScannedExtension;+use exthost::session::{ForwardedRequest, Session, SessionPaths, init_data, workspace_data};+use exthost::{ExtensionHost, HostOptions, Inbox, Runtime, WakingSender};+use futures::StreamExt;+use futures::channel::mpsc::{UnboundedSender, unbounded};+use futures::channel::oneshot;+use gpui::{Context, Window};+use serde_json::{Value, json};+use storage::state::FileStorage;++use crate::host_sync::{HostMessage, HostSync};+use crate::languages::Languages;+use crate::main_thread::{HostRequest, WorkbenchMainThread};+use crate::theme::ThemeKind;+use crate::workbench::Workbench;+use crate::workbench::extension_host_restart::{serve_host_requests, serve_main_thread_requests};+use crate::{main_thread_commands, main_thread_status_bar, perf, product};++/// How a window's hosts run: set by `open_window`, the same for each restart.+#[derive(Clone)]+pub(crate) struct HostLaunch {+ pub process: HostProcess,+ /// `--user-data-dir`, whose `User` folder has the settings and the global storage.+ pub user_data: PathBuf,+}++#[derive(Clone)]+pub(crate) enum HostProcess {+ /// A Bun process (Node with `--node`) that runs the host bundle.+ Runtime(Runtime),+ /// `ExtensionHost::silent`: the test gets the init data and its end of the host's socket.+ #[cfg(test)]+ Silent(std::sync::mpsc::Sender<(Value, exthost::SilentPeer)>),+}++/// A host that does not run yet: what the workbench queues for it waits in `messages`.+pub(crate) struct HostStart {+ inbox: Inbox,+ messages: Receiver<HostMessage>,+}++impl HostStart {+ /// The `HostSync` of a new host, with the color theme and the language ids queued first.+ pub fn new(theme: ThemeKind, languages: &Languages) -> (HostStart, HostSync) {+ let (sender, messages) = channel();+ let inbox = Inbox::default();+ let host = HostSync::new(WakingSender::new(sender, inbox.waker()));+ host.send_color_theme(theme);+ host.send_language_ids(languages);+ (HostStart { inbox, messages }, host)+ }+}++impl Workbench {+ /// Runs the host of `start` with the window's running extensions, settings, storage, trust and workspace as they+ /// are now. The receiver fires when its eager extensions activated.+ pub(crate) fn spawn_extension_host(&mut self, start: HostStart, launch: HostLaunch, development: Option<ExtensionDevelopment>, window: &mut Window, cx: &mut Context<Self>) -> oneshot::Receiver<()> {+ let HostStart { inbox, messages } = start;+ let (status, mut status_lines) = unbounded::<String>();+ let (request_sender, requests) = unbounded::<ForwardedRequest>();+ let (reply_sender, replies) = channel();+ let reply_sender = WakingSender::new(reply_sender, inbox.waker());+ let (main_thread_sender, main_thread_requests) = unbounded::<HostRequest>();+ let user = self.extensions_viewlet.user.as_ref().expect("the user extensions are set at startup").clone_for_profile();+ let extensions = WindowExtensions { builtins: self.extensions_viewlet.builtins.clone(), user, running: self.extensions.clone(), proposed_api: self.proposed_api.clone() };+ let main_thread = WorkbenchMainThread { requests: main_thread_sender, messages, waiting: Vec::new(), content_providers: Default::default(), extensions };+ let window_state = WindowState {+ launch,+ app_root: self.app_root.clone(),+ extensions: self.extensions.clone(),+ settings: self.settings.clone(),+ storage: MainThreadStorage { profile: self.profile_storage.clone(), workspace: self.workspace_storage.clone() },+ workspace_trusted: self.workspace_trust.is_trusted(),+ workspace: self.workspace().cloned(),+ development,+ host_debug: self.extension_host_debug.clone(),+ };+ let window_closed = Arc::new(AtomicBool::new(false));+ let (session_ended, ended) = oneshot::channel::<()>();+ self.watch_session_end(window_closed.clone(), inbox.waker(), ended, cx);+ let start = self.extension_host_started(cx);+ std::thread::Builder::new()+ .name("exthost-session".into())+ .spawn(move || {+ let runs_tests = window_state.development.as_ref().is_some_and(|development| development.tests_path.is_some());+ if let Err(error) = run_extension_host(window_state, main_thread, request_sender, replies, inbox, &status, &window_closed) {+ if runs_tests {+ eprintln!("extension host failed: {error:#}");+ std::process::exit(1);+ }+ let _ = status.unbounded_send(format!("extension host failed: {error:#}"));+ }+ let _ = session_ended.send(());+ })+ .expect("spawn exthost session thread");+ serve_host_requests(requests, reply_sender, window, cx);+ serve_main_thread_requests(main_thread_requests, window, cx);+ let (activated_sender, activated) = oneshot::channel();+ let mut activated_sender = Some(activated_sender);+ cx.spawn_in(window, async move |workbench, cx| {+ while let Some(line) = status_lines.next().await {+ eprintln!("{line}");+ if line == EXITED_LINE {+ let _ = workbench.update_in(cx, |workbench, window, cx| workbench.extension_host_exited(start, window, cx));+ }+ if line.starts_with(HANDSHAKE_PREFIX) {+ let _ = workbench.update(cx, |workbench, _| {+ workbench.host.installed_extensions_registered = true;+ workbench.store_custom_editors_memento();+ });+ if start == 1 {+ perf::mark("code/didLoadExtensions");+ }+ }+ if line.starts_with(ACTIVATED_PREFIX)+ && let Some(sender) = activated_sender.take()+ {+ let _ = sender.send(());+ }+ }+ })+ .detach();+ activated+ }+}++/// What the session thread takes from the window, read when the host starts.+struct WindowState {+ launch: HostLaunch,+ app_root: PathBuf,+ extensions: Vec<ScannedExtension>,+ settings: Arc<Mutex<Settings>>,+ storage: MainThreadStorage,+ workspace_trusted: bool,+ workspace: Option<Workspace>,+ development: Option<ExtensionDevelopment>,+ host_debug: ExtensionHostDebug,+}++/// The extension host bundle: in the app files of VSRustium.app, else port/tools/build-exthost's output in the checkout.+fn exthost_entry(app_root: &Path) -> PathBuf {+ let bundled = app_root.join("out-exthost/bootstrap-exthost.js");+ if bundled.is_file() {+ return bundled;+ }+ Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../out-exthost/bootstrap-exthost.js")).to_path_buf()+}++/// Owns the session for the life of the host: handshake, one call each way, then serves host requests and+/// forwards what the workbench tells the host.+fn run_extension_host(+ window_state: WindowState,+ main_thread: WorkbenchMainThread,+ workbench_requests: UnboundedSender<ForwardedRequest>,+ workbench_replies: Receiver<(u32, Result<Value, Value>)>,+ inbox: Inbox,+ status: &UnboundedSender<String>,+ window_closed: &AtomicBool,+) -> anyhow::Result<()> {+ let WindowState { launch, app_root, extensions, settings, mut storage, workspace_trusted, workspace, development, host_debug } = window_state;+ let user_data = launch.user_data;+ let paths = SessionPaths { app_root: &app_root, user_data: &user_data, workspace: workspace.as_ref() };+ let extension_tests = development.as_ref().is_some_and(|development| development.tests_path.is_some());+ let mut init = init_data(&paths, &extensions, &crate::VERSION);+ init["quality"] = json!(product::quality());+ // localProcessExtensionHost.ts: console stacks are forwarded unless a packaged (built) stable build runs.+ init["consoleForward"]["includeStack"] = json!(!(product::is_bundled(&app_root) && product::is_stable()));+ // StateService of main.ts: `storage.json` in the global storage folder.+ let global_storage = user_data.join("User/globalStorage");+ std::fs::create_dir_all(&global_storage)?;+ init["telemetryInfo"] = storage.telemetry_info(&mut FileStorage::open(&global_storage.join("storage.json")));+ if let Some(development) = &development {+ development.add_to_init_data(&mut init);+ }+ init["environment"]["isExtensionDevelopmentDebug"] = json!(host_debug.port.is_some());+ let waker = inbox.waker();+ let host = match launch.process {+ HostProcess::Runtime(runtime) => {+ let entry = exthost_entry(&app_root);+ let (runtime, extra_args) = match host_debug.port {+ Some(port) => (Runtime::Node, host_debug.node_args(port)),+ None => (runtime, Vec::new()),+ };+ ExtensionHost::start(HostOptions { runtime, entry: &entry, extra_env: host_debug.env.into_iter().chain(files::unc::utility_process_env()).collect(), extra_args, inbox }, &init)?+ }+ #[cfg(test)]+ HostProcess::Silent(opened) => {+ let (host, peer) = ExtensionHost::silent(inbox);+ opened.send((init.clone(), peer))?;+ host+ }+ };+ let _ = status.unbounded_send(format!("{HANDSHAKE_PREFIX}{}", host.child.id()));+ let mut session = Session::new(host);+ let folders: Vec<PathBuf> = workspace.iter().flat_map(|workspace| workspace.folders.iter().map(|folder| folder.path.clone())).collect();+ let mut watched = Vec::new();+ for folder in &folders {+ let excludes = settings.lock().unwrap().get_value(Some("files.watcherExclude"), &Overrides { resource: Some(folder), ..Overrides::default() });+ let excludes: Vec<String> = excludes.as_ref().and_then(|excludes| excludes.as_object()).into_iter().flatten().filter(|(_, on)| **on == true).map(|(pattern, _)| pattern.clone()).collect();+ watched.push((folder.clone(), excludes));+ }+ session.files = Some(MainThreadFiles::new(&watched, &extensions, settings.clone(), waker.clone())?);+ session.workspace = Some(MainThreadWorkspace::new(folders, settings.clone(), &app_root, waker));+ session.configuration = Some(MainThreadConfiguration::new(settings, development.is_some()));+ session.storage = Some(storage);+ session.workspace_trusted = workspace_trusted;+ // secrets.ts: without encryption the secret storage falls back to memory.+ session.secrets = Some(match extension_tests {+ true => MainThreadSecretState::in_memory(),+ false => MainThreadSecretState::keychain().unwrap_or_else(|error| {+ eprintln!("[secrets] the Keychain is unavailable, secrets stay in memory: {error}");+ MainThreadSecretState::in_memory()+ }),+ });+ session.forward(main_thread_commands::path, move |request| {+ let _ = workbench_requests.unbounded_send(request);+ }, workbench_replies);+ session.main_thread = Some(Box::new(main_thread));+ session.notify("ExtHostStatusBar", "$acceptStaticEntries", vec![json!(main_thread_status_bar::static_entry_dtos(&extensions))]);+ perf::mark("code/willStartExtensionHost");+ session.start(&extensions, workspace.as_ref().map(|workspace| workspace_data(&init, workspace)))?;+ perf::mark("code/didStartExtensionHost");+ // No timeout: a host paused in a debugger answers once it runs on.+ let reply = session.request("ExtHostExtensionService", "$test_latency", vec![Arg::Json(json!(7))], None)?;+ let _ = status.unbounded_send(format!("main -> host: $test_latency(7) = {reply:?}"));+ let _ = status.unbounded_send(format!("host -> main: {} requests so far", session.log.host_calls.values().sum::<u32>()));+ let _ = status.unbounded_send(format!("{ACTIVATED_PREFIX}{}", session.log.activated.join(", ")));+ if extension_tests {+ session.execute_extension_tests();+ }+ // Workbench changes, answers, file events and the window's close wake the wait (`exthost::Waker`).+ loop {+ // A closed window's host goes with its session (ExtensionHost's drop terminates it).+ if window_closed.load(Ordering::Relaxed) {+ return Ok(());+ }+ session.flush_main_thread();+ if !session.pump(session.idle_timeout())? {+ break;+ }+ }+ if let Some(code) = session.extension_tests_exit_code() {+ drop(session);+ std::process::exit(code);+ }+ let _ = status.unbounded_send(EXITED_LINE.into());+ Ok(())+}++const ACTIVATED_PREFIX: &str = "eager extensions activated: ";+const HANDSHAKE_PREFIX: &str = "handshake done, pid ";+const EXITED_LINE: &str = "extension host exited";diff --git a/native/crates/app/src/host_sync.rs b/native/crates/app/src/host_sync.rsindex 3c9fbda9241..db7d446ac2d 100644--- a/native/crates/app/src/host_sync.rs+++ b/native/crates/app/src/host_sync.rs@@ -312,13 +312,6 @@ impl HostSync {self.send("ExtHostEditorTabs", "$acceptTabOperation", vec![operation]);}- /// Tells the host the text of code editor `editor` changed (mainThreadDocuments.ts ModelTracker), then the- /// dirty state and tabs when it flipped, then where the cursor went.- pub fn send_content_change(&mut self, group: &EditorGroup, editor: &OpenEditor, change: &ContentChanged) {- self.send_model_change(group, editor, change);- self.send_selection(editor, "keyboard");- }-/// The text of `editor`, shown or a model without an editor, changed: the change, then the dirty state and tabs when it flipped, the tabs also for an untitled model.pub fn send_model_change(&mut self, group: &EditorGroup, editor: &OpenEditor, change: &ContentChanged) {let document = &editor.document();@@ -953,6 +946,12 @@ mod tests {assert_eq!(sent[1].method, "$acceptEditorTabModel");}+ /// An edit of the active editor as model_events.rs sends it: the change, then the selection.+ fn send_edit(sync: &mut HostSync, group: &EditorGroup, change: &ContentChanged) {+ sync.send_model_change(group, group.active().unwrap(), change);+ sync.send_selection(group.active().unwrap(), "keyboard");+ }+#[test]fn sends_content_changes_with_the_dirty_state_when_it_flips() {let (sender, receiver) = channel();@@ -964,7 +963,7 @@ mod tests {let editor = group.active_mut().unwrap();editor.move_to(Position::new(0, 5), false);let change = editor.type_text("!").unwrap();- sync.send_content_change(&group, group.active().unwrap(), &change);+ send_edit(&mut sync, &group, &change);let sent = drain(&receiver);let methods: Vec<_> = sent.iter().map(|message| message.method).collect();assert_eq!(methods, ["$acceptModelChanged", "$acceptDirtyStateChanged", "$acceptTabOperation", "$acceptEditorPropertiesChanged"]);@@ -979,11 +978,11 @@ mod tests {// Still dirty: no dirty state or tab update.let change = group.active_mut().unwrap().type_text("?").unwrap();- sync.send_content_change(&group, group.active().unwrap(), &change);+ send_edit(&mut sync, &group, &change);assert_eq!(drain(&receiver).len(), 2);let change = group.active_mut().unwrap().undo().unwrap();- sync.send_content_change(&group, group.active().unwrap(), &change);+ send_edit(&mut sync, &group, &change);let sent = drain(&receiver);assert_eq!((sent[0].args[1]["isUndoing"].clone(), sent[0].args[1]["detailedReason"].clone()), (json!(true), json!({ "source": "applyEdits" })));assert_eq!(sent[1].args[1], false);@@ -1046,7 +1045,7 @@ mod tests {let editor = group.active_mut().unwrap();editor.move_to(Position::new(1, 0), false);let change = editor.type_text("const broken: number = 'text';\n").unwrap();- sync.send_content_change(&group, group.active().unwrap(), &change);+ send_edit(&mut sync, &group, &change);forward(&mut session);pump_until(&mut session, 60, &|session| diagnostics(session) > before);assert!(diagnostics(&session) > before, "no diagnostics after the edit; console: {:#?}", session.log.console);diff --git a/native/crates/app/src/language_features.rs b/native/crates/app/src/language_features.rsindex 93cee63be37..af8ec2ee5bf 100644--- a/native/crates/app/src/language_features.rs+++ b/native/crates/app/src/language_features.rs@@ -6,18 +6,90 @@ use serde_json::Value;#[cfg(test)]mod tests;-/// One `$register*` call: its method names the kind, its arguments start with the handle and, for providers-/// scored per model, the document selector.+/// One `$register*` call decoded once by `register`, its fields named as in extHost.protocol.ts+/// `MainThreadLanguageFeaturesShape`. A field the method does not carry keeps its default.+#[derive(Default)]pub struct Registration {pub handle: u64,pub method: String,- pub args: Vec<Value>,+ /// The document selector; null for `$registerNavigateTypeSupport`, which has none.+ pub selector: Value,+ /// The method's DTO after the selector: the metadata of code actions, paste, drop and signature help, the+ /// legend of semantic tokens, the status of `$setLanguageStatus`.+ pub metadata: Value,+ /// `supportsResolve`, `supportsResolveDetails` (completions), `supportsResolveInitialValues` (rename).+ pub supports_resolve: bool,+ pub event_handle: Option<u64>,+ /// `ExtensionIdentifier.value`, or the plain string of inline completions.+ pub extension_id: String,+ /// `displayName` of a formatter or a document symbol provider.+ pub display_name: Option<String>,+ /// Completion trigger characters, or the `autoFormatTriggerCharacters` of on-type formatting.+ pub trigger_characters: Vec<String>,+ /// `supportRanges` of `$registerRangeFormattingSupport`.+ pub supports_ranges: bool,+ /// `groupId` and `debounceDelayMs` of `$registerInlineCompletionsSupport`.+ pub group_id: Option<String>,+ pub debounce_delay_ms: Option<u64>,time: u64,}impl Registration {- pub fn selector(&self) -> &Value {- self.args.get(1).unwrap_or(&Value::Null)+ /// Reads `args` at the positions extHost.protocol.ts gives `method`.+ fn decode(method: &str, handle: u64, args: &[Value]) -> Self {+ let arg = |index: usize| args.get(index).cloned().unwrap_or(Value::Null);+ let flag = |index: usize| args.get(index) == Some(&Value::Bool(true));+ let number = |index: usize| args.get(index).and_then(Value::as_u64);+ let string = |index: usize| args.get(index).and_then(Value::as_str).map(str::to_owned);+ let extension_id = |index: usize| args.get(index).and_then(|id| id["value"].as_str().or(id.as_str())).unwrap_or_default().to_owned();+ let strings = |index: usize| args.get(index).and_then(Value::as_array).into_iter().flatten().filter_map(Value::as_str).map(str::to_owned).collect();+ let mut registration = Registration { handle, method: method.to_owned(), selector: arg(1), ..Registration::default() };+ match method {+ "$registerNavigateTypeSupport" => {+ registration.selector = Value::Null;+ registration.supports_resolve = flag(1);+ }+ "$registerCompletionsProvider" => {+ registration.trigger_characters = strings(2);+ registration.supports_resolve = flag(3);+ }+ "$registerCodeActionSupport" => {+ registration.metadata = arg(2);+ registration.supports_resolve = flag(5);+ }+ "$registerPasteEditProvider" | "$registerDocumentOnDropEditProvider" | "$registerSignatureHelpProvider" | "$setLanguageStatus" => registration.metadata = arg(2),+ "$registerDocumentSemanticTokensProvider" | "$registerDocumentRangeSemanticTokensProvider" => {+ registration.metadata = arg(2);+ registration.event_handle = number(3);+ }+ "$registerDocumentFormattingSupport" | "$registerRangeFormattingSupport" => {+ registration.extension_id = extension_id(2);+ registration.display_name = string(3);+ registration.supports_ranges = method == "$registerRangeFormattingSupport" && flag(4);+ }+ "$registerOnTypeFormattingSupport" => {+ registration.trigger_characters = strings(2);+ registration.extension_id = extension_id(3);+ }+ "$registerRenameSupport" | "$registerDocumentLinkProvider" => registration.supports_resolve = flag(2),+ "$registerInlayHintsProvider" => {+ registration.supports_resolve = flag(2);+ registration.event_handle = number(3);+ }+ "$registerCodeLensSupport" => registration.event_handle = number(2),+ "$registerFoldingRangeProvider" => {+ registration.extension_id = extension_id(2);+ registration.event_handle = number(3);+ }+ "$registerDocumentSymbolProvider" => registration.display_name = string(2),+ "$registerInlineCompletionsSupport" => {+ registration.extension_id = extension_id(3);+ registration.group_id = string(5);+ registration.debounce_delay_ms = number(8);+ }+ _ => {}+ }+ registration}}@@ -38,7 +110,7 @@ impl LanguageFeatures {pub fn register(&mut self, method: &str, args: Vec<Value>) {let Some(handle) = args.first().and_then(Value::as_u64) else { return };self.clock += 1;- self.registrations.push(Registration { handle, method: method.to_owned(), args, time: self.clock });+ self.registrations.push(Registration { time: self.clock, ..Registration::decode(method, handle, &args) });}/// Removes the registration of `handle`; answers its method.@@ -79,8 +151,8 @@ impl LanguageFeatures {fn scored(&self, method: &str, candidate: &Candidate) -> Vec<(u32, &Registration)> {let mut scored: Vec<(u32, &Registration)> = Vec::new();for registration in self.registrations.iter().filter(|registration| registration.method == method) {- let value = score(registration.selector(), candidate.uri, candidate.language, true);- if value > 0 && is_exclusive(registration.selector()) {+ let value = score(®istration.selector, candidate.uri, candidate.language, true);+ if value > 0 && is_exclusive(®istration.selector) {return vec![(value, registration)];}if value > 0 {@@ -88,7 +160,7 @@ impl LanguageFeatures {}}scored.sort_by(|(a_score, a), (b_score, b)| {- b_score.cmp(a_score).then(is_builtin(a.selector()).cmp(&is_builtin(b.selector()))).then(b.time.cmp(&a.time))+ b_score.cmp(a_score).then(is_builtin(&a.selector).cmp(&is_builtin(&b.selector))).then(b.time.cmp(&a.time))});scored}diff --git a/native/crates/app/src/language_features/tests.rs b/native/crates/app/src/language_features/tests.rsindex 04832f0ab62..2931d6ceea2 100644--- a/native/crates/app/src/language_features/tests.rs+++ b/native/crates/app/src/language_features/tests.rs@@ -56,3 +56,36 @@ fn ordered_sorts_by_score_then_builtin_then_newest() {features.register("$registerHoverProvider", vec![json!(7), json!([{ "language": "typescript", "exclusive": true }])]);assert_eq!(handles(&features), [7]);}++/// extHost.protocol.ts `MainThreadLanguageFeaturesShape`: each `$register*` method's arguments land in the named+/// field of their position.+#[test]+fn register_decodes_each_method_at_its_protocol_positions() {+ let mut features = LanguageFeatures::default();+ let selector = json!([{ "language": "rust" }]);+ let extension = json!({ "value": "pub.ext", "_lower": "pub.ext" });+ features.register("$registerNavigateTypeSupport", vec![json!(1), json!(true)]);+ features.register("$registerCompletionsProvider", vec![json!(2), selector.clone(), json!([".", "::"]), json!(true), extension.clone()]);+ features.register("$registerCodeActionSupport", vec![json!(3), selector.clone(), json!({ "providedKinds": ["quickfix"] }), json!("Fix"), json!("pub.ext"), json!(true)]);+ features.register("$registerDocumentSemanticTokensProvider", vec![json!(4), selector.clone(), json!({ "tokenTypes": ["type"] }), json!(40)]);+ features.register("$registerRangeFormattingSupport", vec![json!(5), selector.clone(), extension.clone(), json!("Formatter"), json!(true)]);+ features.register("$registerOnTypeFormattingSupport", vec![json!(6), selector.clone(), json!(["}"]), extension.clone()]);+ features.register("$registerInlayHintsProvider", vec![json!(7), selector.clone(), json!(true), json!(70), json!("Hints")]);+ features.register("$registerCodeLensSupport", vec![json!(8), selector.clone(), json!(80)]);+ features.register("$registerFoldingRangeProvider", vec![json!(9), selector.clone(), extension.clone(), json!(90)]);+ features.register("$registerDocumentSymbolProvider", vec![json!(10), selector.clone(), json!("Outline")]);+ let inline = vec![json!(11), selector.clone(), json!(false), json!("pub.ext"), json!("1.0.0"), json!("group"), json!([]), json!("Inline"), json!(25), json!([])];+ features.register("$registerInlineCompletionsSupport", inline);+ let at = |handle| features.registration(handle).unwrap();+ assert_eq!((at(1).selector.clone(), at(1).supports_resolve), (Value::Null, true));+ assert_eq!((at(2).selector.clone(), at(2).trigger_characters.clone(), at(2).supports_resolve), (selector.clone(), vec![".".to_owned(), "::".to_owned()], true));+ assert_eq!((at(3).metadata["providedKinds"][0].clone(), at(3).supports_resolve), (json!("quickfix"), true));+ assert_eq!((at(4).metadata["tokenTypes"][0].clone(), at(4).event_handle), (json!("type"), Some(40)));+ assert_eq!((at(5).extension_id.as_str(), at(5).display_name.as_deref(), at(5).supports_ranges), ("pub.ext", Some("Formatter"), true));+ assert_eq!((at(6).trigger_characters.clone(), at(6).extension_id.as_str()), (vec!["}".to_owned()], "pub.ext"));+ assert_eq!((at(7).supports_resolve, at(7).event_handle), (true, Some(70)));+ assert_eq!(at(8).event_handle, Some(80));+ assert_eq!((at(9).extension_id.as_str(), at(9).event_handle), ("pub.ext", Some(90)));+ assert_eq!(at(10).display_name.as_deref(), Some("Outline"));+ assert_eq!((at(11).extension_id.as_str(), at(11).group_id.as_deref(), at(11).debounce_delay_ms), ("pub.ext", Some("group"), Some(25)));+}diff --git a/native/crates/app/src/main.rs b/native/crates/app/src/main.rsindex 0cff52cd215..9547a30b850 100644--- a/native/crates/app/src/main.rs+++ b/native/crates/app/src/main.rs@@ -39,6 +39,7 @@ mod navigation;mod editor_history;mod explorer;mod extension_enablement;+mod extension_host_start;mod extension_point_messages;mod extension_recommendations;mod extensions_model;@@ -142,7 +143,6 @@ mod workspace_trust;mod x11;use std::path::{Path, PathBuf};-use std::sync::mpsc::{Receiver, channel};use std::sync::{Arc, Mutex};use std::time::Duration;@@ -151,26 +151,17 @@ use config::registry::Registry;use config::service::Settings;use config::workspace::Workspace;use exthost::extension_development::{ExtensionDevelopment, ExtensionHostDebug};-use exthost::extension_management::{UserExtensions, WindowExtensions, add_user_extensions};-use exthost::main_thread_configuration::MainThreadConfiguration;-use exthost::main_thread_files::MainThreadFiles;-use exthost::main_thread_secret_state::MainThreadSecretState;+use exthost::extension_management::{UserExtensions, add_user_extensions};use exthost::main_thread_storage::MainThreadStorage;-use exthost::main_thread_workspace::MainThreadWorkspace;-use exthost::rpc::Arg;use exthost::scan::{ScannedExtension, scan_builtin_extensions};-use exthost::session::{ForwardedRequest, Session, SessionPaths, init_data, workspace_data};-use exthost::{ExtensionHost, HostOptions, Inbox, Runtime, WakingSender};-use futures::StreamExt;-use futures::channel::mpsc::{UnboundedSender, unbounded};+use exthost::session::SessionPaths;+use exthost::Runtime;use gpui::{App, Bounds, Keystroke, TitlebarOptions, Window, WindowBounds, WindowOptions, point, prelude::*, px, size};use gpui_platform::application;use serde_json::json;-use storage::state::FileStorage;use anyhow::Context as _;-use host_sync::HostSync;+use extension_host_start::{HostLaunch, HostProcess, HostStart};use languages::Languages;-use main_thread::{HostRequest, WorkbenchMainThread};use theme::load_theme;use workbench::Workbench;@@ -501,7 +492,6 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resul}settings.update_workspace_trust(false);}- let window_extensions = WindowExtensions { builtins: builtins.clone(), user: user_extensions.clone_for_profile(), running: extensions.clone(), proposed_api: proposed_api.clone() };let theme = match flag_value("--theme") {Some(theme_id) => load_theme(&extensions, &theme_id)?,None => settings_theme(&extensions, &settings, cx)?,@@ -510,7 +500,6 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resullet color_themes = theme::color_themes(&extensions)?;let settings = Arc::new(Mutex::new(settings));let keybindings_file = profile.current.keybindings_resource.clone();- let session_closed = Arc::new(std::sync::atomic::AtomicBool::new(false));// Same size as the reference capture in port/tools/ref-screenshot, so pixel diffs line up.let mut bounds = Bounds::centered(None, size(px(1024.), px(768.)), cx);@@ -549,20 +538,10 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resulcx.open_window(options, |window, cx| {perf::mark("code/willStartWorkbench");cx.new(|cx| {- let (sender, mut receiver) = unbounded::<String>();- let (host_sender, host_receiver) = channel();- let (request_sender, requests) = unbounded::<ForwardedRequest>();- let (reply_sender, replies) = channel::<(u32, Result<serde_json::Value, serde_json::Value>)>();- let inbox = Inbox::default();- let reply_sender = WakingSender::new(reply_sender, inbox.waker());- let (main_thread_sender, main_thread_requests) = unbounded::<HostRequest>();- let main_thread = WorkbenchMainThread { requests: main_thread_sender, messages: host_receiver, waiting: Vec::new(), content_providers: Default::default(), extensions: window_extensions };let languages = Languages::new(&extensions);- let mut host = HostSync::new(WakingSender::new(host_sender, inbox.waker()));+ let (host_start, mut host) = HostStart::new(theme.kind, &languages);host.configuration_scopes = development.is_some();- host.send_color_theme(theme.kind);perf::mark("code/willCreateWorkbenchContributions/1");- host.send_language_ids(&languages);let mut workbench = Workbench::new(theme, app_root.clone(), workspace.clone(), languages, settings.clone(), host, cx);perf::mark("code/didCreateWorkbench");perf::mark("code/didCreateWorkbenchContributions/2");@@ -610,7 +589,6 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resul}workbench.restore_profile_state(storage.profile.clone(), application_storage);workbench.restore_workspace_state(storage.workspace.clone());- let workspace_trusted = workspace_trust.is_trusted();workbench.workspace_trust = workspace_trust;workbench.shared_storage = shared_storage;workbench.watch_recently_opened(window, cx);@@ -652,39 +630,14 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resulif let Some(url) = &open_url {workbench.open_protocol_url(url, window, cx);}- let (session_ended, ended) = futures::channel::oneshot::channel::<()>();- workbench.watch_session_end(session_closed.clone(), inbox.waker(), ended, cx);- let start = workbench.extension_host_started(cx);- std::thread::Builder::new()- .name("exthost-session".into())- .spawn(move || {- let runs_tests = development.as_ref().is_some_and(|development| development.tests_path.is_some());- if let Err(error) = run_extension_host(runtime, app_root, extensions, settings, storage, workspace_trusted, user_data, workspace, development, host_debug, main_thread, request_sender, replies, inbox, &sender, &session_closed) {- if runs_tests {- eprintln!("extension host failed: {error:#}");- std::process::exit(1);- }- let _ = sender.unbounded_send(format!("extension host failed: {error:#}"));- }- let _ = session_ended.send(());- })- .expect("spawn exthost session thread");- workbench::extension_host_restart::serve_host_requests(requests, reply_sender, window, cx);- workbench::extension_host_restart::serve_main_thread_requests(main_thread_requests, window, cx);- cx.spawn_in(window, async move |workbench, cx| {- while let Some(line) = receiver.next().await {- eprintln!("{line}");- if line == EXITED_LINE {- let _ = workbench.update_in(cx, |workbench, window, cx| workbench.extension_host_exited(start, window, cx));+ let launch = HostLaunch { process: HostProcess::Runtime(runtime), user_data: user_data.clone() };+ workbench.host_launch = Some(launch.clone());+ let activated = workbench.spawn_extension_host(host_start, launch, development, window, cx);+ if let Some(path) = screenshot {+ cx.spawn_in(window, async move |workbench, cx| {+ if activated.await.is_err() {+ return;}- if line.starts_with(HANDSHAKE_PREFIX) {- let _ = workbench.update(cx, |workbench, _| {- workbench.host.installed_extensions_registered = true;- workbench.store_custom_editors_memento();- });- perf::mark("code/didLoadExtensions");- }- let (true, Some(path)) = (line.starts_with(ACTIVATED_PREFIX), screenshot.as_ref()) else { continue };// Captured once eager extensions are up, so the frame shows the workbench as the host left it.cx.background_executor().timer(Duration::from_millis(500)).await;if !screenshot_keys.is_empty() {@@ -711,15 +664,15 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::Resulworkbench.update(cx, |workbench, _| workbench.input_carets_hidden = true).ok();cx.update(|window, _| window.refresh()).ok();cx.background_executor().timer(Duration::from_millis(100)).await;- let saved = cx.update(|window, _| save_screenshot(window, path)).and_then(|result| result);+ let saved = cx.update(|window, _| save_screenshot(window, &path)).and_then(|result| result);if let Err(error) = saved {eprintln!("screenshot failed: {error:#}");std::process::exit(1);}cx.update(|_, cx| cx.quit()).ok();- }- })- .detach();+ })+ .detach();+ }perf::mark("code/didStartWorkbench");workbench.restored_at = Some(std::time::Instant::now());workbench@@ -733,115 +686,6 @@ pub(crate) fn open_window(request: WindowRequest, cx: &mut App) -> anyhow::ResulOk(window)}-/// The extension host bundle: in the app files of VSRustium.app, else port/tools/build-exthost's output in the checkout.-fn exthost_entry(app_root: &Path) -> PathBuf {- let bundled = app_root.join("out-exthost/bootstrap-exthost.js");- if bundled.is_file() {- return bundled;- }- Path::new(concat!(env!("CARGO_MANIFEST_DIR"), "/../../../out-exthost/bootstrap-exthost.js")).to_path_buf()-}--/// Owns the session for the life of the app: handshake, one call each way, then serves host requests and-/// forwards what the workbench tells the host.-// It takes what main parsed for the session thread; a struct for one call site would only rename the list.-#[allow(clippy::too_many_arguments)]-fn run_extension_host(- runtime: Runtime,- app_root: PathBuf,- extensions: Vec<ScannedExtension>,- settings: Arc<Mutex<Settings>>,- mut storage: MainThreadStorage,- workspace_trusted: bool,- user_data: PathBuf,- workspace: Option<Workspace>,- development: Option<ExtensionDevelopment>,- host_debug: ExtensionHostDebug,- main_thread: WorkbenchMainThread,- workbench_requests: UnboundedSender<ForwardedRequest>,- workbench_replies: Receiver<(u32, Result<serde_json::Value, serde_json::Value>)>,- inbox: Inbox,- status: &UnboundedSender<String>,- window_closed: &std::sync::atomic::AtomicBool,-) -> anyhow::Result<()> {- let paths = SessionPaths { app_root: &app_root, user_data: &user_data, workspace: workspace.as_ref() };- let extension_tests = development.as_ref().is_some_and(|development| development.tests_path.is_some());- let mut init = init_data(&paths, &extensions, &VERSION);- init["quality"] = json!(product::quality());- // localProcessExtensionHost.ts: console stacks are forwarded unless a packaged (built) stable build runs.- init["consoleForward"]["includeStack"] = json!(!(product::is_bundled(&app_root) && product::is_stable()));- // StateService of main.ts: `storage.json` in the global storage folder.- let global_storage = user_data.join("User/globalStorage");- std::fs::create_dir_all(&global_storage)?;- init["telemetryInfo"] = storage.telemetry_info(&mut FileStorage::open(&global_storage.join("storage.json")));- if let Some(development) = &development {- development.add_to_init_data(&mut init);- }- init["environment"]["isExtensionDevelopmentDebug"] = json!(host_debug.port.is_some());- let entry = exthost_entry(&app_root);- let (runtime, extra_args) = match host_debug.port {- Some(port) => (Runtime::Node, host_debug.node_args(port)),- None => (runtime, Vec::new()),- };- let waker = inbox.waker();- let host = ExtensionHost::start(HostOptions { runtime, entry: &entry, extra_env: host_debug.env.into_iter().chain(files::unc::utility_process_env()).collect(), extra_args, inbox }, &init)?;- let _ = status.unbounded_send(format!("{HANDSHAKE_PREFIX}{}", host.child.id()));- let mut session = Session::new(host);- let folders: Vec<PathBuf> = workspace.iter().flat_map(|workspace| workspace.folders.iter().map(|folder| folder.path.clone())).collect();- let mut watched = Vec::new();- for folder in &folders {- let excludes = settings.lock().unwrap().get_value(Some("files.watcherExclude"), &Overrides { resource: Some(folder), ..Overrides::default() });- let excludes: Vec<String> = excludes.as_ref().and_then(|excludes| excludes.as_object()).into_iter().flatten().filter(|(_, on)| **on == true).map(|(pattern, _)| pattern.clone()).collect();- watched.push((folder.clone(), excludes));- }- session.files = Some(MainThreadFiles::new(&watched, &extensions, settings.clone(), waker.clone())?);- session.workspace = Some(MainThreadWorkspace::new(folders, settings.clone(), &app_root, waker));- session.configuration = Some(MainThreadConfiguration::new(settings, development.is_some()));- session.storage = Some(storage);- session.workspace_trusted = workspace_trusted;- // secrets.ts: without encryption the secret storage falls back to memory.- session.secrets = Some(match extension_tests {- true => MainThreadSecretState::in_memory(),- false => MainThreadSecretState::keychain().unwrap_or_else(|error| {- eprintln!("[secrets] the Keychain is unavailable, secrets stay in memory: {error}");- MainThreadSecretState::in_memory()- }),- });- session.forward(&["MainThreadCommands", "MainThreadComments", "MainThreadCustomEditors", "MainThreadDebugService", "MainThreadDecorations", "MainThreadDiagnostics", "MainThreadDialogs", "MainThreadDownloadService", "MainThreadEditorInsets", "MainThreadEditorTabs", "MainThreadGitHub", "MainThreadLanguageFeatures", "MainThreadLanguages.$removeLanguageStatus", "MainThreadLanguages.$setLanguageStatus", "MainThreadLogger", "MainThreadMessageService", "MainThreadNotebook", "MainThreadNotebookDocuments", "MainThreadNotebookEditors", "MainThreadNotebookKernels", "MainThreadNotebookRenderers", "MainThreadOutputService", "MainThreadProgress", "MainThreadQuickDiff", "MainThreadQuickOpen", "MainThreadSCM", "MainThreadStatusBar", "MainThreadTask", "MainThreadTerminalService", "MainThreadTerminalShellIntegration", "MainThreadTesting", "MainThreadTimeline", "MainThreadTreeViews", "MainThreadUriOpeners", "MainThreadUrls", "MainThreadUrls.$registerUriHandler", "MainThreadUrls.$unregisterUriHandler", "MainThreadWebviewPanels", "MainThreadWebviewViews", "MainThreadWebviews", "MainThreadWindow.$openUri", "MainThreadWorkspace"], move |request| {- let _ = workbench_requests.unbounded_send(request);- }, workbench_replies);- session.main_thread = Some(Box::new(main_thread));- session.notify("ExtHostStatusBar", "$acceptStaticEntries", vec![json!(main_thread_status_bar::static_entry_dtos(&extensions))]);- perf::mark("code/willStartExtensionHost");- session.start(&extensions, workspace.as_ref().map(|workspace| workspace_data(&init, workspace)))?;- perf::mark("code/didStartExtensionHost");- // No timeout: a host paused in a debugger answers once it runs on.- let reply = session.request("ExtHostExtensionService", "$test_latency", vec![Arg::Json(json!(7))], None)?;- let _ = status.unbounded_send(format!("main -> host: $test_latency(7) = {reply:?}"));- let _ = status.unbounded_send(format!("host -> main: {} requests so far", session.log.host_calls.values().sum::<u32>()));- let _ = status.unbounded_send(format!("{ACTIVATED_PREFIX}{}", session.log.activated.join(", ")));- if development.is_some_and(|development| development.tests_path.is_some()) {- session.execute_extension_tests();- }- // Workbench changes, answers, file events and the window's close wake the wait (`exthost::Waker`).- loop {- // A closed window's host goes with its session (ExtensionHost's drop terminates it).- if window_closed.load(std::sync::atomic::Ordering::Relaxed) {- return Ok(());- }- session.flush_main_thread();- if !session.pump(session.idle_timeout())? {- break;- }- }- if let Some(code) = session.extension_tests_exit_code() {- drop(session);- std::process::exit(code);- }- let _ = status.unbounded_send(EXITED_LINE.into());- Ok(())-}-/// package.json `version`, with `-<quality>` on a build that is not stable (`insider`), as gulpfile.vscode.ts writes it.static VERSION: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| version_for_quality(product::quality()));@@ -852,10 +696,6 @@ fn version_for_quality(quality: Option<&str>) -> String {}}-const ACTIVATED_PREFIX: &str = "eager extensions activated: ";-const HANDSHAKE_PREFIX: &str = "handshake done, pid ";-const EXITED_LINE: &str = "extension host exited";-/// The OS whose key conventions gpui-fast's keystroke parsing and printing take, before an `App` exists.fn host_os() -> gpui::OperatingSystem {match () {diff --git a/native/crates/app/src/main_thread.rs b/native/crates/app/src/main_thread.rsindex f62be21363e..02820321cda 100644--- a/native/crates/app/src/main_thread.rs+++ b/native/crates/app/src/main_thread.rs@@ -7,7 +7,7 @@ use std::time::Duration;use base64::Engine;use base64::engine::general_purpose::STANDARD;use exthost::extension_management::WindowExtensions;-use exthost::main_thread::{MainThread, serialized_error};+use exthost::main_thread::{MainThread, Path, serialized_error};use exthost::main_thread_files::{Providers, resource};use exthost::rpc::{Arg, Reply};use exthost::session::{CallResult, Session, URL_PROTOCOL};@@ -18,11 +18,13 @@ use serde_json::{Value, json};use crate::host_sync::HostMessage;use crate::uri::Uri;-use crate::workbench::host_requests::HOST_REQUESTS;use crate::workbench::text_model_resolver::ContentProviders;+#[cfg(test)]+mod tests;+pub struct HostRequest {- pub proxy: String,+ pub proxy: &'static str,pub method: String,pub args: Vec<Value>,pub reply: Sender<Result<Value, Value>>,@@ -39,7 +41,7 @@ pub struct WorkbenchMainThread {}impl MainThread for WorkbenchMainThread {- fn handle(&mut self, session: &mut Session, proxy: &str, method: &str, args: &[Arg]) -> Option<Result<Reply, Value>> {+ fn handle(&mut self, session: &mut Session, proxy: &'static str, method: &str, args: &[Arg]) -> Option<Result<Reply, Value>> {let mut args: Vec<Value> = args.iter().map(|arg| match arg {@@ -76,7 +78,7 @@ impl MainThread for WorkbenchMainThread {std::fs::read(path.as_str().unwrap_or_default()).map(Reply::Buffer).map_err(|error| serialized_error(&error.to_string()))}));}- _ if !HOST_REQUESTS.contains(&(proxy, method)) => return None,+ _ if crate::main_thread_commands::path(proxy, method) != Some(Path::Blocking) => return None,_ => {}}// mainThreadFileSystem.ts reads and writes through the extension host; the session thread can call it, the GPUI thread cannot.@@ -191,9 +193,9 @@ impl MainThread for WorkbenchMainThread {impl WorkbenchMainThread {/// Runs one request on the GPUI thread and waits for its answer.- fn ask(&self, proxy: &str, method: &str, args: Vec<Value>) -> Result<Value, Value> {+ fn ask(&self, proxy: &'static str, method: &str, args: Vec<Value>) -> Result<Value, Value> {let (reply, receiver) = channel();- let request = HostRequest { proxy: proxy.to_string(), method: method.to_string(), args, reply };+ let request = HostRequest { proxy, method: method.to_string(), args, reply };// The workbench is gone once its window closes; the host hears the request was canceled.if self.requests.unbounded_send(request).is_err() {return Err(serialized_error("Canceled"));@@ -203,9 +205,9 @@ impl WorkbenchMainThread {/// `ask` for an answer that waits on the workbench's dialogs and host calls (a save's dialogs and format on save):/// the workbench's calls go out and their answers come in meanwhile; the host's own requests wait, as in `serve`.- fn ask_while_pumping(&mut self, session: &mut Session, proxy: &str, method: &str, args: Vec<Value>) -> Result<Value, Value> {+ fn ask_while_pumping(&mut self, session: &mut Session, proxy: &'static str, method: &str, args: Vec<Value>) -> Result<Value, Value> {let (reply, receiver) = channel();- let request = HostRequest { proxy: proxy.to_string(), method: method.to_string(), args, reply };+ let request = HostRequest { proxy, method: method.to_string(), args, reply };if self.requests.unbounded_send(request).is_err() {return Err(serialized_error("Canceled"));}diff --git a/native/crates/app/src/main_thread/tests.rs b/native/crates/app/src/main_thread/tests.rsnew file mode 100644index 00000000000..f9463f4f5b4--- /dev/null+++ b/native/crates/app/src/main_thread/tests.rs@@ -0,0 +1,62 @@+use std::io::{Read, Write};+use std::time::{Duration, Instant};++use exthost::extension_management::{UserExtensions, WindowExtensions};+use exthost::frame::{Frame, FrameReader, FrameType, encode_frame};+use exthost::proposed_api::ProposedApi;+use exthost::rpc::{self, Arg, Message, Reply};+use exthost::session::Session;+use exthost::{ExtensionHost, Inbox, proxy_id};+use serde_json::json;++use super::WorkbenchMainThread;++/// mainThreadLanguageFeatures.ts `$resolvePasteFileData`: the bytes of the data transfer's file, read on the session+/// thread once the workbench named the file.+#[test]+fn resolve_paste_file_data_answers_the_files_bytes() {+ let file = std::env::temp_dir().join(format!("resolve-paste-file-data-{}", std::process::id()));+ std::fs::write(&file, b"pasted bytes").unwrap();+ let (host, mut peer) = ExtensionHost::silent(Inbox::default());+ let mut session = Session::new(host);+ let (forward, mut forwarded) = futures::channel::mpsc::unbounded();+ session.forward(crate::main_thread_commands::path, move |request| drop(forward.unbounded_send(request.method)), std::sync::mpsc::channel().1);+ let (requests, mut asked) = futures::channel::mpsc::unbounded();+ let extensions = WindowExtensions { builtins: Vec::new(), user: UserExtensions::new(std::env::temp_dir(), "1.148.0"), running: Vec::new(), proposed_api: ProposedApi::unbuilt() };+ session.main_thread = Some(Box::new(WorkbenchMainThread { requests, messages: std::sync::mpsc::channel().1, waiting: Vec::new(), content_providers: Default::default(), extensions }));++ let args = vec![Arg::Json(json!(7)), Arg::Json(json!(1)), Arg::Json(json!("file-id"))];+ let request = Message::Request { req: 1, rpc_id: proxy_id("MainThreadLanguageFeatures"), method: "$resolvePasteFileData".into(), args, cancellable: false };+ let mut bytes = Vec::new();+ encode_frame(&Frame { kind: FrameType::Regular, id: 1, ack: 0, data: rpc::encode(&request) }, &mut bytes);+ peer.write_all(&bytes).unwrap();+ std::thread::spawn(move || drop(session.pump(Duration::from_secs(5))));++ let deadline = Instant::now() + Duration::from_secs(5);+ let asked = loop {+ if let Ok(request) = asked.try_recv() {+ break request;+ }+ assert!(Instant::now() < deadline, "the session thread never asked the workbench; forwarded: {:?}", forwarded.try_recv());+ std::thread::sleep(Duration::from_millis(10));+ };+ assert_eq!(asked.method, "$resolvePasteFileData");+ asked.reply.send(Ok(json!(file.to_str().unwrap()))).unwrap();++ peer.set_read_timeout(Some(Duration::from_secs(5))).unwrap();+ let mut reader = FrameReader::default();+ let mut chunk = vec![0; 64 * 1024];+ let reply = loop {+ if let Some(frame) = reader.next_frame().unwrap() {+ match rpc::decode(&frame.data) {+ Ok(Message::ReplyOk { value, .. }) if frame.kind == FrameType::Regular => break Ok(value),+ Ok(Message::ReplyErr { error, .. }) if frame.kind == FrameType::Regular => break Err(error),+ _ => continue,+ }+ }+ let read = peer.read(&mut chunk).expect("the session answers");+ reader.push(&chunk[..read]);+ };+ std::fs::remove_file(&file).unwrap();+ assert_eq!(reply, Ok(Reply::Buffer(b"pasted bytes".to_vec())));+}diff --git a/native/crates/app/src/main_thread_commands.rs b/native/crates/app/src/main_thread_commands.rsindex 11b04e8bd05..983a0ee2801 100644--- a/native/crates/app/src/main_thread_commands.rs+++ b/native/crates/app/src/main_thread_commands.rs@@ -1,204 +1,374 @@-//! The main-thread side of `vscode.commands`: workbench/api/browser/mainThreadCommands.ts.+//! The main-thread side of `vscode.commands`: workbench/api/browser/mainThreadCommands.ts, and `route`, the one place+//! that says who serves a MainThread* call the workbench answers and how.+use exthost::main_thread::{Path, serialized_error};use exthost::session::ForwardedRequest;use futures::channel::oneshot;-use gpui::{Context, Window};+use gpui::{ClipboardItem, Context, Window};use serde_json::{Value, json};use crate::commands::{Outcome, error_value};use crate::host_sync::Activation;use crate::workbench::Workbench;+use crate::workbench::host_requests::uri_parts;++type Handler = fn(&mut Workbench, ForwardedRequest, &mut Window, &mut Context<Workbench>) -> Outcome;++/// Who serves a host call; `None` leaves it to the session. `Session::forward` reads it on the session thread.+pub fn path(proxy: &str, method: &str) -> Option<Path> {+ route(proxy, method).map(|(path, _)| path)+}impl Workbench {- /// Answers one forwarded host request; the reply goes back to the host once the outcome is ready.+ /// Answers one host request, forwarded or blocking; the reply goes back to the host once the outcome is ready.pub fn handle_host_request(&mut self, request: ForwardedRequest, window: &mut Window, cx: &mut Context<Self>) -> Outcome {- let arg = |index: usize| request.args.get(index).cloned().unwrap_or(Value::Null);- match (request.proxy, request.method.as_str()) {- ("MainThreadQuickOpen", _) | ("", "$cancel") => self.handle_quick_open_request(request, window, cx),- ("MainThreadMessageService", "$showMessage") => self.show_extension_message(&request.args, window, cx),- ("MainThreadProgress", "$startProgress") => self.start_progress(&request.args, window, cx),- ("MainThreadProgress", "$progressReport") => self.report_progress(&request.args, window, cx),- ("MainThreadProgress", "$progressEnd") => self.end_progress(&request.args, window, cx),- ("MainThreadEditorInsets", method) => self.handle_editor_insets_request(method, &request.args, cx),- ("MainThreadWebviews" | "MainThreadWebviewPanels", method) => self.handle_webview_request(method, &request.args, window, cx),- ("MainThreadDecorations", method) => self.handle_decorations_request(method, &request.args, cx),- ("MainThreadTreeViews", method) => self.handle_tree_view_request(method, &request.args, window, cx),- ("MainThreadSCM", method) => self.handle_scm_request(method, &request.args, window, cx),- (proxy @ ("MainThreadNotebook" | "MainThreadNotebookDocuments" | "MainThreadNotebookEditors" | "MainThreadNotebookKernels" | "MainThreadNotebookRenderers"), method) => {- self.handle_notebook_request(proxy, method, &request.args, window, cx)- }- ("MainThreadQuickDiff", method) => self.handle_quick_diff_request(method, &request.args, cx),- ("MainThreadTimeline", method) => self.handle_timeline_request(method, &request.args, cx),- ("MainThreadComments", method) => self.handle_comments_request(method, &request.args, window, cx),- ("MainThreadGitHub", method) => self.handle_github_request(method, &request.args, cx),- ("MainThreadWebviewViews", method) => self.handle_webview_views_request(method, &request.args, window, cx),- ("MainThreadCustomEditors", method) => self.handle_custom_editors_request(method, &request.args, window, cx),- ("MainThreadStatusBar", "$setEntry") => self.set_extension_status_entry(&request.args, cx),- ("MainThreadLanguages", "$setLanguageStatus") => {- self.set_language_status(request.args[0].as_u64().unwrap_or_default(), request.args[1].clone(), cx);- Outcome::done()- }- ("MainThreadLanguages", "$removeLanguageStatus") => {- self.remove_language_status(request.args[0].as_u64().unwrap_or_default(), cx);- Outcome::done()- }- ("MainThreadStatusBar", "$disposeEntry") => self.dispose_extension_status_entry(&request.args, cx),- ("MainThreadOutputService" | "MainThreadLogger", _) => self.handle_output_request(request, window, cx),- ("MainThreadConsole" | "MainThreadErrors" | "MainThreadExtensionService", _) => self.handle_observed_request(&request, cx),- ("MainThreadDebugService", _) => self.handle_debug_request(request, window, cx),- ("MainThreadTesting", _) => self.handle_testing_request(request, window, cx),- ("MainThreadTerminalService" | "MainThreadTerminalShellIntegration", _) => self.handle_terminal_request(request, window, cx),- ("MainThreadTask", _) => self.handle_task_request(request, window, cx),- ("MainThreadCommands", "$registerCommand") => {- let id = arg(0).as_str().unwrap_or_default().to_owned();- let handler_id = id.clone();- let registration = self.commands.register(id.clone(), move |workbench, args, _, _| {- let mut call_args = vec![json!(handler_id)];- call_args.extend(args);- Outcome::Pending(workbench.host.call("ExtHostCommands", "$executeContributedCommand", call_args))- });- // DisposableMap.set disposes the registration it replaces.- if let Some(replaced) = self.extension_commands.insert(id.clone(), registration) {- self.commands.dispose(&id, replaced);- }- Outcome::done()- }- ("MainThreadCommands", "$unregisterCommand") => {- let id = arg(0).as_str().unwrap_or_default().to_owned();- if let Some(registration) = self.extension_commands.remove(&id) {- self.commands.dispose(&id, registration);- }- Outcome::done()- }- ("MainThreadCommands", "$fireCommandActivationEvent") => {- // Not awaited: drive-by activation for commands the host already knows.- drop(self.host.activate_by_event(&format!("onCommand:{}", arg(0).as_str().unwrap_or_default())));- Outcome::done()- }- ("MainThreadCommands", "$executeCommand") => {- let id = arg(0).as_str().unwrap_or_default().to_owned();- let args = arg(1).as_array().cloned().unwrap_or_default();- let retry = arg(2).as_bool().unwrap_or(false);- if retry && !args.is_empty() && self.commands.get(&id).is_none() {- return retry_after_activation(self.host.activate_by_event(&format!("onCommand:{id}")), cx);- }- self.execute_command(&id, args, window, cx)- }- ("MainThreadFileSystemEventService", "$confirmParticipantEdits") => {- let names = arg(1).as_array().cloned().unwrap_or_default();- self.confirm_participant_edits(arg(0).as_u64().unwrap_or_default(), &names, arg(2) == true, window, cx)- }- ("MainThreadDownloadService", "$download") => self.download_resource(&arg(0), &arg(1), cx),- ("MainThreadWorkspace", "$save") => self.save_resource(&arg(0), cx),- ("MainThreadWorkspace", "$saveAll") => self.save_all(arg(0) == true, cx),- ("MainThreadWorkspace", "$updateWorkspaceFolders") => self.api_update_workspace_folders(&request.args, window, cx),- ("MainThreadEditorTabs", "$moveTab") => self.move_tab(arg(0).as_str().unwrap_or_default(), arg(1).as_i64().unwrap_or(-1), arg(2).as_i64().unwrap_or(-1), cx),- ("MainThreadEditorTabs", "$closeTab") => self.close_tabs(arg(0).as_array().map_or(&[], Vec::as_slice), window, cx),- ("MainThreadEditorTabs", "$closeGroup") => self.close_groups(arg(0).as_array().map_or(&[], Vec::as_slice), window, cx),- ("MainThreadDialogs", "$showOpenDialog") => self.api_show_open_dialog(&arg(0), cx),- ("MainThreadDialogs", "$showSaveDialog") => self.api_show_save_dialog(&arg(0), cx),- ("MainThreadWindow", "$openUri") => self.api_open_uri(&request.args, window, cx),- ("MainThreadUrls", "$registerUriHandler") => {- // ExtensionIdentifier serializes as `{ value, _lower }`.- let extension = arg(1)["value"].as_str().unwrap_or_default().to_owned();- self.register_uri_handler(arg(0).as_u64().unwrap_or_default(), &extension, arg(2).as_str().unwrap_or_default());- Outcome::done()- }- ("MainThreadUrls", "$unregisterUriHandler") => {- self.unregister_uri_handler(arg(0).as_u64().unwrap_or_default());- Outcome::done()- }- ("MainThreadUrls", "$createAppUri") => Outcome::Ready(Ok(exthost::session::app_uri(&arg(0)))),- ("MainThreadUriOpeners", "$registerUriOpener") => self.register_uri_opener(&request.args),- ("MainThreadUriOpeners", "$unregisterUriOpener") => {- self.urls.openers.retain(|opener| Some(opener.id.as_str()) != arg(0).as_str());- Outcome::done()- }- ("MainThreadWorkspace", "$requestWorkspaceTrust") => self.request_workspace_trust(&arg(0), window, cx),- ("MainThreadWorkspace", "$isResourceTrusted") => self.is_resource_trusted(&arg(0)),- ("MainThreadWorkspace", "$resolveDecoding" | "$validateDetectedEncoding" | "$resolveEncoding") => Outcome::Ready(Ok(self.resolve_text_file_encoding(&request.method, &arg(0), &arg(1), &arg(2)))),- ("workbench", "debugMemory") => self.debug_memory_request(&request.args, cx),- ("workbench", "defaultSettingsContent") => Outcome::Ready(Ok(self.default_settings_content(&arg(0)))),- ("MainThreadWorkspace", "$loadCertificates") => self.load_certificates(cx),- ("MainThreadWorkspace", "$lookupAuthorization") => self.lookup_authorization(&arg(0), window, cx),- ("MainThreadWorkspace", "$resolveProxy") => self.resolve_proxy(&arg(0), cx),- ("MainThreadWorkspace", "$lookupKerberosAuthorization") => self.lookup_kerberos_authorization(&arg(0), cx),- ("workbench", "previewWorkspaceEdit") => self.preview_workspace_edit(&arg(0), window, cx),- ("workbench", "applyTextEdits") => Outcome::Ready(self.apply_workspace_text_edits(&arg(0), &arg(1), arg(2).as_u64().unwrap_or_else(files::operations::new_undo_group), None, cx)),- ("workbench", "applyCellEdits") => Outcome::Ready(self.apply_workspace_cell_edits(arg(0).as_array().map_or(&[], Vec::as_slice), arg(1).as_u64().unwrap_or_else(files::operations::new_undo_group), cx)),- ("workbench", "pushFileUndo") => {- self.push_file_undo(serde_json::from_value(arg(0)).expect("main_thread_bulk_edits.rs sends a FileUndo"));- Outcome::done()- }- ("workbench", "fileSystemProviderChanged") => {- let scheme = arg(0).as_str().unwrap_or_default().to_owned();- if arg(1) == true {- self.file_system_providers.insert(scheme);- } else {- self.file_system_providers.remove(&scheme);- }- Outcome::done()- }- ("workbench", "didRunFileOperation") => {- self.models_after_file_operation(arg(0).as_u64().unwrap_or_default(), &arg(1), cx);- Outcome::done()- }- ("MainThreadDiagnostics", "$changeMany") => {- self.change_many_markers(arg(0).as_str().unwrap_or_default(), &arg(1), cx);- Outcome::done()- }- ("MainThreadDiagnostics", "$clear") => {- self.clear_markers(arg(0).as_str().unwrap_or_default(), cx);- Outcome::done()- }- // codelensController.ts: `codeLensProvider.onDidChange` asks for the lenses again.- ("MainThreadLanguageFeatures", "$unregister") => {- let handle = arg(0).as_u64().unwrap_or_default();- if let Some(method) = self.language_features.unregister(handle) {- self.language_providers_changed(&method, cx);- }- if let Some(language) = self.languages.remove_extension_configuration(handle) {- self.language_configuration_changed(&language, cx);- }- Outcome::done()- }- ("MainThreadLanguageFeatures", "$setLanguageConfiguration") => {- let language = arg(1).as_str().unwrap_or_default().to_owned();- if self.languages.set_extension_configuration(arg(0).as_u64().unwrap_or_default(), &language, &arg(2)) {- self.language_configuration_changed(&language, cx);- }- Outcome::done()+ let Some((path, handle)) = route(request.proxy, &request.method) else { return unknown_method(self, request, window, cx) };+ if path == Path::Blocking {+ self.release_host_models(cx);+ }+ handle(self, request, window, cx)+ }+}++fn arg(request: &ForwardedRequest, index: usize) -> Value {+ request.args.get(index).cloned().unwrap_or(Value::Null)+}++/// rpcProtocol.ts `_doInvokeHandler`: a method the actor does not have.+fn unknown_method(_: &mut Workbench, request: ForwardedRequest, _: &mut Window, _: &mut Context<Workbench>) -> Outcome {+ Outcome::Ready(Err(serialized_error(&format!("Unknown method {} on actor {}", request.method, request.proxy))))+}++/// The upstream methods the port answers with `undefined` and nothing else; each is a gap of its ledger row.+fn not_ported(_: &mut Workbench, _: ForwardedRequest, _: &mut Window, _: &mut Context<Workbench>) -> Outcome {+ Outcome::done()+}++/// The path and the handler of every MainThread* call the workbench serves. A proxy's `_` arm forwards the rest of+/// its methods to `unknown_method`; a proxy without one leaves them to the session.+fn route(proxy: &str, method: &str) -> Option<(Path, Handler)> {+ use Path::{Blocking, Forwarded, Observed};+ let route: (Path, Handler) = match (proxy, method) {+ ("MainThreadQuickOpen", _) | ("", "$cancel") => (Forwarded, |workbench, request, window, cx| workbench.handle_quick_open_request(request, window, cx)),+ ("MainThreadMessageService", "$showMessage") => (Forwarded, |workbench, request, window, cx| workbench.show_extension_message(&request.args, window, cx)),+ ("MainThreadMessageService", _) => (Forwarded, unknown_method),+ ("MainThreadProgress", "$startProgress") => (Forwarded, |workbench, request, window, cx| workbench.start_progress(&request.args, window, cx)),+ ("MainThreadProgress", "$progressReport") => (Forwarded, |workbench, request, window, cx| workbench.report_progress(&request.args, window, cx)),+ ("MainThreadProgress", "$progressEnd") => (Forwarded, |workbench, request, window, cx| workbench.end_progress(&request.args, window, cx)),+ ("MainThreadProgress", _) => (Forwarded, unknown_method),+ ("MainThreadEditorInsets", _) => (Forwarded, |workbench, request, _, cx| workbench.handle_editor_insets_request(&request.method, &request.args, cx)),+ ("MainThreadWebviews" | "MainThreadWebviewPanels", _) => (Forwarded, |workbench, request, window, cx| workbench.handle_webview_request(&request.method, &request.args, window, cx)),+ ("MainThreadDecorations", _) => (Forwarded, |workbench, request, _, cx| workbench.handle_decorations_request(&request.method, &request.args, cx)),+ ("MainThreadTreeViews", _) => (Forwarded, |workbench, request, window, cx| workbench.handle_tree_view_request(&request.method, &request.args, window, cx)),+ ("MainThreadSCM", _) => (Forwarded, |workbench, request, window, cx| workbench.handle_scm_request(&request.method, &request.args, window, cx)),+ ("MainThreadNotebook" | "MainThreadNotebookDocuments" | "MainThreadNotebookEditors" | "MainThreadNotebookKernels" | "MainThreadNotebookRenderers", _) => {+ (Forwarded, |workbench, request, window, cx| workbench.handle_notebook_request(request.proxy, &request.method, &request.args, window, cx))+ }+ ("MainThreadQuickDiff", _) => (Forwarded, |workbench, request, _, cx| workbench.handle_quick_diff_request(&request.method, &request.args, cx)),+ ("MainThreadTimeline", _) => (Forwarded, |workbench, request, _, cx| workbench.handle_timeline_request(&request.method, &request.args, cx)),+ ("MainThreadComments", _) => (Forwarded, |workbench, request, window, cx| workbench.handle_comments_request(&request.method, &request.args, window, cx)),+ ("MainThreadGitHub", _) => (Forwarded, |workbench, request, _, cx| workbench.handle_github_request(&request.method, &request.args, cx)),+ ("MainThreadWebviewViews", _) => (Forwarded, |workbench, request, window, cx| workbench.handle_webview_views_request(&request.method, &request.args, window, cx)),+ ("MainThreadCustomEditors", _) => (Forwarded, |workbench, request, window, cx| workbench.handle_custom_editors_request(&request.method, &request.args, window, cx)),+ ("MainThreadStatusBar", "$setEntry") => (Forwarded, |workbench, request, _, cx| workbench.set_extension_status_entry(&request.args, cx)),+ ("MainThreadStatusBar", "$disposeEntry") => (Forwarded, |workbench, request, _, cx| workbench.dispose_extension_status_entry(&request.args, cx)),+ ("MainThreadStatusBar", _) => (Forwarded, unknown_method),+ ("MainThreadLanguages", "$setLanguageStatus") => (Forwarded, |workbench, request, _, cx| {+ workbench.set_language_status(arg(&request, 0).as_u64().unwrap_or_default(), arg(&request, 1), cx);+ Outcome::done()+ }),+ ("MainThreadLanguages", "$removeLanguageStatus") => (Forwarded, |workbench, request, _, cx| {+ workbench.remove_language_status(arg(&request, 0).as_u64().unwrap_or_default(), cx);+ Outcome::done()+ }),+ ("MainThreadLanguages", "$changeLanguage") => (Blocking, |workbench, request, _, cx| Outcome::Ready(workbench.change_host_language(&arg(&request, 0), &arg(&request, 1), cx))),+ ("MainThreadLanguages", "$tokensAtPosition") => {+ (Blocking, |workbench, request, _, _| Outcome::Ready(uri_parts(&arg(&request, 0)).map(|(scheme, path)| workbench.tokens_at_position(scheme, &path, &arg(&request, 1)))))+ }+ ("MainThreadLanguages", "$computeFullSyntaxHighlighting") => (Blocking, |workbench, request, _, _| {+ Outcome::Ready(Ok(workbench.full_syntax_highlighting(arg(&request, 0).as_str().unwrap_or_default(), arg(&request, 1).as_str().unwrap_or_default())))+ }),+ ("MainThreadOutputService" | "MainThreadLogger", _) => (Forwarded, |workbench, request, window, cx| workbench.handle_output_request(request, window, cx)),+ ("MainThreadConsole", "$logExtensionHostMessage") | ("MainThreadErrors", "$onUnexpectedError") | ("MainThreadExtensionService", "$onExtensionActivationError") => {+ (Observed, |workbench, request, _, cx| workbench.handle_observed_request(&request, cx))+ }+ ("MainThreadDebugService", _) => (Forwarded, |workbench, request, window, cx| workbench.handle_debug_request(request, window, cx)),+ ("MainThreadTesting", _) => (Forwarded, |workbench, request, window, cx| workbench.handle_testing_request(request, window, cx)),+ ("MainThreadTerminalService" | "MainThreadTerminalShellIntegration", _) => (Forwarded, |workbench, request, window, cx| workbench.handle_terminal_request(request, window, cx)),+ ("MainThreadTask", _) => (Forwarded, |workbench, request, window, cx| workbench.handle_task_request(request, window, cx)),+ ("MainThreadCommands", "$registerCommand") => (Forwarded, |workbench, request, _, _| {+ let id = arg(&request, 0).as_str().unwrap_or_default().to_owned();+ let handler_id = id.clone();+ let registration = workbench.commands.register(id.clone(), move |workbench, args, _, _| {+ let mut call_args = vec![json!(handler_id)];+ call_args.extend(args);+ Outcome::Pending(workbench.host.call("ExtHostCommands", "$executeContributedCommand", call_args))+ });+ // DisposableMap.set disposes the registration it replaces.+ if let Some(replaced) = workbench.extension_commands.insert(id.clone(), registration) {+ workbench.commands.dispose(&id, replaced);}- ("MainThreadLanguageFeatures", "$emitFoldingRangeEvent") => {- self.folding_range_event(&arg(0), cx);- Outcome::done()+ Outcome::done()+ }),+ ("MainThreadCommands", "$unregisterCommand") => (Forwarded, |workbench, request, _, _| {+ let id = arg(&request, 0).as_str().unwrap_or_default().to_owned();+ if let Some(registration) = workbench.extension_commands.remove(&id) {+ workbench.commands.dispose(&id, registration);}- ("MainThreadLanguageFeatures", "$emitDocumentSemanticTokensEvent" | "$emitDocumentRangeSemanticTokensEvent") => {- self.semantic_tokens_event(arg(0).as_u64().unwrap_or_default(), cx);- Outcome::done()+ Outcome::done()+ }),+ ("MainThreadCommands", "$fireCommandActivationEvent") => (Forwarded, |workbench, request, _, _| {+ // Not awaited: drive-by activation for commands the host already knows.+ drop(workbench.host.activate_by_event(&format!("onCommand:{}", arg(&request, 0).as_str().unwrap_or_default())));+ Outcome::done()+ }),+ ("MainThreadCommands", "$executeCommand") => (Forwarded, |workbench, request, window, cx| {+ let id = arg(&request, 0).as_str().unwrap_or_default().to_owned();+ let args = arg(&request, 1).as_array().cloned().unwrap_or_default();+ let retry = arg(&request, 2).as_bool().unwrap_or(false);+ if retry && !args.is_empty() && workbench.commands.get(&id).is_none() {+ return retry_after_activation(workbench.host.activate_by_event(&format!("onCommand:{id}")), cx);}- ("MainThreadLanguageFeatures", "$emitInlayHintsEvent") => {- self.inlay_hints_provider_changed(arg(0).as_u64().unwrap_or_default(), cx);- Outcome::done()+ workbench.execute_command(&id, args, window, cx)+ }),+ ("MainThreadCommands", "$getCommands") => (Forwarded, |workbench, _, _, _| Outcome::Ready(Ok(json!(workbench.commands.ids().collect::<Vec<_>>())))),+ ("MainThreadCommands", _) => (Forwarded, unknown_method),+ ("MainThreadFileSystemEventService", "$confirmParticipantEdits") => (Forwarded, |workbench, request, window, cx| {+ let names = arg(&request, 1).as_array().cloned().unwrap_or_default();+ workbench.confirm_participant_edits(arg(&request, 0).as_u64().unwrap_or_default(), &names, arg(&request, 2) == true, window, cx)+ }),+ ("MainThreadDownloadService", "$download") => (Forwarded, |workbench, request, _, cx| workbench.download_resource(&arg(&request, 0), &arg(&request, 1), cx)),+ ("MainThreadDownloadService", _) => (Forwarded, unknown_method),+ ("MainThreadWorkspace", "$save") => (Forwarded, |workbench, request, _, cx| workbench.save_resource(&arg(&request, 0), cx)),+ ("MainThreadWorkspace", "$saveAll") => (Forwarded, |workbench, request, _, cx| workbench.save_all(arg(&request, 0) == true, cx)),+ ("MainThreadWorkspace", "$updateWorkspaceFolders") => (Forwarded, |workbench, request, window, cx| workbench.api_update_workspace_folders(&request.args, window, cx)),+ ("MainThreadWorkspace", "$requestWorkspaceTrust") => (Forwarded, |workbench, request, window, cx| workbench.request_workspace_trust(&arg(&request, 0), window, cx)),+ ("MainThreadWorkspace", "$isResourceTrusted") => (Forwarded, |workbench, request, _, _| workbench.is_resource_trusted(&arg(&request, 0))),+ ("MainThreadWorkspace", "$resolveDecoding" | "$validateDetectedEncoding" | "$resolveEncoding") => {+ (Forwarded, |workbench, request, _, _| Outcome::Ready(Ok(workbench.resolve_text_file_encoding(&request.method, &arg(&request, 0), &arg(&request, 1), &arg(&request, 2)))))+ }+ ("MainThreadWorkspace", "$loadCertificates") => (Forwarded, |workbench, _, _, cx| workbench.load_certificates(cx)),+ ("MainThreadWorkspace", "$lookupAuthorization") => (Forwarded, |workbench, request, window, cx| workbench.lookup_authorization(&arg(&request, 0), window, cx)),+ ("MainThreadWorkspace", "$resolveProxy") => (Forwarded, |workbench, request, _, cx| workbench.resolve_proxy(&arg(&request, 0), cx)),+ ("MainThreadWorkspace", "$lookupKerberosAuthorization") => (Forwarded, |workbench, request, _, cx| workbench.lookup_kerberos_authorization(&arg(&request, 0), cx)),+ (+ "MainThreadWorkspace",+ "$checkExists"+ | "$getWorkspaceFolderLocations"+ | "$registerCanonicalUriProvider"+ | "$unregisterCanonicalUriProvider"+ | "$registerEditSessionIdentityProvider"+ | "$unregisterEditSessionIdentityProvider",+ ) => (Forwarded, not_ported),+ // The session's MainThreadWorkspace serves these when the window has a workspace; without one they answer null.+ ("MainThreadWorkspace", "$startFileSearch" | "$startTextSearch" | "$requestResourceTrust") => (Forwarded, |_, _, _, _| Outcome::done()),+ ("MainThreadWorkspace", _) => (Forwarded, unknown_method),+ ("MainThreadEditorTabs", "$moveTab") => (Forwarded, |workbench, request, _, cx| {+ workbench.move_tab(arg(&request, 0).as_str().unwrap_or_default(), arg(&request, 1).as_i64().unwrap_or(-1), arg(&request, 2).as_i64().unwrap_or(-1), cx)+ }),+ ("MainThreadEditorTabs", "$closeTab") => (Forwarded, |workbench, request, window, cx| workbench.close_tabs(arg(&request, 0).as_array().map_or(&[], Vec::as_slice), window, cx)),+ ("MainThreadEditorTabs", "$closeGroup") => (Forwarded, |workbench, request, window, cx| workbench.close_groups(arg(&request, 0).as_array().map_or(&[], Vec::as_slice), window, cx)),+ ("MainThreadEditorTabs", _) => (Forwarded, unknown_method),+ ("MainThreadDialogs", "$showOpenDialog") => (Forwarded, |workbench, request, _, cx| workbench.api_show_open_dialog(&arg(&request, 0), cx)),+ ("MainThreadDialogs", "$showSaveDialog") => (Forwarded, |workbench, request, _, cx| workbench.api_show_save_dialog(&arg(&request, 0), cx)),+ ("MainThreadDialogs", _) => (Forwarded, unknown_method),+ ("MainThreadWindow", "$openUri") => (Forwarded, |workbench, request, window, cx| workbench.api_open_uri(&request.args, window, cx)),+ ("MainThreadWindow", "$getInitialState") => (Blocking, |workbench, _, window, _| Outcome::Ready(Ok(workbench.window_initial_state(window)))),+ ("MainThreadUrls", "$registerUriHandler") => (Forwarded, |workbench, request, _, _| {+ // ExtensionIdentifier serializes as `{ value, _lower }`.+ let extension = arg(&request, 1)["value"].as_str().unwrap_or_default().to_owned();+ workbench.register_uri_handler(arg(&request, 0).as_u64().unwrap_or_default(), &extension, arg(&request, 2).as_str().unwrap_or_default());+ Outcome::done()+ }),+ ("MainThreadUrls", "$unregisterUriHandler") => (Forwarded, |workbench, request, _, _| {+ workbench.unregister_uri_handler(arg(&request, 0).as_u64().unwrap_or_default());+ Outcome::done()+ }),+ ("MainThreadUrls", "$createAppUri") => (Forwarded, |_, request, _, _| Outcome::Ready(Ok(exthost::session::app_uri(&arg(&request, 0))))),+ ("MainThreadUrls", _) => (Forwarded, unknown_method),+ ("MainThreadUriOpeners", "$registerUriOpener") => (Forwarded, |workbench, request, _, _| workbench.register_uri_opener(&request.args)),+ ("MainThreadUriOpeners", "$unregisterUriOpener") => (Forwarded, |workbench, request, _, _| {+ workbench.urls.openers.retain(|opener| Some(opener.id.as_str()) != arg(&request, 0).as_str());+ Outcome::done()+ }),+ ("MainThreadUriOpeners", _) => (Forwarded, unknown_method),+ ("MainThreadDiagnostics", "$changeMany") => (Forwarded, |workbench, request, _, cx| {+ workbench.change_many_markers(arg(&request, 0).as_str().unwrap_or_default(), &arg(&request, 1), cx);+ Outcome::done()+ }),+ ("MainThreadDiagnostics", "$clear") => (Forwarded, |workbench, request, _, cx| {+ workbench.clear_markers(arg(&request, 0).as_str().unwrap_or_default(), cx);+ Outcome::done()+ }),+ ("MainThreadDiagnostics", _) => (Forwarded, unknown_method),+ // codelensController.ts: `codeLensProvider.onDidChange` asks for the lenses again.+ ("MainThreadLanguageFeatures", "$unregister") => (Forwarded, |workbench, request, _, cx| {+ let handle = arg(&request, 0).as_u64().unwrap_or_default();+ if let Some(method) = workbench.language_features.unregister(handle) {+ workbench.language_providers_changed(&method, cx);}- ("MainThreadLanguageFeatures", "$emitCodeLensEvent") => {- self.code_lens_provider_changed(arg(0).as_u64().unwrap_or_default(), cx);- Outcome::done()+ if let Some(language) = workbench.languages.remove_extension_configuration(handle) {+ workbench.language_configuration_changed(&language, cx);}- ("MainThreadLanguageFeatures", "$emitInlineCompletionsChange") => {- self.inline_completions_provider_changed(arg(0).as_u64().unwrap_or_default(), arg(1), cx);- Outcome::done()+ Outcome::done()+ }),+ ("MainThreadLanguageFeatures", "$setLanguageConfiguration") => (Forwarded, |workbench, request, _, cx| {+ let language = arg(&request, 1).as_str().unwrap_or_default().to_owned();+ if workbench.languages.set_extension_configuration(arg(&request, 0).as_u64().unwrap_or_default(), &language, &arg(&request, 2)) {+ workbench.language_configuration_changed(&language, cx);}- ("MainThreadLanguageFeatures", method) if method.starts_with("$register") => {- self.language_features.register(method, request.args.clone());- self.language_providers_changed(method, cx);- Outcome::done()+ Outcome::done()+ }),+ ("MainThreadLanguageFeatures", "$emitFoldingRangeEvent") => (Forwarded, |workbench, request, _, cx| {+ workbench.folding_range_event(&arg(&request, 0), cx);+ Outcome::done()+ }),+ ("MainThreadLanguageFeatures", "$emitDocumentSemanticTokensEvent" | "$emitDocumentRangeSemanticTokensEvent") => (Forwarded, |workbench, request, _, cx| {+ workbench.semantic_tokens_event(arg(&request, 0).as_u64().unwrap_or_default(), cx);+ Outcome::done()+ }),+ ("MainThreadLanguageFeatures", "$emitInlayHintsEvent") => (Forwarded, |workbench, request, _, cx| {+ workbench.inlay_hints_provider_changed(arg(&request, 0).as_u64().unwrap_or_default(), cx);+ Outcome::done()+ }),+ ("MainThreadLanguageFeatures", "$emitCodeLensEvent") => (Forwarded, |workbench, request, _, cx| {+ workbench.code_lens_provider_changed(arg(&request, 0).as_u64().unwrap_or_default(), cx);+ Outcome::done()+ }),+ ("MainThreadLanguageFeatures", "$emitInlineCompletionsChange") => (Forwarded, |workbench, request, _, cx| {+ workbench.inline_completions_provider_changed(arg(&request, 0).as_u64().unwrap_or_default(), arg(&request, 1), cx);+ Outcome::done()+ }),+ ("MainThreadLanguageFeatures", "$emitInlineCompletionModelInfoChange" | "$emitInlineCompletionProviderOptionsChange" | "$emitInlineValuesEvent") => (Forwarded, not_ported),+ // `DataTransferFileCache.resolveFileData`: main_thread.rs reads the bytes of the file the workbench names.+ ("MainThreadLanguageFeatures", "$resolvePasteFileData" | "$resolveDocumentOnDropFileData") => {+ (Blocking, |workbench, request, _, _| Outcome::Ready(workbench.transfer_file_path(arg(&request, 1).as_u64().unwrap_or_default(), arg(&request, 2).as_str().unwrap_or_default())))+ }+ ("MainThreadLanguageFeatures", method) if method.starts_with("$register") => (Forwarded, |workbench, request, _, cx| {+ workbench.language_features.register(&request.method, request.args.clone());+ workbench.language_providers_changed(&request.method, cx);+ Outcome::done()+ }),+ ("MainThreadLanguageFeatures", _) => (Forwarded, unknown_method),+ ("MainThreadClipboard", "$readText") => (Blocking, |_, _, _, cx| Outcome::Ready(Ok(json!(cx.read_from_clipboard().and_then(|item| item.text()).unwrap_or_default())))),+ ("MainThreadClipboard", "$writeText") => (Blocking, |_, request, _, cx| {+ cx.write_to_clipboard(ClipboardItem::new_string(arg(&request, 0).as_str().unwrap_or_default().to_string()));+ Outcome::done()+ }),+ ("MainThreadPower", _) => (Blocking, |_, request, _, _| Outcome::Ready(crate::power::request(&request.method, &request.args).map_err(|error| serialized_error(&error)))),+ ("MainThreadDocuments", "$tryOpenDocument") => {+ (Blocking, |workbench, request, _, cx| Outcome::Ready(workbench.try_open_document(&arg(&request, 0), &arg(&request, 1), &arg(&request, 2), arg(&request, 3) == true, cx)))+ }+ ("MainThreadDocuments", "$tryCreateDocument") => (Blocking, |workbench, request, _, cx| Outcome::Ready(workbench.try_create_document(&arg(&request, 0), cx))),+ ("MainThreadDocuments", "$trySaveDocument") => (Blocking, |workbench, request, _, cx| match workbench.try_save_document(&arg(&request, 0), cx) {+ Ok(saved) => answer_saved(saved, cx),+ Err(error) => Outcome::Ready(Err(error)),+ }),+ ("MainThreadDocumentContentProviders", "$onVirtualDocumentChange") => {+ (Blocking, |workbench, request, _, cx| Outcome::Ready(workbench.virtual_document_change(&arg(&request, 0), &arg(&request, 1), cx)))+ }+ ("MainThreadDocumentDiff", "$computeDocumentDiff") => (Blocking, |workbench, request, _, _| {+ Outcome::Ready(Ok(workbench.compute_document_diff(&arg(&request, 0), &arg(&request, 1), arg(&request, 2) == true, arg(&request, 3).as_u64().unwrap_or(0), arg(&request, 4) == true)))+ }),+ ("MainThreadTextEditors", "$tryShowTextDocument") => (Blocking, |workbench, request, window, cx| Outcome::Ready(workbench.try_show_text_document(&arg(&request, 0), &arg(&request, 1), window, cx))),+ ("MainThreadTextEditors", "$registerTextEditorDecorationType") => (Blocking, |workbench, request, _, cx| {+ workbench.editors.decoration_types.insert(arg(&request, 1).as_str().unwrap_or_default().to_string(), arg(&request, 2));+ cx.notify();+ Outcome::done()+ }),+ ("MainThreadTextEditors", "$removeTextEditorDecorationType") => (Blocking, |workbench, request, _, cx| {+ workbench.remove_decoration_type(arg(&request, 0).as_str().unwrap_or_default(), cx);+ Outcome::done()+ }),+ ("MainThreadTextEditors", "$tryShowEditor") => (Blocking, |workbench, request, window, cx| Outcome::Ready(workbench.show_host_editor(&request.args, window, cx))),+ ("MainThreadTextEditors", "$tryHideEditor") => (Blocking, |workbench, request, window, cx| Outcome::Ready(workbench.hide_host_editor(&request.args, window, cx))),+ ("MainThreadTextEditors", "$getDiffInformation") => (Blocking, |workbench, request, _, _| Outcome::Ready(workbench.editor_line_changes(arg(&request, 0).as_str().unwrap_or_default()))),+ ("MainThreadTextEditors", "$trySetSelections") => {+ (Blocking, |workbench, request, _, cx| Outcome::Ready(workbench.with_host_editor(&request.args, |workbench| workbench.set_host_selections(&arg(&request, 1), cx))))+ }+ ("MainThreadTextEditors", "$tryRevealRange") => {+ (Blocking, |workbench, request, _, cx| Outcome::Ready(workbench.with_host_editor(&request.args, |workbench| workbench.reveal_host_range(&arg(&request, 1), &arg(&request, 2), cx))))+ }+ ("MainThreadTextEditors", "$trySetOptions") => {+ (Blocking, |workbench, request, _, cx| Outcome::Ready(workbench.with_host_editor(&request.args, |workbench| workbench.set_host_options(&arg(&request, 1), cx))))+ }+ ("MainThreadTextEditors", "$tryApplyEdits") => (Blocking, |workbench, request, _, cx| {+ Outcome::Ready(workbench.with_host_editor(&request.args, |workbench| workbench.apply_host_edits(&arg(&request, 1), &arg(&request, 2), &arg(&request, 3), cx)))+ }),+ ("MainThreadTextEditors", "$tryInsertSnippet") => (Blocking, |workbench, request, window, cx| {+ Outcome::Ready(workbench.with_host_editor(&request.args, |workbench| workbench.insert_host_snippet(&arg(&request, 1), &arg(&request, 2), &arg(&request, 3), &arg(&request, 4), window, cx)))+ }),+ ("MainThreadTextEditors", "$trySetDecorations") => (Blocking, |workbench, request, _, cx| {+ let key = arg(&request, 1).as_str().unwrap_or_default().to_owned();+ let decorations = crate::editor::decoration_types::decorations_from_options(&key, &arg(&request, 2));+ Outcome::Ready(workbench.with_host_editor(&request.args, |workbench| workbench.set_host_decorations(&key, decorations, cx)))+ }),+ ("MainThreadTextEditors", "$trySetDecorationsFast") => (Blocking, |workbench, request, _, cx| {+ let key = arg(&request, 1).as_str().unwrap_or_default().to_owned();+ let decorations = crate::editor::decoration_types::decorations_from_numbers(&key, &arg(&request, 2));+ Outcome::Ready(workbench.with_host_editor(&request.args, |workbench| workbench.set_host_decorations(&key, decorations, cx)))+ }),+ // The workbench's own calls: main_thread.rs blocks on the first four, the session asks the rest (`Session::ask_workbench`).+ ("workbench", "isDirty") => (Blocking, |workbench, request, _, _| {+ Outcome::Ready(uri_parts(&arg(&request, 0)).map(|(scheme, path)| json!(workbench.editors.model(scheme, &path).is_some_and(|model| model.is_dirty()))))+ }),+ ("workbench", "hasModel") => (Blocking, |workbench, request, _, _| Outcome::Ready(uri_parts(&arg(&request, 0)).map(|(scheme, path)| json!(workbench.editors.model(scheme, &path).is_some())))),+ ("workbench", "providerSaveText") => (Blocking, |workbench, request, _, cx| Outcome::Ready(workbench.provider_save_bytes(&arg(&request, 0), cx))),+ ("workbench", "providerSaved") => (Blocking, |workbench, request, _, cx| Outcome::Ready(workbench.provider_saved(&arg(&request, 0), cx))),+ ("workbench", "debugMemory") => (Forwarded, |workbench, request, _, cx| workbench.debug_memory_request(&request.args, cx)),+ ("workbench", "defaultSettingsContent") => (Forwarded, |workbench, request, _, _| Outcome::Ready(Ok(workbench.default_settings_content(&arg(&request, 0))))),+ ("workbench", "previewWorkspaceEdit") => (Forwarded, |workbench, request, window, cx| workbench.preview_workspace_edit(&arg(&request, 0), window, cx)),+ ("workbench", "applyTextEdits") => (Forwarded, |workbench, request, _, cx| {+ Outcome::Ready(workbench.apply_workspace_text_edits(&arg(&request, 0), &arg(&request, 1), arg(&request, 2).as_u64().unwrap_or_else(files::operations::new_undo_group), None, cx))+ }),+ ("workbench", "applyCellEdits") => (Forwarded, |workbench, request, _, cx| {+ Outcome::Ready(workbench.apply_workspace_cell_edits(arg(&request, 0).as_array().map_or(&[], Vec::as_slice), arg(&request, 1).as_u64().unwrap_or_else(files::operations::new_undo_group), cx))+ }),+ ("workbench", "pushFileUndo") => (Forwarded, |workbench, request, _, _| {+ workbench.push_file_undo(serde_json::from_value(arg(&request, 0)).expect("main_thread_bulk_edits.rs sends a FileUndo"));+ Outcome::done()+ }),+ ("workbench", "fileSystemProviderChanged") => (Forwarded, |workbench, request, _, _| {+ let scheme = arg(&request, 0).as_str().unwrap_or_default().to_owned();+ if arg(&request, 1) == true {+ workbench.file_system_providers.insert(scheme);+ } else {+ workbench.file_system_providers.remove(&scheme);}- ("MainThreadCommands", "$getCommands") => Outcome::Ready(Ok(json!(self.commands.ids().collect::<Vec<_>>()))),- _ => Outcome::done(),+ Outcome::done()+ }),+ ("workbench", "didRunFileOperation") => (Forwarded, |workbench, request, _, cx| {+ workbench.models_after_file_operation(arg(&request, 0).as_u64().unwrap_or_default(), &arg(&request, 1), cx);+ Outcome::done()+ }),+ _ => return None,+ };+ Some(route)+}++/// The host awaits a save through its dialogs and format on save; main_thread.rs pumps the session meanwhile.+fn answer_saved(saved: oneshot::Receiver<bool>, cx: &mut Context<Workbench>) -> Outcome {+ let (sender, receiver) = oneshot::channel();+ cx.background_executor()+ .spawn(async move {+ let _ = sender.send(Ok(json!(saved.await == Ok(true))));+ })+ .detach();+ Outcome::Pending(receiver)+}++#[cfg(test)]+impl Workbench {+ /// `handle_host_request` of a call answered at once, as the blocking ones are.+ pub(crate) fn answer_host_request(&mut self, proxy: &'static str, method: &str, args: &[Value], window: &mut Window, cx: &mut Context<Self>) -> Result<Value, Value> {+ match self.handle_host_request(ForwardedRequest { req: 1, proxy, method: method.to_owned(), args: args.to_vec() }, window, cx) {+ Outcome::Ready(result) => result,+ Outcome::Pending(_) => panic!("{proxy}.{method} answers later"),}}+}+impl Workbench {/// `LanguageConfigurationService.onDidChange`: the open models of the language read its configuration again.fn language_configuration_changed(&mut self, language: &str, cx: &mut Context<Self>) {for editor in self.editors.all_editors() {diff --git a/native/crates/app/src/main_thread_commands/tests.rs b/native/crates/app/src/main_thread_commands/tests.rsindex 8e42b60be7e..93bc6e5623e 100644--- a/native/crates/app/src/main_thread_commands/tests.rs+++ b/native/crates/app/src/main_thread_commands/tests.rs@@ -68,3 +68,14 @@ fn an_extension_language_configuration_applies_until_unregistered(cx: &mut TestAassert_eq!(enter(&workbench, cx), ["/**", ""]);let _ = std::fs::remove_dir_all(dir);}++/// rpcProtocol.ts `_doInvokeHandler`: a method the actor does not have is an error, not `undefined`.+#[gpui::test]+fn an_unknown_method_of_a_routed_proxy_answers_an_error(cx: &mut TestAppContext) {+ let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();+ let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();+ let (sender, _receiver) = std::sync::mpsc::channel();+ let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root, None, Languages::new(&[]), crate::default_settings(), HostSync::new(sender), cx));+ let answer = workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadStatusBar", "$bar", &[], window, cx));+ assert_eq!(answer, Err(exthost::main_thread::serialized_error("Unknown method $bar on actor MainThreadStatusBar")));+}diff --git a/native/crates/app/src/workbench.rs b/native/crates/app/src/workbench.rsindex 4787c35134a..ffe7a2807c1 100644--- a/native/crates/app/src/workbench.rs+++ b/native/crates/app/src/workbench.rs@@ -65,6 +65,7 @@ mod dialogs;mod lifecycle;mod editor_commands;mod editor_menus;+mod editor_options;mod side_by_side_editor;mod editor_type_picker;mod breadcrumbs;@@ -142,6 +143,7 @@ pub mod menubar;mod middle_scroll;mod drag_scrolling;mod minimap_view;+mod model_events;pub mod logs_actions;pub mod interactive;mod kernel_picker;@@ -371,6 +373,8 @@ pub struct Workbench {pub extension_host_debug: exthost::extension_development::ExtensionHostDebug,/// Extension hosts started in this window: the exit of one that a restart replaced is not the window's.pub extension_host_starts: u32,+ /// How `open_window` runs this window's hosts; `None` in a workbench a test builds, whose restart starts no host.+ pub(crate) host_launch: Option<crate::extension_host_start::HostLaunch>,/// extensionsProposedApi.ts of this window, for the extensions a host restart scans again.pub proposed_api: exthost::proposed_api::ProposedApi,proxy_auth: proxy_auth::ProxyAuth,@@ -563,11 +567,11 @@ pub struct Workbench {/// menubarControl.ts `menuUpdater`, pending.menubar_update: Option<Task<()>>,/// StorageScope.PROFILE of the current profile, shared with the extension host's MainThreadStorage.- profile_storage: Arc<Mutex<Storage>>,+ pub(crate) profile_storage: Arc<Mutex<Storage>>,/// StorageScope.APPLICATION: the default profile's storage, the same as `profile_storage` in that profile.application_storage: Arc<Mutex<Storage>>,/// StorageScope.WORKSPACE of the opened folder, shared with the extension host's MainThreadStorage.- workspace_storage: Arc<Mutex<Storage>>,+ pub(crate) workspace_storage: Arc<Mutex<Storage>>,pub(crate) user_data_profiles: user_data_profile::UserDataProfiles,icon_select: icon_select_box::IconSelect,part_grid: part_grid::PartGrid,@@ -790,6 +794,7 @@ impl Workbench {development: None,extension_host_debug: Default::default(),extension_host_starts: 0,+ host_launch: None,proposed_api: exthost::proposed_api::ProposedApi::unbuilt(),proxy_auth: proxy_auth::ProxyAuth::default(),cli_profile: Default::default(),@@ -1064,7 +1069,7 @@ impl Workbench {workbench.register_color_detector();workbench.register_standalone_color_picker();workbench.register_inline_completions();- workbench.register_language_detection(cx);+ workbench.register_language_detection();workbench.register_rename();workbench.register_links();workbench.register_linked_editing();diff --git a/native/crates/app/src/workbench/accessibility.rs b/native/crates/app/src/workbench/accessibility.rsindex 4664a314d7d..43639bcd4fc 100644--- a/native/crates/app/src/workbench/accessibility.rs+++ b/native/crates/app/src/workbench/accessibility.rs@@ -23,6 +23,7 @@ use crate::main_thread_status_bar::StatusEntry;use crate::markers::{ERROR, ReadOptions, WARNING};use crate::notifications::Severity;use crate::quick_input::{Button, Event, Item, Kind, QuickInput};+use crate::workbench::editor_options::{ACCESSIBILITY_PAGE_SIZE, ACCESSIBILITY_SUPPORT, ARIA_LABEL};const SCREEN_READER_STATUS_ID: &str = "status.editor.screenReaderMode";/// Signals played as a user gesture by default (`userGestureSignals` of commands.ts).@@ -125,7 +126,7 @@ impl Workbench {/// `isScreenReaderOptimized`: `editor.accessibilitySupport` on, or auto with a screen reader attached.pub(crate) fn is_screen_reader_optimized(&self) -> bool {- match self.setting("editor.accessibilitySupport").as_str() {+ match self.setting(ACCESSIBILITY_SUPPORT.key).as_str() {Some("on") => true,Some("off") => false,_ => self.accessibility.screen_reader_attached,@@ -171,7 +172,7 @@ impl Workbench {/// accessibilityStatus.ts `onScreenReaderModeChange`: the prompt once per window with `auto`, and the status entry.fn screen_reader_mode_changed(&mut self, cx: &mut Context<Self>) {let optimized = self.is_screen_reader_optimized();- if optimized && self.setting("editor.accessibilitySupport") == json!("auto") && !self.accessibility.prompted {+ if optimized && self.setting(ACCESSIBILITY_SUPPORT.key) == json!("auto") && !self.accessibility.prompted {self.accessibility.prompted = true;self.show_screen_reader_notification(cx);}@@ -524,15 +525,15 @@ impl Workbench {/// selection as text runs with the selection on them (`SimplePagedScreenReaderStrategy`), computed only while a/// screen reader reads the tree.pub(super) fn editor_accessibility<E: StatefulInteractiveElement>(&self, element: E, editor: &OpenEditor, window: &Window) -> E {- let label = match self.setting("editor.accessibilitySupport").as_str() {- Some("off") => "The editor is not accessible at this time. To enable screen reader optimized mode, use ⇧⌥F1".to_owned(),- _ => self.setting("editor.ariaLabel").as_str().unwrap_or("Editor content").to_owned(),+ let label = match self.editor_option(editor, &ACCESSIBILITY_SUPPORT) {+ "off" => "The editor is not accessible at this time. To enable screen reader optimized mode, use ⇧⌥F1".to_owned(),+ _ => self.editor_option(editor, &ARIA_LABEL),};let element = element.role(Role::MultilineTextInput).aria_label(label);if !window.is_a11y_active() {return element;}- let page_size = self.setting("editor.accessibilityPageSize").as_u64().unwrap_or(500).max(1) as usize;+ let page_size = self.editor_option(editor, &ACCESSIBILITY_PAGE_SIZE);let page = screen_reader_page(&editor.document().lines, editor.selections[0].anchor, editor.selections[0].head, page_size);element.a11y_synthetic_children(move |builder| page.build(builder))}diff --git a/native/crates/app/src/workbench/accessible_view.rs b/native/crates/app/src/workbench/accessible_view.rsindex 75e13610516..855b3cf4272 100644--- a/native/crates/app/src/workbench/accessible_view.rs+++ b/native/crates/app/src/workbench/accessible_view.rs@@ -16,6 +16,7 @@ use crate::main_thread_quick_open::Owner;use crate::markdown::{MarkdownString, parse, plain_text};use crate::notifications::{Action, Severity};use crate::quick_input::{Entry, Event, Item, Kind, QuickInput};+use crate::workbench::editor_options::{ACCESSIBILITY_PAGE_SIZE, STICKY_SCROLL_ENABLED};/// accessibleView.ts `DIMENSIONS`.const MAX_WIDTH: f32 = 900.;@@ -375,7 +376,7 @@ impl Workbench {"Accept suggestion<keybinding:acceptSelectedSuggestion> to accept the currently selected suggestion.","Toggle focus between the suggest widget and the editor<keybinding:focusSuggestion> and toggle details focus with<keybinding:toggleSuggestionFocus> to learn more about the suggestion.",]);- if self.setting("editor.stickyScroll.enabled") == json!(true) {+ if self.global_editor_option(&STICKY_SCROLL_ENABLED) {content.push("Focus Sticky Scroll<keybinding:editor.action.focusStickyDebugConsole> to focus the currently nested scopes.");}content.push(match self.tab_focus_mode() {@@ -963,7 +964,7 @@ impl Workbench {}text = text.child(row);}- let page = window.is_a11y_active().then(|| super::accessibility::screen_reader_page(&shown.lines, shown.selection.anchor, shown.selection.head, self.setting("editor.accessibilityPageSize").as_u64().unwrap_or(500).max(1) as usize));+ let page = window.is_a11y_active().then(|| super::accessibility::screen_reader_page(&shown.lines, shown.selection.anchor, shown.selection.head, self.global_editor_option(&ACCESSIBILITY_PAGE_SIZE)));let body = div().id("accessible-view-editor").track_focus(&self.accessibility.view.focus)diff --git a/native/crates/app/src/workbench/breakpoint_widget.rs b/native/crates/app/src/workbench/breakpoint_widget.rsindex b036a63e86a..c4e6164a771 100644--- a/native/crates/app/src/workbench/breakpoint_widget.rs+++ b/native/crates/app/src/workbench/breakpoint_widget.rs@@ -366,8 +366,8 @@ impl Workbench {/// nothing but whitespace before it (`.start-of-line` is absolute).pub(super) fn sync_stack_frame_columns(&mut self) {let char_width = self.editors.viewport.char_width;- let wanted: Vec<Vec<InjectedText>> = self.editors.editors.iter().chain(&self.editors.models).map(|editor| self.stack_frame_columns(editor, char_width)).collect();- for (editor, injections) in self.editors.editors.iter_mut().chain(&mut self.editors.models).zip(wanted) {+ let wanted: Vec<Vec<InjectedText>> = self.editors.all_editors().map(|editor| self.stack_frame_columns(editor, char_width)).collect();+ for (editor, injections) in self.editors.all_editors_mut().zip(wanted) {let current = editor.injected_text.iter().filter(|injection| injection.owner == InjectionOwner::StackFrameColumn);if !current.eq(injections.iter()) {editor.set_injected_text(InjectionOwner::StackFrameColumn, injections);@@ -500,7 +500,7 @@ impl Workbench {pub(crate) fn close_breakpoint_widget(&mut self, window: &mut Window, cx: &mut Context<Self>) {let Some(widget) = self.breakpoint_widget.take() else { return };- if let Some(editor) = self.editors.editors.iter_mut().find(|editor| editor.document().uri_string() == widget.model_uri) {+ if let Some(editor) = self.editors.all_tabs_mut().find(|editor| editor.document().uri_string() == widget.model_uri) {editor.remove_view_zone(widget.zone_id);}window.focus(&self.editor_focus, cx);diff --git a/native/crates/app/src/workbench/bulk_text_edits.rs b/native/crates/app/src/workbench/bulk_text_edits.rsindex dff07ead7ed..28fa9b167ad 100644--- a/native/crates/app/src/workbench/bulk_text_edits.rs+++ b/native/crates/app/src/workbench/bulk_text_edits.rs@@ -11,7 +11,7 @@ use super::Workbench;use super::format::more_minimal_edits;use super::host_requests::{range, snippet_edits, uri_parts};use crate::editor::edit_stack::{MultiModelEditStackElement, SingleModelEditStackElement, UndoElement};-use crate::editor::{ContentChanged, EditReason, Position, SharedModel, TextDocument, expand_snippet, uri_string};+use crate::editor::{EditReason, Position, SharedModel, TextDocument, expand_snippet, uri_string};use crate::local_history;impl Workbench {@@ -119,12 +119,12 @@ impl Workbench {model.execute_edits(edits, None, EditReason::ApplyEdits)};if let Some(change) = change {- self.send_model_edit(scheme, path, &change, cx);+ self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);}if let Some(sequence) = eol&& let Some(change) = self.editors.model_mut(scheme, path).expect("resolved above").push_eol(sequence){- self.send_model_edit(scheme, path, &change, cx);+ self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);}}if let Some(element) = undo_redo.borrow_mut().last_element_mut(&first_key) {@@ -307,21 +307,10 @@ impl Workbench {model.push_undo_stop();model.mark_saved();if let Some(change) = change {- self.send_model_edit(scheme, path, &change, cx);+ self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);}true}-- /// The change of a model edited without the keyboard: with the cursor when the active editor shows it.- pub(super) fn send_model_edit(&mut self, scheme: &str, path: &Path, change: &ContentChanged, cx: &mut Context<Self>) {- match self.editors.active_index().filter(|&index| self.editors.editors[index].document().is(scheme, path)) {- Some(index) => self.host.send_content_change(&self.editors, self.editors.tab_model(index), change),- None => self.host.send_model_change(&self.editors, self.editors.model(scheme, path).expect("just edited"), change),- }- self.search_model_changed(scheme, path);- self.language_detection.content_changed(scheme, path);- self.semantic_tokens_content_changed(&uri_string(scheme, path), cx);- }}pub(super) fn document_end(lines: &[String]) -> Position {diff --git a/native/crates/app/src/workbench/bulk_undo.rs b/native/crates/app/src/workbench/bulk_undo.rsindex 057ad619cf1..eb105baf447 100644--- a/native/crates/app/src/workbench/bulk_undo.rs+++ b/native/crates/app/src/workbench/bulk_undo.rs@@ -90,7 +90,7 @@ impl Workbench {}let model = self.editors.model_mut(&element.scheme, &element.path).expect("checked above");if let Some(change) = model.apply_stack_element(element, direction) {- self.send_model_edit(&element.scheme, &element.path, &change, cx);+ self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);}}drop(elements);diff --git a/native/crates/app/src/workbench/code_actions.rs b/native/crates/app/src/workbench/code_actions.rsindex 0d2feec0a20..5935babd2db 100644--- a/native/crates/app/src/workbench/code_actions.rs+++ b/native/crates/app/src/workbench/code_actions.rs@@ -208,7 +208,7 @@ impl Workbench {let settings_renderer = self.has_unsupported_settings_code_actions(editor);context.insert("editorHasCodeActionsProvider".into(), json!(!providers.is_empty() || snippets || settings_renderer));if self.active_editor_readonly().is_none() {- let mut kinds: Vec<&str> = providers.iter().flat_map(|registration| provided_kinds(®istration.args)).collect();+ let mut kinds: Vec<&str> = providers.iter().flat_map(|registration| provided_kinds(®istration.metadata)).collect();// `FileTemplateCodeActionProvider.providedCodeActionKinds`.if snippets {kinds.push("refactor.surround");@@ -247,7 +247,7 @@ impl Workbench {/// `CodeActionsContribution.updateConfigurationSchema` on a provider change.fn code_actions_on_save_kinds_changed(&mut self) {let registrations: Vec<_> = self.language_features.all(REGISTER).collect();- let mut kinds: Vec<&str> = registrations.iter().flat_map(|registration| provided_kinds(®istration.args)).collect();+ let mut kinds: Vec<&str> = registrations.iter().flat_map(|registration| provided_kinds(®istration.metadata)).collect();kinds.dedup();let source_kinds: Vec<&str> = kinds.iter().copied().filter(|kind| contains(SOURCE, kind)).collect();let registry = &mut self.settings.lock().unwrap().registry;@@ -378,13 +378,13 @@ impl Workbench {let context = json!({ "only": trigger.filter.include, "trigger": trigger.kind });let mut calls = Vec::new();for registration in self.language_features.ordered(REGISTER, &candidate) {- let kinds = provided_kinds(®istration.args);- if registration.args.get(2).is_some_and(|metadata| metadata["providedKinds"].is_array()) && !kinds.iter().any(|kind| may_include_kind(&provider_filter, kind)) {+ let kinds = provided_kinds(®istration.metadata);+ if registration.metadata["providedKinds"].is_array() && !kinds.iter().any(|kind| may_include_kind(&provider_filter, kind)) {continue;}let args = vec![json!(registration.handle), uri.clone(), range.clone(), context.clone()];let call = self.host.call_cancellable("ExtHostLanguageFeatures", "$provideCodeActions", args);- let documentation = registration.args.get(2).map(|metadata| metadata["documentation"].clone()).unwrap_or_default();+ let documentation = registration.metadata["documentation"].clone();calls.push((registration.handle, call, documentation));}// The settings renderer's provider matches the file's path, so it scores above the snippet providers' `*`,@@ -452,7 +452,7 @@ impl Workbench {/// Preview with `preview` or an edit that needs confirmation), then its command runs unless the edit was not/// applied; a failed command is an error notification. With `retrigger` an automatic request follows.pub(super) fn apply_code_action(&mut self, item: CodeActionItem, set: Rc<CodeActionSet>, retrigger: bool, preview: bool, window: AnyWindowHandle, cx: &mut Context<Self>) -> Task<()> {- let supports_resolve = self.language_features.registration(item.handle).is_some_and(|registration| registration.args.get(5) == Some(&json!(true)));+ let supports_resolve = self.language_features.registration(item.handle).is_some_and(|registration| registration.supports_resolve);let resolve = match supports_resolve && item.action["edit"].is_null() && item.action["cacheId"].is_array() {true => Some(self.host.call("ExtHostLanguageFeatures", "$resolveCodeAction", vec![json!(item.handle), item.action["cacheId"].clone()])),false => None,@@ -529,7 +529,7 @@ impl Workbench {let resolving = workbench.update(cx, |workbench, _| {let mut resolving = Vec::new();for (index, item) in set.valid.iter().enumerate().take(resolve_count) {- let supports_resolve = workbench.language_features.registration(item.handle).is_some_and(|registration| registration.args.get(5) == Some(&json!(true)));+ let supports_resolve = workbench.language_features.registration(item.handle).is_some_and(|registration| registration.supports_resolve);if supports_resolve && item.action["edit"].is_null() {resolving.push((index, workbench.host.call("ExtHostLanguageFeatures", "$resolveCodeAction", vec![json!(item.handle), item.action["cacheId"].clone()])));}@@ -1011,8 +1011,8 @@ fn intersects(a: &str, b: &str) -> bool {contains(a, b) || contains(b, a)}-fn provided_kinds(args: &[Value]) -> Vec<&str> {- args.get(2).and_then(|metadata| metadata["providedKinds"].as_array()).into_iter().flatten().filter_map(Value::as_str).collect()+fn provided_kinds(metadata: &Value) -> Vec<&str> {+ metadata["providedKinds"].as_array().into_iter().flatten().filter_map(Value::as_str).collect()}/// `excludesAction`: an exclude that contains the kind, unless the include is more specific.diff --git a/native/crates/app/src/workbench/code_actions/on_save.rs b/native/crates/app/src/workbench/code_actions/on_save.rsindex 93f36b72e3c..a35a7088830 100644--- a/native/crates/app/src/workbench/code_actions/on_save.rs+++ b/native/crates/app/src/workbench/code_actions/on_save.rs@@ -8,6 +8,7 @@ use serde_json::{Value, json};use super::*;use crate::workbench::auto_save::SaveReason;+use crate::workbench::editor_options::CODE_ACTIONS_TRIGGER_ON_FOCUS_CHANGE;use crate::workbench::text_input::SavePhase;const SOURCE_FIX_ALL: &str = "source.fixAll";@@ -30,7 +31,7 @@ impl Workbench {/// `editor.codeActions.triggerOnFocusChange` and `files.autoSave` `afterDelay`, the active editor's `always`/// source kinds run, without exclusions.pub(in crate::workbench) fn trigger_code_actions_on_focus_change(&mut self, cx: &mut Context<Self>) {- if self.setting("editor.codeActions.triggerOnFocusChange") != true || self.setting("files.autoSave") != "afterDelay" {+ if !self.global_editor_option(&CODE_ACTIONS_TRIGGER_ON_FOCUS_CHANGE) || self.setting("files.autoSave") != "afterDelay" {return;}let Some(window) = cx.active_window().or_else(|| cx.windows().first().copied()) else { return };diff --git a/native/crates/app/src/workbench/code_actions/tests.rs b/native/crates/app/src/workbench/code_actions/tests.rsindex f8f8aded4a8..66d5355f409 100644--- a/native/crates/app/src/workbench/code_actions/tests.rs+++ b/native/crates/app/src/workbench/code_actions/tests.rs@@ -332,6 +332,28 @@ fn each_problems_marker_keeps_its_quick_fixes(cx: &mut TestAppContext) {workbench.read_with(cx, |workbench, _| assert_eq!(workbench.problems_quick_fix_icon(&first), None, "a changed resource's markers are new ones"));}+/// markersTreeViewer.ts `MarkerViewModel` asks `modelService.getModel(resource)`, whichever group shows it: a Problems+/// row of a file open only in another group gets its fixes at once.+#[gpui::test]+fn a_problems_marker_of_a_file_in_another_group_gets_its_quick_fixes(cx: &mut TestAppContext) {+ let (workbench, cx, receiver) = open("let x = y\n", cx);+ answer(&receiver, json!([]), cx);+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ answer(&receiver, json!([]), cx);+ let uri = json!({ "scheme": "file", "path": test_dir().join("a.ts").to_string_lossy() });+ let marker = json!({ "severity": 8, "message": "bad x", "startLineNumber": 1, "startColumn": 5, "endLineNumber": 1, "endColumn": 6 });+ let marker = workbench.update_in(cx, |workbench, _, cx| {+ workbench.change_many_markers("test", &json!([[uri, [marker]]]), cx);+ let marker = workbench.diagnostics.service.read(crate::markers::ReadOptions::default()).remove(0);+ workbench.problems_marker_hovered(&marker, cx);+ marker+ });+ cx.executor().advance_clock(std::time::Duration::from_millis(300));+ cx.run_until_parked();+ answer(&receiver, json!([edit_action("Fix", "f")]), cx);+ workbench.read_with(cx, |workbench, _| assert_eq!(workbench.problems_quick_fix_icon(&marker), Some("lightbulb")));+}+#[gpui::test]fn a_kind_command_applies_a_single_action_and_reports_none(cx: &mut TestAppContext) {let (workbench, cx, receiver) = open("let x\n", cx);diff --git a/native/crates/app/src/workbench/code_lens.rs b/native/crates/app/src/workbench/code_lens.rsindex 05d192cb169..5f7efc630b5 100644--- a/native/crates/app/src/workbench/code_lens.rs+++ b/native/crates/app/src/workbench/code_lens.rs@@ -228,7 +228,7 @@ impl Workbench {let uri = editor.document().uri();let language = editor.document().language_id.clone();let candidate = Candidate { uri: &uri, language: &language };- if self.language_features.ordered(REGISTER, &candidate).iter().any(|registration| registration.args.get(2) == Some(&json!(event_handle))) {+ if self.language_features.ordered(REGISTER, &candidate).iter().any(|registration| registration.event_handle == Some(event_handle)) {self.schedule_code_lenses(cx);}}diff --git a/native/crates/app/src/workbench/color_picker.rs b/native/crates/app/src/workbench/color_picker.rsindex 8edcf156f2c..ff343f7fcf9 100644--- a/native/crates/app/src/workbench/color_picker.rs+++ b/native/crates/app/src/workbench/color_picker.rs@@ -12,6 +12,8 @@ use serde_json::{Value, json};use super::Workbench;use super::color_detector::{ColorData, range_dto};+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::default_document_colors::default_color_presentations;use crate::editor::{EditReason, OpenEditor, Position, char_column, text_between};@@ -296,7 +298,7 @@ impl Workbench {picker.end = new_end;picker.updated_by_picker = change.is_some();}- self.editor_edited(change, true, "api", cx);+ self.model_content_changed(change, Cursor { moved: true, source: "api", reveal: Reveal::All }, cx);}/// The picker's `onDidChangeModelContent`: an edit not made by the picker hides the hover.diff --git a/native/crates/app/src/workbench/configuration.rs b/native/crates/app/src/workbench/configuration.rsindex 032ff3ec0df..f0971522af8 100644--- a/native/crates/app/src/workbench/configuration.rs+++ b/native/crates/app/src/workbench/configuration.rs@@ -251,15 +251,13 @@ impl Workbench {pub(super) fn model_creation_options(&self) -> Vec<CreationOptions> {let settings = self.settings.lock().unwrap();- let models = self.editors.editors.iter().chain(&self.editors.models);- models.map(|model| creation_options(&settings.configuration, &model.document().path, &model.document().language_id)).collect()+ self.editors.all_editors().map(|model| creation_options(&settings.configuration, &model.document().path, &model.document().language_id)).collect()}/// modelService.ts `_updateModelOptions` for each model whose creation options changed.fn update_model_options(&mut self, before: Vec<CreationOptions>) {let after = self.model_creation_options();- let models = self.editors.editors.iter_mut().chain(&mut self.editors.models);- for ((model, old), new) in models.zip(before).zip(after) {+ for ((model, old), new) in self.editors.all_editors_mut().zip(before).zip(after) {if old == new {continue;}diff --git a/native/crates/app/src/workbench/content_hover.rs b/native/crates/app/src/workbench/content_hover.rsindex b5a816330e7..0a0265d5514 100644--- a/native/crates/app/src/workbench/content_hover.rs+++ b/native/crates/app/src/workbench/content_hover.rs@@ -17,6 +17,7 @@ use crate::editor::unicode_highlighter::{CodePointHighlighter, HighlightReason,use crate::editor::{OpenEditor, Position, utf16_column, column_x};use crate::language_features::Candidate;use crate::markers::{ERROR, INFO, Marker, WARNING};+use crate::workbench::editor_options::MULTI_CURSOR_MODIFIER;#[derive(Default)]pub(super) struct ContentHover {@@ -283,7 +284,7 @@ impl Workbench {"on" => true,"off" => false,// isTriggerModifierPressed: the modifier `editor.multiCursorModifier` leaves free.- _ => match self.setting("editor.multiCursorModifier") == "alt" {+ _ => match self.global_editor_option(&MULTI_CURSOR_MODIFIER) == "alt" {true => mouse.modifiers.platform,false => mouse.modifiers.alt,},diff --git a/native/crates/app/src/workbench/coverage_decorations.rs b/native/crates/app/src/workbench/coverage_decorations.rsindex 546be7b83fa..ab33a7a8d6c 100644--- a/native/crates/app/src/workbench/coverage_decorations.rs+++ b/native/crates/app/src/workbench/coverage_decorations.rs@@ -21,14 +21,14 @@ impl Workbench {pub(super) fn sync_inline_coverage(&mut self, cx: &mut Context<Self>) {let mut inline = std::collections::HashMap::new();let mut wanted = Vec::new();- for editor in self.editors.editors.iter().chain(&self.editors.models) {+ for editor in self.editors.all_editors() {let document = editor.document();let ranges = self.file_coverage(&document.uri()).and_then(|file| Some(inline_coverage(self.coverage_details(&file, cx)?, &document.lines))).unwrap_or_default();wanted.push(if self.shows_inline_coverage(editor.model_id) { self.coverage_injections(&ranges) } else { Vec::new() });inline.insert(editor.model_id, ranges);}self.testing.coverage.inline = inline;- for (editor, injections) in self.editors.editors.iter_mut().chain(&mut self.editors.models).zip(wanted) {+ for (editor, injections) in self.editors.all_editors_mut().zip(wanted) {let current = editor.injected_text.iter().filter(|injection| injection.owner == InjectionOwner::Coverage);if !current.eq(injections.iter()) {editor.set_injected_text(InjectionOwner::Coverage, injections);@@ -41,9 +41,9 @@ impl Workbench {/// line of each editor whose file has coverage makes room for the toolbar.fn sync_coverage_toolbar_zones(&mut self) {let enabled = self.setting("testing.coverageToolbarEnabled") != false;- let shown: Vec<bool> = self.editors.editors.iter().map(|editor| enabled && self.file_coverage(&editor.document().uri()).is_some()).collect();+ let shown: Vec<bool> = self.editors.all_tabs().map(|editor| enabled && self.file_coverage(&editor.document().uri()).is_some()).collect();let zones = &mut self.testing.coverage.toolbar_zones;- for (editor, shown) in self.editors.editors.iter_mut().zip(shown) {+ for (editor, shown) in self.editors.all_tabs_mut().zip(shown) {match (zones.get(&editor.model_id).copied(), shown) {(None, true) => drop(zones.insert(editor.model_id, editor.add_view_zone(None, 30.))),(Some(zone), false) => {diff --git a/native/crates/app/src/workbench/custom_editors.rs b/native/crates/app/src/workbench/custom_editors.rsindex 8520937111f..f0aec687c7f 100644--- a/native/crates/app/src/workbench/custom_editors.rs+++ b/native/crates/app/src/workbench/custom_editors.rs@@ -576,7 +576,8 @@ impl Workbench {/// openWithEditorPicker.ts `doPick`: the text editor, then the resource's editors by rank, and the entry that/// picks a new default; `configure_default` is the picker that entry opens./// fileCommands.ts `OPEN_WITH_EXPLORER_COMMAND_ID`: the picker marks the editor the resource shows in as active- /// (`findEditors(resource).at(0)`), and the pick opens the resource with that editor.+ /// in the active group (openWithEditorPicker.ts `activeGroup.findEditors(resource).at(0)`), and the pick opens+ /// the resource with that editor.pub(super) fn show_open_with_picker_for(&mut self, resource: &crate::diff_editor::Side, window: &mut Window, cx: &mut Context<Self>) {let uri = crate::editor::uri_value(&resource.scheme, &resource.path);let custom = self.webview_panels.panels.iter().find(|panel| panel.custom.as_ref().is_some_and(|custom| uri_parts(&custom.resource).is_ok_and(|(scheme, path)| scheme == resource.scheme && path == resource.path))).map(|panel| panel.view_type.clone());diff --git a/native/crates/app/src/workbench/debug_inline_values.rs b/native/crates/app/src/workbench/debug_inline_values.rsindex d5427be301b..743227cc13e 100644--- a/native/crates/app/src/workbench/debug_inline_values.rs+++ b/native/crates/app/src/workbench/debug_inline_values.rs@@ -163,7 +163,7 @@ impl Workbench {}fn clear_debug_inline_values(&mut self) {- for editor in self.editors.editors.iter_mut().chain(&mut self.editors.models) {+ for editor in self.editors.all_editors_mut() {if editor.injected_text.iter().any(|injection| injection.owner == InjectionOwner::DebugInlineValue) {editor.set_injected_text(InjectionOwner::DebugInlineValue, Vec::new());}diff --git a/native/crates/app/src/workbench/debug_inline_values/tests.rs b/native/crates/app/src/workbench/debug_inline_values/tests.rsindex 58469f9c634..b4c62b538d7 100644--- a/native/crates/app/src/workbench/debug_inline_values/tests.rs+++ b/native/crates/app/src/workbench/debug_inline_values/tests.rs@@ -115,6 +115,35 @@ fn the_focused_frame_shows_its_variables_after_the_lines_naming_them(cx: &mut Testd::fs::remove_dir_all(dir).unwrap();}+/// The values of a file that leaves the active group go with the rest when the frame's file is no longer active,+/// instead of staying stale in the other group's editor.+#[gpui::test]+fn the_values_of_a_file_moved_to_another_group_are_removed(cx: &mut TestAppContext) {+ let dir = std::env::temp_dir().join(format!("vsrustium-inline-values-other-group-{}", std::process::id()));+ std::fs::create_dir_all(&dir).unwrap();+ let file = dir.join("a.js");+ std::fs::write(&file, "function f(a) {\n let b = a + 1;\n return b;\n}\n").unwrap();+ let (workbench, host, cx) = workbench(cx, &file);+ workbench.update(cx, |workbench, _| drop(workbench.settings.lock().unwrap().update_value("debug.inlineValues", Some(&json!("on")), config::service::Target::User, None, &[]).unwrap()));+ let focus = DebugFocus { session: Some("s".into()), thread: Some(1), frame: Some(9) };+ workbench.update_in(cx, |workbench, window, cx| workbench.set_debug_focus(focus, Reveal::No, window, cx));+ cx.run_until_parked();+ respond(&workbench, &host, &[("scopes", json!({ "scopes": [{ "name": "Local", "variablesReference": 4, "expensive": false }] }))], cx);+ respond(&workbench, &host, &[("variables", json!({ "variables": [{ "name": "a", "value": "1", "variablesReference": 0 }] }))], cx);+ assert!(!shown(&workbench, cx).is_empty());++ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ workbench.update(cx, |workbench, cx| workbench.update_debug_inline_values(cx));+ cx.executor().advance_clock(REMOVE_DELAY);+ cx.run_until_parked();+ let left = workbench.read_with(cx, |workbench, _| {+ let editor = workbench.editors.model("file", &file).unwrap();+ editor.injected_text.iter().filter(|injection| injection.owner == InjectionOwner::DebugInlineValue).count()+ });+ assert_eq!(left, 0);+ std::fs::remove_dir_all(dir).unwrap();+}+/// `debug.inlineValues: auto` asks the providers only; a variable lookup takes the value from the scopes.#[gpui::test]fn auto_shows_the_providers_values_in_column_order(cx: &mut TestAppContext) {diff --git a/native/crates/app/src/workbench/debug_view.rs b/native/crates/app/src/workbench/debug_view.rsindex 59221f9b3bf..ca842ad6ae2 100644--- a/native/crates/app/src/workbench/debug_view.rs+++ b/native/crates/app/src/workbench/debug_view.rs@@ -441,6 +441,11 @@ impl Workbench {}));}+ /// debugModel.ts `Breakpoint.verified`'s `textFileService.isDirty(uri)`: the file's model in any group is dirty.+ pub(super) fn breakpoint_file_is_dirty(&self, breakpoint: &crate::debug::Breakpoint) -> bool {+ self.editors.all_editors().any(|editor| editor.document().uri_string() == breakpoint.uri_string() && editor.is_dirty())+ }+/// The focused session's debugger's `strings.unverifiedBreakpoints` while breakpoints are active and an enabled/// breakpoint in one of its languages is unverified.fn unverified_breakpoints_message(&self) -> Option<String> {@@ -451,7 +456,7 @@ impl Workbench {let debugger = self.debug.debugger(self.debug.focused_session()?.configuration["type"].as_str()?)?;let message = debugger.contribution["strings"]["unverifiedBreakpoints"].as_str()?;let unverified = model.breakpoints.iter().any(|breakpoint| {- let dirty = self.editors.editors.iter().chain(&self.editors.models).any(|editor| editor.document().uri_string() == breakpoint.uri_string() && editor.is_dirty());+ let dirty = self.breakpoint_file_is_dirty(breakpoint);let path = crate::editor_history::file_path(&breakpoint.uri_string());let language = path.and_then(|path| self.languages.guess_language(&path, "").map(str::to_owned));breakpoint.base.enabled && !breakpoint.verified(dirty) && language.is_some_and(|language| debugger.interested_in_language(&language))@@ -865,7 +870,7 @@ impl Workbench {}for breakpoint in &model.breakpoints {let id = breakpoint.id().to_owned();- let dirty = self.editors.editors.iter().chain(&self.editors.models).any(|editor| editor.document().uri_string() == breakpoint.uri_string() && editor.is_dirty());+ let dirty = self.breakpoint_file_is_dirty(breakpoint);let (icon, _) = super::breakpoint_widget::breakpoint_icon(breakpoint, model, debug_active, dirty);let path = crate::uri::json_fs_path(&breakpoint.uri);let name = path.rsplit(std::path::is_separator).next().unwrap_or_default().to_owned();diff --git a/native/crates/app/src/workbench/diagnostics.rs b/native/crates/app/src/workbench/diagnostics.rsindex 3bd3d48e62a..76ee33124d4 100644--- a/native/crates/app/src/workbench/diagnostics.rs+++ b/native/crates/app/src/workbench/diagnostics.rs@@ -13,6 +13,7 @@ use super::host_requests::uri_parts;use crate::editor::marker_decorations::{MAX_MARKER_DECORATIONS, MarkerDecoration};use crate::editor::{LINE_HEIGHT, OpenEditor, expand_tabs};use crate::markers::{DEPRECATED, ERROR, HINT, INFO, MarkerService, MarkerStatistics, ReadOptions, UNNECESSARY, WARNING};+use crate::workbench::editor_options::{SHOW_DEPRECATED, SHOW_UNUSED};/// `MainThreadDiagnostics.extHostId`: the window's one extension host is the first.pub(super) const EXT_HOST_ID: &str = "extHost1";@@ -109,7 +110,7 @@ impl Workbench {/// `_updateDecorations` of every model, or of the models of `resources`.pub(super) fn update_marker_decorations(&mut self, resources: Option<&[String]>) {let service = &self.diagnostics.service;- for editor in self.editors.editors.iter_mut().chain(&mut self.editors.models) {+ for editor in self.editors.all_editors_mut() {let resource = editor.document().uri_string();if resources.is_some_and(|resources| !resources.contains(&resource)) {continue;@@ -148,7 +149,7 @@ impl Workbench {let element = match marker.severity {HINT if marker.has_tag(DEPRECATED) => continue,HINT if marker.has_tag(UNNECESSARY) => {- let border = self.theme.color("editorUnnecessaryCode.border").filter(|_| self.setting("editor.showUnused") != false);+ let border = self.theme.color("editorUnnecessaryCode.border").filter(|_| self.editor_option(editor, &SHOW_UNUSED));// Accepted platform difference: .squiggly-unnecessary's 2px dashed bottom border is solid: GPUI's quad shader// leaves a single dashed border wrong at its ends (TODO in gpui_apple shaders.metal).border.map(|border| div().absolute().top(px(LINE_HEIGHT)).h(px(2.)).left(px(left)).w(px(width)).bg(border).into_any_element())@@ -170,11 +171,11 @@ impl Workbench {pub(super) fn marker_text_styles(&self, editor: &OpenEditor, line: usize, tab_size: usize) -> Vec<(Range<usize>, HighlightStyle)> {let text = &editor.document().lines[line];let byte = |column: usize| expand_tabs(&text.chars().take(column).collect::<String>(), tab_size).len();- let fade = match self.setting("editor.showUnused") != false {+ let fade = match self.editor_option(editor, &SHOW_UNUSED) {true => self.theme.color("editorUnnecessaryCode.opacity").map(|opacity| 1. - opacity.a),false => None,};- let strikethrough = (self.setting("editor.showDeprecated") != false).then(|| StrikethroughStyle { thickness: px(1.), color: self.theme.color("editor.foreground").map(Into::into) });+ let strikethrough = self.editor_option(editor, &SHOW_DEPRECATED).then(|| StrikethroughStyle { thickness: px(1.), color: self.theme.color("editor.foreground").map(Into::into) });let mut styles = Vec::new();for decoration in editor.text_model().markers.iter().filter(|decoration| decoration.start.line <= line && line <= decoration.end.line) {let style = match (decoration.marker.has_tag(DEPRECATED), decoration.marker.has_tag(UNNECESSARY)) {diff --git a/native/crates/app/src/workbench/document_highlights.rs b/native/crates/app/src/workbench/document_highlights.rsindex f71629246c5..6ffc5a457a4 100644--- a/native/crates/app/src/workbench/document_highlights.rs+++ b/native/crates/app/src/workbench/document_highlights.rs@@ -12,6 +12,7 @@ use super::Workbench;use crate::commands::Outcome;use crate::editor::{OpenEditor, Position, char_column, utf16_column};use crate::language_features::Candidate;+use crate::workbench::editor_options::OCCURRENCES_HIGHLIGHT_FROM_ALL_PROVIDERS;const REGISTER: &str = "$registerDocumentHighlightProvider";const TEXT: u64 = 0;@@ -37,7 +38,7 @@ impl Workbench {self.commands.register("_executeDocumentHighlights", |workbench, args, _, cx| {let (Some(uri), Some(position)) = (args.first(), args.get(1)) else { return Outcome::error("Illegal argument") };let Ok((scheme, path)) = super::host_requests::uri_parts(uri) else { return Outcome::error("Illegal argument") };- let Some(editor) = workbench.editors.editors.iter().chain(&workbench.editors.models).find(|editor| editor.document().is(scheme, &path)) else {+ let Some(editor) = workbench.editors.model(scheme, &path) else {return Outcome::error("Illegal argument");};let request = workbench.occurrences_at_position(editor, position.clone());@@ -66,7 +67,7 @@ impl Workbench {if handles.is_empty() {return None;}- let merge = self.setting("editor.occurrencesHighlightFromAllProviders") == json!(true);+ let merge = self.editor_option(editor, &OCCURRENCES_HIGHLIGHT_FROM_ALL_PROVIDERS);let calls: Vec<_> = handles.iter().map(|handle| self.host.call_cancellable("ExtHostLanguageFeatures", "$provideDocumentHighlights", vec![json!(handle), uri.clone(), position.clone()])).collect();Some(async move {match merge {diff --git a/native/crates/app/src/workbench/document_symbols.rs b/native/crates/app/src/workbench/document_symbols.rsindex c40a019adac..a9f2cc5e8ec 100644--- a/native/crates/app/src/workbench/document_symbols.rs+++ b/native/crates/app/src/workbench/document_symbols.rs@@ -26,7 +26,7 @@ impl Workbench {pub(super) fn register_document_symbol_commands(&mut self) {self.commands.register("_executeDocumentSymbolProvider", |workbench, args, _, cx| {let Some((scheme, path)) = args.first().and_then(|uri| super::host_requests::uri_parts(uri).ok()) else { return Outcome::error("Illegal argument") };- let Some(model_id) = workbench.editors.editors.iter().chain(&workbench.editors.models).find(|editor| editor.document().is(scheme, &path)).map(|editor| editor.model_id) else {+ let Some(model_id) = workbench.editors.model(scheme, &path).map(|editor| editor.model_id) else {return Outcome::error("Illegal argument");};let outline = workbench.outline_model(model_id, cx);@@ -50,7 +50,7 @@ impl Workbench {/// `OutlineModelService.getOrCreate`: the cached model of this version, else every provider asked in score order/// (a failing one gives no symbols), grouped by provider under its display name. `None` for a closed model.pub(super) fn outline_model(&mut self, model_id: u32, cx: &mut Context<Self>) -> Task<Option<OutlineModel>> {- let Some(editor) = self.editors.editor_by_id(model_id) else { return Task::ready(None) };+ let Some(editor) = self.editors.editor_by_id(model_id).or_else(|| self.editors.all_tabs().find(|editor| editor.model_id == model_id)) else { return Task::ready(None) };let version = editor.text_model().version_id;let uri = editor.document().uri();let candidate = Candidate { uri: &uri, language: &editor.document().language_id };@@ -65,7 +65,7 @@ impl Workbench {}let mut calls = Vec::new();for registration in registrations {- let label = registration.args.get(2).and_then(Value::as_str).unwrap_or("Unknown Outline Provider").to_string();+ let label = registration.display_name.clone().unwrap_or_else(|| "Unknown Outline Provider".to_owned());calls.push((label, self.host.call_cancellable("ExtHostLanguageFeatures", "$provideDocumentSymbols", vec![json!(registration.handle), uri.clone()])));}cx.spawn(async move |workbench, cx| {diff --git a/native/crates/app/src/workbench/editor_commands.rs b/native/crates/app/src/workbench/editor_commands.rsindex 45c881dae63..aa015db9183 100644--- a/native/crates/app/src/workbench/editor_commands.rs+++ b/native/crates/app/src/workbench/editor_commands.rs@@ -10,6 +10,8 @@ use gpui::{ClipboardItem, Context, Window};use serde_json::{Value, json};use super::Workbench;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::commands::Outcome;use crate::editor::auto_closing::{self, AutoClose};use crate::editor::auto_indent::{AutoIndent, Strategy};@@ -221,7 +223,7 @@ impl Workbench {self.commands.register(id, move |workbench, _, _, cx| {let Some(editor) = workbench.editors.active_mut().filter(|editor| editor.selection_anchor.is_some()) else { return Outcome::done() };command(editor);- workbench.host.send_selection(editor, "api");+ workbench.cursor_position_changed(Cursor { moved: true, source: "api", reveal: Reveal::Nothing }, cx);cx.notify();Outcome::done()});@@ -282,7 +284,8 @@ impl Workbench {if let Some(editor) = workbench.editors.active_mut() {let before = editor.selections.clone();let reveal = editor.column_selection_mode_changed(on);- workbench.cursors_changed(before, reveal, "keyboard", cx);+ let moved = editor.selections != before;+ workbench.cursor_position_changed(Cursor { moved, source: "keyboard", reveal }, cx);}cx.notify();Outcome::done()@@ -619,7 +622,7 @@ impl Workbench {fn editor_command_ran(&mut self, change: Option<ContentChanged>, selections_before: Vec<Selection>, cx: &mut Context<Self>) -> Outcome {let moved = self.editors.active().is_some_and(|editor| editor.selections != selections_before);self.marked_text = None;- self.editor_edited(change, moved, "keyboard", cx);+ self.model_content_changed(change, Cursor { moved, source: "keyboard", reveal: Reveal::All }, cx);Outcome::Ready(Ok(Value::Null))}diff --git a/native/crates/app/src/workbench/editor_groups.rs b/native/crates/app/src/workbench/editor_groups.rsindex 521485f0715..791e48ce123 100644--- a/native/crates/app/src/workbench/editor_groups.rs+++ b/native/crates/app/src/workbench/editor_groups.rs@@ -1338,4 +1338,4 @@ mod locked_groups;mod part_state;#[cfg(test)]-mod tests;+pub(super) mod tests;diff --git a/native/crates/app/src/workbench/editor_groups/tests.rs b/native/crates/app/src/workbench/editor_groups/tests.rsindex 0e984fda32f..a0c4b55f6ec 100644--- a/native/crates/app/src/workbench/editor_groups/tests.rs+++ b/native/crates/app/src/workbench/editor_groups/tests.rs@@ -10,7 +10,7 @@ use crate::languages::Languages;use crate::theme::load_theme;use crate::workbench::Workbench;-fn workbench_with<'a>(name: &str, files: &[&str], cx: &'a mut TestAppContext) -> (PathBuf, gpui::Entity<Workbench>, &'a mut VisualTestContext) {+pub(in crate::workbench) fn workbench_with<'a>(name: &str, files: &[&str], cx: &'a mut TestAppContext) -> (PathBuf, gpui::Entity<Workbench>, &'a mut VisualTestContext) {let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();let themes = scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();let theme = load_theme(&[themes], "Dark Modern").unwrap();@@ -40,6 +40,23 @@ fn run(workbench: &gpui::Entity<Workbench>, command: &str, cx: &mut VisualTestCocx.run_until_parked();}+/// Moves the active editor of a group without other editors into a new group to the right and activates the first+/// group again, which an untitled editor keeps open (`workbench.editor.closeEmptyGroups` closes an emptied group).+pub(in crate::workbench) fn move_active_editor_to_another_group(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) {+ workbench.update_in(cx, |workbench, window, cx| {+ assert_eq!(workbench.editors.editors.len(), 1, "the active editor alone");+ drop(workbench.execute_command("workbench.action.files.newUntitledFile", vec![], window, cx));+ workbench.editors.activate(0);+ drop(workbench.execute_command("workbench.action.moveEditorToNextGroup", vec![], window, cx));+ drop(workbench.execute_command("workbench.action.focusPreviousGroup", vec![], window, cx));+ });+ cx.run_until_parked();+ workbench.read_with(cx, |workbench, _| {+ assert_eq!(workbench.editors.editors.len(), 1, "the moved editor is only in the other group");+ assert_eq!(workbench.editors.active().unwrap().document().scheme, "untitled");+ });+}+/// The groups in grid order with their tab names, and the active group's index.fn groups(workbench: &gpui::Entity<Workbench>, cx: &mut VisualTestContext) -> (Vec<Vec<String>>, usize) {workbench.read_with(cx, |workbench, _| {@@ -581,3 +598,187 @@ fn pills_on_separate_rows_keep_a_4px_gap(cx: &mut TestAppContext) {assert_eq!(lower.top() - pinned.bottom(), gpui::px(4.));std::fs::remove_dir_all(dir).unwrap();}++/// modelService.ts `_updateModelOptions` runs over `getModels()`: a changed `editor.tabSize` reaches a file whose only+/// editor is in another group.+#[gpui::test]+fn a_changed_tab_size_reaches_a_model_in_another_group(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = workbench_with("other-group-tab-size", &["a.txt"], cx);+ move_active_editor_to_another_group(&workbench, cx);+ workbench.update(cx, |workbench, cx| {+ let settings = config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("User"), None);+ workbench.settings = std::sync::Arc::new(std::sync::Mutex::new(settings));+ let before = workbench.model_creation_options();+ let change = workbench.settings.lock().unwrap().update_value("editor.tabSize", Some(&json!(2)), config::service::Target::User, None, &[]).unwrap();+ workbench.configuration_changed(&change, before, cx);+ });+ let tab_size = workbench.read_with(cx, |workbench, _| workbench.editors.model("file", &dir.join("a.txt")).unwrap().document().indentation.tab_size);+ assert_eq!(tab_size, 2);+ std::fs::remove_dir_all(dir).unwrap();+}++/// breakpointEditorContribution.ts sets the inline breakpoint widgets in every code editor: a column breakpoint in a+/// file shown only in another group gets its widget.+#[gpui::test]+fn a_column_breakpoint_in_another_group_gets_its_inline_widget(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = workbench_with("other-group-inline-breakpoint", &["a.txt"], cx);+ move_active_editor_to_another_group(&workbench, cx);+ let uri = crate::editor::uri_value("file", &dir.join("a.txt"));+ workbench.update(cx, |workbench, cx| {+ workbench.debug.model.add_breakpoints(&uri, vec![crate::debug::BreakpointData { column: Some(7), ..crate::debug::BreakpointData::at(1) }]);+ cx.notify();+ });+ cx.run_until_parked();+ cx.update(|window, cx| drop(window.draw(cx)));+ let widgets = workbench.read_with(cx, |workbench, _| workbench.debug.inline_breakpoints.widgets.keys().cloned().collect::<Vec<_>>());+ assert_eq!(widgets, [crate::editor::uri_string("file", &dir.join("a.txt"))]);+ std::fs::remove_dir_all(dir).unwrap();+}++/// debugModel.ts `Breakpoint.verified` asks `textFileService.isDirty(uri)`, which no group limits: a breakpoint in a+/// dirty file shown only in another group sees the file dirty.+#[gpui::test]+fn a_breakpoint_in_a_dirty_file_in_another_group_sees_the_file_dirty(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = workbench_with("other-group-dirty-breakpoint", &["a.txt"], cx);+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("type", vec![json!({ "text": "x" })], window, cx)));+ move_active_editor_to_another_group(&workbench, cx);+ let uri = crate::editor::uri_value("file", &dir.join("a.txt"));+ let dirty = workbench.update(cx, |workbench, _| {+ workbench.debug.model.add_breakpoints(&uri, vec![crate::debug::BreakpointData::at(1)]);+ workbench.breakpoint_file_is_dirty(&workbench.debug.model.breakpoints[0])+ });+ assert!(dirty);+ std::fs::remove_dir_all(dir).unwrap();+}++/// markerDecorationsService.ts `_onMarkerChanged` updates the decorations of `modelService.getModel(resource)`: a+/// marker on a file shown only in another group decorates its model.+#[gpui::test]+fn a_marker_decorates_a_model_in_another_group(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = workbench_with("other-group-markers", &["a.txt"], cx);+ move_active_editor_to_another_group(&workbench, cx);+ let uri = crate::editor::uri_value("file", &dir.join("a.txt"));+ let marker = json!({ "severity": 8, "message": "problem", "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 2 });+ workbench.update(cx, |workbench, cx| workbench.change_many_markers("test", &json!([[uri, [marker], false]]), cx));+ let decorations = workbench.read_with(cx, |workbench, _| workbench.editors.model("file", &dir.join("a.txt")).unwrap().text_model().markers.len());+ assert_eq!(decorations, 1);+ std::fs::remove_dir_all(dir).unwrap();+}++/// wordHighlighter.ts `_executeDocumentHighlights` and outlineModel.ts `_executeDocumentSymbolProvider` take the model+/// from `modelService.getModel(resource)`: a file shown only in another group answers instead of failing.+#[gpui::test]+fn model_commands_answer_for_a_model_in_another_group(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = workbench_with("other-group-model-commands", &["a.txt"], cx);+ move_active_editor_to_another_group(&workbench, cx);+ let uri = json!({ "scheme": "file", "path": dir.join("a.txt").to_string_lossy() });+ let (highlights, symbols) = workbench.update_in(cx, |workbench, window, cx| {+ let highlights = workbench.execute_command("_executeDocumentHighlights", vec![uri.clone(), json!({ "lineNumber": 1, "column": 1 })], window, cx);+ let symbols = workbench.execute_command("_executeDocumentSymbolProvider", vec![uri], window, cx);+ (highlights, symbols)+ });+ assert!(matches!(highlights, crate::commands::Outcome::Pending(_)));+ assert!(matches!(symbols, crate::commands::Outcome::Pending(_)));+ std::fs::remove_dir_all(dir).unwrap();+}++/// contextkeys.ts sets `dirtyWorkingCopies` from `workingCopyService.hasDirty`, which no group limits: a dirty file+/// shown only in another group keeps Save All enabled.+#[gpui::test]+fn a_dirty_file_in_another_group_sets_dirty_working_copies(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = workbench_with("other-group-dirty-context", &["a.txt"], cx);+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("type", vec![json!({ "text": "x" })], window, cx)));+ move_active_editor_to_another_group(&workbench, cx);+ let dirty = workbench.update_in(cx, |workbench, window, _| workbench.key_context(window)["dirtyWorkingCopies"].clone());+ assert_eq!(dirty, json!(true));+ std::fs::remove_dir_all(dir).unwrap();+}++/// smartSelect.ts `_executeSelectionRangeProvider` takes the model from `modelService.getModel(resource)`: a file+/// shown only in another group answers its ranges, not an empty list.+#[gpui::test]+fn selection_ranges_answer_for_a_model_in_another_group(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = workbench_with("other-group-selection-ranges", &["a.txt"], cx);+ move_active_editor_to_another_group(&workbench, cx);+ let uri = json!({ "scheme": "file", "path": dir.join("a.txt").to_string_lossy() });+ let answer = workbench.update_in(cx, |workbench, window, cx| workbench.execute_command("_executeSelectionRangeProvider", vec![uri, json!([{ "lineNumber": 1, "column": 2 }])], window, cx));+ let crate::commands::Outcome::Ready(Ok(ranges)) = answer else { panic!("answered at once without providers") };+ assert!(!ranges[0].as_array().unwrap().is_empty(), "{ranges}");+ std::fs::remove_dir_all(dir).unwrap();+}++/// callStackEditorContribution.ts decorates every code editor with the top stack frame's column: a file shown only in+/// another group gets its column marker.+#[gpui::test]+fn a_stopped_frame_in_another_group_gets_its_column_marker(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = workbench_with("other-group-frame-column", &["a.txt"], cx);+ move_active_editor_to_another_group(&workbench, cx);+ let path = dir.join("a.txt");+ workbench.update(cx, |workbench, cx| {+ let mut session = crate::debug::session::Session::new("s".into(), 1, json!({ "name": "s", "type": "node", "request": "launch" }), json!({}), None, json!({}));+ session.set_threads(&[json!({ "id": 1, "name": "main" })]);+ let thread = session.thread_mut(1).unwrap();+ thread.stopped = true;+ thread.frames = vec![crate::debug::session::StackFrame { id: 9, name: "f".into(), source: json!({ "path": path.to_string_lossy() }), line: 1, column: 3, end_line: 1, end_column: 3, ..Default::default() }];+ workbench.debug.sessions.push(session);+ cx.notify();+ });+ cx.run_until_parked();+ cx.update(|window, cx| drop(window.draw(cx)));+ let markers = workbench.read_with(cx, |workbench, _| {+ let editor = workbench.editors.model("file", &path).unwrap();+ editor.injected_text.iter().filter(|injection| injection.owner == crate::editor::injected_text::InjectionOwner::StackFrameColumn).count()+ });+ assert_eq!(markers, 1);+ std::fs::remove_dir_all(dir).unwrap();+}++/// gotoError.ts `MarkerController._cleanUp` disposes the widget, whose zone leaves the editor it lives in: a marker+/// navigation closed after its editor moved to another group leaves no empty zone behind.+#[gpui::test]+fn closing_marker_navigation_in_another_group_removes_its_zone(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = workbench_with("other-group-marker-navigation", &["a.txt"], cx);+ let uri = crate::editor::uri_value("file", &dir.join("a.txt"));+ let marker = json!({ "severity": 8, "message": "problem", "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 2 });+ workbench.update_in(cx, |workbench, window, cx| {+ workbench.change_many_markers("test", &json!([[uri, [marker], false]]), cx);+ drop(workbench.execute_command("editor.action.marker.next", vec![], window, cx));+ });+ cx.run_until_parked();+ let zones = |workbench: &Workbench| workbench.editors.model("file", &dir.join("a.txt")).unwrap().view_zones.len();+ assert_eq!(workbench.read_with(cx, |workbench, _| zones(workbench)), 1, "the widget's zone");+ move_active_editor_to_another_group(&workbench, cx);+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("closeMarkersNavigation", vec![], window, cx)));+ cx.run_until_parked();+ assert_eq!(workbench.read_with(cx, |workbench, _| zones(workbench)), 0);+ std::fs::remove_dir_all(dir).unwrap();+}++/// zoneWidget.ts `ZoneWidget.dispose` removes the zone from its own editor: the exception widget (exceptionWidget.ts)+/// closed after its editor moved to another group leaves no empty zone behind.+#[gpui::test]+fn closing_the_exception_widget_in_another_group_removes_its_zone(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = workbench_with("other-group-exception-widget", &["a.txt"], cx);+ let path = dir.join("a.txt").to_string_lossy().into_owned();+ workbench.update(cx, |workbench, cx| workbench.show_exception_widget(&path, 1, json!({ "description": "boom" }), cx));+ let zones = |workbench: &Workbench| workbench.editors.model("file", &dir.join("a.txt")).unwrap().view_zones.len();+ assert_eq!(workbench.read_with(cx, |workbench, _| zones(workbench)), 1, "the widget's zone");+ move_active_editor_to_another_group(&workbench, cx);+ workbench.update(cx, |workbench, cx| workbench.close_exception_widget(cx));+ assert_eq!(workbench.read_with(cx, |workbench, _| zones(workbench)), 0);+ std::fs::remove_dir_all(dir).unwrap();+}++/// zoneWidget.ts `ZoneWidget.dispose`: the breakpoint widget (breakpointWidget.ts) closed after its editor moved to+/// another group leaves no empty zone behind.+#[gpui::test]+fn closing_the_breakpoint_widget_in_another_group_removes_its_zone(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = workbench_with("other-group-breakpoint-widget", &["a.txt"], cx);+ workbench.update_in(cx, |workbench, window, cx| workbench.show_breakpoint_widget(1, None, None, crate::workbench::breakpoint_widget::WidgetContext::Condition, window, cx));+ let zones = |workbench: &Workbench| workbench.editors.model("file", &dir.join("a.txt")).unwrap().view_zones.len();+ assert_eq!(workbench.read_with(cx, |workbench, _| zones(workbench)), 1, "the widget's zone");+ move_active_editor_to_another_group(&workbench, cx);+ workbench.update_in(cx, |workbench, window, cx| workbench.close_breakpoint_widget(window, cx));+ assert_eq!(workbench.read_with(cx, |workbench, _| zones(workbench)), 0);+ std::fs::remove_dir_all(dir).unwrap();+}diff --git a/native/crates/app/src/workbench/editor_menus.rs b/native/crates/app/src/workbench/editor_menus.rsindex f5f31d3c641..a2b4974fd9a 100644--- a/native/crates/app/src/workbench/editor_menus.rs+++ b/native/crates/app/src/workbench/editor_menus.rs@@ -8,10 +8,13 @@ use gpui::{Bounds, Context, Div, Pixels, Point, Rgba, Size, Stateful, Window, cause serde_json::{Value, json};use super::Workbench;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::commands::Outcome;use crate::editor::minimap::{MinimapSide, MinimapSize};use crate::editor::{Position, column_at_visible};use crate::menus::{MenuAction, MenuId};+use crate::workbench::editor_options::CONTEXTMENU;impl Workbench {pub(super) fn register_editor_menu_commands(&mut self) {@@ -152,7 +155,7 @@ impl Workbench {let position = Position::new(line, column_at_visible(&editor.document().lines[line], visible, editor.document().indentation.tab_size));if !editor.selections.iter().any(|selection| selection.start() <= position && position <= selection.end()) {editor.move_to(position, false);- self.editor_edited(None, true, "mouse", cx);+ self.model_content_changed(None, Cursor { moved: true, source: "mouse", reveal: Reveal::All }, cx);}let uri = document_uri(self.editors.active().expect("checked above"));let context = self.key_context(window);@@ -162,7 +165,7 @@ impl Workbench {/// `ShowContextMenu` (Shift+F10): `MenuId.EditorContext` below the cursor, which stays where it is; not with/// `editor.contextmenu` off.pub(super) fn show_editor_context_menu_at_cursor(&mut self, window: &mut Window, cx: &mut Context<Self>) {- if self.setting("editor.contextmenu") == json!(false) {+ if !self.global_editor_option(&CONTEXTMENU) {return;}let Some(anchor) = self.cursor_anchor(window) else { return };@@ -181,7 +184,8 @@ impl Workbench {if on_line_numbers && !touched {let before = editor.selections.clone();editor.set_selections(vec![crate::editor::Selection { anchor: Position::new(line, 0), head: line_end }]);- self.cursors_changed(before, crate::editor::Reveal::Nothing, "api", cx);+ let moved = editor.selections != before;+ self.cursor_position_changed(Cursor { moved, source: "api", reveal: Reveal::Nothing }, cx);}let editor = self.editors.active().expect("checked above");let mut context = self.key_context(window);diff --git a/native/crates/app/src/workbench/editor_options.rs b/native/crates/app/src/workbench/editor_options.rsnew file mode 100644index 00000000000..cdbab53ac07--- /dev/null+++ b/native/crates/app/src/workbench/editor_options.rs@@ -0,0 +1,191 @@+//! The editor options the workbench reads (editorOptions.ts `EditorOptions`): each option's key, default and+//! `validate`, read for a code editor with its language's `[lang]` block or, outside one, from the configuration.++use config::configuration::Overrides;+use serde_json::{Value, json};++use super::Workbench;+use crate::editor::OpenEditor;++/// editorOptions.ts `IEditorOption`: the setting and its `validate`, which falls back to the option's default.+pub(super) struct EditorOption<T> {+ pub(super) key: &'static str,+ validate: fn(&Value) -> T,+}++impl Workbench {+ /// textEditor.ts `updateEditorConfiguration`: a code editor's option, read for its resource and language+ /// (textResourceConfigurationService.ts), so a `[lang]` block overrides it.+ pub(super) fn editor_option<T>(&self, editor: &OpenEditor, option: &EditorOption<T>) -> T {+ let document = editor.document();+ let overrides = Overrides { resource: Some(&document.path), override_identifier: Some(&document.language_id) };+ let value = self.settings.lock().unwrap().get_value(Some(option.key), &overrides);+ (option.validate)(value.as_ref().unwrap_or(&Value::Null))+ }++ /// `configurationService.getValue` of an editor option outside a code editor: no language override.+ pub(super) fn global_editor_option<T>(&self, option: &EditorOption<T>) -> T {+ (option.validate)(&self.setting(option.key))+ }+}++/// editorOptions.ts `Constants.MAX_SAFE_SMALL_INTEGER`.+const MAX_SAFE_SMALL_INTEGER: usize = (1 << 30) - 1;+/// fontInfo.ts `EDITOR_FONT_DEFAULTS.fontSize`.+const DEFAULT_FONT_SIZE: f32 = if cfg!(target_os = "macos") { 12. } else { 14. };+/// fontInfo.ts `EDITOR_FONT_DEFAULTS.fontFamily`.+const DEFAULT_FONT_FAMILY: &str = if cfg!(target_os = "macos") {+ "Menlo, Monaco, 'Courier New', monospace"+} else if cfg!(windows) {+ "Consolas, 'Courier New', monospace"+} else {+ "'Droid Sans Mono', monospace"+};+const CURSOR_STYLES: &[&str] = &["line", "block", "underline", "line-thin", "block-outline", "underline-thin"];++pub(super) const ACCESSIBILITY_PAGE_SIZE: EditorOption<usize> = EditorOption { key: "editor.accessibilityPageSize", validate: |value| clamped_int(value, 500, 1, MAX_SAFE_SMALL_INTEGER) };+pub(super) const ACCESSIBILITY_SUPPORT: EditorOption<&str> = EditorOption { key: "editor.accessibilitySupport", validate: |value| string_set(value, "auto", &["auto", "off", "on"]) };+pub(super) const ARIA_LABEL: EditorOption<String> = EditorOption { key: "editor.ariaLabel", validate: |value| string(value, "Editor content") };+/// codeActionContributions.ts, not an editor option: the schema's default.+pub(super) const CODE_ACTIONS_TRIGGER_ON_FOCUS_CHANGE: EditorOption<bool> = EditorOption { key: "editor.codeActions.triggerOnFocusChange", validate: |value| boolean(value, false) };+pub(super) const COLUMN_SELECTION: EditorOption<bool> = EditorOption { key: "editor.columnSelection", validate: |value| boolean(value, false) };+pub(super) const CONTEXTMENU: EditorOption<bool> = EditorOption { key: "editor.contextmenu", validate: |value| boolean(value, true) };+pub(super) const CURSOR_BLINKING: EditorOption<&str> = EditorOption { key: "editor.cursorBlinking", validate: |value| string_set(value, "blink", &["blink", "smooth", "phase", "expand", "solid"]) };+pub(super) const CURSOR_STYLE: EditorOption<&str> = EditorOption { key: "editor.cursorStyle", validate: |value| string_set(value, "line", CURSOR_STYLES) };+pub(super) const DEFINITION_LINK_OPENS_IN_PEEK: EditorOption<bool> = EditorOption { key: "editor.definitionLinkOpensInPeek", validate: |value| boolean(value, false) };+pub(super) const DOUBLE_CLICK_SELECTS_BLOCK: EditorOption<bool> = EditorOption { key: "editor.doubleClickSelectsBlock", validate: |value| boolean(value, true) };+pub(super) const DRAG_AND_DROP: EditorOption<bool> = EditorOption { key: "editor.dragAndDrop", validate: |value| boolean(value, true) };+pub(super) const FIND_ADD_EXTRA_SPACE_ON_TOP: EditorOption<bool> = EditorOption { key: "editor.find.addExtraSpaceOnTop", validate: |value| boolean(value, true) };+/// `EditorFind.validate`: a boolean is `always` or `never`.+pub(super) const FIND_AUTO_FIND_IN_SELECTION: EditorOption<&str> = EditorOption { key: "editor.find.autoFindInSelection", validate: |value| find_string_set(value, "never", &["never", "always", "multiline"]) };+pub(super) const FIND_CURSOR_MOVE_ON_TYPE: EditorOption<bool> = EditorOption { key: "editor.find.cursorMoveOnType", validate: |value| boolean(value, true) };+pub(super) const FIND_FIND_ON_TYPE: EditorOption<bool> = EditorOption { key: "editor.find.findOnType", validate: |value| boolean(value, true) };+pub(super) const FIND_GLOBAL_FIND_CLIPBOARD: EditorOption<bool> = EditorOption { key: "editor.find.globalFindClipboard", validate: |value| boolean(value, false) };+pub(super) const FIND_LOOP: EditorOption<bool> = EditorOption { key: "editor.find.loop", validate: |value| boolean(value, true) };+pub(super) const FIND_SEED_SEARCH_STRING_FROM_SELECTION: EditorOption<&str> = EditorOption { key: "editor.find.seedSearchStringFromSelection", validate: |value| find_string_set(value, "always", &["never", "always", "selection"]) };+pub(super) const FOLDING: EditorOption<bool> = EditorOption { key: "editor.folding", validate: |value| boolean(value, true) };+pub(super) const FONT_FAMILY: EditorOption<String> = EditorOption { key: "editor.fontFamily", validate: |value| string(value, DEFAULT_FONT_FAMILY) };+/// `EditorFontSize.validate`: 0 is the default, else clamped to 6 to 100.+pub(super) const FONT_SIZE: EditorOption<f32> = EditorOption { key: "editor.fontSize", validate: |value| match float(value, DEFAULT_FONT_SIZE as f64) { 0. => DEFAULT_FONT_SIZE, size => size.clamp(6., 100.) as f32 } };+pub(super) const GLYPH_MARGIN: EditorOption<bool> = EditorOption { key: "editor.glyphMargin", validate: |value| boolean(value, true) };+/// `GuideOptions.validate`: `true`, `false` or `active`.+pub(super) const GUIDES_BRACKET_PAIRS: EditorOption<Value> = EditorOption { key: "editor.guides.bracketPairs", validate: |value| primitive_set(value, json!(false), &[json!(true), json!(false), json!("active")]) };+pub(super) const GUIDES_BRACKET_PAIRS_HORIZONTAL: EditorOption<Value> = EditorOption { key: "editor.guides.bracketPairsHorizontal", validate: |value| primitive_set(value, json!("active"), &[json!(true), json!(false), json!("active")]) };+pub(super) const GUIDES_HIGHLIGHT_ACTIVE_BRACKET_PAIR: EditorOption<bool> = EditorOption { key: "editor.guides.highlightActiveBracketPair", validate: |value| boolean(value, true) };+pub(super) const GUIDES_HIGHLIGHT_ACTIVE_INDENTATION: EditorOption<Value> = EditorOption { key: "editor.guides.highlightActiveIndentation", validate: |value| primitive_set(value, json!(true), &[json!(true), json!(false), json!("always")]) };+pub(super) const GUIDES_INDENTATION: EditorOption<bool> = EditorOption { key: "editor.guides.indentation", validate: |value| boolean(value, true) };+/// editorConfigurationSchema.ts, a model option: the schema's default.+pub(super) const INSERT_SPACES: EditorOption<bool> = EditorOption { key: "editor.insertSpaces", validate: |value| boolean(value, true) };+pub(super) const MINIMAP_ENABLED: EditorOption<bool> = EditorOption { key: "editor.minimap.enabled", validate: |value| boolean(value, true) };+/// `EditorMinimap.validate`: a pattern that does not compile is the default.+pub(super) const MINIMAP_MARK_SECTION_HEADER_REGEX: EditorOption<String> = EditorOption {+ key: "editor.minimap.markSectionHeaderRegex",+ validate: |value| value.as_str().filter(|pattern| onig::Regex::new(pattern).is_ok()).unwrap_or(crate::editor::section_headers::MARK_SECTION_HEADER_REGEX).to_string(),+};+pub(super) const MINIMAP_RENDER_CHARACTERS: EditorOption<bool> = EditorOption { key: "editor.minimap.renderCharacters", validate: |value| boolean(value, true) };+pub(super) const MINIMAP_SHOW_MARK_SECTION_HEADERS: EditorOption<bool> = EditorOption { key: "editor.minimap.showMarkSectionHeaders", validate: |value| boolean(value, true) };+pub(super) const MINIMAP_SHOW_REGION_SECTION_HEADERS: EditorOption<bool> = EditorOption { key: "editor.minimap.showRegionSectionHeaders", validate: |value| boolean(value, true) };+pub(super) const MOUSE_MIDDLE_CLICK_ACTION: EditorOption<&str> = EditorOption { key: "editor.mouseMiddleClickAction", validate: |value| string_set(value, "default", &["default", "openLink", "ctrlLeftClick"]) };+pub(super) const MOUSE_WHEEL_ZOOM: EditorOption<bool> = EditorOption { key: "editor.mouseWheelZoom", validate: |value| boolean(value, false) };+pub(super) const MULTI_CURSOR_MODIFIER: EditorOption<&str> = EditorOption { key: "editor.multiCursorModifier", validate: |value| string_set(value, "alt", &["ctrlCmd", "alt"]) };+pub(super) const OCCURRENCES_HIGHLIGHT_FROM_ALL_PROVIDERS: EditorOption<bool> = EditorOption { key: "editor.occurrencesHighlightFromAllProviders", validate: |value| boolean(value, false) };+pub(super) const OVERTYPE_CURSOR_STYLE: EditorOption<&str> = EditorOption { key: "editor.overtypeCursorStyle", validate: |value| string_set(value, "block", CURSOR_STYLES) };+/// rename.ts, not an editor option: the schema's default.+pub(super) const RENAME_ENABLE_PREVIEW: EditorOption<bool> = EditorOption { key: "editor.rename.enablePreview", validate: |value| boolean(value, true) };+pub(super) const RENDER_CONTROL_CHARACTERS: EditorOption<bool> = EditorOption { key: "editor.renderControlCharacters", validate: |value| boolean(value, true) };+pub(super) const RENDER_WHITESPACE: EditorOption<&str> = EditorOption { key: "editor.renderWhitespace", validate: |value| string_set(value, "selection", &["none", "boundary", "selection", "trailing", "all"]) };+pub(super) const ROUNDED_SELECTION: EditorOption<bool> = EditorOption { key: "editor.roundedSelection", validate: |value| boolean(value, true) };+pub(super) const SCROLL_BEYOND_LAST_LINE: EditorOption<bool> = EditorOption { key: "editor.scrollBeyondLastLine", validate: |value| boolean(value, true) };+pub(super) const SCROLL_ON_MIDDLE_CLICK: EditorOption<bool> = EditorOption { key: "editor.scrollOnMiddleClick", validate: |value| boolean(value, false) };+pub(super) const SELECTED_TEXT_MATCH_MODE: EditorOption<&str> = EditorOption { key: "editor.selectedTextMatchMode", validate: |value| string_set(value, "findOptions", &["findOptions", "caseSensitive", "caseInsensitive"]) };+pub(super) const SELECTION_HIGHLIGHT: EditorOption<bool> = EditorOption { key: "editor.selectionHighlight", validate: |value| boolean(value, true) };+pub(super) const SELECTION_HIGHLIGHT_MAX_LENGTH: EditorOption<usize> = EditorOption { key: "editor.selectionHighlightMaxLength", validate: |value| clamped_int(value, 200, 0, MAX_SAFE_SMALL_INTEGER) };+pub(super) const SELECTION_HIGHLIGHT_MULTILINE: EditorOption<bool> = EditorOption { key: "editor.selectionHighlightMultiline", validate: |value| boolean(value, false) };+pub(super) const SHOW_DEPRECATED: EditorOption<bool> = EditorOption { key: "editor.showDeprecated", validate: |value| boolean(value, true) };+pub(super) const SHOW_UNUSED: EditorOption<bool> = EditorOption { key: "editor.showUnused", validate: |value| boolean(value, true) };+pub(super) const SMOOTH_SCROLLING: EditorOption<bool> = EditorOption { key: "editor.smoothScrolling", validate: |value| boolean(value, false) };+/// editorConfigurationSchema.ts, not an editor option: the schema's default.+pub(super) const STABLE_PEEK: EditorOption<bool> = EditorOption { key: "editor.stablePeek", validate: |value| boolean(value, false) };+pub(super) const STICKY_SCROLL_ENABLED: EditorOption<bool> = EditorOption { key: "editor.stickyScroll.enabled", validate: |value| boolean(value, true) };+pub(super) const STICKY_SCROLL_MAX_LINE_COUNT: EditorOption<usize> = EditorOption { key: "editor.stickyScroll.maxLineCount", validate: |value| clamped_int(value, 5, 1, 20) };+pub(super) const STICKY_SCROLL_SCROLL_WITH_EDITOR: EditorOption<bool> = EditorOption { key: "editor.stickyScroll.scrollWithEditor", validate: |value| boolean(value, true) };+pub(super) const TAB_FOCUS_MODE: EditorOption<bool> = EditorOption { key: "editor.tabFocusMode", validate: |value| boolean(value, false) };+/// editorConfigurationSchema.ts, a model option: the schema's default and minimum.+pub(super) const TAB_SIZE: EditorOption<usize> = EditorOption { key: "editor.tabSize", validate: |value| clamped_int(value, 4, 1, MAX_SAFE_SMALL_INTEGER) };+/// `UnicodeHighlight.validateBooleanMap`: the characters mapped to `true`.+pub(super) const UNICODE_HIGHLIGHT_ALLOWED_CHARACTERS: EditorOption<Value> = EditorOption {+ key: "editor.unicodeHighlight.allowedCharacters",+ validate: |value| match value {+ Value::Object(map) => Value::Object(map.iter().filter(|(_, allowed)| **allowed == json!(true)).map(|(character, _)| (character.clone(), json!(true))).collect()),+ _ => json!({}),+ },+};+pub(super) const WORD_SEPARATORS: EditorOption<String> = EditorOption { key: "editor.wordSeparators", validate: |value| string(value, crate::editor::word_operations::DEFAULT_WORD_SEPARATORS) };+pub(super) const WORD_WRAP_INDICATOR: EditorOption<bool> = EditorOption { key: "editor.wordWrapIndicator", validate: |value| boolean(value, false) };++/// editorOptions.ts `boolean`: the string `"false"` is false, any other value is JavaScript's `Boolean(value)`.+/// shortcut: an unset option and an explicit `null` are both the default, upstream makes `null` false.+fn boolean(value: &Value, default: bool) -> bool {+ match value {+ Value::Null => default,+ Value::Bool(value) => *value,+ Value::Number(number) => number.as_f64() != Some(0.),+ Value::String(text) => !text.is_empty() && text != "false",+ Value::Array(_) | Value::Object(_) => true,+ }+}++/// editorOptions.ts `clampedInt`: a string is `parseInt`, a number is clamped then truncated.+fn clamped_int(value: &Value, default: usize, minimum: usize, maximum: usize) -> usize {+ let number = match value {+ Value::Number(number) => number.as_f64(),+ Value::String(text) => parse_number(text, |character| character.is_ascii_digit()),+ _ => None,+ };+ number.map_or(default, |number| number.clamp(minimum as f64, maximum as f64) as usize)+}++/// `EditorFloatOption.float`: a string is `parseFloat`.+fn float(value: &Value, default: f64) -> f64 {+ let number = match value {+ Value::Number(number) => number.as_f64(),+ Value::String(text) => parse_number(text, |character| character.is_ascii_digit() || matches!(character, '.' | 'e' | 'E' | '+' | '-')),+ _ => None,+ };+ number.unwrap_or(default)+}++/// `parseInt` and `parseFloat`: the longest number at the start, after white space.+fn parse_number(text: &str, part: fn(char) -> bool) -> Option<f64> {+ let text = text.trim_start();+ let sign = usize::from(text.starts_with(['+', '-']));+ let end = sign + text[sign..].find(|character| !part(character)).unwrap_or(text.len() - sign);+ (sign + 1..=end).rev().find_map(|end| text[..end].parse().ok())+}++/// `EditorStringOption.string`.+fn string(value: &Value, default: &str) -> String {+ value.as_str().unwrap_or(default).to_string()+}++/// editorOptions.ts `stringSet`, and `EditorEnumOption.validate` before its `convert`.+fn string_set(value: &Value, default: &'static str, allowed: &[&'static str]) -> &'static str {+ value.as_str().and_then(|value| allowed.iter().find(|allowed| **allowed == value)).copied().unwrap_or(default)+}++/// `EditorFind.validate` of `seedSearchStringFromSelection` and `autoFindInSelection`.+fn find_string_set(value: &Value, default: &'static str, allowed: &[&'static str]) -> &'static str {+ match value {+ Value::Bool(true) => "always",+ Value::Bool(false) => "never",+ _ => string_set(value, default, allowed),+ }+}++/// editorOptions.ts `primitiveSet`.+fn primitive_set(value: &Value, default: Value, allowed: &[Value]) -> Value {+ allowed.iter().find(|allowed| *allowed == value).cloned().unwrap_or(default)+}++#[cfg(test)]+mod tests;diff --git a/native/crates/app/src/workbench/editor_options/tests.rs b/native/crates/app/src/workbench/editor_options/tests.rsnew file mode 100644index 00000000000..146084b4e8b--- /dev/null+++ b/native/crates/app/src/workbench/editor_options/tests.rs@@ -0,0 +1,135 @@+use std::path::Path;+use std::sync::{Arc, Mutex};++use config::registry::Registry;+use config::service::Settings;+use exthost::scan::scan_extension;+use gpui::TestAppContext;+use serde_json::{Value, json};++use super::*;+use crate::host_sync::HostSync;+use crate::languages::Languages;+use crate::theme::load_theme;++fn validate<T>(option: &EditorOption<T>, value: Value) -> T {+ (option.validate)(&value)+}++/// editorOptions.ts `EditorBooleanOption.boolean`: unset is the default, the string "false" is false, any other value is+/// `Boolean(value)`.+#[test]+fn a_boolean_option_reads_like_upstream() {+ assert!(validate(&FOLDING, Value::Null));+ assert!(!validate(&MOUSE_WHEEL_ZOOM, Value::Null));+ assert!(!validate(&FOLDING, json!("false")));+ assert!(validate(&MOUSE_WHEEL_ZOOM, json!("true")));+ assert!(!validate(&FOLDING, json!(0)));+ assert!(validate(&MOUSE_WHEEL_ZOOM, json!(1)));+ assert!(!validate(&FOLDING, json!("")));+}++/// editorOptions.ts `EditorIntOption.clampedInt`: a string is `parseInt`, a number is clamped, anything else is the+/// default.+#[test]+fn an_int_option_is_clamped_and_parsed() {+ assert_eq!(validate(&SELECTION_HIGHLIGHT_MAX_LENGTH, Value::Null), 200);+ assert_eq!(validate(&SELECTION_HIGHLIGHT_MAX_LENGTH, json!(true)), 200);+ assert_eq!(validate(&SELECTION_HIGHLIGHT_MAX_LENGTH, json!(-5)), 0);+ assert_eq!(validate(&SELECTION_HIGHLIGHT_MAX_LENGTH, json!(" 42px")), 42);+ assert_eq!(validate(&SELECTION_HIGHLIGHT_MAX_LENGTH, json!("px")), 200);+ assert_eq!(validate(&STICKY_SCROLL_MAX_LINE_COUNT, json!(50)), 20);+ assert_eq!(validate(&STICKY_SCROLL_MAX_LINE_COUNT, json!(0)), 1);+ assert_eq!(validate(&STICKY_SCROLL_MAX_LINE_COUNT, json!(3.7)), 3);+ assert_eq!(validate(&ACCESSIBILITY_PAGE_SIZE, json!(0)), 1);+ assert_eq!(validate(&TAB_SIZE, Value::Null), 4);+}++/// editorOptions.ts `EditorFontSize.validate` and fontInfo.ts `EDITOR_FONT_DEFAULTS`: 0 is the platform default, else+/// clamped to 6 to 100; a string is `parseFloat`.+#[test]+fn the_font_size_is_clamped_with_the_platform_default() {+ let default = if cfg!(target_os = "macos") { 12. } else { 14. };+ assert_eq!(validate(&FONT_SIZE, Value::Null), default);+ assert_eq!(validate(&FONT_SIZE, json!(0)), default);+ assert_eq!(validate(&FONT_SIZE, json!(2)), 6.);+ assert_eq!(validate(&FONT_SIZE, json!(500)), 100.);+ assert_eq!(validate(&FONT_SIZE, json!("13.5px")), 13.5);+ assert!(validate(&FONT_FAMILY, Value::Null).ends_with("monospace"));+}++/// editorOptions.ts `stringSet`: a value outside the set is the default.+#[test]+fn a_string_set_option_falls_back_to_its_default() {+ assert_eq!(validate(&RENDER_WHITESPACE, Value::Null), "selection");+ assert_eq!(validate(&RENDER_WHITESPACE, json!("everything")), "selection");+ assert_eq!(validate(&RENDER_WHITESPACE, json!("all")), "all");+ assert_eq!(validate(&CURSOR_STYLE, json!(true)), "line");+ assert_eq!(validate(&OVERTYPE_CURSOR_STYLE, Value::Null), "block");+ assert_eq!(validate(&CURSOR_BLINKING, json!("solid")), "solid");+ assert_eq!(validate(&MULTI_CURSOR_MODIFIER, json!("ctrl")), "alt");+ assert_eq!(validate(&ACCESSIBILITY_SUPPORT, json!("maybe")), "auto");+ assert_eq!(validate(&SELECTED_TEXT_MATCH_MODE, Value::Null), "findOptions");+ assert_eq!(validate(&MOUSE_MIDDLE_CLICK_ACTION, json!("openLink")), "openLink");+}++/// editorOptions.ts `EditorFind.validate`: `seedSearchStringFromSelection` and `autoFindInSelection` take a boolean+/// as `always` or `never`.+#[test]+fn the_find_options_take_a_boolean() {+ assert_eq!(validate(&FIND_SEED_SEARCH_STRING_FROM_SELECTION, json!(false)), "never");+ assert_eq!(validate(&FIND_SEED_SEARCH_STRING_FROM_SELECTION, json!("selection")), "selection");+ assert_eq!(validate(&FIND_SEED_SEARCH_STRING_FROM_SELECTION, json!("other")), "always");+ assert_eq!(validate(&FIND_AUTO_FIND_IN_SELECTION, json!(true)), "always");+ assert_eq!(validate(&FIND_AUTO_FIND_IN_SELECTION, Value::Null), "never");+}++/// editorOptions.ts `GuideOptions.validate` (`primitiveSet`) and `EditorMinimap.validate` of `markSectionHeaderRegex`.+#[test]+fn guides_and_the_mark_regex_fall_back_to_their_defaults() {+ assert_eq!(validate(&GUIDES_BRACKET_PAIRS, json!("active")), json!("active"));+ assert_eq!(validate(&GUIDES_BRACKET_PAIRS, json!("sometimes")), json!(false));+ assert_eq!(validate(&GUIDES_BRACKET_PAIRS_HORIZONTAL, Value::Null), json!("active"));+ assert_eq!(validate(&GUIDES_HIGHLIGHT_ACTIVE_INDENTATION, json!(1)), json!(true));+ let default = crate::editor::section_headers::MARK_SECTION_HEADER_REGEX;+ assert_eq!(validate(&MINIMAP_MARK_SECTION_HEADER_REGEX, json!("(unclosed")), default);+ assert_eq!(validate(&MINIMAP_MARK_SECTION_HEADER_REGEX, json!("MARK: (.*)")), "MARK: (.*)");+}++/// editorOptions.ts `UnicodeHighlight.validateBooleanMap`: only the characters set to `true` stay.+#[test]+fn the_allowed_characters_keep_the_true_entries() {+ assert_eq!(validate(&UNICODE_HIGHLIGHT_ALLOWED_CHARACTERS, json!({ "a": true, "b": false, "c": 1 })), json!({ "a": true }));+ assert_eq!(validate(&UNICODE_HIGHLIGHT_ALLOWED_CHARACTERS, json!("a")), json!({}));+}++/// textResourceConfigurationService.ts `getValue(resource, position, section)`: a code editor reads its options with+/// its language's `[lang]` block; outside one the block does not apply.+#[gpui::test]+fn a_code_editor_reads_its_language_block(cx: &mut TestAppContext) {+ let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();+ let themes = scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap();+ let theme = load_theme(&[themes], "Dark Modern").unwrap();+ let dir = std::env::temp_dir().join(format!("code-gpui-editor-options-{}", std::process::id()));+ let _ = std::fs::remove_dir_all(&dir);+ std::fs::create_dir_all(dir.join("User")).unwrap();+ let settings = r#"{ "editor.renderWhitespace": "none", "editor.guides.indentation": false, "[plaintext]": { "editor.renderWhitespace": "all", "editor.guides.indentation": true } }"#;+ std::fs::write(dir.join("User/settings.json"), settings).unwrap();+ let file = dir.join("a.txt");+ std::fs::write(&file, "a\n").unwrap();+ let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), dir.join("User"), None)));+ let (workbench, cx) = cx.add_window_view(|window, cx| {+ let mut workbench = Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx);+ workbench.open_file(file.clone(), true, window, cx);+ workbench+ });+ cx.run_until_parked();+ workbench.read_with(cx, |workbench, _| {+ let editor = workbench.editors.active().unwrap();+ assert_eq!(editor.document().language_id, "plaintext");+ assert_eq!(workbench.editor_option(editor, &RENDER_WHITESPACE), "all");+ assert!(workbench.editor_option(editor, &GUIDES_INDENTATION));+ assert_eq!(workbench.global_editor_option(&RENDER_WHITESPACE), "none");+ });+ std::fs::remove_dir_all(dir).unwrap();+}diff --git a/native/crates/app/src/workbench/editor_status.rs b/native/crates/app/src/workbench/editor_status.rsindex dcdd50ae83b..74bb688534e 100644--- a/native/crates/app/src/workbench/editor_status.rs+++ b/native/crates/app/src/workbench/editor_status.rs@@ -19,6 +19,7 @@ use crate::editor::{Indentation, OpenEditor};use crate::languages::Languages;use crate::main_thread_quick_open::Owner;use crate::quick_input::{Entry, Event, Item, Kind, QuickInput};+use crate::workbench::editor_options::TAB_FOCUS_MODE;/// `changeEditorIndentation${targetWindowId}` of the main window, whose `vscodeWindowId` is 1.pub const CHANGE_INDENTATION: &str = "changeEditorIndentation1";@@ -555,7 +556,7 @@ impl Workbench {}fn tab_focus_configured(&self) -> bool {- self.setting("editor.tabFocusMode") == json!(true)+ self.global_editor_option(&TAB_FOCUS_MODE)}/// `TabFocus` as editorStatus.ts `TabFocusMode` drives it: `editor.tabFocusMode` at start and on each change ofdiff --git a/native/crates/app/src/workbench/editor_view.rs b/native/crates/app/src/workbench/editor_view.rsindex 88deabf9db1..f46b738fd19 100644--- a/native/crates/app/src/workbench/editor_view.rs+++ b/native/crates/app/src/workbench/editor_view.rs@@ -39,6 +39,7 @@ use super::minimap_view::minimap_info;use super::search_editor_view::SEARCH_EDITOR_SCHEME;use super::terminal_editor::TERMINAL_EDITOR_SCHEME;use super::webview_panels::WEBVIEW_PANEL_SCHEME;+use super::model_events::Cursor;use crate::brackets::BracketRange;use crate::editor::minimap::MinimapLayoutInfo;use crate::editor::{@@ -49,6 +50,7 @@ use crate::editor::folding::FoldDecoration;use crate::editor::whitespace::whitespace_marks;use crate::multi_diff_editor::MULTI_DIFF_EDITOR_SCHEME;use crate::theme::ThemeKind;+use crate::workbench::editor_options::{COLUMN_SELECTION, CURSOR_STYLE, DOUBLE_CLICK_SELECTS_BLOCK, GUIDES_BRACKET_PAIRS, GUIDES_BRACKET_PAIRS_HORIZONTAL, GUIDES_HIGHLIGHT_ACTIVE_BRACKET_PAIR, GUIDES_HIGHLIGHT_ACTIVE_INDENTATION, GUIDES_INDENTATION, MOUSE_WHEEL_ZOOM, MULTI_CURSOR_MODIFIER, OVERTYPE_CURSOR_STYLE, RENDER_CONTROL_CHARACTERS, RENDER_WHITESPACE, ROUNDED_SELECTION};pub(super) const EDITOR_FONT: &str = "Menlo";/// `editor.fontSize` at zoom level 0.@@ -1711,7 +1713,7 @@ impl Workbench {ScrollDelta::Pixels(delta) => (f32::from(delta.x) / 40., f32::from(delta.y) / 40.),ScrollDelta::Lines(delta) => (delta.x, delta.y),};- if self.setting("editor.mouseWheelZoom").as_bool().unwrap_or(false) {+ if self.global_editor_option(&MOUSE_WHEEL_ZOOM) {let modifiers = event.modifiers;let has_zoom_modifiers = (modifiers.platform || modifiers.control) && !modifiers.shift && !modifiers.alt;// ScrollDelta::Lines is AppKit's imprecise delta of a mouse wheel, `isPhysicalMouseWheel` upstream.@@ -1985,9 +1987,9 @@ impl Workbench {let unicode = self.unicode_highlights(editor).filter(|(_, highlights)| !highlights.has_more);let bracket_box = (self.theme.color("editorBracketMatch.background"), self.theme.color("editorBracketMatch.border"));// indentGuides.ts: the guide around the primary cursor with `editor.guides.highlightActiveIndentation`.- let highlight_active_indentation = self.language_setting(editor, "editor.guides.highlightActiveIndentation");+ let highlight_active_indentation = self.editor_option(editor, &GUIDES_HIGHLIGHT_ACTIVE_INDENTATION);let active_guide = (highlight_active_indentation != json!(false)).then(|| crate::editor::active_indent_guide(&editor.text_model().guides, editor.selections[0].head.line));- let indentation = self.language_setting(editor, "editor.guides.indentation") != json!(false);+ let indentation = self.editor_option(editor, &GUIDES_INDENTATION);let (guides_start, bracket_guides) = self.bracket_guides(editor, range.clone());// indentGuides.ts `_maxIndentLeft`: with word wrap no guide starts past the wrapping column.let max_indent_left = editor.word_wrap.options().map(|options| options.column as f32 * metrics.char_width);@@ -2016,7 +2018,7 @@ impl Workbench {// editorOptions.ts: overtype input mode draws `overtypeCursorStyle`, else `cursorStyle`; only block and line are drawn.let cursor_style = match (self.overtype, editor.cursor_style_override) {(false, Some(style)) => json!(style),- (overtype, _) => self.setting(if overtype { "editor.overtypeCursorStyle" } else { "editor.cursorStyle" }),+ (overtype, _) => json!(self.editor_option(editor, if overtype { &OVERTYPE_CURSOR_STYLE } else { &CURSOR_STYLE })),};let block_cursor = cursor_style == json!("block");let cursor_background = self.theme.color("editorCursor.background");@@ -2032,10 +2034,9 @@ impl Workbench {let fold_background = self.color("editor.foldBackground");let coverage = self.coverage_lines(&editor.document().uri(), editor.document().lines.len(), cx);let fold_placeholder = self.color("editor.foldPlaceholderForeground");- let rounded_selection = self.setting("editor.roundedSelection") != json!(false);- let render_whitespace = self.setting("editor.renderWhitespace");- let render_whitespace = render_whitespace.as_str().unwrap_or_default();- let render_control_characters = self.setting("editor.renderControlCharacters") != serde_json::Value::Bool(false);+ let rounded_selection = self.editor_option(editor, &ROUNDED_SELECTION);+ let render_whitespace = self.editor_option(editor, &RENDER_WHITESPACE);+ let render_control_characters = self.editor_option(editor, &RENDER_CONTROL_CHARACTERS);let whitespace_color = self.color("editorWhitespace.foreground");let line_height = metrics.line_height;// selections.css: high contrast themes square the corners.@@ -2550,7 +2551,8 @@ impl Workbench {let editor = self.editors.active_mut().expect("folding controls show only with an editor open");let before = (editor.selections.clone(), editor.folding.hidden().to_vec());if editor.click_fold_control(line, icon, modifiers.alt, middle || modifiers.shift) {- self.cursors_changed(before.0, Reveal::CenterIfOutside(Position::new(line, 0)), "mouse", cx);+ let moved = editor.selections != before.0;+ self.cursor_position_changed(Cursor { moved, source: "mouse", reveal: Reveal::CenterIfOutside(Position::new(line, 0)) }, cx);self.folds_changed(&before.1);}}@@ -2570,16 +2572,16 @@ impl Workbench {/// the first; none with `editor.guides.bracketPairs` false.fn bracket_guides(&self, editor: &OpenEditor, range: Range<usize>) -> (usize, Vec<Vec<crate::brackets::BracketGuide>>) {use crate::brackets::{BracketGuideOptions, HorizontalGuides};- let bracket_pairs = self.language_setting(editor, "editor.guides.bracketPairs");+ let bracket_pairs = self.editor_option(editor, &GUIDES_BRACKET_PAIRS);if bracket_pairs == json!(false) || range.is_empty() {return (0, Vec::new());}- let horizontal = match self.language_setting(editor, "editor.guides.bracketPairsHorizontal") {+ let horizontal = match self.editor_option(editor, &GUIDES_BRACKET_PAIRS_HORIZONTAL) {Value::Bool(true) => HorizontalGuides::Enabled,Value::String(value) if value == "active" => HorizontalGuides::EnabledForActive,_ => HorizontalGuides::Disabled,};- let options = BracketGuideOptions { include_inactive: bracket_pairs == json!(true), highlight_active: self.language_setting(editor, "editor.guides.highlightActiveBracketPair") != json!(false), horizontal };+ let options = BracketGuideOptions { include_inactive: bracket_pairs == json!(true), highlight_active: self.editor_option(editor, &GUIDES_HIGHLIGHT_ACTIVE_BRACKET_PAIR), horizontal };let document = editor.document();let start = editor.segment(range.start).line;// indentGuides.ts asks for one line past the visible ones.@@ -2727,8 +2729,8 @@ impl Workbench {/// too it selects a column. `visible` is the pointer's visible column (`mouseColumn`).#[allow(clippy::too_many_arguments)]fn dispatch_mouse(&mut self, position: Position, visible: f32, modifiers: gpui::Modifiers, select: bool, click_count: usize, reveal: bool, cx: &mut Context<Self>) {- let column_selection = self.setting("editor.columnSelection") == json!(true);- let selects_block = self.setting("editor.doubleClickSelectsBlock") != json!(false);+ let column_selection = self.global_editor_option(&COLUMN_SELECTION);+ let selects_block = self.global_editor_option(&DOUBLE_CLICK_SELECTS_BLOCK);let classifier = self.word_classifier(false).expect("text is clickable only with an editor open");// viewController.ts `_hasMulticursorModifier` and `_hasNonMulticursorModifier`; `ctrlCmd` is Cmd on macOS.let (multi_cursor, non_multi_cursor) = match self.multi_cursor_modifier_is_cmd() {@@ -2762,7 +2764,8 @@ impl Workbench {Reveal::Nothing}};- self.cursors_changed(before, if reveal { shown } else { Reveal::Nothing }, "mouse", cx);+ let moved = editor.selections != before;+ self.cursor_position_changed(Cursor { moved, source: "mouse", reveal: if reveal { shown } else { Reveal::Nothing } }, cx);return;}match click_count {@@ -2775,19 +2778,22 @@ impl Workbench {},_ if select && (column_selection || modifiers.alt) => {let shown = editor.column_select_to_pointer(line, mouse_column(visible), true);- self.cursors_changed(before, if reveal { shown } else { Reveal::Nothing }, "mouse", cx);+ let moved = editor.selections != before;+ self.cursor_position_changed(Cursor { moved, source: "mouse", reveal: if reveal { shown } else { Reveal::Nothing } }, cx);return;}_ if select => editor.move_to_select(position),_ => editor.move_to(position, false),}let moved = editor.selections != before;- self.editor_edited_revealing(None, moved, "mouse", reveal, cx);+ // `NavigationCommandRevealType.None` leaves the scroll.+ let reveal = if reveal { Reveal::All } else { Reveal::Nothing };+ self.cursor_position_changed(Cursor { moved, source: "mouse", reveal }, cx);}/// `editor.multiCursorModifier`: any value but `ctrlCmd` is Alt (editorOptions.ts `_multiCursorModifierFromString`).pub(super) fn multi_cursor_modifier_is_cmd(&self) -> bool {- self.setting("editor.multiCursorModifier") == "ctrlCmd"+ self.global_editor_option(&MULTI_CURSOR_MODIFIER) == "ctrlCmd"}/// The middle button selects a column (`editor.scrollOnMiddleClick` off): from the pointer, or with@@ -2796,7 +2802,8 @@ impl Workbench {let editor = self.editors.active_mut().expect("text is clickable only with an editor open");let before = editor.selections.clone();let reveal = editor.column_select_to_pointer(line, mouse_column(visible), extend);- self.cursors_changed(before, reveal, "mouse", cx);+ let moved = editor.selections != before;+ self.cursor_position_changed(Cursor { moved, source: "mouse", reveal }, cx);}/// Runs an editor command; false when its precondition does not hold.@@ -2808,33 +2815,12 @@ impl Workbench {let Some(reveal) = commands::run(editor, command, viewport) else {return false;};- self.cursors_changed(before, reveal, source, cx);+ let moved = editor.selections != before;+ self.cursor_position_changed(Cursor { moved, source, reveal }, cx);self.folds_changed(&hidden_before);true}- /// After a command that moves cursors only: scrolls to what it reveals and tells the host.- pub(super) fn cursors_changed(&mut self, before: Vec<Selection>, reveal: Reveal, source: &str, cx: &mut Context<Self>) {- let scrolled = self.scroll_smoothly(cx, |editor, viewport| match reveal {- Reveal::Nothing => {}- Reveal::All => editor.reveal_cursors(source, viewport),- Reveal::Position(position) => editor.reveal_position(position, source, viewport),- Reveal::CenterIfOutside(position) => editor.reveal_range(position, position, VerticalReveal::CenterIfOutsideViewport, viewport),- });- let moved = self.editors.active().expect("cursors change in the active editor").selections != before;- if moved {- self.record_navigation(Some(crate::navigation::Reason::of_source(source)));- self.output_cursor_moved();- self.find_editor_edited(None);- self.host.send_selection(self.editors.active().expect("still open"), source);- self.suggest_editor_changed(false, source, cx);- }- if scrolled {- self.editor_scrolled(cx);- }- cx.notify();- }-/// decorationsOverviewRuler.ts `_render`, in device pixels: word highlights, matched brackets and find matches in the center lane, the cursor/// across all lanes, then the 1px border on the left and top edges./// cellEditorOptions.ts and simpleEditorOptions.ts: no minimap and no overview ruler lanes in a cell or input editor.@@ -3022,7 +3008,7 @@ impl Workbench {pub(super) fn editor_status_items(&self, foreground: Rgba, window: &Window, cx: &mut Context<Self>) -> Vec<(bool, gpui::AnyElement)> {// editorStatus.ts `updateColumnSelectionModeElement`, `updateTabFocusModeElement` and `updateInputModeElement`: prominent entries.let mut items = Vec::new();- if self.editors.active().is_some() && self.setting("editor.columnSelection") == true {+ if self.editors.active().is_some() && self.global_editor_option(&COLUMN_SELECTION) {items.push(("Column Selection".to_string(), "Disable Column Selection Mode", "editor.action.toggleColumnSelection", "status.editor.columnSelectionMode"));}if self.tab_focus_mode() {diff --git a/native/crates/app/src/workbench/editor_view/cursor_blink.rs b/native/crates/app/src/workbench/editor_view/cursor_blink.rsindex 85d24baf2cc..4e19512e8d4 100644--- a/native/crates/app/src/workbench/editor_view/cursor_blink.rs+++ b/native/crates/app/src/workbench/editor_view/cursor_blink.rs@@ -6,6 +6,7 @@ use gpui::{App, Context, EntityId, Task, Window};use super::super::Workbench;use crate::editor::{OpenEditor, Selection};+use crate::workbench::editor_options::CURSOR_BLINKING;/// viewCursors.ts `BLINK_INTERVAL`.const BLINK_INTERVAL: Duration = Duration::from_millis(500);@@ -101,11 +102,11 @@ impl Workbench {/// cursors last changed (`_startCursorBlinkAnimation`); "solid" and a read-only editor keep them.pub(in crate::workbench) fn focused_cursor_look(&self, editor: &OpenEditor, layout: Layout, window: &mut Window, cx: &mut Context<Self>) -> Option<CursorLook> {let mut blink = self.cursor_blink.borrow_mut();- let style = match self.language_setting(editor, "editor.cursorBlinking").as_str() {- Some("blink") => Some(Style::Blink),- Some("smooth") => Some(Style::Smooth),- Some("phase") => Some(Style::Phase),- Some("expand") => Some(Style::Expand),+ let style = match self.editor_option(editor, &CURSOR_BLINKING) {+ "blink" => Some(Style::Blink),+ "smooth" => Some(Style::Smooth),+ "phase" => Some(Style::Phase),+ "expand" => Some(Style::Expand),_ => None,};// A screenshot draws the cursor as ref-screenshot's `editor.cursorBlinking: solid` does.diff --git a/native/crates/app/src/workbench/editor_view/diff_editor_view.rs b/native/crates/app/src/workbench/editor_view/diff_editor_view.rsindex 4366c189f0d..da380be91fa 100644--- a/native/crates/app/src/workbench/editor_view/diff_editor_view.rs+++ b/native/crates/app/src/workbench/editor_view/diff_editor_view.rs@@ -382,7 +382,7 @@ impl Workbench {/// mainThreadDocumentDiff.ts `$computeDocumentDiff`: the advanced diff of two open models, null when either is/// not open (editorWorker.ts `computeDiff` finds no model).- pub(in crate::workbench) fn compute_document_diff(&self, original: &Value, modified: &Value, ignore_trim_whitespace: bool, max_computation_time_ms: u64, compute_moves: bool) -> Value {+ pub(crate) fn compute_document_diff(&self, original: &Value, modified: &Value, ignore_trim_whitespace: bool, max_computation_time_ms: u64, compute_moves: bool) -> Value {let model = |uri: &Value| uri_parts(uri).ok().and_then(|(scheme, path)| self.editors.model(scheme, &path));let (Some(original), Some(modified)) = (model(original), model(modified)) else { return Value::Null };let (original, modified) = (&original.document().lines, &modified.document().lines);diff --git a/native/crates/app/src/workbench/editor_view/diff_editor_view/tests.rs b/native/crates/app/src/workbench/editor_view/diff_editor_view/tests.rsindex 711b6e9c7a6..2ab74fb3690 100644--- a/native/crates/app/src/workbench/editor_view/diff_editor_view/tests.rs+++ b/native/crates/app/src/workbench/editor_view/diff_editor_view/tests.rs@@ -104,12 +104,12 @@ fn compute_document_diff_answers_with_line_ranges_and_inner_changes(cx: &mut Teslet (dir, workbench, _receiver, cx) = workbench_in("diff-document", cx);let (a, b) = (file_uri(&dir.join("a.txt")), file_uri(&dir.join("b.txt")));// Without models the editor worker has nothing to diff.- let missing = workbench.update_in(cx, |workbench, window, cx| workbench.host_request("MainThreadDocumentDiff", "$computeDocumentDiff", &[a.clone(), b.clone(), json!(false), json!(0), json!(false)], window, cx));+ let missing = workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadDocumentDiff", "$computeDocumentDiff", &[a.clone(), b.clone(), json!(false), json!(0), json!(false)], window, cx));assert_eq!(missing, Ok(Value::Null));for uri in [&a, &b] {- workbench.update_in(cx, |workbench, window, cx| workbench.host_request("MainThreadDocuments", "$tryOpenDocument", &[uri.clone()], window, cx)).unwrap();+ workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadDocuments", "$tryOpenDocument", &[uri.clone()], window, cx)).unwrap();}- let result = workbench.update_in(cx, |workbench, window, cx| workbench.host_request("MainThreadDocumentDiff", "$computeDocumentDiff", &[a, b, json!(false), json!(0), json!(false)], window, cx)).unwrap();+ let result = workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadDocumentDiff", "$computeDocumentDiff", &[a, b, json!(false), json!(0), json!(false)], window, cx)).unwrap();assert_eq!(result["identical"], false);assert_eq!(result["changes"][0]["originalRange"], json!({ "startLineNumber": 2, "startColumn": 1, "endLineNumber": 3, "endColumn": 1 }));assert_eq!(result["changes"][0]["innerChanges"][0]["modifiedRange"], json!({ "startLineNumber": 2, "startColumn": 1, "endLineNumber": 2, "endColumn": 4 }));diff --git a/native/crates/app/src/workbench/editor_view/diff_gutter.rs b/native/crates/app/src/workbench/editor_view/diff_gutter.rsindex 98226eb1fca..63e0653b34d 100644--- a/native/crates/app/src/workbench/editor_view/diff_gutter.rs+++ b/native/crates/app/src/workbench/editor_view/diff_gutter.rs@@ -263,7 +263,7 @@ impl Workbench {let change = model.execute_edits(edits, None, EditReason::Unknown("revert"));model.push_undo_stop();if let Some(change) = change {- self.send_model_edit(scheme, path, &change, cx);+ self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);}cx.notify();crate::commands::Outcome::done()diff --git a/native/crates/app/src/workbench/editor_view/drag_and_drop.rs b/native/crates/app/src/workbench/editor_view/drag_and_drop.rsindex 8f4132a48c7..63469d9d4c1 100644--- a/native/crates/app/src/workbench/editor_view/drag_and_drop.rs+++ b/native/crates/app/src/workbench/editor_view/drag_and_drop.rs@@ -4,6 +4,9 @@use gpui::{Context, CursorStyle, Div, Modifiers, Rgba, div, prelude::*, px, rgb};use super::Workbench;+use crate::workbench::editor_options::{COLUMN_SELECTION, DRAG_AND_DROP};+use crate::workbench::model_events::Cursor;+use crate::editor::Reveal;use crate::editor::{Position, Selection, column_at_visible, drag_and_drop, column_x};use crate::theme::ThemeKind;@@ -27,7 +30,7 @@ impl Workbench {let on_text = visible < column_x(text, text.chars().count(), tab_size);let position = Position::new(line, column_at_visible(text, visible, tab_size));let primary = editor.selection();- let enabled = self.setting("editor.dragAndDrop") == true && self.setting("editor.columnSelection") != true && self.active_editor_readonly().is_none();+ let enabled = self.editor_option(editor, &DRAG_AND_DROP) && !self.editor_option(editor, &COLUMN_SELECTION) && self.active_editor_readonly().is_none();if !(enabled && !modifiers.alt && click_count < 2 && on_text && !primary.is_empty() && drag_and_drop::contains(primary, position)) {return false;}@@ -68,7 +71,7 @@ impl Workbench {}};let moved = editor.selections != before;- self.editor_edited(change, moved, "mouse", cx);+ self.model_content_changed(change, Cursor { moved, source: "mouse", reveal: Reveal::All }, cx);}/// `_onEditorMouseDropCanceled`: a key press or the release away from the text ends the drag without a drop.diff --git a/native/crates/app/src/workbench/editor_view/merge_editor_view.rs b/native/crates/app/src/workbench/editor_view/merge_editor_view.rsindex 4a983275d06..758ba3c989e 100644--- a/native/crates/app/src/workbench/editor_view/merge_editor_view.rs+++ b/native/crates/app/src/workbench/editor_view/merge_editor_view.rs@@ -18,6 +18,7 @@ use crate::editor::{EditReason, OpenEditor, Position, TextDocument, VerticalReveuse crate::menus::MenuAction;use crate::merge_editor::{DocumentRangeMap, Input, InputData, LAYOUT_KEY, Layout, LineEdit, MERGE_EDITOR_SCHEME, MergeInput, MergeModel, SHOW_NON_CONFLICTING_KEY, State, ViewZones, Zone, ZoneKind, ZoneOptions, text_edit, text_of};use crate::quick_input::{Entry, Item, Kind, QuickInput};+use crate::workbench::editor_options::FONT_SIZE;use crate::workbench::host_requests::uri_parts;use crate::workbench::hover::{HoverContent, HoverOptions};@@ -764,7 +765,7 @@ impl Workbench {/// conflictActions.ts `_getLayoutInfo`: 90% of the editor font size.fn merge_code_lens_font_size(&self) -> f32 {- let font_size = self.setting("editor.fontSize").as_f64().unwrap_or(12.) as f32 * self.editor_zoom.multiplier();+ let font_size = self.global_editor_option(&FONT_SIZE) * self.editor_zoom.multiplier();(font_size * 0.9).floor()}diff --git a/native/crates/app/src/workbench/editor_view/quick_diff.rs b/native/crates/app/src/workbench/editor_view/quick_diff.rsindex 44e09cffe37..e102a742d22 100644--- a/native/crates/app/src/workbench/editor_view/quick_diff.rs+++ b/native/crates/app/src/workbench/editor_view/quick_diff.rs@@ -374,7 +374,7 @@ impl Workbench {/// mainThreadEditors.ts `$getDiffInformation`: a diff editor side's `getLineChanges`, else the primary quick diff's/// changes of the editor's file, as `IChange`s.- pub(in crate::workbench) fn editor_line_changes(&self, id: &str) -> Result<Value, Value> {+ pub(crate) fn editor_line_changes(&self, id: &str) -> Result<Value, Value> {let Some(editor) = self.visible_code_editors().find(|editor| crate::host_sync::snapshot_id(editor) == id) else {// A cell or the Output view: a code editor without a text file's quick diff.return match self.host.editor_ids().iter().any(|known| known == id) {diff --git a/native/crates/app/src/workbench/editor_view/quick_diff_widget.rs b/native/crates/app/src/workbench/editor_view/quick_diff_widget.rsindex 634d1912921..2baaf7db2e5 100644--- a/native/crates/app/src/workbench/editor_view/quick_diff_widget.rs+++ b/native/crates/app/src/workbench/editor_view/quick_diff_widget.rs@@ -6,6 +6,8 @@ use serde_json::{Value, json};use super::quick_diff::{ChangeKind, QuickDiffChange};use super::{EditorMetrics, LineNumbers, Workbench};+use crate::editor::Reveal;+use crate::workbench::model_events::Cursor;use crate::commands::Outcome;use crate::editor::{OpenEditor, PeekOwner, Position, Selection, VERTICAL_SCROLLBAR_WIDTH, VerticalReveal, Viewport, column_x};use crate::menus::{MenuAction, MenuId};@@ -201,7 +203,7 @@ impl Workbench {let position = Position::new(changes[index].start.max(1) - 1, 0);editor.set_selections(vec![Selection::caret(position)]);editor.reveal_range(position, position, VerticalReveal::Center, viewport);- self.host.send_selection(editor, "api");+ self.cursor_position_changed(Cursor { moved: true, source: "api", reveal: Reveal::Nothing }, cx);self.editor_scrolled(cx);window.focus(&self.editor_focus, cx);cx.notify();@@ -250,7 +252,7 @@ impl Workbench {editor.set_selections(vec![Selection::caret(position)]);let below = Position::new((position.line + 1).min(editor.document().lines.len() - 1), 0);editor.reveal_range(below, below, VerticalReveal::CenterIfOutsideViewport, viewport);- self.host.send_selection(editor, "api");+ self.cursor_position_changed(Cursor { moved: true, source: "api", reveal: Reveal::Nothing }, cx);self.editor_scrolled(cx);}cx.notify();@@ -330,7 +332,7 @@ impl Workbench {/// `QuickDiffEditorController.close`.pub(in crate::workbench) fn close_quick_diff(&mut self, cx: &mut Context<Self>) {let Some(widget) = self.quick_diffs.widget.take() else { return };- if let Some(editor) = self.editors.editors.iter_mut().find(|editor| editor.model_id == widget.model_id) {+ if let Some(editor) = self.editors.all_tabs_mut().find(|editor| editor.model_id == widget.model_id) {editor.remove_view_zone(widget.zone_id);}self.drop_peek_editor(PeekOwner::QuickDiff);@@ -765,4 +767,19 @@ mod tests {run("closeQuickDiff", cx);assert!(workbench.read_with(cx, |workbench, _| workbench.editors.peek_editor(PeekOwner::QuickDiff).is_none()));}++ /// zoneWidget.ts `ZoneWidget.dispose` removes the zone from its own editor: the peek closed after its editor moved+ /// to another group leaves no empty zone behind.+ #[gpui::test]+ fn closing_the_quick_diff_in_another_group_removes_its_zone(cx: &mut gpui::TestAppContext) {+ let originals = [("", "one\ntwo\nthree", QuickDiffKind::Primary, "git.quickDiffProvider")];+ let (workbench, cx) = quick_diff_window(cx, "other-group", "one\nTWO\nthree", &originals);+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("editor.action.dirtydiff.next", Vec::new(), window, cx)));+ cx.run_until_parked();+ let zones = |workbench: &Workbench| workbench.editors.all_tabs().find(|editor| editor.document().scheme == "file").unwrap().view_zones.len();+ assert_eq!(workbench.read_with(cx, |workbench, _| zones(workbench)), 1, "the peek's zone");+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ workbench.update(cx, |workbench, cx| workbench.close_quick_diff(cx));+ assert_eq!(workbench.read_with(cx, |workbench, _| zones(workbench)), 0);+ }}diff --git a/native/crates/app/src/workbench/editor_view/sticky_scroll_view.rs b/native/crates/app/src/workbench/editor_view/sticky_scroll_view.rsindex 7f7e94b8334..8d50c5ae6d0 100644--- a/native/crates/app/src/workbench/editor_view/sticky_scroll_view.rs+++ b/native/crates/app/src/workbench/editor_view/sticky_scroll_view.rs@@ -7,6 +7,8 @@ use gpui::{BoxShadow, ClickEvent, Context, Div, FocusHandle, HighlightStyle, Moduse serde_json::json;use super::{DECORATIONS_WIDTH, EditorMetrics, FoldControls, Workbench};+use crate::workbench::editor_options::{STICKY_SCROLL_ENABLED, STICKY_SCROLL_MAX_LINE_COUNT, STICKY_SCROLL_SCROLL_WITH_EDITOR};+use crate::workbench::model_events::Cursor;use crate::commands::Outcome;use super::super::goto_symbol::DEFINITION;use crate::editor::{OpenEditor, Position, Reveal, Selection, VERTICAL_SCROLLBAR_WIDTH, expand_tabs, utf16_column, column_x};@@ -55,10 +57,10 @@ struct StickyLine {impl Workbench {/// `editor.stickyScroll.maxLineCount` (1 to 20) with sticky scroll on, else 0.pub(super) fn sticky_scroll_lines(&self) -> usize {- if self.setting(ENABLED) != json!(true) {+ if !self.global_editor_option(&STICKY_SCROLL_ENABLED) {return 0;}- self.setting("editor.stickyScroll.maxLineCount").as_u64().map_or(5, |count| count.clamp(1, 20) as usize)+ self.global_editor_option(&STICKY_SCROLL_MAX_LINE_COUNT)}/// `_findRenderingData`: the lines the widget shows, with the one under Shift showing its scope's end, and@@ -98,7 +100,7 @@ impl Workbench {}let fold_icon_opacity = self.sticky_scroll.fold_icons.opacity(now);let focused_index = self.sticky_scroll.is_focused(window).then_some(self.sticky_scroll.focused_index);- let scroll_left = if self.setting("editor.stickyScroll.scrollWithEditor") == json!(false) { 0. } else { editor.scroll.left };+ let scroll_left = if !self.editor_option(editor, &STICKY_SCROLL_SCROLL_WITH_EDITOR) { 0. } else { editor.scroll.left };let gutter = self.color("editorStickyScrollGutter.background");let background = self.color("editorStickyScroll.background");let hover = self.color("editorStickyScrollHover.background");@@ -368,7 +370,8 @@ impl Workbench {let editor = self.editors.active_mut().expect("sticky lines show only with an editor open");let before = (editor.selections.clone(), editor.folding.hidden().to_vec());if editor.toggle_sticky_fold(line, index, viewport) {- self.cursors_changed(before.0, Reveal::Nothing, "api", cx);+ let moved = editor.selections != before.0;+ self.cursor_position_changed(Cursor { moved, source: "api", reveal: Reveal::Nothing }, cx);self.folds_changed(&before.1);self.editor_scrolled(cx);}@@ -379,7 +382,8 @@ impl Workbench {let editor = self.editors.active_mut().expect("sticky lines show only with an editor open");let before = editor.selections.clone();editor.set_selections(vec![Selection::caret(position)]);- self.cursors_changed(before, reveal, "api", cx);+ let moved = editor.selections != before;+ self.cursor_position_changed(Cursor { moved, source: "api", reveal }, cx);window.focus(&self.editor_focus, cx);}diff --git a/native/crates/app/src/workbench/exception_widget.rs b/native/crates/app/src/workbench/exception_widget.rsindex 6955f1cb1ff..8ae1f160cb8 100644--- a/native/crates/app/src/workbench/exception_widget.rs+++ b/native/crates/app/src/workbench/exception_widget.rs@@ -46,7 +46,7 @@ impl Workbench {.detach();}- fn show_exception_widget(&mut self, path: &str, line: u32, info: Value, cx: &mut Context<Self>) {+ pub(super) fn show_exception_widget(&mut self, path: &str, line: u32, info: Value, cx: &mut Context<Self>) {self.close_exception_widget(cx);let viewport = self.editors.viewport;let Some(editor) = self.editors.editors.iter_mut().find(|editor| editor.document().scheme == "file" && editor.document().path.to_string_lossy() == path) else { return };@@ -60,7 +60,7 @@ impl Workbench {pub(super) fn close_exception_widget(&mut self, cx: &mut Context<Self>) {let Some(widget) = self.debug_view.exception.take() else { return };- if let Some(editor) = self.editors.editors.iter_mut().find(|editor| editor.document().uri_string() == widget.model_uri) {+ if let Some(editor) = self.editors.all_tabs_mut().find(|editor| editor.document().uri_string() == widget.model_uri) {editor.remove_view_zone(widget.zone_id);}cx.notify();diff --git a/native/crates/app/src/workbench/explorer_actions.rs b/native/crates/app/src/workbench/explorer_actions.rsindex b7e1fef97d9..a8fa751184a 100644--- a/native/crates/app/src/workbench/explorer_actions.rs+++ b/native/crates/app/src/workbench/explorer_actions.rs@@ -1302,7 +1302,7 @@ async fn delete_files(workbench: WeakEntity<Workbench>, cx: &mut AsyncWindowContloop {let primary = if use_trash { "Move to Trash" } else { "Delete" };let Ok((dirty, confirm_delete)) = workbench.update(cx, |workbench, _| {- let dirty = workbench.editors.editors.iter().filter(|editor| editor.is_dirty() && items.iter().any(|item| editor.document().path.starts_with(item))).count();+ let dirty = workbench.editors.all_editors().filter(|editor| editor.is_dirty() && items.iter().any(|item| editor.document().path.starts_with(item))).count();(dirty, workbench.setting("explorer.confirmDelete") != json!(false))}) else {return;diff --git a/native/crates/app/src/workbench/explorer_actions/tests.rs b/native/crates/app/src/workbench/explorer_actions/tests.rsindex 8a222ecc1dd..16474c86a8a 100644--- a/native/crates/app/src/workbench/explorer_actions/tests.rs+++ b/native/crates/app/src/workbench/explorer_actions/tests.rs@@ -416,6 +416,30 @@ fn a_delete_confirmation_follows_the_dialog_style(cx: &mut TestAppContext) {std::fs::remove_dir_all(&dir).unwrap();}+/// fileActions.ts `deleteFiles` asks `workingCopyFileService.getDirty(resource)`, which no group limits: a file dirty+/// only in another group gets the unsaved changes warning.+#[gpui::test]+fn deleting_a_file_dirty_in_another_group_warns_of_unsaved_changes(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = explorer("delete-dirty-other-group", cx);+ let user = std::env::temp_dir().join(format!("code-gpui-delete-dirty-other-group-user-{}", std::process::id()));+ std::fs::create_dir_all(&user).unwrap();+ std::fs::write(user.join("settings.json"), r#"{ "window.dialogStyle": "custom" }"#).unwrap();+ workbench.update_in(cx, |workbench, window, cx| {+ workbench.skip_dialogs = false;+ workbench.settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), user.clone(), None)));+ workbench.open_file(dir.join("a.txt"), true, window, cx);+ drop(workbench.execute_command("type", vec![json!({ "text": "x" })], window, cx));+ });+ cx.run_until_parked();+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ select(&workbench, &dir.join("a.txt"), cx);+ run(&workbench, "deleteFile", cx);+ let shown = workbench.read_with(cx, |workbench, _| workbench.dialogs.first().map(|shown| shown.dialog.message.clone()));+ assert_eq!(shown.as_deref(), Some("You are deleting a.txt with unsaved changes. Do you want to continue?"));+ std::fs::remove_dir_all(user).unwrap();+ std::fs::remove_dir_all(&dir).unwrap();+}+/// explorerViewer.ts `handleExternalDrop`: a folder dropped on a workspace folder can be added to the workspace.#[gpui::test]fn a_folder_dropped_on_the_root_is_added_to_the_workspace(cx: &mut TestAppContext) {diff --git a/native/crates/app/src/workbench/extension_host_restart.rs b/native/crates/app/src/workbench/extension_host_restart.rsindex 49b59cf75ef..4454e11815d 100644--- a/native/crates/app/src/workbench/extension_host_restart.rs+++ b/native/crates/app/src/workbench/extension_host_restart.rs@@ -2,27 +2,22 @@//! `startExtensionHosts`): the host is told to terminate, what it registered in the workbench is disposed as each//! MainThread* `dispose` does, and a new host starts with the window's current extensions, settings and storage.-use std::sync::Arc;-use std::sync::atomic::AtomicBool;-use std::sync::mpsc::channel;-use config::configuration::Overrides;+use exthost::WakingSender;use exthost::extension_development::ExtensionDevelopment;-use exthost::extension_management::{WindowExtensions, add_user_extensions};-use exthost::main_thread_storage::MainThreadStorage;+use exthost::extension_management::add_user_extensions;use exthost::scan::ScannedExtension;use exthost::session::ForwardedRequest;-use exthost::{Inbox, Runtime, WakingSender};use futures::StreamExt;-use futures::channel::mpsc::{UnboundedReceiver, unbounded};+use futures::channel::mpsc::UnboundedReceiver;use gpui::{App, Context, PromptLevel, Task, Window};-use serde_json::{Value, json};+use serde_json::Value;use super::Workbench;use super::host_requests::uri_parts;use crate::commands::Outcome;-use crate::host_sync::HostSync;-use crate::main_thread::{HostRequest, WorkbenchMainThread};+use crate::extension_host_start::HostStart;+use crate::main_thread::HostRequest;use crate::markers::ReadOptions;@@ -98,8 +93,8 @@ impl Workbench {/// `startExtensionHosts`: a new host with the window's extensions to run.pub(super) fn start_extension_hosts(&mut self, window: &mut Window, cx: &mut Context<Self>) {let extensions = self.extensions_to_run();- self.set_running_extensions_after_restart(extensions.clone(), cx);- self.start_extension_host(extensions, window, cx);+ self.set_running_extensions_after_restart(extensions, cx);+ self.start_extension_host(window, cx);}pub(super) fn stop_extension_host(&mut self, cx: &mut Context<Self>) {@@ -167,73 +162,21 @@ impl Workbench {self.configuration_changed(&change, before, cx);}- /// The channels, session thread and workbench loops of a new host, as main.rs starts the first one.- fn start_extension_host(&mut self, extensions: Vec<ScannedExtension>, window: &mut Window, cx: &mut Context<Self>) {- // A host process needs bun and a built app root, and its threads would wake the test scheduler.- if cfg!(test) {+ /// A new host for the window's running extensions; the old one's documents, editors and tabs are sent again.+ fn start_extension_host(&mut self, window: &mut Window, cx: &mut Context<Self>) {+ let Some(launch) = self.host_launch.clone() else {self.extension_host_started(cx);return;- }- let (status, mut status_lines) = unbounded::<String>();- let (host_sender, host_receiver) = channel();- let (request_sender, requests) = unbounded::<ForwardedRequest>();- let (reply_sender, replies) = channel();- let inbox = Inbox::default();- let reply_sender = WakingSender::new(reply_sender, inbox.waker());- let (main_thread_sender, main_thread_requests) = unbounded::<HostRequest>();- let user = self.extensions_viewlet.user.as_ref().expect("the user extensions are set at startup").clone_for_profile();- let window_extensions = WindowExtensions { builtins: self.extensions_viewlet.builtins.clone(), user, running: extensions.clone(), proposed_api: self.proposed_api.clone() };- let main_thread = WorkbenchMainThread { requests: main_thread_sender, messages: host_receiver, waiting: Vec::new(), content_providers: Default::default(), extensions: window_extensions };- let mut host = HostSync::new(WakingSender::new(host_sender, inbox.waker()));+ };+ let (start, mut host) = HostStart::new(self.theme.kind, &self.languages);host.configuration_scopes = self.host.configuration_scopes;host.untitled_names_from_content = self.host.untitled_names_from_content;host.search_tabs = std::mem::take(&mut self.host.search_tabs);host.terminal_tabs = std::mem::take(&mut self.host.terminal_tabs);- host.send_color_theme(self.theme.kind);- host.send_language_ids(&self.languages);self.host = host;self.send_host_changes();-- let runtime = if std::env::args().any(|arg| arg == "--node") { Runtime::Node } else { Runtime::Bun };- let app_root = self.app_root.clone();- let settings = self.settings.clone();- let user_data = settings.lock().unwrap().user_home().parent().expect("the user home is <user data>/User").to_path_buf();- let storage = MainThreadStorage { profile: self.profile_storage.clone(), workspace: self.workspace_storage.clone() };- let trusted = self.workspace_trust.is_trusted();- let workspace = self.workspace().cloned();- let window_closed = Arc::new(AtomicBool::new(false));- let (session_ended, ended) = futures::channel::oneshot::channel::<()>();- self.watch_session_end(window_closed.clone(), inbox.waker(), ended, cx);let development = self.development_without_tests();- let host_debug = self.extension_host_debug.clone();- let start = self.extension_host_started(cx);- std::thread::Builder::new()- .name("exthost-session".into())- .spawn(move || {- let started = crate::run_extension_host(runtime, app_root, extensions, settings, storage, trusted, user_data, workspace, development, host_debug, main_thread, request_sender, replies, inbox, &status, &window_closed);- if let Err(error) = started {- let _ = status.unbounded_send(format!("extension host failed: {error:#}"));- }- let _ = session_ended.send(());- })- .expect("spawn exthost session thread");- serve_host_requests(requests, reply_sender, window, cx);- serve_main_thread_requests(main_thread_requests, window, cx);- cx.spawn_in(window, async move |workbench, cx| {- while let Some(line) = status_lines.next().await {- eprintln!("{line}");- if line == crate::EXITED_LINE {- let _ = workbench.update_in(cx, |workbench, window, cx| workbench.extension_host_exited(start, window, cx));- }- if line.starts_with(crate::HANDSHAKE_PREFIX) {- let _ = workbench.update(cx, |workbench, _| {- workbench.host.installed_extensions_registered = true;- workbench.store_custom_editors_memento();- });- }- }- })- .detach();+ drop(self.spawn_extension_host(start, launch, development, window, cx));}}@@ -296,19 +239,16 @@ pub fn serve_host_requests(mut requests: UnboundedReceiver<ForwardedRequest>, repub fn serve_main_thread_requests(mut requests: UnboundedReceiver<HostRequest>, window: &mut Window, cx: &mut Context<Workbench>) {cx.spawn_in(window, async move |workbench, cx| {while let Some(request) = requests.next().await {- // The host awaits a save through its dialogs; the session pumps meanwhile (main_thread.rs `ask_while_pumping`).- if (request.proxy.as_str(), request.method.as_str()) == ("MainThreadDocuments", "$trySaveDocument") {- let saved = workbench.update(cx, |workbench, cx| workbench.try_save_document(&request.args[0], cx));- let result = match saved {- Ok(Ok(saved)) => Ok(json!(saved.await == Ok(true))),- Ok(Err(error)) => Err(error),- Err(_) => Err(exthost::main_thread::serialized_error("Canceled")),- };- let _ = request.reply.send(result);- continue;- }- let result = workbench.update_in(cx, |workbench, window, cx| workbench.host_request(&request.proxy, &request.method, &request.args, window, cx));- let _ = request.reply.send(result.unwrap_or_else(|_| Err(exthost::main_thread::serialized_error("Canceled"))));+ let HostRequest { proxy, method, args, reply } = request;+ // A blocking call's answer goes back through `reply`, never by its `req`.+ let request = ForwardedRequest { req: 0, proxy, method, args };+ let result = match workbench.update_in(cx, |workbench, window, cx| workbench.handle_host_request(request, window, cx)) {+ Ok(Outcome::Ready(result)) => result,+ // A save waits on its dialogs; the session pumps meanwhile (main_thread.rs `ask_while_pumping`).+ Ok(Outcome::Pending(pending)) => pending.await.unwrap_or_else(|_| Err(exthost::main_thread::serialized_error("Canceled"))),+ Err(_) => Err(exthost::main_thread::serialized_error("Canceled")),+ };+ let _ = reply.send(result);}}).detach();diff --git a/native/crates/app/src/workbench/extension_host_restart/tests.rs b/native/crates/app/src/workbench/extension_host_restart/tests.rsindex 17647545f5e..423a0024ecd 100644--- a/native/crates/app/src/workbench/extension_host_restart/tests.rs+++ b/native/crates/app/src/workbench/extension_host_restart/tests.rs@@ -5,6 +5,7 @@ use exthost::scan::{ScannedExtension, scan_extension};use gpui::TestAppContext;use serde_json::json;+use crate::extension_host_start::{HostLaunch, HostProcess};use crate::host_sync::HostSync;use crate::languages::Languages;use crate::theme::load_theme;@@ -56,6 +57,32 @@ fn a_host_restart_gives_the_extensions_the_proposals_its_window_allows(cx: &mutassert_eq!(running[0].description["enabledApiProposals"], json!(["activeComment"]));}+/// abstractExtensionService.ts `_startExtensionHostsIfNecessary`: a restarted host starts as the window's first one,+/// with the window's user data folder (main.rs `--user-data-dir`), not one derived again from the settings path.+#[gpui::test]+fn a_host_restart_starts_the_host_as_the_window_did(cx: &mut TestAppContext) {+ // The exthost-session thread wakes the window's status loop.+ cx.executor().allow_parking();+ let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();+ let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();+ let dir = std::env::temp_dir().join(format!("vsrustium-restart-start-{}", std::process::id()));+ let settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), dir.join("settings/User"), None)));+ let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx));+ let (opened, host_opened) = std::sync::mpsc::channel();+ let user_data = dir.join("user-data");+ workbench.update(cx, |workbench, _| {+ workbench.extensions_viewlet.user = Some(exthost::extension_management::UserExtensions::new(dir.join("extensions"), "1.148.0"));+ workbench.host_launch = Some(HostLaunch { process: HostProcess::Silent(opened), user_data: user_data.clone() });+ });+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.restartExtensionHost", Vec::new(), window, cx)));+ cx.run_until_parked();+ let (init, peer) = host_opened.recv_timeout(std::time::Duration::from_secs(10)).expect("the restart starts a host");+ drop(peer);+ assert_eq!(init["environment"]["globalStorageHome"], exthost::scan::file_uri(&user_data.join("User/globalStorage")));+ assert_eq!(workbench.read_with(cx, |workbench, _| workbench.extension_host_starts), 1);+ let _ = std::fs::remove_dir_all(dir);+}+/// abstractExtensionService.ts `_doStopExtensionHostsWithVeto`: a running debug session (debugService.ts `onWillStop`)/// vetoes Restart Extension Host; Cancel keeps the host, Restart Anyway stops and starts it.#[gpui::test]diff --git a/native/crates/app/src/workbench/find_widget.rs b/native/crates/app/src/workbench/find_widget.rsindex 214cc7215b8..f9d205afcfb 100644--- a/native/crates/app/src/workbench/find_widget.rs+++ b/native/crates/app/src/workbench/find_widget.rs@@ -25,6 +25,7 @@ use crate::input_box::InputBox;use crate::main_thread_quick_open::Owner;use crate::quick_input::{Event, Kind, QuickInput};use crate::theme::ThemeKind;+use crate::workbench::editor_options::{FIND_ADD_EXTRA_SPACE_ON_TOP, FIND_AUTO_FIND_IN_SELECTION, FIND_CURSOR_MOVE_ON_TYPE, FIND_FIND_ON_TYPE, FIND_GLOBAL_FIND_CLIPBOARD, FIND_LOOP, FIND_SEED_SEARCH_STRING_FROM_SELECTION, SELECTED_TEXT_MATCH_MODE, SELECTION_HIGHLIGHT, SELECTION_HIGHLIGHT_MAX_LENGTH, SELECTION_HIGHLIGHT_MULTILINE};const FIND_WIDGET_INITIAL_WIDTH: f32 = 419.;/// `new HistoryNavigator<string>(options.history, 100)` of `HistoryInputBox`.@@ -65,6 +66,8 @@ pub struct FindWidget {/// The model's version the matches were last found or updated in; an edit in another code editor of the model/// finds them again (`FindModelBoundToEditorModel` listens to the model's content changes).version_id: u32,+ /// findModel.ts `_ignoreModelContentChanged`: the find's own edits and selections are no outside change.+ ignore_own_change: bool,/// The width the sash set (`_resized`).resized_width: Option<f32>,/// The widget width and pointer x when a sash drag started.@@ -116,6 +119,7 @@ impl FindWidget {button_focus,model_id: None,version_id: 0,+ ignore_own_change: false,resized_width: None,sash_drag: None,sash_hover: None,@@ -319,16 +323,10 @@ impl Workbench {let moved = self.editors.active().expect("checked above").selections != selections;// findModel.ts reveals matches with `ScrollType.Smooth`.let scrolled = self.animate_scroll_from(scroll, cx) || self.editors.viewport.top_whitespace != top_whitespace;- let editor = self.editors.active().expect("checked above");- self.find.version_id = editor.text_model().version_id;- match &change {- Some(change) => {- self.host.send_content_change(&self.editors, editor, change);- self.host.send_visible_ranges(&self.editors);- }- None if moved => self.host.send_selection(editor, "api"),- None => {}- }+ self.find.version_id = self.editors.active().expect("checked above").text_model().version_id;+ self.find.ignore_own_change = true;+ self.model_content_changed(change, crate::workbench::model_events::Cursor { moved, source: "api", reveal: crate::editor::Reveal::Nothing }, cx);+ self.find.ignore_own_change = false;if scrolled {self.editor_scrolled(cx);}@@ -503,19 +501,19 @@ impl Workbench {/// `editor.find` settings the controller reads.fn find_options(&self) -> FindOptions {- let seed = match self.setting("editor.find.seedSearchStringFromSelection") {- Value::String(seed) if seed == "never" => SeedFromSelection::Never,- Value::String(seed) if seed == "selection" => SeedFromSelection::Selection,+ let seed = match self.global_editor_option(&FIND_SEED_SEARCH_STRING_FROM_SELECTION) {+ "never" => SeedFromSelection::Never,+ "selection" => SeedFromSelection::Selection,_ => SeedFromSelection::Always,};- let auto_find_in_selection = match self.setting("editor.find.autoFindInSelection") {- Value::String(auto) if auto == "always" => AutoFindInSelection::Always,- Value::String(auto) if auto == "multiline" => AutoFindInSelection::Multiline,+ let auto_find_in_selection = match self.global_editor_option(&FIND_AUTO_FIND_IN_SELECTION) {+ "always" => AutoFindInSelection::Always,+ "multiline" => AutoFindInSelection::Multiline,_ => AutoFindInSelection::Never,};- let is_loop = self.setting("editor.find.loop").as_bool().unwrap_or(true);- let cursor_move_on_type = self.setting("editor.find.cursorMoveOnType").as_bool().unwrap_or(true);- let global_find_clipboard = self.setting("editor.find.globalFindClipboard").as_bool().unwrap_or(false);+ let is_loop = self.global_editor_option(&FIND_LOOP);+ let cursor_move_on_type = self.global_editor_option(&FIND_CURSOR_MOVE_ON_TYPE);+ let global_find_clipboard = self.global_editor_option(&FIND_GLOBAL_FIND_CLIPBOARD);let (word_separators, word_segmenter_locales) = self.word_separators(false).unwrap_or((word_operations::DEFAULT_WORD_SEPARATORS.to_string(), Vec::new()));FindOptions { seed_search_string_from_selection: seed, auto_find_in_selection, is_loop, global_find_clipboard, cursor_move_on_type, word_separators, word_segmenter_locales, ..FindOptions::default() }}@@ -532,7 +530,7 @@ impl Workbench {}// `editor.find.findOnType` off: the search string waits for Enter (`find_input_key_down`); a line more or// less still resizes the widget and its zone (`onDidHeightChange`, `_showViewZone`).- if id == InputId::Find && self.setting("editor.find.findOnType") == Value::Bool(false) {+ if id == InputId::Find && !self.global_editor_option(&FIND_FIND_ON_TYPE) {let top_whitespace = self.editors.viewport.top_whitespace;self.layout_find_zone(true);if self.editors.viewport.top_whitespace != top_whitespace {@@ -553,7 +551,7 @@ impl Workbench {/// The find input's keydown, before the keybindings: with `editor.find.findOnType` off Enter searches.pub(super) fn find_input_key_down(&mut self, keystroke: &Keystroke, window: &mut Window, cx: &mut Context<Self>) {let modifiers = keystroke.modifiers;- if keystroke.key != "enter" || modifiers.modified() || !self.find.find_focus.is_focused(window) || self.setting("editor.find.findOnType") != Value::Bool(false) {+ if keystroke.key != "enter" || modifiers.modified() || !self.find.find_focus.is_focused(window) || self.global_editor_option(&FIND_FIND_ON_TYPE) {return;}let new = NewFindState { search_string: Some(self.find.find_input.value.clone()), ..Default::default() };@@ -620,6 +618,9 @@ impl Workbench {/// An edit the find did not make: its matches follow the text, and the next search starts at the cursor./// The multi-cursor session ends unless it made the cursor change.pub(super) fn find_editor_edited(&mut self, change: Option<&ContentChanged>) {+ if self.find.ignore_own_change {+ return;+ }let viewport = self.editors.viewport;let match_mode = self.selected_text_match_mode();let Some(editor) = self.editors.active_mut() else { return };@@ -632,7 +633,7 @@ impl Workbench {}fn selected_text_match_mode(&self) -> String {- self.setting("editor.selectedTextMatchMode").as_str().unwrap_or("findOptions").to_string()+ self.global_editor_option(&SELECTED_TEXT_MATCH_MODE).to_string()}/// `SelectionHighlighter._update`, run on every render; the matches are searched again only when the query, the@@ -643,9 +644,9 @@ impl Workbench {return;};let options = SelectionHighlightOptions {- enabled: self.setting("editor.selectionHighlight").as_bool().unwrap_or(true),- multiline: self.setting("editor.selectionHighlightMultiline").as_bool().unwrap_or(false),- max_length: self.setting("editor.selectionHighlightMaxLength").as_u64().unwrap_or(200) as usize,+ enabled: self.editor_option(editor, &SELECTION_HIGHLIGHT),+ multiline: self.editor_option(editor, &SELECTION_HIGHLIGHT_MULTILINE),+ max_length: self.editor_option(editor, &SELECTION_HIGHLIGHT_MAX_LENGTH),};let query = multicursor::selection_highlight_query(&self.find.controller, editor, &self.multicursor_context(window), options);let key = query.map(|query| (editor.model_id, editor.text_model().version_id, editor.selections.clone(), query));@@ -678,7 +679,7 @@ impl Workbench {/// widget sits above line 1; the scroll moves with it, so the text stays put, unless `adjust` is false on show.fn layout_find_zone(&mut self, adjust: bool) {let state = &self.find.controller.state;- let extra_space = self.setting("editor.find.addExtraSpaceOnTop").as_bool().unwrap_or(true);+ let extra_space = self.global_editor_option(&FIND_ADD_EXTRA_SPACE_ON_TOP);let height = if state.is_revealed && extra_space { self.find_widget_height() } else { 0. };let delta = height - self.editors.viewport.top_whitespace;if delta == 0. {diff --git a/native/crates/app/src/workbench/folding_providers.rs b/native/crates/app/src/workbench/folding_providers.rsindex 7788715cadf..44658c35ea8 100644--- a/native/crates/app/src/workbench/folding_providers.rs+++ b/native/crates/app/src/workbench/folding_providers.rs@@ -195,7 +195,7 @@ impl Workbench {let default_provider = settings.get_value(Some("editor.defaultFoldingRangeProvider"), &overrides).and_then(|value| value.as_str().map(str::to_string));drop(settings);let providers = self.language_features.ordered("$registerFoldingRangeProvider", &Candidate { uri, language });- let selected = providers.into_iter().filter(|registration| default_provider.as_deref().is_none_or(|id| registration.args.get(2).is_some_and(|extension| extension["value"] == id)));+ let selected = providers.into_iter().filter(|registration| default_provider.as_deref().is_none_or(|id| registration.extension_id == id));selected.map(|registration| registration.handle).collect()}@@ -205,7 +205,7 @@ impl Workbench {let uri = editor.document().uri();let language = editor.document().language_id.clone();let registrations = self.language_features.ordered("$registerFoldingRangeProvider", &Candidate { uri: &uri, language: &language });- if registrations.iter().any(|registration| registration.args.get(3) == Some(event_handle)) {+ if registrations.iter().any(|registration| registration.event_handle.is_some_and(|handle| event_handle.as_u64() == Some(handle))) {self.trigger_folding_model_changed(cx);}}diff --git a/native/crates/app/src/workbench/format.rs b/native/crates/app/src/workbench/format.rsindex 1cc4351d0f9..bf7870f3554 100644--- a/native/crates/app/src/workbench/format.rs+++ b/native/crates/app/src/workbench/format.rs@@ -13,6 +13,8 @@ use super::auto_save::SaveReason;use super::host_requests::range as model_range;use super::text_files::SaveOptions;use super::text_input::SavePhase;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::commands::Outcome;use crate::dialog;use crate::editor::{ContentChanged, EditReason, OpenEditor, Position, utf16_column};@@ -130,19 +132,19 @@ impl Workbench {pub(crate) fn formatters_changed(&mut self) {let mut ids: Vec<String> = Vec::new();for method in [DOCUMENT, RANGE] {- ids.extend(self.language_features.all(method).map(|registration| extension_id(®istration.args[2])));+ ids.extend(self.language_features.all(method).map(|registration| registration.extension_id.clone()));}let extensions: Vec<(&str, &Value)> = self.extensions.iter().map(|extension| (extension.id.as_str(), &extension.description)).collect();self.settings.lock().unwrap().registry.list_default_formatters(&extensions, &ids);}fn formatter(&self, method: &str, handle: u64) -> Option<Formatter> {- let args = &self.language_features.registration(handle)?.args;+ let registration = self.language_features.registration(handle)?;Some(Formatter {handle,- extension_id: extension_id(&args[2]),- display_name: args.get(3).and_then(Value::as_str).unwrap_or_default().to_owned(),- supports_ranges: method == RANGE && args.get(4) == Some(&json!(true)),+ extension_id: registration.extension_id.clone(),+ display_name: registration.display_name.clone().unwrap_or_default(),+ supports_ranges: method == RANGE && registration.supports_ranges,whole_document: false,})}@@ -571,8 +573,8 @@ impl Workbench {scroll.restore_relative_cursor(editor, viewport);let changes: Vec<ContentChanged> = [eol_change, change].into_iter().flatten().collect();if !shown {- for change in &changes {- self.send_model_edit(&key.scheme, &key.path, change, cx);+ for change in changes {+ self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);}self.host.send_visible_ranges(&self.editors);cx.notify();@@ -584,7 +586,7 @@ impl Workbench {editor.reveal_range(head, head, crate::editor::VerticalReveal::CenterIfOutsideViewport, viewport);}for change in changes {- self.editor_edited(Some(change), true, "formatEditsCommand", cx);+ self.model_content_changed(Some(change), Cursor { moved: true, source: "formatEditsCommand", reveal: Reveal::All }, cx);}true}@@ -599,8 +601,8 @@ impl Workbench {let Some(last) = typed.chars().last() else { return };let uri = editor.document().uri();let candidate = Candidate { uri: &uri, language: &editor.document().language_id };- let Some(support) = self.language_features.ordered(ON_TYPE, &candidate).first().map(|registration| (registration.handle, registration.args[2].clone())) else { return };- let triggers: Vec<char> = support.1.as_array().into_iter().flatten().filter_map(|trigger| trigger.as_str()?.chars().next()).collect();+ let Some(support) = self.language_features.ordered(ON_TYPE, &candidate).first().map(|registration| (registration.handle, ®istration.trigger_characters)) else { return };+ let triggers: Vec<char> = support.1.iter().filter_map(|trigger| trigger.chars().next()).collect();if !triggers.contains(&last) || editor.selections.len() > 1 || !editor.selection().is_empty() {return;}@@ -840,11 +842,6 @@ fn pending<T: 'static>(cx: &mut Context<Workbench>, task: Task<T>) -> Outcome {Outcome::Pending(receiver)}-/// `ExtensionIdentifier` as the host sends it: an object with `value`, or a string.-fn extension_id(value: &Value) -> String {- value["value"].as_str().or(value.as_str()).unwrap_or_default().to_owned()-}-/// `_maybeQuotes`.fn maybe_quotes(name: &str) -> String {if name.contains(char::is_whitespace) { format!("'{name}'") } else { name.to_owned() }diff --git a/native/crates/app/src/workbench/format/tests.rs b/native/crates/app/src/workbench/format/tests.rsindex 37ae56058da..a37f4b34704 100644--- a/native/crates/app/src/workbench/format/tests.rs+++ b/native/crates/app/src/workbench/format/tests.rs@@ -6,6 +6,8 @@ use exthost::scan::scan_extension;use gpui::{TestAppContext, VisualTestContext};use super::*;+use crate::workbench::model_events::Cursor;+use crate::editor::Reveal;use crate::host_sync::{HostMessage, HostSync};use crate::languages::Languages;use crate::theme::load_theme;@@ -253,7 +255,7 @@ fn on_type_preserves_pending_edits_after_changes_below_the_trigger_line(cx: &mutworkbench.update(cx, |workbench, cx| {let editor = workbench.editors.active_mut().unwrap();let change = editor.execute_edits(vec![(at(1, 0), at(1, 4), "changed".into(), false)], None, EditReason::Unknown("test")).unwrap();- workbench.editor_edited(Some(change), false, "api", cx);+ workbench.model_content_changed(Some(change), Cursor { moved: false, source: "api", reveal: Reveal::All }, cx);});assert_eq!(complete_on_type(&workbench, &receiver, cx), "const x = 1;\nchanged");std::fs::remove_dir_all(dir).unwrap();diff --git a/native/crates/app/src/workbench/goto_definition_link.rs b/native/crates/app/src/workbench/goto_definition_link.rsindex 20d1eb91807..5f5d1fe9078 100644--- a/native/crates/app/src/workbench/goto_definition_link.rs+++ b/native/crates/app/src/workbench/goto_definition_link.rs@@ -294,7 +294,7 @@ impl Workbench {/// first) without the common indentation, in a code block of the file's language; `None` when the target cannot/// be read or the range starts outside it.fn definition_preview(&self, link: &Location) -> Option<Option<String>> {- let open = self.editors.editors.iter().chain(&self.editors.models).find(|editor| editor.document().uri_string() == link.uri);+ let open = self.editors.all_editors().find(|editor| editor.document().uri_string() == link.uri);let (_, path) = super::host_requests::uri_parts(&link.resource).ok()?;let lines: Vec<String> = match open {Some(editor) => editor.document().lines.clone(),diff --git a/native/crates/app/src/workbench/goto_symbol.rs b/native/crates/app/src/workbench/goto_symbol.rsindex cbd409e61c3..8aa1f0000df 100644--- a/native/crates/app/src/workbench/goto_symbol.rs+++ b/native/crates/app/src/workbench/goto_symbol.rs@@ -14,6 +14,7 @@ use crate::commands::Outcome;use crate::editor::{OpenEditor, Position, utf16_column};use crate::language_features::Candidate;use crate::references_model::{Location, ReferencesModel};+use crate::workbench::editor_options::DEFINITION_LINK_OPENS_IN_PEEK;/// A provider registry: its `$register*Support`, the host's `$provide*`, the model title and the messages.#[derive(Clone, Copy, PartialEq)]@@ -224,7 +225,7 @@ impl Workbench {/// goToDefinitionAtPosition.ts `gotoDefinition`: the cursor moves to the clicked position, then a muted Go to/// Definition runs, in the peek with `editor.definitionLinkOpensInPeek` unless it opens to the side.pub(super) fn go_to_definition_at(&mut self, position: Position, open_to_side: bool, window: &mut Window, cx: &mut Context<Self>) {- let open_in_peek = !open_to_side && self.setting("editor.definitionLinkOpensInPeek") == json!(true);+ let open_in_peek = !open_to_side && self.global_editor_option(&DEFINITION_LINK_OPENS_IN_PEEK);self.editors.active_mut().expect("the link is in the active editor").move_to(position, false);let action = Action { id: "", kind: DEFINITION, open_to_side, open_in_peek, compact: false, mute_message: true };self.run_symbol_navigation(action, None, None, window, cx);@@ -233,7 +234,7 @@ impl Workbench {/// inlayHintsLocations.ts `goToDefinitionWithLocation`: a muted Go to Definition anchored at the span's start,/// with the peek over the span, the cursor left where it is.pub(super) fn go_to_definition_with_location(&mut self, span: Range<Position>, open_to_side: bool, window: &mut Window, cx: &mut Context<Self>) {- let open_in_peek = !open_to_side && self.setting("editor.definitionLinkOpensInPeek") == json!(true);+ let open_in_peek = !open_to_side && self.global_editor_option(&DEFINITION_LINK_OPENS_IN_PEEK);let action = Action { id: "", kind: DEFINITION, open_to_side, open_in_peek, compact: false, mute_message: true };self.run_symbol_navigation(action, None, Some(span), window, cx);}diff --git a/native/crates/app/src/workbench/goto_symbol/tests.rs b/native/crates/app/src/workbench/goto_symbol/tests.rsindex 9296d0a9c80..569b6d13453 100644--- a/native/crates/app/src/workbench/goto_symbol/tests.rs+++ b/native/crates/app/src/workbench/goto_symbol/tests.rs@@ -241,6 +241,25 @@ fn show_definition_preview_hover_shows_the_preview_at_the_cursor(cx: &mut TestApworkbench.read_with(cx, |workbench, _| assert!(workbench.definition_link_styles(workbench.editors.active().unwrap(), 1, 4).is_empty()));}+/// goToCommands.ts `getPreviewValue` reads the target through `textModelResolverService.createModelReference`, the+/// open model whichever group shows it: a dirty target in another group previews its unsaved text, not the disk's.+#[gpui::test]+fn the_definition_preview_of_a_dirty_file_in_another_group_is_its_unsaved_text(cx: &mut TestAppContext) {+ let (workbench, cx, receiver, dir) = open(cx, "preview-other-group", "const foo = 1;\n");+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("type", vec![json!({ "text": "x" })], window, cx)));+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("type", vec![json!({ "text": "foo" })], window, cx)));+ run(&workbench, cx, "cursorHome");+ run(&workbench, cx, "editor.action.showDefinitionPreviewHover");+ answer(&receiver, "$provideDefinition", json!([link(&dir, 1, 1, 5)]), cx);+ workbench.read_with(cx, |workbench, _| {+ let shown = workbench.content_hover.shown.as_ref().expect("the hover shows");+ let super::super::content_hover::PartContent::Markdown(value) = &shown.parts[0].content else { panic!("a markdown part") };+ assert_eq!(value[0]["value"], "\n```plaintext\nxcon\n```\n");+ });+ std::fs::remove_dir_all(dir).unwrap();+}+/// contentHoverWidget.ts `handleContentsChanged`: the contents take their rounded `offsetWidth` + 2.#[gpui::test]fn the_hover_contents_take_their_rounded_width_plus_two(cx: &mut TestAppContext) {diff --git a/native/crates/app/src/workbench/gutter_mouse.rs b/native/crates/app/src/workbench/gutter_mouse.rsindex fd8e1638078..d419db8c803 100644--- a/native/crates/app/src/workbench/gutter_mouse.rs+++ b/native/crates/app/src/workbench/gutter_mouse.rs@@ -6,6 +6,7 @@ use gpui::{Context, Div, InteractiveElement, MouseButton, MouseDownEvent, MouseMuse super::Workbench;use super::editor_view::MouseDown;+use super::model_events::Cursor;use crate::editor::{Position, Reveal, Selection};impl Workbench {@@ -51,6 +52,7 @@ impl Workbench {Reveal::All}};- self.cursors_changed(before, if reveal { shown } else { Reveal::Nothing }, "mouse", cx);+ let moved = editor.selections != before;+ self.cursor_position_changed(Cursor { moved, source: "mouse", reveal: if reveal { shown } else { Reveal::Nothing } }, cx);}}diff --git a/native/crates/app/src/workbench/hierarchy_peek.rs b/native/crates/app/src/workbench/hierarchy_peek.rsindex eac0d5b6528..b6e67be13a4 100644--- a/native/crates/app/src/workbench/hierarchy_peek.rs+++ b/native/crates/app/src/workbench/hierarchy_peek.rs@@ -599,7 +599,7 @@ impl Workbench {/// the position, the session kept for the resolve commands.fn api_prepare_hierarchy(&mut self, kind: HierarchyKind, args: &[Value], cx: &mut Context<Self>) -> Outcome {let Some((scheme, path)) = args.first().and_then(|uri| super::host_requests::uri_parts(uri).ok()) else { return Outcome::error("Illegal argument") };- let Some(editor) = self.editors.editors.iter().chain(&self.editors.models).find(|editor| editor.document().is(scheme, &path)) else { return Outcome::error("Illegal argument") };+ let Some(editor) = self.editors.model(scheme, &path) else { return Outcome::error("Illegal argument") };let Some(handle) = self.hierarchy_provider(kind, editor) else { return Outcome::Ready(Ok(json!([]))) };let call = self.host.call_cancellable("ExtHostLanguageFeatures", spec(kind).prepare, vec![json!(handle), editor.document().uri(), args.get(1).cloned().unwrap_or_default()]);let (sender, receiver) = futures::channel::oneshot::channel();diff --git a/native/crates/app/src/workbench/hierarchy_peek/tests.rs b/native/crates/app/src/workbench/hierarchy_peek/tests.rsindex be3a741f9c7..cabb7750be6 100644--- a/native/crates/app/src/workbench/hierarchy_peek/tests.rs+++ b/native/crates/app/src/workbench/hierarchy_peek/tests.rs@@ -74,3 +74,14 @@ fn the_type_hierarchy_api_commands_use_the_prepared_session(cx: &mut TestAppContlet Outcome::Pending(mut supertypes) = supertypes else { panic!("pending") };assert_eq!(supertypes.try_recv().unwrap().unwrap().unwrap()[0]["name"], "A");}++/// callHierarchy.ts `_executePrepareCallHierarchy` takes the model from `modelService.getModel(resource)`, whichever+/// group shows it: a file only in another group prepares (no provider, no roots) instead of failing.+#[gpui::test]+fn prepare_call_hierarchy_finds_a_model_in_another_group(cx: &mut TestAppContext) {+ let (workbench, cx, _receiver, dir) = open(cx, "hierarchy-other-group", "main\n");+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ let uri = json!({ "scheme": "file", "path": dir.join("a.txt").to_string_lossy() });+ let prepared = workbench.update_in(cx, |workbench, window, cx| workbench.execute_command("_executePrepareCallHierarchy", vec![uri, json!({ "lineNumber": 1, "column": 1 })], window, cx));+ assert!(matches!(prepared, Outcome::Ready(Ok(ref roots)) if *roots == json!([])));+}diff --git a/native/crates/app/src/workbench/history_actions.rs b/native/crates/app/src/workbench/history_actions.rsindex f1fb6b29a15..131c6b448f2 100644--- a/native/crates/app/src/workbench/history_actions.rs+++ b/native/crates/app/src/workbench/history_actions.rs@@ -9,6 +9,8 @@ use gpui::{Context, PromptLevel, Window};use serde_json::{Value, json};use super::Workbench;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::commands::Outcome;use crate::editor::{ClosedEditor, Selection, VerticalReveal};use crate::navigation::{Entry, Filter, Reason, Stacks};@@ -194,7 +196,7 @@ impl Workbench {let anchor = if start == head { clamp(head) } else { clamp(start) };editor.set_selections(vec![Selection { anchor, head: clamp(head) }]);editor.reveal_range(clamp(head), clamp(head), VerticalReveal::CenterIfOutsideViewport, viewport);- self.host.send_selection(self.editors.active().expect("just selected"), "code.navigation");+ self.cursor_position_changed(Cursor { moved: true, source: "code.navigation", reveal: Reveal::Nothing }, cx);self.record_navigation(Some(Reason::Programmatic));self.editor_scrolled(cx);}diff --git a/native/crates/app/src/workbench/host_requests.rs b/native/crates/app/src/workbench/host_requests.rsindex 62235c5a2a2..64cf0fcae0b 100644--- a/native/crates/app/src/workbench/host_requests.rs+++ b/native/crates/app/src/workbench/host_requests.rs@@ -1,5 +1,5 @@-//! The MainThread* requests the workbench answers itself: mainThreadDocuments.ts, mainThreadEditors.ts with-//! mainThreadEditor.ts, and mainThreadClipboard.ts. They arrive from the session thread through `main_thread.rs`.+//! The MainThread* requests the session thread blocks on: mainThreadDocuments.ts, mainThreadEditors.ts with+//! mainThreadEditor.ts. `main_thread_commands.rs::route` names them; they arrive through `main_thread.rs`.use std::path::{Path, PathBuf};use std::time::Instant;@@ -10,168 +10,90 @@ use exthost::main_thread::serialized_error;use exthost::main_thread_files::resource;use exthost::settings_file_system;use files::encoding;-use gpui::{ClipboardItem, Context, Window};+use gpui::{Context, Window};use serde_json::{Value, json};use super::Workbench;use super::auto_save::SaveReason;use super::bulk_text_edits::document_end;use super::snippet_controller::SnippetInsert;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::editor::{CursorEdit, EditReason, OpenEditor, Position, Replace, Selection, SnippetText, TextDocument, VerticalReveal, char_column, end_of, expand_snippet,on_disk, selections_after, text_between, uri_string,};use crate::commands::Outcome;+use crate::editor::decoration_types::TextDecoration;use crate::editor::injected_text::InjectionOwner;use crate::languages::Languages;use crate::host_sync::snapshot_id;-/// The requests `host_request` answers; every other one stays with the session.-pub const HOST_REQUESTS: &[(&str, &str)] = &[- ("MainThreadClipboard", "$readText"),- ("MainThreadWindow", "$getInitialState"),- ("MainThreadClipboard", "$writeText"),- ("MainThreadDocuments", "$tryOpenDocument"),- ("MainThreadDocuments", "$trySaveDocument"),- ("MainThreadDocuments", "$tryCreateDocument"),- ("MainThreadDocumentContentProviders", "$onVirtualDocumentChange"),- ("MainThreadDocumentDiff", "$computeDocumentDiff"),- ("MainThreadLanguages", "$changeLanguage"),- ("MainThreadLanguages", "$tokensAtPosition"),- ("MainThreadLanguages", "$computeFullSyntaxHighlighting"),- ("MainThreadTextEditors", "$tryShowTextDocument"),- ("MainThreadTextEditors", "$trySetSelections"),- ("MainThreadTextEditors", "$tryRevealRange"),- ("MainThreadTextEditors", "$trySetOptions"),- ("MainThreadTextEditors", "$tryApplyEdits"),- ("MainThreadTextEditors", "$tryInsertSnippet"),- ("MainThreadTextEditors", "$registerTextEditorDecorationType"),- ("MainThreadTextEditors", "$removeTextEditorDecorationType"),- ("MainThreadTextEditors", "$trySetDecorations"),- ("MainThreadTextEditors", "$trySetDecorationsFast"),- ("MainThreadTextEditors", "$tryShowEditor"),- ("MainThreadTextEditors", "$tryHideEditor"),- ("MainThreadTextEditors", "$getDiffInformation"),- ("MainThreadPower", "$getSystemIdleState"),- ("MainThreadPower", "$getSystemIdleTime"),- ("MainThreadPower", "$getCurrentThermalState"),- ("MainThreadPower", "$isOnBatteryPower"),- ("MainThreadPower", "$startPowerSaveBlocker"),- ("MainThreadPower", "$stopPowerSaveBlocker"),- ("MainThreadPower", "$isPowerSaveBlockerStarted"),- ("MainThreadLanguageFeatures", "$resolvePasteFileData"),- ("MainThreadLanguageFeatures", "$resolveDocumentOnDropFileData"),-];-#[cfg(test)]mod tests;type HostResult = Result<Value, Value>;impl Workbench {- /// Answers one of `HOST_REQUESTS`: `Ok` is the reply, `Err` a `SerializedError`.- pub fn host_request(&mut self, proxy: &str, method: &str, args: &[Value], window: &mut Window, cx: &mut Context<Self>) -> HostResult {- let null = Value::Null;- let arg = |index: usize| args.get(index).unwrap_or(&null);- self.release_host_models(cx);- match (proxy, method) {- ("MainThreadLanguageFeatures", _) => self.transfer_file_path(arg(1).as_u64().unwrap_or_default(), arg(2).as_str().unwrap_or_default()),- ("MainThreadClipboard", "$readText") => Ok(json!(cx.read_from_clipboard().and_then(|item| item.text()).unwrap_or_default())),- ("MainThreadClipboard", "$writeText") => {- cx.write_to_clipboard(ClipboardItem::new_string(arg(0).as_str().unwrap_or_default().to_string()));- Ok(null)- }- ("MainThreadWindow", "$getInitialState") => Ok(self.window_initial_state(window)),- ("MainThreadPower", method) => crate::power::request(method, args).map_err(|error| serialized_error(&error)),- ("MainThreadDocuments", "$tryOpenDocument") => self.try_open_document(arg(0), arg(1), arg(2), arg(3) == true, cx),- ("MainThreadDocuments", "$tryCreateDocument") => self.try_create_document(arg(0), cx),- ("workbench", "isDirty") => uri_parts(arg(0)).map(|(scheme, path)| json!(self.editors.model(scheme, &path).is_some_and(|model| model.is_dirty()))),- ("workbench", "hasModel") => uri_parts(arg(0)).map(|(scheme, path)| json!(self.editors.model(scheme, &path).is_some())),- ("MainThreadDocumentContentProviders", "$onVirtualDocumentChange") => self.virtual_document_change(arg(0), arg(1), cx),- ("MainThreadDocumentDiff", "$computeDocumentDiff") => Ok(self.compute_document_diff(arg(0), arg(1), arg(2) == true, arg(3).as_u64().unwrap_or(0), arg(4) == true)),- ("MainThreadLanguages", "$changeLanguage") => self.change_host_language(arg(0), arg(1), cx),- ("MainThreadLanguages", "$tokensAtPosition") => uri_parts(arg(0)).map(|(scheme, path)| self.tokens_at_position(scheme, &path, arg(1))),- ("MainThreadLanguages", "$computeFullSyntaxHighlighting") => Ok(self.full_syntax_highlighting(arg(0).as_str().unwrap_or_default(), arg(1).as_str().unwrap_or_default())),- ("workbench", "providerSaveText") => self.provider_save_bytes(arg(0), cx),- ("workbench", "providerSaved") => self.provider_saved(arg(0), cx),- ("MainThreadTextEditors", "$tryShowTextDocument") => self.try_show_text_document(arg(0), arg(1), window, cx),- ("MainThreadTextEditors", "$registerTextEditorDecorationType") => {- self.editors.decoration_types.insert(arg(1).as_str().unwrap_or_default().to_string(), arg(2).clone());- cx.notify();- Ok(null)- }- ("MainThreadTextEditors", "$removeTextEditorDecorationType") => {- let key = arg(0).as_str().unwrap_or_default();- self.editors.decoration_types.remove(key);- let others = self.editors.other_groups.iter_mut().flat_map(|group| &mut group.editors);- for editor in self.editors.editors.iter_mut().chain(self.editors.models.iter_mut()).chain(others) {- editor.text_decorations.retain(|decoration| decoration.key != key);- }- let content: Vec<_> = self.editors.all_editors().map(|editor| self.decoration_content_text(editor)).collect();- let others = self.editors.other_groups.iter_mut().flat_map(|group| &mut group.editors);- for (editor, injections) in self.editors.editors.iter_mut().chain(self.editors.models.iter_mut()).chain(others).zip(content) {- editor.set_injected_text(InjectionOwner::DecorationContent, injections);- }- cx.notify();- Ok(null)- }- // mainThreadEditors.ts: an editor the host no longer has is left alone, without an error.- ("MainThreadTextEditors", method @ ("$tryShowEditor" | "$tryHideEditor")) => {- let id = arg(0).as_str().unwrap_or_default();- let groups = self.groups_in_grid_order();- let Some(group) = groups.into_iter().find(|&group| self.editors.group_active(group).is_some_and(|(editor, _)| snapshot_id(editor) == id)) else { return Ok(null) };- if method == "$tryShowEditor" {- let uri = self.editors.group_active(group).expect("found above").0.document().uri();- self.try_show_text_document(&uri, &json!({ "position": arg(1), "preserveFocus": false }), window, cx)?;- return Ok(null);- }- self.focus_group(group, window, cx);- let index = self.editors.active_index().expect("the group shows the editor");- // shortcut: answers before a dirty editor's save prompt closes it, upstream awaits closeEditor; route through the forwarded requests if an extension awaits it.- drop(self.close_editors(vec![index], window, cx));- Ok(null)- }- ("MainThreadTextEditors", "$getDiffInformation") => self.editor_line_changes(arg(0).as_str().unwrap_or_default()),- ("MainThreadTextEditors", method) => {- let id = arg(0).as_str().unwrap_or_default();- // A group's active editor or a peek widget's editor, the text editors the host knows.- let groups = self.groups_in_grid_order();- let group = groups.into_iter().find(|&group| self.editors.group_active(group).is_some_and(|(editor, _)| snapshot_id(editor) == id));- let peek = self.editors.peek_editors.iter().map(|peek| &peek.editor).find(|editor| snapshot_id(editor) == id).map(|editor| editor.model_id);- let run = |workbench: &mut Self| match method {- "$trySetSelections" => workbench.set_host_selections(arg(1), cx),- "$tryRevealRange" => workbench.reveal_host_range(arg(1), arg(2), cx),- "$trySetOptions" => workbench.set_host_options(arg(1), cx),- "$tryApplyEdits" => workbench.apply_host_edits(arg(1), arg(2), arg(3), cx),- "$tryInsertSnippet" => workbench.insert_host_snippet(arg(1), arg(2), arg(3), arg(4), window, cx),- "$trySetDecorations" | "$trySetDecorationsFast" => {- let key = arg(1).as_str().unwrap_or_default();- let decorations = match method {- "$trySetDecorations" => crate::editor::decoration_types::decorations_from_options(key, arg(2)),- _ => crate::editor::decoration_types::decorations_from_numbers(key, arg(2)),- };- let editor = workbench.editors.active_mut().expect("the group's active editor has the id");- editor.text_decorations.retain(|decoration| decoration.key != key);- editor.text_decorations.extend(decorations);- let injections = workbench.decoration_content_text(workbench.editors.active().expect("found above"));- workbench.editors.active_mut().expect("found above").set_injected_text(InjectionOwner::DecorationContent, injections);- cx.notify();- Ok(Value::Null)- }- _ => unreachable!("not in HOST_REQUESTS: {method}"),- };- match (group, peek) {- (Some(group), _) => self.with_group(group, run),- (None, Some(peek)) => self.with_code_editor(peek, run),- (None, None) => Err(serialized_error(&format!("Illegal argument: TextEditor({id})"))),- }- }- _ => unreachable!("not in HOST_REQUESTS: {proxy}.{method}"),+ pub(crate) fn remove_decoration_type(&mut self, key: &str, cx: &mut Context<Self>) {+ self.editors.decoration_types.remove(key);+ for editor in self.editors.all_editors_mut() {+ editor.text_decorations.retain(|decoration| decoration.key != key);}+ let content: Vec<_> = self.editors.all_editors().map(|editor| self.decoration_content_text(editor)).collect();+ for (editor, injections) in self.editors.all_editors_mut().zip(content) {+ editor.set_injected_text(InjectionOwner::DecorationContent, injections);+ }+ cx.notify();+ }++ /// The group whose active editor is the host's text editor `id`.+ fn host_editor_group(&self, id: &str) -> Option<u32> {+ self.groups_in_grid_order().into_iter().find(|&group| self.editors.group_active(group).is_some_and(|(editor, _)| snapshot_id(editor) == id))+ }++ // mainThreadEditors.ts: an editor the host no longer has is left alone, without an error.+ pub(crate) fn show_host_editor(&mut self, args: &[Value], window: &mut Window, cx: &mut Context<Self>) -> HostResult {+ let Some(group) = self.host_editor_group(args[0].as_str().unwrap_or_default()) else { return Ok(Value::Null) };+ let uri = self.editors.group_active(group).expect("found above").0.document().uri();+ let position = args.get(1).cloned().unwrap_or(Value::Null);+ self.try_show_text_document(&uri, &json!({ "position": position, "preserveFocus": false }), window, cx)?;+ Ok(Value::Null)+ }++ pub(crate) fn hide_host_editor(&mut self, args: &[Value], window: &mut Window, cx: &mut Context<Self>) -> HostResult {+ let Some(group) = self.host_editor_group(args[0].as_str().unwrap_or_default()) else { return Ok(Value::Null) };+ self.focus_group(group, window, cx);+ let index = self.editors.active_index().expect("the group shows the editor");+ // shortcut: answers before a dirty editor's save prompt closes it, upstream awaits closeEditor; route through the forwarded requests if an extension awaits it.+ drop(self.close_editors(vec![index], window, cx));+ Ok(Value::Null)+ }++ /// Runs `run` with the host's text editor `args[0]` active: a group's active editor or a peek widget's editor.+ pub(crate) fn with_host_editor(&mut self, args: &[Value], run: impl FnOnce(&mut Self) -> HostResult) -> HostResult {+ let id = args[0].as_str().unwrap_or_default();+ let group = self.host_editor_group(id);+ let peek = self.editors.peek_editors.iter().map(|peek| &peek.editor).find(|editor| snapshot_id(editor) == id).map(|editor| editor.model_id);+ match (group, peek) {+ (Some(group), _) => self.with_group(group, run),+ (None, Some(peek)) => self.with_code_editor(peek, run),+ (None, None) => Err(serialized_error(&format!("Illegal argument: TextEditor({id})"))),+ }+ }++ pub(crate) fn set_host_decorations(&mut self, key: &str, decorations: Vec<TextDecoration>, cx: &mut Context<Self>) -> HostResult {+ let editor = self.editors.active_mut().expect("with_host_editor made it active");+ editor.text_decorations.retain(|decoration| decoration.key != key);+ editor.text_decorations.extend(decorations);+ let injections = self.decoration_content_text(self.editors.active().expect("found above"));+ self.editors.active_mut().expect("found above").set_injected_text(InjectionOwner::DecorationContent, injections);+ cx.notify();+ Ok(Value::Null)}/// `BoundModelReferenceCollection`: models the host opened and no editor shows are disposed after 3 minutes.- pub(super) fn release_host_models(&mut self, cx: &mut Context<Self>) {+ pub(crate) fn release_host_models(&mut self, cx: &mut Context<Self>) {let count = self.editors.models.len();let scm_inputs = self.scm_input_models();// A notebook cell's text model lives as long as its notebook, a playground snippet's as long as the playground.@@ -190,13 +112,12 @@ impl Workbench {/// `$tryOpenDocument`: the model of a file, of the bytes an extension's file system provider read/// (`provider_content` an array) or of a content provider's text (a string), opened without an editor and kept/// while the host references it. `options.encoding` decodes a new model, or a clean open one again.- pub(super) fn try_open_document(&mut self, uri: &Value, options: &Value, provider_content: &Value, ignore_path_case: bool, cx: &mut Context<Self>) -> HostResult {+ pub(crate) fn try_open_document(&mut self, uri: &Value, options: &Value, provider_content: &Value, ignore_path_case: bool, cx: &mut Context<Self>) -> HostResult {let (scheme, ref path) = uri_parts(uri)?;// uriIdentityService.ts `asCanonicalUri`: where the provider ignores path case, the casing opened first wins.if ignore_path_case {let lowercase = path.to_string_lossy().to_lowercase();- let models = self.editors.editors.iter().chain(&self.editors.models);- let first_casing = models.map(|model| model.document()).find(|document| document.scheme == scheme && document.path != *path && document.path.to_string_lossy().to_lowercase() == lowercase).map(|document| document.uri());+ let first_casing = self.editors.all_editors().map(|model| model.document()).find(|document| document.scheme == scheme && document.path != *path && document.path.to_string_lossy().to_lowercase() == lowercase).map(|document| document.uri());if let Some(uri) = first_casing {return self.try_open_document(&uri, options, provider_content, false, cx);}@@ -325,7 +246,7 @@ impl Workbench {}/// mainThreadLanguages.ts `$changeLanguage`: a registered language for the model, opened when needed.- fn change_host_language(&mut self, uri: &Value, language_id: &Value, cx: &mut Context<Self>) -> HostResult {+ pub(crate) fn change_host_language(&mut self, uri: &Value, language_id: &Value, cx: &mut Context<Self>) -> HostResult {let language_id = language_id.as_str().unwrap_or_default();if !self.languages.is_registered(language_id) {return Err(serialized_error(&format!("Unknown language id: {language_id}")));@@ -341,7 +262,7 @@ impl Workbench {/// mainThreadLanguages.ts `$tokensAtPosition`: the standard type and range of the token at the position, none/// for a model that is not open.- fn tokens_at_position(&self, scheme: &str, path: &Path, position: &Value) -> Value {+ pub(crate) fn tokens_at_position(&self, scheme: &str, path: &Path, position: &Value) -> Value {let Some(editor) = self.editors.model(scheme, path) else { return Value::Null };let document = editor.document();let line_number = position["lineNumber"].as_u64().unwrap_or(1) as usize;@@ -362,7 +283,7 @@ impl Workbench {/// `$computeFullSyntaxHighlighting`: the source's TextMate tokens in the language (by id or name) as UTF-16 lengths/// with their theme foreground index and font style, a 1-long token per newline, and the theme's color map.- fn full_syntax_highlighting(&self, source: &str, language: &str) -> Value {+ pub(crate) fn full_syntax_highlighting(&self, source: &str, language: &str) -> Value {let color_map: Vec<String> = self.theme.tokens.color_map().iter().map(|color| css_hex_alpha(color)).collect();let language = if self.languages.is_registered(language) { Some(language) } else { self.languages.id_by_name(language) };let Some(grammar) = language.and_then(|language| self.languages.grammars.grammar(language)) else {@@ -395,7 +316,7 @@ impl Workbench {}/// `$tryCreateDocument`: a new untitled model named `Untitled-<n>` with the first free n.- fn try_create_document(&mut self, options: &Value, cx: &mut Context<Self>) -> HostResult {+ pub(crate) fn try_create_document(&mut self, options: &Value, cx: &mut Context<Self>) -> HostResult {let path = (1..).map(|n| PathBuf::from(format!("Untitled-{n}"))).find(|path| self.editors.model("untitled", path).is_none()).expect("a free name");let content = options["content"].as_str().unwrap_or_default();let language = self.untitled_language(options["language"].as_str().map(str::to_string));@@ -412,7 +333,7 @@ impl Workbench {/// `$onVirtualDocumentChange`: a content provider's new text replaces the model's through `computeMoreMinimalEdits`,/// so the change events carry only the changed chars.- fn virtual_document_change(&mut self, uri: &Value, value: &Value, cx: &mut Context<Self>) -> HostResult {+ pub(crate) fn virtual_document_change(&mut self, uri: &Value, value: &Value, cx: &mut Context<Self>) -> HostResult {let (scheme, ref path) = uri_parts(uri)?;let Some(model) = self.editors.model(scheme, path) else { return Ok(Value::Null) };let document = model.document();@@ -437,12 +358,7 @@ impl Workbench {model.mark_saved();}if let Some(change) = change {- self.send_model_edit(scheme, path, &change, cx);- // links.ts `onDidChangeModelContent` of the active editor's model, whatever edited it (a search editor's results).- if self.editors.active().is_some_and(|editor| editor.document().is(scheme, path)) {- self.links_content_changed(&change, cx);- }- cx.notify();+ self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);}}@@ -459,7 +375,7 @@ impl Workbench {}/// First half of `$trySaveDocument` through a provider: false without a model, true when clean, else the bytes to write.- fn provider_save_bytes(&mut self, uri: &Value, cx: &mut Context<Self>) -> HostResult {+ pub(crate) fn provider_save_bytes(&mut self, uri: &Value, cx: &mut Context<Self>) -> HostResult {let (scheme, ref path) = uri_parts(uri)?;match self.editors.model(scheme, path) {None => return Ok(json!(false)),@@ -470,7 +386,7 @@ impl Workbench {}/// Second half: the provider wrote the bytes, so the model is clean.- fn provider_saved(&mut self, uri: &Value, cx: &mut Context<Self>) -> HostResult {+ pub(crate) fn provider_saved(&mut self, uri: &Value, cx: &mut Context<Self>) -> HostResult {let (scheme, ref path) = uri_parts(uri)?;let Some(model) = self.editors.model_mut(scheme, path) else { return Ok(json!(false)) };model.mark_saved();@@ -481,7 +397,7 @@ impl Workbench {}/// `$tryShowTextDocument`: opens the model in the group, preview unless pinned, and returns the editor's id.- pub(super) fn try_show_text_document(&mut self, uri: &Value, options: &Value, window: &mut Window, cx: &mut Context<Self>) -> HostResult {+ pub(crate) fn try_show_text_document(&mut self, uri: &Value, options: &Value, window: &mut Window, cx: &mut Context<Self>) -> HostResult {// A notebook cell's document shows in its notebook's editor.if uri["scheme"] == crate::notebook::CELL_SCHEME&& let Some(shown) = self.show_notebook_of_cell(uri, options, window, cx)@@ -594,8 +510,8 @@ impl Workbench {}/// `setSelections`: one cursor per selection, the first the primary one; nothing scrolls.- fn set_host_selections(&mut self, selections: &Value, cx: &mut Context<Self>) -> HostResult {- let editor = self.editors.active_mut().expect("checked by host_request");+ pub(crate) fn set_host_selections(&mut self, selections: &Value, cx: &mut Context<Self>) -> HostResult {+ let editor = self.editors.active_mut().expect("with_host_editor made it active");let selections: Vec<Selection> = selections.as_array().into_iter()@@ -609,13 +525,13 @@ impl Workbench {return Ok(Value::Null);}editor.set_selections(selections);- self.host.send_selection(self.editors.active().expect("checked by host_request"), "api");+ self.cursor_position_changed(Cursor { moved: true, source: "api", reveal: Reveal::Nothing }, cx);cx.notify();Ok(Value::Null)}/// mainThreadEditor.ts `revealRange`: `TextEditorRevealType` Default, InCenter, InCenterIfOutsideViewport, AtTop.- fn reveal_host_range(&mut self, range_value: &Value, reveal_type: &Value, cx: &mut Context<Self>) -> HostResult {+ pub(crate) fn reveal_host_range(&mut self, range_value: &Value, reveal_type: &Value, cx: &mut Context<Self>) -> HostResult {let reveal = match reveal_type.as_u64() {Some(1) => VerticalReveal::Center,Some(2) => VerticalReveal::CenterIfOutsideViewport,@@ -635,8 +551,8 @@ impl Workbench {/// mainThreadEditor.ts `setConfiguration`: `_setIndentConfiguration` (tab size, indent size and spaces, or "auto" to/// detect them again from the text), then the code editor's `cursorStyle` and `lineNumbers`.- fn set_host_options(&mut self, options: &Value, cx: &mut Context<Self>) -> HostResult {- let editor = self.editors.active_mut().expect("checked by host_request");+ pub(crate) fn set_host_options(&mut self, options: &Value, cx: &mut Context<Self>) -> HostResult {+ let editor = self.editors.active_mut().expect("with_host_editor made it active");if options["tabSize"] == json!("auto") || options["insertSpaces"] == json!("auto") {let created = creation_options(&self.settings.lock().unwrap().configuration, &editor.document().path, &editor.document().language_id);let insert_spaces = options["insertSpaces"].as_bool().unwrap_or(created.insert_spaces);@@ -675,7 +591,7 @@ impl Workbench {_ => "off",});}- let editor = self.editors.active().expect("checked by host_request");+ let editor = self.editors.active().expect("with_host_editor made it active");let options = self.host_editor_options(editor);if self.host.send_options(editor, options) {cx.notify();@@ -684,15 +600,15 @@ impl Workbench {}/// mainThreadEditor.ts `applyEdits`: false when the model moved past the host's version.- fn apply_host_edits(&mut self, version: &Value, edits: &Value, options: &Value, cx: &mut Context<Self>) -> HostResult {- let editor = self.editors.active_mut().expect("checked by host_request");+ pub(crate) fn apply_host_edits(&mut self, version: &Value, edits: &Value, options: &Value, cx: &mut Context<Self>) -> HostResult {+ let editor = self.editors.active_mut().expect("with_host_editor made it active");if version.as_u64() != Some(editor.text_model().version_id.into()) {return Ok(json!(false));}if let Some(eol_change) = options["setEndOfLine"].as_u64().and_then(|sequence| editor.push_eol(sequence)) {- self.host.send_model_change(&self.editors, self.editors.active().expect("checked by host_request"), &eol_change);+ self.model_content_changed(Some(eol_change), Cursor::model_change(), cx);}- let editor = self.editors.active_mut().expect("checked by host_request");+ let editor = self.editors.active_mut().expect("with_host_editor made it active");let edits = edits.as_array().into_iter()@@ -710,15 +626,15 @@ impl Workbench {editor.push_undo_stop();}if change.is_some() {- self.editor_edited(change, true, "MainThreadTextEditor", cx);+ self.model_content_changed(change, Cursor { moved: true, source: "MainThreadTextEditor", reveal: Reveal::All }, cx);}Ok(json!(true))}/// mainThreadEditor.ts `insertSnippet`: the snippet replaces every range, and each copy's first tab stop is selected.- fn insert_host_snippet(&mut self, version: &Value, template: &Value, ranges: &Value, options: &Value, window: &mut Window, cx: &mut Context<Self>) -> HostResult {+ pub(crate) fn insert_host_snippet(&mut self, version: &Value, template: &Value, ranges: &Value, options: &Value, window: &mut Window, cx: &mut Context<Self>) -> HostResult {let clipboard = cx.read_from_clipboard().and_then(|item| item.text());- let editor = self.editors.active_mut().expect("checked by host_request");+ let editor = self.editors.active_mut().expect("with_host_editor made it active");if version.as_u64() != Some(editor.text_model().version_id.into()) {return Ok(json!(false));}@@ -791,7 +707,7 @@ fn saved_already(saved: bool) -> futures::channel::oneshot::Receiver<bool> {/// The scheme and path a model is keyed by; the authority of a non-file URI leads its path as `//authority`,/// which `TextDocument::uri` splits off again.-pub(super) fn uri_parts(uri: &Value) -> Result<(&str, PathBuf), Value> {+pub(crate) fn uri_parts(uri: &Value) -> Result<(&str, PathBuf), Value> {let part = |key: &str| uri[key].as_str().unwrap_or_default();let (scheme, authority, path, query) = (part("scheme"), part("authority"), part("path"), part("query"));// editor.rs `split_query`: a non-file query stays in the model's path.diff --git a/native/crates/app/src/workbench/host_requests/tests.rs b/native/crates/app/src/workbench/host_requests/tests.rsindex d90b97dd4ae..f0ae341ac92 100644--- a/native/crates/app/src/workbench/host_requests/tests.rs+++ b/native/crates/app/src/workbench/host_requests/tests.rs@@ -75,7 +75,7 @@ fn decoration_types_set_and_remove_editor_decorations(cx: &mut TestAppContext) {let (dir, workbench, cx) = workbench_in("decorations", cx);open(&workbench, vec![file_uri(&dir.join("far.js"))], cx).unwrap();let id = workbench.read_with(cx, |workbench, _| crate::host_sync::snapshot_id(workbench.editors.active().unwrap()));- let request = |method: &str, args: Vec<Value>, cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.host_request("MainThreadTextEditors", method, &args, window, cx));+ let request = |method: &str, args: Vec<Value>, cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadTextEditors", method, &args, window, cx));let options = json!({ "isWholeLine": true, "backgroundColor": { "id": "merge.currentHeaderBackground" }, "after": { "contentText": " (Current Change)" } });request("$registerTextEditorDecorationType", vec![json!("vscode.merge-conflict"), json!("TextEditorDecorationType1"), options], cx).unwrap();request("$trySetDecorationsFast", vec![json!(id), json!("TextEditorDecorationType1"), json!([2, 1, 2, 4])], cx).unwrap();@@ -102,7 +102,7 @@ fn a_decoration_outline_is_drawn_outside_its_range(cx: &mut TestAppContext) {let (dir, workbench, cx) = workbench_in("decoration-outline", cx);open(&workbench, vec![file_uri(&dir.join("far.js"))], cx).unwrap();let id = workbench.read_with(cx, |workbench, _| crate::host_sync::snapshot_id(workbench.editors.active().unwrap()));- let request = |method: &str, args: Vec<Value>, cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.host_request("MainThreadTextEditors", method, &args, window, cx));+ let request = |method: &str, args: Vec<Value>, cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadTextEditors", method, &args, window, cx));let options = json!({ "outlineColor": "#ff0000", "outlineStyle": "solid", "outlineWidth": "2px" });request("$registerTextEditorDecorationType", vec![json!("test"), json!("TextEditorDecorationType1"), options], cx).unwrap();request("$trySetDecorationsFast", vec![json!(id), json!("TextEditorDecorationType1"), json!([3, 2, 3, 5])], cx).unwrap();@@ -136,7 +136,7 @@ fn set_options_apply_the_cursor_style_and_line_numbers(cx: &mut TestAppContext)let added: Vec<Value> = messages.try_iter().filter(|message| message.method == "$acceptDocumentsAndEditorsDelta").map(|message| message.args[0]["addedEditors"][0]["options"].clone()).collect();assert_eq!((&added[0]["cursorStyle"], &added[0]["lineNumbers"]), (&json!(1), &json!(1)));- let set = |options: Value, cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.host_request("MainThreadTextEditors", "$trySetOptions", &[json!(id), options], window, cx));+ let set = |options: Value, cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadTextEditors", "$trySetOptions", &[json!(id), options], window, cx));assert_eq!(set(json!({ "cursorStyle": 2, "lineNumbers": 2 }), cx), Ok(Value::Null));let line_numbers = workbench.read_with(cx, |workbench, _| workbench.line_numbers(workbench.editors.active().unwrap()));assert_eq!(line_numbers, crate::workbench::editor_view::LineNumbers::Relative);@@ -163,7 +163,7 @@ fn text_editor_show_and_hide_open_and_close_the_editor(cx: &mut TestAppContext)std::fs::write(dir.join("near.js"), "four").unwrap();open(&workbench, vec![file_uri(&dir.join("far.js"))], cx).unwrap();let id = workbench.read_with(cx, |workbench, _| crate::host_sync::snapshot_id(workbench.editors.active().unwrap()));- let request = |method: &str, args: Vec<Value>, cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.host_request("MainThreadTextEditors", method, &args, window, cx));+ let request = |method: &str, args: Vec<Value>, cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadTextEditors", method, &args, window, cx));// extHostTextEditor.ts `show(column)`: the editor's document opens in that column.assert_eq!(request("$tryShowEditor", vec![json!(id), json!(1)], cx), Ok(Value::Null));let (groups, active) = workbench.read_with(cx, |workbench, _| (workbench.groups_in_grid_order().len(), workbench.editors.active().unwrap().document().name()));@@ -215,7 +215,7 @@ fn workbench_open_reads_a_provider_resource_through_the_host(cx: &mut TestAppCon// mainThreadDocumentContentProviders.ts `$onVirtualDocumentChange`: computeMoreMinimalEdits keeps "from the " untouched._ = messages.try_iter().count();- workbench.update_in(cx, |workbench, window, cx| workbench.host_request("MainThreadDocumentContentProviders", "$onVirtualDocumentChange", &[uri.clone(), json!("from the server")], window, cx)).unwrap();+ workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadDocumentContentProviders", "$onVirtualDocumentChange", &[uri.clone(), json!("from the server")], window, cx)).unwrap();let changed = messages.try_iter().find(|message| message.method == "$acceptModelChanged").expect("the host hears the change");let offsets: Vec<u64> = changed.args[1]["changes"].as_array().unwrap().iter().map(|change| change["rangeOffset"].as_u64().unwrap()).collect();assert!(!offsets.is_empty() && offsets.iter().all(|&offset| offset >= 9), "changes at {offsets:?}");@@ -241,7 +241,7 @@ fn tokens_at_position_answers_the_token_of_an_open_model(cx: &mut TestAppContextlet (dir, workbench, cx) = workbench_in("tokens-at-position", cx);let uri = file_uri(&dir.join("far.js"));let position = json!({ "lineNumber": 2, "column": 2 });- let ask = |cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.host_request("MainThreadLanguages", "$tokensAtPosition", &[uri.clone(), position.clone()], window, cx));+ let ask = |cx: &mut VisualTestContext| workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadLanguages", "$tokensAtPosition", &[uri.clone(), position.clone()], window, cx));assert_eq!(ask(cx), Ok(Value::Null));assert_eq!(open(&workbench, vec![uri.clone()], cx), Ok(Value::Null));assert_eq!(ask(cx), Ok(json!({ "type": 0, "range": { "startLineNumber": 2, "startColumn": 1, "endLineNumber": 2, "endColumn": 4 } })));@@ -258,7 +258,7 @@ fn full_syntax_highlighting_tokenizes_with_the_theme(cx: &mut TestAppContext) {let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, languages, crate::default_settings(), HostSync::new(std::sync::mpsc::channel().0), cx));let ask = |source: &str, language: &str, cx: &mut VisualTestContext| {let args = [json!(source), json!(language)];- workbench.update_in(cx, |workbench, window, cx| workbench.host_request("MainThreadLanguages", "$computeFullSyntaxHighlighting", &args, window, cx)).unwrap()+ workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadLanguages", "$computeFullSyntaxHighlighting", &args, window, cx)).unwrap()};let result = ask("let x\nx", "TypeScript", cx);let tokens: Vec<(u64, u64)> = result["tokens"].as_array().unwrap().iter().map(|token| (token["length"].as_u64().unwrap(), token["foreground"].as_u64().unwrap())).collect();@@ -322,10 +322,10 @@ fn save_document_answers_after_the_save_dialog(cx: &mut TestAppContext) {let (workbench, cx) = cx.add_window_view(|_, cx| Workbench::new(theme, app_root.clone(), None, Languages::new(&[]), settings, HostSync::new(std::sync::mpsc::channel().0), cx));let (requests, received) = futures::channel::mpsc::unbounded();workbench.update_in(cx, |_, window, cx| crate::workbench::extension_host_restart::serve_main_thread_requests(received, window, cx));- let uri = workbench.update_in(cx, |workbench, window, cx| workbench.host_request("MainThreadDocuments", "$tryCreateDocument", &[json!({ "content": "hello" })], window, cx)).unwrap();+ let uri = workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadDocuments", "$tryCreateDocument", &[json!({ "content": "hello" })], window, cx)).unwrap();let (reply, answer) = std::sync::mpsc::channel();- requests.unbounded_send(crate::main_thread::HostRequest { proxy: "MainThreadDocuments".into(), method: "$trySaveDocument".into(), args: vec![uri], reply }).unwrap();+ requests.unbounded_send(crate::main_thread::HostRequest { proxy: "MainThreadDocuments", method: "$trySaveDocument".into(), args: vec![uri], reply }).unwrap();cx.run_until_parked();assert!(answer.try_recv().is_err(), "no answer while the save dialog is open");let target = dir.join("saved.txt");@@ -353,3 +353,15 @@ fn open_document_with_an_encoding_decodes_a_provider_model_again(cx: &mut TestApassert_eq!(document, Some(("café".to_string(), "iso88591".to_string())));std::fs::remove_dir_all(dir).unwrap();}++/// uriIdentityService.ts `asCanonicalUri` keeps the casing opened first in any group: `openTextDocument` of another+/// casing resolves to the model whose only editor is in another group.+#[gpui::test]+fn open_document_in_another_casing_finds_the_model_in_another_group(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = workbench_in("casing-other-group", cx);+ assert_eq!(open(&workbench, vec![file_uri(&dir.join("far.js"))], cx), Ok(Value::Null));+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ let opened = workbench.update(cx, |workbench, cx| workbench.try_open_document(&file_uri(&dir.join("FAR.js")), &json!({}), &Value::Null, true, cx));+ assert_eq!(opened.unwrap()["path"], json!(dir.join("far.js").to_string_lossy()));+ std::fs::remove_dir_all(dir).unwrap();+}diff --git a/native/crates/app/src/workbench/inlay_hints.rs b/native/crates/app/src/workbench/inlay_hints.rsindex 587b508f302..0fdb155f359 100644--- a/native/crates/app/src/workbench/inlay_hints.rs+++ b/native/crates/app/src/workbench/inlay_hints.rs@@ -11,6 +11,8 @@ use serde_json::{Value, json};use super::Workbench;use super::editor_view::EDITOR_FONT;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::commands::Outcome;use crate::editor::injected_text::{InjectedText, InjectionOwner, WrapWidth};use crate::editor::{OpenEditor, Position, TextDocument, char_column, utf16_column};@@ -18,6 +20,7 @@ use crate::languages::Languages;use crate::theme::Theme;use crate::language_feature_debounce::FeatureDebounce;use crate::language_features::Candidate;+use crate::workbench::editor_options::MULTI_CURSOR_MODIFIER;const REGISTER: &str = "$registerInlayHintsProvider";/// `_updateHintsDecorators`: after an edit the hints before the cursor keep their lengths this long at least.@@ -258,7 +261,7 @@ impl Workbench {let uri = editor.document().uri();let language = editor.document().language_id.clone();let candidate = Candidate { uri: &uri, language: &language };- self.language_features.ordered(REGISTER, &candidate).iter().filter_map(|registration| registration.args.get(3).and_then(Value::as_u64)).collect()+ self.language_features.ordered(REGISTER, &candidate).iter().filter_map(|registration| registration.event_handle).collect()}fn release_inlay_hint_lists(&self, lists: Vec<(u64, u64)>) {@@ -536,7 +539,7 @@ impl Workbench {return None;}item.resolved = true;- let supports_resolve = self.language_features.all(REGISTER).any(|registration| registration.handle == item.handle && registration.args.get(2) == Some(&json!(true)));+ let supports_resolve = self.language_features.all(REGISTER).any(|registration| registration.handle == item.handle && registration.supports_resolve);if !supports_resolve {return None;}@@ -613,13 +616,13 @@ impl Workbench {}).collect();let change = editor.execute_edits(replaces, None, crate::editor::EditReason::Unknown("inlayHint.default"));- self.editor_edited(change, true, "api", cx);+ self.model_content_changed(change, Cursor { moved: true, source: "api", reveal: Reveal::All }, cx);self.schedule_inlay_hints(Duration::ZERO, cx);}/// clickLinkGesture.ts `hasTriggerModifier`: Cmd, or Alt when `editor.multiCursorModifier` is `ctrlCmd`.fn link_modifier(&self, modifiers: Modifiers) -> bool {- match self.setting("editor.multiCursorModifier") == json!("ctrlCmd") {+ match self.global_editor_option(&MULTI_CURSOR_MODIFIER) == "ctrlCmd" {true => modifiers.alt,false => modifiers.platform,}@@ -663,11 +666,11 @@ struct HintLayout {}fn hint_editor(editors: &crate::editor::EditorGroup, model_id: u32) -> Option<&OpenEditor> {- editors.editors.iter().chain(&editors.models).find(|editor| editor.model_id == model_id)+ editors.all_editors().find(|editor| editor.model_id == model_id)}fn hint_editor_mut(editors: &mut crate::editor::EditorGroup, model_id: u32) -> Option<&mut OpenEditor> {- editors.editors.iter_mut().chain(&mut editors.models).find(|editor| editor.model_id == model_id)+ editors.all_editors_mut().find(|editor| editor.model_id == model_id)}fn pressed(modifiers: Modifiers) -> bool {diff --git a/native/crates/app/src/workbench/inlay_hints/tests.rs b/native/crates/app/src/workbench/inlay_hints/tests.rsindex 4f839fd1190..09c38eec7e6 100644--- a/native/crates/app/src/workbench/inlay_hints/tests.rs+++ b/native/crates/app/src/workbench/inlay_hints/tests.rs@@ -189,3 +189,31 @@ fn a_scroll_asks_nothing_while_hints_are_off(cx: &mut TestAppContext) {assert_eq!(receiver.try_iter().filter(|message| message.method == "$provideInlayHints").count(), 0);std::fs::remove_dir_all(dir).unwrap();}++/// inlayHintsController.ts `_removeAllDecorations` clears the hints of the editor they were drawn in: hints drawn in an+/// editor of another group go when the focus moves away, not stay stale there.+#[gpui::test]+fn the_hints_of_an_editor_in_another_group_go_when_the_focus_leaves_it(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = crate::workbench::editor_groups::tests::workbench_with("inlay-hints-other-group", &["a.txt"], cx);+ let (sender, receiver) = std::sync::mpsc::channel::<HostMessage>();+ workbench.update(cx, |workbench, cx| {+ workbench.host = HostSync::new(sender);+ workbench.language_features.register(REGISTER, vec![json!(1), json!({ "scheme": "file" }), json!(null), json!(2)]);+ workbench.inlay_hints_registrations_changed(cx);+ });+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.focusNextGroup", vec![], window, cx)));+ cx.executor().advance_clock(Duration::from_secs(1));+ cx.run_until_parked();+ let hints = json!({ "hints": [{ "label": ": number", "position": { "lineNumber": 1, "column": 1 } }] });+ for message in receiver.try_iter().filter(|message| message.method == "$provideInlayHints") {+ let _ = message.reply.expect("a call").send(Ok(hints.clone()));+ }+ cx.run_until_parked();+ let shown = |workbench: &Workbench| workbench.editors.model("file", &dir.join("a.txt")).unwrap().injected_text.iter().filter(|injection| injection.owner == InjectionOwner::InlayHint).count();+ assert_eq!(workbench.read_with(cx, |workbench, _| shown(workbench)), 1, "the hint shows");+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("workbench.action.focusPreviousGroup", vec![], window, cx)));+ cx.run_until_parked();+ assert_eq!(workbench.read_with(cx, |workbench, _| shown(workbench)), 0);+ std::fs::remove_dir_all(dir).unwrap();+}diff --git a/native/crates/app/src/workbench/inline_breakpoints.rs b/native/crates/app/src/workbench/inline_breakpoints.rsindex 6f262cc0a73..e16ad69e614 100644--- a/native/crates/app/src/workbench/inline_breakpoints.rs+++ b/native/crates/app/src/workbench/inline_breakpoints.rs@@ -49,7 +49,7 @@ impl Workbench {let placeholder = 0.9 * super::editor_view::EDITOR_FONT_SIZE * self.editor_zoom.multiplier() / self.editors.viewport.char_width;let mut widgets = HashMap::new();let mut wanted = Vec::new();- for editor in self.editors.editors.iter().chain(&self.editors.models) {+ for editor in self.editors.all_editors() {let (editor_widgets, injections) = self.inline_breakpoints(editor, placeholder);if !editor_widgets.is_empty() {widgets.insert(editor.document().uri_string(), editor_widgets);@@ -57,7 +57,7 @@ impl Workbench {wanted.push(injections);}self.debug.inline_breakpoints.widgets = widgets;- for (editor, injections) in self.editors.editors.iter_mut().chain(&mut self.editors.models).zip(wanted) {+ for (editor, injections) in self.editors.all_editors_mut().zip(wanted) {let current = editor.injected_text.iter().filter(|injection| injection.owner == InjectionOwner::InlineBreakpoint);if !current.eq(injections.iter()) {editor.set_injected_text(InjectionOwner::InlineBreakpoint, injections);@@ -118,7 +118,7 @@ impl Workbench {return;};let mut asks = Vec::new();- for editor in self.editors.editors.iter().chain(&self.editors.models) {+ for editor in self.editors.all_editors() {let document = editor.document();let uri = document.uri_string();let mut lines: Vec<u32> = self.debug.model.breakpoints_in(&uri).map(Breakpoint::line_number).filter(|line| *line as usize <= document.lines.len()).collect();diff --git a/native/crates/app/src/workbench/inline_completions.rs b/native/crates/app/src/workbench/inline_completions.rsindex 3e21ef5e79c..139e671c7d3 100644--- a/native/crates/app/src/workbench/inline_completions.rs+++ b/native/crates/app/src/workbench/inline_completions.rs@@ -18,6 +18,8 @@ use super::content_hover_view::RADIUS;use super::editor_message::layout_in_page;use super::peek_view::UI_FONT;use super::hover::{HoverContent, HoverOptions};+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::menus::{ALWAYS_SHOW_INLINE_TOOLBAR, MenuAction, MenuId, menu_actions, menu_group_actions};use super::editor_view::EDITOR_FONT;use crate::commands::Outcome;@@ -132,8 +134,8 @@ impl Workbench {pub(super) fn inline_completion_providers_changed(&mut self) {let mut matchers = Vec::new();for registration in self.language_features.all(REGISTER) {- let extension = registration.args[3].as_str().unwrap_or_default();- let exact = match registration.args[5].as_str() {+ let extension = ®istration.extension_id;+ let exact = match ®istration.group_id {Some(group) => format!("{extension}:{group}"),None => extension.to_owned(),};@@ -216,11 +218,11 @@ impl Workbench {context.insert("inlineSuggestionHasIndentationLessThanTabSize".into(), json!(less_than_tab_size));}- pub(super) fn inline_completion_handles(&self, editor: &OpenEditor) -> Vec<(u64, Vec<Value>)> {+ pub(super) fn inline_completion_handles(&self, editor: &OpenEditor) -> Vec<(u64, Option<u64>)> {let uri = editor.document().uri();let language = editor.document().language_id.clone();let candidate = Candidate { uri: &uri, language: &language };- self.language_features.ordered(REGISTER, &candidate).iter().map(|registration| (registration.handle, registration.args.clone())).collect()+ self.language_features.ordered(REGISTER, &candidate).iter().map(|registration| (registration.handle, registration.debounce_delay_ms)).collect()}/// `createStateWithAppliedEdit`, then the refetch of a text change: typing (and the keyboard's deletes and Tab,@@ -330,7 +332,7 @@ impl Workbench {// `debounceDelayMs` of the providers, the feature's otherwise.let delay = match explicit {true => Duration::ZERO,- false => providers.iter().filter_map(|(_, args)| args.get(8).and_then(Value::as_u64)).max().map_or(DEBOUNCE, Duration::from_millis),+ false => providers.iter().filter_map(|(_, debounce)| *debounce).max().map_or(DEBOUNCE, Duration::from_millis),};self.inline_completions.request = Some(cx.spawn(async move |workbench, cx| {cx.background_executor().timer(delay).await;@@ -360,7 +362,7 @@ impl Workbench {}));}- fn request_inline_completions(&self, model_id: u32, explicit: bool, change_hint: &Value, providers: &[(u64, Vec<Value>)]) -> Vec<(u64, futures::channel::oneshot::Receiver<Result<Value, Value>>)> {+ fn request_inline_completions(&self, model_id: u32, explicit: bool, change_hint: &Value, providers: &[(u64, Option<u64>)]) -> Vec<(u64, futures::channel::oneshot::Receiver<Result<Value, Value>>)> {let Some(editor) = self.editors.active().filter(|editor| editor.model_id == model_id) else { return Vec::new() };let uri = editor.document().uri();let head = editor.selection().head;@@ -767,7 +769,7 @@ impl Workbench {let mut edits = vec![(item.edit.start, item.edit.end, String::new(), false)];edits.extend(item.additional_edits.iter().map(|(start, end, text)| (*start, *end, text.clone(), false)));let change = editor.execute_edits(edits, Some(vec![crate::editor::Selection::caret(item.edit.start)]), EditReason::Unknown("inlineSuggestion.accept"));- self.editor_edited(change, true, "inlineSuggestion.accept", cx);+ self.model_content_changed(change, Cursor { moved: true, source: "inlineSuggestion.accept", reveal: Reveal::All }, cx);let snippets = [(item.edit.start, item.edit.start, template.as_str(), false)];self.insert_snippets(super::snippet_controller::SnippetInsert { snippets: &snippets, clipboard: None, undo_stop_before: false, undo_stop_after: true, reason: "inlineSuggestion.accept" }, cx);}@@ -781,7 +783,7 @@ impl Workbench {edits.extend(item.additional_edits.iter().map(|(start, end, text)| (*start, *end, text.clone(), false)));let change = editor.execute_edits(edits, Some(selections), EditReason::Unknown("inlineSuggestion.accept"));editor.push_undo_stop();- self.editor_edited(change, true, "inlineSuggestion.accept", cx);+ self.model_content_changed(change, Cursor { moved: true, source: "inlineSuggestion.accept", reveal: Reveal::All }, cx);}}if let Some(id) = item.command["id"].as_str().filter(|id| !id.is_empty()) {@@ -822,7 +824,7 @@ impl Workbench {let edits = replacements.into_iter().map(|edit| (edit.start, edit.end, edit.text, false)).collect();let change = editor.execute_edits(edits, Some(selections), EditReason::Unknown("inlineSuggestion.accept"));self.host.send("ExtHostLanguageFeatures", "$handleInlineCompletionPartialAccept", vec![json!(item.handle), json!(item.pid), json!(item.idx), json!(text.encode_utf16().count()), json!({ "kind": if kind == PartialKind::Word { 0 } else { 1 }, "acceptedLength": text.encode_utf16().count() })]);- self.editor_edited(change, true, "inlineSuggestion.accept", cx);+ self.model_content_changed(change, Cursor { moved: true, source: "inlineSuggestion.accept", reveal: Reveal::All }, cx);}/// ghostTextView.ts: a ghost text part drawn in the gap of its injected text in `editorGhostText.foreground`, italicdiff --git a/native/crates/app/src/workbench/input_box_view.rs b/native/crates/app/src/workbench/input_box_view.rsindex cca2136cead..c5f57806232 100644--- a/native/crates/app/src/workbench/input_box_view.rs+++ b/native/crates/app/src/workbench/input_box_view.rs@@ -17,6 +17,7 @@ use super::search_editor_widget::SEARCH_EDITOR_FIELDS;use super::search_view::{SEARCH_FIELDS, SearchField};use crate::commands::Outcome;use crate::input_box::{InputBox, Motion};+use crate::workbench::editor_options::CURSOR_BLINKING;/// Which input element: the quick input's, the Explorer's inline editor, the find widget's, one of the Search view's/// inputs, one of the search editor's query widget, or the Keyboard Shortcuts editor's.@@ -506,7 +507,7 @@ impl Workbench {pub(super) fn input_caret_on(&self, id: InputId, since_moved: Duration) -> bool {let code_editor = matches!(id, InputId::SettingsSearch | InputId::ExtensionsSearch | InputId::ScmInput | InputId::DebugConsole | InputId::BreakpointWidget);if code_editor {- if self.input_carets_hidden || self.setting("editor.cursorBlinking") == "solid" {+ if self.input_carets_hidden || self.global_editor_option(&CURSOR_BLINKING) == "solid" {return true;}} else if self.input_carets_hidden {diff --git a/native/crates/app/src/workbench/keyboard.rs b/native/crates/app/src/workbench/keyboard.rsindex 9c7408df930..43faf245505 100644--- a/native/crates/app/src/workbench/keyboard.rs+++ b/native/crates/app/src/workbench/keyboard.rs@@ -19,6 +19,7 @@ use crate::commands::Outcome;use crate::editor::TextDocument;use crate::keybindings::{self, Chord, Item, Resolution, Resolver};use crate::system_wide_keybindings::{HotKeys, SystemWide};+use crate::workbench::editor_options::{COLUMN_SELECTION, FOLDING};/// The keybindings and the dispatch state of `AbstractKeybindingService`.pub struct Keybindings {@@ -462,7 +463,7 @@ impl Workbench {// viewDescriptorService.ts `<view id>.active`: the Changes view has no `when`, so it is always active.context.insert("workbench.scm.active".into(), json!(true));context.insert("scm.providerCount".into(), json!(self.scm.model.providers.len()));- context.insert("dirtyWorkingCopies".into(), json!(self.editors.editors.iter().any(|editor| editor.is_dirty())));+ context.insert("dirtyWorkingCopies".into(), json!(self.editors.all_editors().any(|editor| editor.is_dirty())));// toggleMultiCursorModifier.ts `MultiCursorModifierContextKeyController`.context.insert("multiCursorModifier".into(), json!(if self.multi_cursor_modifier_is_cmd() { "ctrlCmd" } else { "altKey" }));self.word_wrap_context(&mut context);@@ -559,8 +560,8 @@ impl Workbench {context.insert("selectionAnchorSet".into(), json!(editor.selection_anchor.is_some()));context.insert("emptyEditorHintActionsVisible".into(), json!(self.empty_editor_hint_actions_visible()));context.insert("editorTabMovesFocus".into(), json!(self.tab_focus_mode()));- context.insert("editorColumnSelection".into(), self.setting("editor.columnSelection"));- context.insert("foldingEnabled".into(), self.setting("editor.folding"));+ context.insert("editorColumnSelection".into(), json!(self.editor_option(editor, &COLUMN_SELECTION)));+ context.insert("foldingEnabled".into(), json!(self.editor_option(editor, &FOLDING)));// A custom editor diff has no code editor.if self.editors.active_diff().is_none_or(|diff| diff.custom.is_none()) {context.insert("editorLangId".into(), json!(editor.document().language_id));diff --git a/native/crates/app/src/workbench/language_detection.rs b/native/crates/app/src/workbench/language_detection.rsindex 2b6ef2cc8ab..666536d9c5a 100644--- a/native/crates/app/src/workbench/language_detection.rs+++ b/native/crates/app/src/workbench/language_detection.rs@@ -9,8 +9,7 @@ use std::process::{ChildStdin, Command, Stdio};use std::sync::{Arc, Mutex};use std::time::Duration;-use futures::StreamExt;-use futures::channel::{mpsc, oneshot};+use futures::channel::oneshot;use gpui::{AnyElement, Context, Rgba, Task, div, prelude::*, px};use serde_json::{Value, json};@@ -36,15 +35,6 @@ pub(super) struct LanguageDetection {status: Option<Task<()>>,/// The detected language the status bar offers for the active untitled model.offered: Option<String>,- /// The models edited where no `Context` reaches (`send_model_edit`), for `language_detection_content_changed`.- edited: Option<mpsc::UnboundedSender<(String, PathBuf)>>,-}--impl LanguageDetection {- pub(super) fn content_changed(&self, scheme: &str, path: &Path) {- let edited = self.edited.as_ref().expect("register_language_detection ran");- drop(edited.unbounded_send((scheme.to_owned(), path.to_owned())));- }}pub(super) enum Detection {@@ -59,17 +49,7 @@ struct Worker {}impl Workbench {- pub(super) fn register_language_detection(&mut self, cx: &mut Context<Self>) {- let (edited, mut edits) = mpsc::unbounded();- self.language_detection.edited = Some(edited);- cx.spawn(async move |workbench, cx| {- while let Some((scheme, path)) = edits.next().await {- if workbench.update(cx, |workbench, cx| workbench.language_detection_content_changed(&scheme, &path, cx)).is_err() {- return;- }- }- })- .detach();+ pub(super) fn register_language_detection(&mut self) {self.commands.register(DETECT_COMMAND, |workbench, _, window, cx| {let Some(editor) = workbench.editors.active() else { return Outcome::done() };let (scheme, path) = (editor.document().scheme.clone(), editor.document().path.clone());diff --git a/native/crates/app/src/workbench/language_status.rs b/native/crates/app/src/workbench/language_status.rsindex 793999f5cfa..803bc1977ca 100644--- a/native/crates/app/src/workbench/language_status.rs+++ b/native/crates/app/src/workbench/language_status.rs@@ -165,7 +165,7 @@ impl Workbench {};let uri = editor.document().uri();let candidate = Candidate { uri: &uri, language: &editor.document().language_id };- let mut statuses: Vec<Status> = self.language_status.registry.ordered(SET, &candidate).into_iter().map(|registration| Status::from_dto(®istration.args[2])).collect();+ let mut statuses: Vec<Status> = self.language_status.registry.ordered(SET, &candidate).into_iter().map(|registration| Status::from_dto(®istration.metadata)).collect();statuses.extend(self.formatter_conflict().map(formatter_conflict_status));statuses.extend(self.limit_indicator_statuses(editor));statuses.sort_by(|a, b| b.severity.cmp(&a.severity).then_with(|| a.source.cmp(&b.source)).then_with(|| a.id.cmp(&b.id)));diff --git a/native/crates/app/src/workbench/linked_editing.rs b/native/crates/app/src/workbench/linked_editing.rsindex 2f433c2348c..8439e4f485d 100644--- a/native/crates/app/src/workbench/linked_editing.rs+++ b/native/crates/app/src/workbench/linked_editing.rs@@ -10,6 +10,8 @@ use serde_json::{Value, json};use super::Workbench;use super::links::{end_after, tracked};+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::commands::Outcome;use crate::editor::{ContentChanged, EditReason, OpenEditor, Position, char_column, expand_tabs, utf16_column};use crate::editor::in_place_replace::DEFAULT_WORD_REGEXP;@@ -162,7 +164,7 @@ impl Workbench {let change = editor.execute_edits_in_last_undo_group(edits, EditReason::Unknown("linkedEditing"));self.linked_editing.ignore_change = true;if let Some(change) = change {- self.editor_edited(Some(change), false, "linkedEditing", cx);+ self.model_content_changed(Some(change), Cursor { moved: false, source: "linkedEditing", reveal: Reveal::All }, cx);}self.linked_editing.ignore_change = false;}@@ -321,7 +323,7 @@ impl Workbench {fn execute_linked_editing_provider(&mut self, args: &[Value], cx: &mut Context<Self>) -> Outcome {let uri = args.first().cloned().unwrap_or(Value::Null);let position = args.get(1).cloned().unwrap_or(Value::Null);- let language = self.editors.editors.iter().find(|editor| editor.document().uri() == uri).map(|editor| editor.document().language_id.clone()).unwrap_or_default();+ let language = self.editors.all_editors().find(|editor| editor.document().uri() == uri).map(|editor| editor.document().language_id.clone()).unwrap_or_default();let candidate = Candidate { uri: &uri, language: &language };let handles: Vec<u64> = self.language_features.ordered(REGISTER, &candidate).iter().map(|registration| registration.handle).collect();let caller = self.host.caller();diff --git a/native/crates/app/src/workbench/linked_editing/tests.rs b/native/crates/app/src/workbench/linked_editing/tests.rsindex ee1e57a3387..c7809ba5cf7 100644--- a/native/crates/app/src/workbench/linked_editing/tests.rs+++ b/native/crates/app/src/workbench/linked_editing/tests.rs@@ -136,3 +136,19 @@ fn escape_ends_linked_editing(cx: &mut TestAppContext) {type_text(&workbench, cx, "x");assert_eq!(text(&workbench, cx), "<dxiv></div>");}++/// linkedEditing.ts `_executeLinkedEditingProvider` takes the model from `modelService.getModel(resource)`: a file+/// shown only in another group asks the provider of its language first.+#[gpui::test]+fn execute_asks_the_language_provider_of_a_model_in_another_group(cx: &mut TestAppContext) {+ let (workbench, cx, receiver) = open(cx);+ answer_ranges(&receiver, json!([]), cx);+ workbench.update(cx, |workbench, _| workbench.language_features.register(REGISTER, vec![json!(4), json!("plaintext")]));+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ receiver.try_iter().for_each(drop);+ let uri = workbench.read_with(cx, |workbench, _| workbench.editors.all_tabs().find(|editor| editor.document().scheme == "file").unwrap().document().uri());+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command("_executeLinkedEditingProvider", vec![uri, json!({ "lineNumber": 1, "column": 3 })], window, cx)));+ cx.run_until_parked();+ let first = receiver.try_iter().find(|message| message.method == "$provideLinkedEditingRanges" && message.args[1]["scheme"] == "file").map(|message| message.args[0].clone());+ assert_eq!(first, Some(json!(4)));+}diff --git a/native/crates/app/src/workbench/links.rs b/native/crates/app/src/workbench/links.rsindex c3d5f8767f2..87a3eb40d3a 100644--- a/native/crates/app/src/workbench/links.rs+++ b/native/crates/app/src/workbench/links.rs@@ -15,6 +15,7 @@ use crate::editor::{ContentChanged, OpenEditor, Position, char_column, expand_tause crate::language_features::Candidate;use crate::link_computer::compute_links;use crate::notifications::{Notification, Severity};+use crate::workbench::editor_options::MOUSE_MIDDLE_CLICK_ACTION;const REGISTER: &str = "$registerDocumentLinkProvider";/// The editor worker's link provider (`editorWorkerService.ts` registers `computeLinks` for every model).@@ -218,7 +219,7 @@ impl Workbench {/// `openLink`, on a link opens it. Answers whether it took the click.pub(super) fn links_mouse_up(&mut self, line: usize, visible: f32, modifiers: Modifiers, middle: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {let triggered = match middle {- true => self.setting("editor.mouseMiddleClickAction") == json!("openLink"),+ true => self.global_editor_option(&MOUSE_MIDDLE_CLICK_ACTION) == "openLink",false => self.link_trigger_modifier(modifiers),};let Some(editor) = self.editors.active().filter(|_| triggered) else { return false };@@ -247,7 +248,7 @@ impl Workbench {/// model's file.fn open_link_occurrence(&mut self, index: usize, window: &mut Window, cx: &mut Context<Self>) {let link = self.links.list[index].clone();- let supports_resolve = self.language_features.registration(link.handle).is_some_and(|registration| registration.args.get(2) == Some(&json!(true)));+ let supports_resolve = self.language_features.registration(link.handle).is_some_and(|registration| registration.supports_resolve);let resolve = match (link.dto.get("url").filter(|url| !url.is_null()), supports_resolve) {(Some(_), _) | (None, false) => None,(None, true) => Some(self.host.call_cancellable("ExtHostLanguageFeatures", "$resolveDocumentLink", vec![json!(link.handle), link.dto["cacheId"].clone()])),@@ -340,7 +341,7 @@ impl Workbench {let candidate = Candidate { uri: &uri, language: &editor.document().language_id };let lines = editor.document().lines.clone();let folders = self.workspace_folders();- let registrations: Vec<(u64, bool)> = self.language_features.ordered(REGISTER, &candidate).iter().rev().map(|registration| (registration.handle, registration.args.get(2) == Some(&json!(true)))).collect();+ let registrations: Vec<(u64, bool)> = self.language_features.ordered(REGISTER, &candidate).iter().rev().map(|registration| (registration.handle, registration.supports_resolve)).collect();let call = self.host.caller();let (sender, receiver) = futures::channel::oneshot::channel();cx.spawn(async move |_, _| {diff --git a/native/crates/app/src/workbench/marker_navigation.rs b/native/crates/app/src/workbench/marker_navigation.rsindex 1b1b95fb4e9..5a9c7c961b7 100644--- a/native/crates/app/src/workbench/marker_navigation.rs+++ b/native/crates/app/src/workbench/marker_navigation.rs@@ -8,6 +8,8 @@ use serde_json::Value;use super::Workbench;use super::hover::HoverOptions;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::commands::Outcome;use crate::editor::marker_decorations::validate;use crate::editor::{LINE_HEIGHT, OpenEditor, Position, Selection, VERTICAL_SCROLLBAR_WIDTH, TextDocument, VerticalReveal, utf16_column, column_x};@@ -226,7 +228,7 @@ impl Workbench {drop(document);editor.set_selections(vec![Selection { anchor: start, head: end }]);editor.reveal_range(start, end, VerticalReveal::NearTop, viewport);- self.host.send_selection(editor, "code.jump");+ self.cursor_position_changed(Cursor { moved: true, source: "code.jump", reveal: Reveal::Nothing }, cx);window.focus(&self.editor_focus, cx);self.navigate_markers(forward, multi_file, window, cx);}@@ -281,7 +283,7 @@ impl Workbench {false => editor.reveal_range(Position::new(position.line, 0), below, VerticalReveal::Simple, viewport),}editor.reveal_range(position, position, VerticalReveal::CenterIfOutsideViewport, viewport);- self.host.send_selection(editor, "api");+ self.cursor_position_changed(Cursor { moved: true, source: "api", reveal: Reveal::Nothing }, cx);self.aria_status(&aria_label);self.editor_scrolled(cx);window.focus(&self.editor_focus, cx);@@ -301,7 +303,7 @@ impl Workbench {fn end_marker_session(&mut self) {let Some(session) = self.marker_navigation.session.take() else { return };let Some(widget) = session.widget else { return };- if let Some(editor) = self.editors.editors.iter_mut().chain(&mut self.editors.models).find(|editor| editor.model_id == session.model_id) {+ if let Some(editor) = self.editors.all_editors_mut().find(|editor| editor.model_id == session.model_id) {editor.remove_view_zone(widget.zone_id);}}@@ -557,7 +559,7 @@ impl Workbench {let position = validate(&editor.document().lines, line, column);editor.set_selections(vec![Selection::caret(position)]);editor.reveal_range(position, position, VerticalReveal::CenterIfOutsideViewport, viewport);- self.host.send_selection(editor, "code.jump");+ self.cursor_position_changed(Cursor { moved: true, source: "code.jump", reveal: Reveal::Nothing }, cx);self.editor_scrolled(cx);}diff --git a/native/crates/app/src/workbench/middle_scroll.rs b/native/crates/app/src/workbench/middle_scroll.rsindex b88c15051fd..3a76d3f5e40 100644--- a/native/crates/app/src/workbench/middle_scroll.rs+++ b/native/crates/app/src/workbench/middle_scroll.rs@@ -4,9 +4,9 @@use std::time::Instant;use gpui::{Context, Div, Pixels, Point, Styled, div, px};-use serde_json::json;use super::Workbench;+use crate::workbench::editor_options::SCROLL_ON_MIDDLE_CLICK;pub(super) struct MiddleScroll {origin: Point<Pixels>,@@ -23,7 +23,7 @@ impl Workbench {cx.notify();return false;}- if !middle || self.setting("editor.scrollOnMiddleClick") != json!(true) {+ if !middle || !self.global_editor_option(&SCROLL_ON_MIDDLE_CLICK) {return false;}self.middle_scroll = Some(MiddleScroll { origin: position, mouse: position, last_frame: Instant::now(), did_scroll: false });@@ -55,7 +55,7 @@ impl Workbench {/// session runs, so the caller asks for the next frame.pub(super) fn middle_scroll_frame(&mut self, cx: &mut Context<Self>) -> bool {// The autorun drops the session when the setting turns off.- if self.setting("editor.scrollOnMiddleClick") != json!(true) {+ if !self.global_editor_option(&SCROLL_ON_MIDDLE_CLICK) {self.middle_scroll = None;}let viewport = self.editors.viewport;diff --git a/native/crates/app/src/workbench/minimap_view.rs b/native/crates/app/src/workbench/minimap_view.rsindex cb28fa71102..ca54a8b26d8 100644--- a/native/crates/app/src/workbench/minimap_view.rs+++ b/native/crates/app/src/workbench/minimap_view.rs@@ -13,7 +13,6 @@ use gpui::{Task, TextRun, Window, canvas, div, fill, font, point, prelude::*, px, size,};use image::{Frame, RgbaImage};-use serde_json::json;use super::Workbench;use crate::editor::minimap::{@@ -21,9 +20,10 @@ use crate::editor::minimap::{SliderOptions, compute_minimap_layout, contained_minimap_line_count, decoration_fills, render_lines,};use crate::editor::folding::{FoldDecoration, hidden_range};-use crate::editor::section_headers::{FindOptions, MARK_SECTION_HEADER_REGEX, SectionHeader, find_section_headers, fit_section_header};+use crate::editor::section_headers::{FindOptions, SectionHeader, find_section_headers, fit_section_header};use crate::editor::{OpenEditor, Position, TextModel, VERTICAL_SCROLLBAR_WIDTH, Viewport};use crate::theme::relative_luminance;+use crate::workbench::editor_options::{MINIMAP_ENABLED, MINIMAP_MARK_SECTION_HEADER_REGEX, MINIMAP_RENDER_CHARACTERS, MINIMAP_SHOW_MARK_SECTION_HEADERS, MINIMAP_SHOW_REGION_SECTION_HEADERS};/// minimap.css `.minimap-slider` opacity transition, and `_hideSliderAfterScrollScheduler`.const SLIDER_FADE: Duration = Duration::from_millis(100);@@ -726,12 +726,12 @@ impl Workbench {_ => MinimapSize::Proportional,},side: if string("side").as_deref() == Some("left") { MinimapSide::Left } else { MinimapSide::Right },- render_characters: self.setting("editor.minimap.renderCharacters").as_bool().unwrap_or(defaults.render_characters),+ render_characters: self.global_editor_option(&MINIMAP_RENDER_CHARACTERS),max_column: number("maxColumn", defaults.max_column, 1., 10000.),scale: number("scale", defaults.scale, 1., 3.),};MinimapSettings {- enabled: self.setting("editor.minimap.enabled").as_bool().unwrap_or(true),+ enabled: self.global_editor_option(&MINIMAP_ENABLED),layout,slider_always: string("showSlider").as_deref() == Some("always"),autohide: match string("autohide").as_deref() {@@ -744,11 +744,9 @@ impl Workbench {pub(super) fn section_header_options(&self) -> SectionHeaderOptions {let float = |key: &str, default: f64, min: f64, max: f64| self.setting(key).as_f64().unwrap_or(default).clamp(min, max);- let mark_regex = self.setting("editor.minimap.markSectionHeaderRegex");- let mark_regex = mark_regex.as_str().filter(|pattern| onig::Regex::new(pattern).is_ok()).unwrap_or(MARK_SECTION_HEADER_REGEX);- SectionHeaderOptions {- show_region: self.setting("editor.minimap.showRegionSectionHeaders") != json!(false),- mark_regex: (self.setting("editor.minimap.showMarkSectionHeaders") != json!(false)).then(|| mark_regex.to_string()),+ SectionHeaderOptions {+ show_region: self.global_editor_option(&MINIMAP_SHOW_REGION_SECTION_HEADERS),+ mark_regex: self.global_editor_option(&MINIMAP_SHOW_MARK_SECTION_HEADERS).then(|| self.global_editor_option(&MINIMAP_MARK_SECTION_HEADER_REGEX)),font_size: float("editor.minimap.sectionHeaderFontSize", 9., 4., 32.),letter_spacing: float("editor.minimap.sectionHeaderLetterSpacing", 1., 0., 5.),}diff --git a/native/crates/app/src/workbench/model_events.rs b/native/crates/app/src/workbench/model_events.rsnew file mode 100644index 00000000000..5f9299a404e--- /dev/null+++ b/native/crates/app/src/workbench/model_events.rs@@ -0,0 +1,139 @@+//! The one announcement of a model content change and of a cursor move: textModel.ts `onDidChangeContent` of the+//! model, then codeEditorWidget.ts `onDidChangeModelContent` and `onDidChangeCursorPosition` of the active code+//! editor when it shows it. The host hears the change first, so every provider request follows the edit.++use std::rc::Rc;++use gpui::Context;++use super::Workbench;+use crate::editor::{ContentChanged, Reveal, VerticalReveal, uri_string};+use crate::navigation::Reason;++/// How the active editor's cursors moved with an announcement.+pub(super) struct Cursor<'a> {+ pub moved: bool,+ /// cursorEvents.ts `source`: "keyboard", "mouse", "api", "modelChange", ...+ pub source: &'a str,+ pub reveal: Reveal,+}++impl Cursor<'_> {+ /// An edit made without the editor (bulk edit, host edit, save participant, revert): the cursors only follow it.+ pub(super) fn model_change() -> Cursor<'static> {+ Cursor { moved: false, source: "modelChange", reveal: Reveal::Nothing }+ }+}++impl Workbench {+ /// `onDidChangeContent` of the change's model, then `onDidChangeModelContent` and `onDidChangeCursorPosition`+ /// when the active code editor shows it. Without a change, `cursor_position_changed`.+ pub(super) fn model_content_changed(&mut self, change: Option<ContentChanged>, cursor: Cursor, cx: &mut Context<Self>) {+ let Some(change) = change else { return self.cursor_position_changed(cursor, cx) };+ let shown = self.editors.active().is_some_and(|editor| Rc::ptr_eq(&editor.model, &change.model));+ self.send_model_change(&change, shown, cursor.source);+ self.model_listeners(&change, cx);+ if shown {+ self.editor_listeners(Some(&change), cursor, cx);+ }+ cx.notify();+ }++ /// `onDidChangeCursorPosition` of the active code editor.+ pub(super) fn cursor_position_changed(&mut self, cursor: Cursor, cx: &mut Context<Self>) {+ if self.editors.active().is_none() {+ return;+ }+ self.editor_listeners(None, cursor, cx);+ cx.notify();+ }++ /// mainThreadDocuments.ts and mainThreadEditor.ts: `$acceptModelChanged`, then the selection of the shown model.+ fn send_model_change(&mut self, change: &ContentChanged, shown: bool, source: &str) {+ let editor = self.editors.all_editors().find(|editor| Rc::ptr_eq(&editor.model, &change.model)).expect("an edited model is open");+ self.host.send_model_change(&self.editors, editor, change);+ if shown {+ self.host.send_selection(self.editors.active().expect("shown"), source);+ }+ }++ /// The listeners of any model.+ fn model_listeners(&mut self, change: &ContentChanged, cx: &mut Context<Self>) {+ let model = change.model.borrow();+ let (scheme, path) = (model.document.scheme.clone(), model.document.path.clone());+ drop(model);+ self.search_model_changed(&scheme, &path);+ self.language_detection_content_changed(&scheme, &path, cx);+ self.semantic_tokens_content_changed(&uri_string(&scheme, &path), cx);+ self.cell_status_bar_content_changed(&scheme, &path, cx);+ }++ /// The listeners of the active code editor: its content changed with `change`, its cursors as `cursor` says.+ fn editor_listeners(&mut self, change: Option<&ContentChanged>, cursor: Cursor, cx: &mut Context<Self>) {+ let Cursor { moved, source, reveal } = cursor;+ let scrolled = self.scroll_smoothly(cx, |editor, viewport| match reveal {+ Reveal::Nothing => {}+ Reveal::All => editor.reveal_cursors(source, viewport),+ Reveal::Position(position) => editor.reveal_position(position, source, viewport),+ Reveal::CenterIfOutside(position) => editor.reveal_range(position, position, VerticalReveal::CenterIfOutsideViewport, viewport),+ });+ if scrolled {+ self.editor_scrolled(cx);+ }+ if change.is_none() && !moved {+ return;+ }+ self.find_editor_edited(change);+ self.record_navigation(Some(if change.is_some() { Reason::Edit } else { Reason::of_source(source) }));+ if change.is_none() {+ self.host.send_selection(self.editors.active().expect("checked by the caller"), source);+ }+ if let Some(change) = change {+ self.editor_content_listeners(change, cx);+ }+ if moved {+ self.output_cursor_moved();+ }+ self.snippet_state_changed(cx);+ self.suggest_editor_changed(change.is_some(), source, cx);+ self.parameter_hints_editor_changed(source, cx);+ self.code_actions_cursor_changed(change.is_some(), cx);+ self.standalone_color_picker_cursor_changed(cx);+ self.linked_editing_editor_changed(change, true, cx);+ match change {+ Some(change) => self.inline_completions_edited(change, source, cx),+ None => self.inline_completions_cursor_moved(cx),+ }+ }++ /// `onDidChangeModelContent` of the active code editor.+ fn editor_content_listeners(&mut self, change: &ContentChanged, cx: &mut Context<Self>) {+ // The edit can unfold a region or change the line count, which changes the visible lines.+ self.host.send_visible_ranges(&self.editors);+ let document = self.editors.active().expect("shown").document();+ let (scheme, path) = (document.scheme.clone(), document.path.clone());+ drop(document);+ self.schedule_debug_inline_values(cx);+ self.search_editor_edited(&path, change);+ self.format_on_type_content_changed(change);+ self.links_content_changed(change, cx);+ // untitledTextEditorModel.ts `onDidChangeName`: the first line names the tab.+ if scheme == "untitled" {+ self.host.send_tabs(&self.editors);+ }+ // commentReply.ts `onDidChangeModelContent`: the comment editor grows or shrinks by its lines.+ if scheme == super::comments::INPUT_SCHEME {+ self.sync_comment_widgets();+ }+ self.schedule_keybinding_marks(cx);+ self.schedule_unsupported_settings_markers(cx);+ self.code_lens_content_changed(cx);+ self.refresh_commenting_ranges(true, cx);+ self.inlay_hints_content_changed(cx);+ self.color_detector_content_changed(cx);+ self.color_picker_content_changed(cx);+ }+}++#[cfg(test)]+mod tests;diff --git a/native/crates/app/src/workbench/model_events/tests.rs b/native/crates/app/src/workbench/model_events/tests.rsnew file mode 100644index 00000000000..03c531a88fb--- /dev/null+++ b/native/crates/app/src/workbench/model_events/tests.rs@@ -0,0 +1,246 @@+use std::path::{Path, PathBuf};+use std::sync::mpsc::Receiver;+use std::sync::{Arc, Mutex};+use std::time::Duration;++use config::registry::Registry;+use config::service::Settings;+use exthost::scan::{file_uri, scan_extension};+use gpui::{TestAppContext, VisualTestContext};+use serde_json::{Value, json};++use crate::host_sync::{HostMessage, HostSync};+use crate::languages::Languages;+use crate::theme::load_theme;+use crate::workbench::Workbench;++/// The test's folder holding `a.ts` with `text` and `.vscode/settings.json` with `settings`, opened with the+/// language feature providers of `registrations` (method, arguments).+fn open<'a>(text: &str, settings: Value, registrations: &[(&str, Value)], cx: &'a mut TestAppContext) -> (gpui::Entity<Workbench>, &'a mut VisualTestContext, Receiver<HostMessage>, PathBuf) {+ let app_root = Path::new(env!("VSCODE_SRC")).to_path_buf();+ let theme = load_theme(&[scan_extension(&app_root.join("extensions/theme-defaults"), true).unwrap()], "Dark Modern").unwrap();+ let dir = std::env::temp_dir().join(format!("code-gpui-model-events-{}-{}", std::process::id(), crate::test_name()));+ std::fs::create_dir_all(dir.join(".vscode")).unwrap();+ std::fs::write(dir.join("a.ts"), text).unwrap();+ std::fs::write(dir.join(".vscode/settings.json"), settings.to_string()).unwrap();+ let workspace = config::workspace::Workspace::folder(dir.clone());+ let settings = Arc::new(Mutex::new(Settings::load(Registry::with_extensions(&[]), dir.join("User"), Some(workspace.clone()))));+ let (sender, receiver) = std::sync::mpsc::channel();+ let registrations: Vec<(String, Vec<Value>)> = registrations.iter().map(|(method, args)| (method.to_string(), args.as_array().unwrap().clone())).collect();+ let (workbench, cx) = cx.add_window_view(|window, cx| {+ let mut workbench = Workbench::new(theme, app_root.clone(), Some(workspace), Languages::new(&[]), settings, HostSync::new(sender), cx);+ workbench.watch_editor_focus(window, cx);+ for (method, args) in registrations {+ workbench.language_features.register(&method, args);+ }+ workbench.open_file(dir.join("a.ts"), true, window, cx);+ window.focus(&workbench.editor_focus, cx);+ workbench.inlay_hints_registrations_changed(cx);+ workbench.color_providers_changed(cx);+ workbench.linked_editing_reinitialize(false, cx);+ workbench+ });+ cx.update(|window, _| window.activate_window());+ cx.run_until_parked();+ (workbench, cx, receiver, dir)+}++/// Waits out every debounce, then answers each provider request sent so far; returns how many came per method.+fn answer(receiver: &Receiver<HostMessage>, cx: &mut VisualTestContext) -> Vec<String> {+ cx.executor().advance_clock(Duration::from_secs(5));+ cx.run_until_parked();+ let mut asked = Vec::new();+ for message in receiver.try_iter() {+ let answer = match message.method {+ "$provideCodeLenses" => json!({ "cacheId": 1, "lenses": [{ "cacheId": [1, 0], "range": { "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 2 }, "command": { "id": "lens.run", "title": "run" } }] }),+ "$provideCodeActions" => json!({ "cacheId": 1, "actions": [] }),+ "$provideSignatureHelp" => json!({ "id": 1, "signatures": [{ "label": "foo(a)", "parameters": [{ "label": "a" }] }], "activeSignature": 0, "activeParameter": 0 }),+ "$provideInlayHints" | "$provideDocumentColors" | "$provideLinkedEditingRanges" => Value::Null,+ _ => continue,+ };+ asked.push(message.method.to_owned());+ let _ = message.reply.expect("a call").send(Ok(answer));+ }+ cx.run_until_parked();+ asked+}++fn run(workbench: &gpui::Entity<Workbench>, command: &str, args: Vec<Value>, cx: &mut VisualTestContext) {+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.execute_command(command, args, window, cx)));+ cx.run_until_parked();+}++/// codelensController.ts, inlayHintsController.ts, colorDetector.ts and links.ts listen to the code editor's+/// `onDidChangeModelContent`, which fires for a workspace edit of its model as for typing.+#[gpui::test]+fn a_workspace_edit_of_the_shown_model_asks_its_providers_again(cx: &mut TestAppContext) {+ let registrations = [+ ("$registerCodeLensSupport", json!([1, "*", 9])),+ ("$registerInlayHintsProvider", json!([2, "*", null, 2])),+ ("$registerDocumentColorProvider", json!([3, "*"])),+ ];+ let (workbench, cx, receiver, dir) = open("a\nb\n", json!({}), ®istrations, cx);+ let mut first = answer(&receiver, cx);+ first.sort();+ assert_eq!(first, ["$provideCodeLenses", "$provideDocumentColors", "$provideInlayHints"]);+ let edit = json!([{ "resource": file_uri(&dir.join("a.ts")), "textEdit": { "range": { "startLineNumber": 2, "startColumn": 1, "endLineNumber": 2, "endColumn": 1 }, "text": "https://example.com " } }]);+ workbench.update(cx, |workbench, cx| workbench.apply_workspace_text_edits(&edit, &json!([]), files::operations::new_undo_group(), None, cx)).unwrap();+ let mut again = answer(&receiver, cx);+ again.sort();+ again.dedup();+ assert_eq!(again, ["$provideCodeLenses", "$provideDocumentColors", "$provideInlayHints"]);+ // The editor worker's link provider found the new URL.+ workbench.read_with(cx, |workbench, _| assert_eq!(workbench.links.list.len(), 1));+ std::fs::remove_dir_all(dir).unwrap();+}++/// codeActionModel.ts `CodeActionOracle`, parameterHintsModel.ts `onCursorChange`, linkedEditing.ts and+/// snippetController2.ts `_updateState` listen to `onDidChangeCursorPosition`, which a jump to the next snippet+/// placeholder and an Alt+click adding a cursor fire.+#[gpui::test]+fn a_cursor_move_wakes_the_cursor_listeners(cx: &mut TestAppContext) {+ let registrations = [+ ("$registerCodeActionSupport", json!([1, "*", {}, "test", "test.ext", false])),+ ("$registerSignatureHelpProvider", json!([2, "*", { "triggerCharacters": [], "retriggerCharacters": [] }])),+ ("$registerLinkedEditingRangeProvider", json!([3, "*"])),+ ];+ let (workbench, cx, receiver, dir) = open("foo\nbar\n", json!({ "editor.linkedEditing": true }), ®istrations, cx);+ run(&workbench, "editor.action.insertSnippet", vec![json!({ "snippet": "x${1:y}z${2:w}$0" })], cx);+ run(&workbench, "editor.action.triggerParameterHints", vec![], cx);+ answer(&receiver, cx);+ workbench.update_in(cx, |workbench, window, _| assert_eq!(workbench.key_context(window)["parameterHintsVisible"], json!(true)));+ run(&workbench, "jumpToNextSnippetPlaceholder", vec![], cx);+ let mut asked = answer(&receiver, cx);+ asked.sort();+ asked.dedup();+ assert_eq!(asked, ["$provideCodeActions", "$provideLinkedEditingRanges", "$provideSignatureHelp"]);++ workbench.read_with(cx, |workbench, _| assert!(workbench.editors.active().unwrap().snippet_session.is_some()));+ workbench.update(cx, |workbench, cx| workbench.click_text(1, 0., alt(), false, 1, cx));+ workbench.read_with(cx, |workbench, _| assert!(workbench.editors.active().unwrap().snippet_session.is_none(), "a cursor left the placeholders"));+ std::fs::remove_dir_all(dir).unwrap();+}++fn alt() -> gpui::Modifiers {+ gpui::Modifiers { alt: true, ..Default::default() }+}++/// outputView.ts `onDidChangeCursorPosition`: a click (`CursorChangeReason.Explicit`) off the last line turns+/// auto scrolling off.+#[gpui::test]+fn a_click_in_the_output_view_locks_its_scroll(cx: &mut TestAppContext) {+ let (workbench, cx, _, dir) = open("", json!({}), &[], cx);+ let file = dir.join("exthost.log");+ std::fs::write(&file, "one\ntwo\n").unwrap();+ let request = exthost::session::ForwardedRequest { req: 1, proxy: "MainThreadLogger", method: "$registerLogger".into(), args: vec![json!({ "id": "exthost", "name": "Extension Host", "resource": file_uri(&file) })] };+ workbench.update_in(cx, |workbench, window, cx| drop(workbench.handle_host_request(request, window, cx)));+ run(&workbench, "workbench.action.output.toggleOutput", vec![], cx);+ workbench.update_in(cx, |workbench, window, cx| workbench.focus_group(crate::editor::PANEL_GROUP, window, cx));+ run(&workbench, "cursorBottom", vec![], cx);+ workbench.read_with(cx, |workbench, _| assert!(!workbench.output_view.scroll_lock));+ workbench.update(cx, |workbench, cx| workbench.click_text(0, 0., gpui::Modifiers::default(), false, 1, cx));+ workbench.read_with(cx, |workbench, _| assert!(workbench.output_view.scroll_lock));+ std::fs::remove_dir_all(dir).unwrap();+}++/// The one-character edit of each path, as the table test makes it.+#[derive(Clone, Copy, Debug)]+enum EditPath {+ Type,+ Command,+ Undo,+ BulkEditOfTheActiveEditor,+ BulkEditOfAnotherGroup,+ BulkEditOfAModelWithoutEditor,+ ReplaceAll,+ HostEdit,+ SaveParticipant,+ Revert,+}++fn insert_at_start(file: &Path, text: &str) -> Value {+ json!([{ "resource": file_uri(file), "textEdit": { "range": { "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 1 }, "text": text } }])+}++/// Every path tells the host first, then wakes the content listeners of the active code editor when it shows the+/// model (codelensController.ts, inlayHintsController.ts, colorDetector.ts) and none when it does not. The shown+/// editor's selection follows with the source cursor.ts gives it; None: a gap of the M27 ledger row.+#[gpui::test]+fn every_path_of_an_edit_tells_the_host_first_and_wakes_the_shown_editor(cx: &mut TestAppContext) {+ let table = [+ (EditPath::Type, true, Some("keyboard")),+ (EditPath::Command, true, None),+ (EditPath::Undo, true, None),+ (EditPath::BulkEditOfTheActiveEditor, true, Some("modelChange")),+ (EditPath::BulkEditOfAnotherGroup, false, None),+ (EditPath::BulkEditOfAModelWithoutEditor, false, None),+ (EditPath::ReplaceAll, true, None),+ (EditPath::HostEdit, true, Some("MainThreadTextEditor")),+ (EditPath::SaveParticipant, true, None),+ (EditPath::Revert, true, Some("modelChange")),+ ];+ let registrations = [+ ("$registerCodeLensSupport", json!([1, "*", 9])),+ ("$registerInlayHintsProvider", json!([2, "*", null, 2])),+ ("$registerDocumentColorProvider", json!([3, "*"])),+ ];+ let providers = ["$provideCodeLenses", "$provideDocumentColors", "$provideInlayHints"];+ for (path, shown, source) in table {+ let (workbench, cx, receiver, dir) = open("a", json!({ "files.insertFinalNewline": true }), ®istrations, cx);+ std::fs::write(dir.join("b.ts"), "b").unwrap();+ let a = dir.join("a.ts");+ match path {+ EditPath::Undo => run(&workbench, "type", vec![json!({ "text": "x" })], cx),+ EditPath::Revert => std::fs::write(&a, "ab").unwrap(),+ EditPath::BulkEditOfAnotherGroup => {+ run(&workbench, "workbench.action.splitEditor", vec![], cx);+ workbench.update_in(cx, |workbench, window, cx| workbench.open_file(dir.join("b.ts"), true, window, cx));+ }+ _ => {}+ }+ answer(&receiver, cx);+ let edit_a = |workbench: &mut Workbench, cx: &mut gpui::Context<Workbench>| workbench.apply_workspace_text_edits(&insert_at_start(&a, "x"), &json!([]), files::operations::new_undo_group(), None, cx).unwrap();+ match path {+ EditPath::Type => run(&workbench, "type", vec![json!({ "text": "x" })], cx),+ EditPath::Command => run(&workbench, "deleteRight", vec![], cx),+ EditPath::Undo => run(&workbench, "undo", vec![], cx),+ EditPath::BulkEditOfTheActiveEditor | EditPath::BulkEditOfAnotherGroup => drop(workbench.update(cx, edit_a)),+ EditPath::BulkEditOfAModelWithoutEditor => drop(workbench.update(cx, |workbench, cx| workbench.apply_workspace_text_edits(&insert_at_start(&dir.join("b.ts"), "x"), &json!([]), files::operations::new_undo_group(), None, cx).unwrap())),+ EditPath::ReplaceAll => {+ run(&workbench, "actions.find", vec![], cx);+ workbench.update(cx, |workbench, _| {+ let viewport = workbench.editors.viewport;+ let editor = workbench.editors.active_mut().unwrap();+ let new = crate::editor::find::state::NewFindState { search_string: Some("a".into()), replace_string: Some("x".into()), ..Default::default() };+ workbench.find.controller.change(editor, viewport, new, false);+ });+ run(&workbench, "editor.action.replaceAll", vec![], cx);+ }+ EditPath::HostEdit => {+ let edits = json!([{ "range": { "startLineNumber": 1, "startColumn": 1, "endLineNumber": 1, "endColumn": 1 }, "text": "x" }]);+ let version = workbench.read_with(cx, |workbench, _| workbench.editors.active().unwrap().text_model().version_id);+ workbench.update(cx, |workbench, cx| workbench.apply_host_edits(&json!(version), &edits, &json!({}), cx)).unwrap();+ }+ EditPath::SaveParticipant => run(&workbench, "workbench.action.files.save", vec![], cx),+ EditPath::Revert => run(&workbench, "workbench.action.files.revert", vec![], cx),+ }+ cx.executor().advance_clock(Duration::from_secs(5));+ cx.run_until_parked();+ let messages: Vec<HostMessage> = receiver.try_iter().collect();+ let methods: Vec<&str> = messages.iter().map(|message| message.method).collect();+ if let Some(source) = source {+ let selection = messages.iter().find(|message| message.method == "$acceptEditorPropertiesChanged").expect("the shown editor's selection");+ assert_eq!(selection.args[1]["selections"]["source"], source, "{path:?}");+ }+ let changed = methods.iter().position(|method| *method == "$acceptModelChanged");+ let first_request = methods.iter().position(|method| providers.contains(method));+ assert!(changed.is_some(), "{path:?}: no $acceptModelChanged in {methods:?}");+ assert!(first_request.is_none_or(|request| changed < Some(request)), "{path:?}: a provider was asked before the host heard the edit: {methods:?}");+ let mut asked: Vec<&str> = methods.iter().copied().filter(|method| providers.contains(method)).collect();+ asked.sort();+ asked.dedup();+ let expected: &[&str] = if shown { &providers } else { &[] };+ assert_eq!(asked, expected, "{path:?}");+ std::fs::remove_dir_all(dir).unwrap();+ }+}diff --git a/native/crates/app/src/workbench/notebook_editor.rs b/native/crates/app/src/workbench/notebook_editor.rsindex 0cfe756f184..183a9666de0 100644--- a/native/crates/app/src/workbench/notebook_editor.rs+++ b/native/crates/app/src/workbench/notebook_editor.rs@@ -24,6 +24,7 @@ use crate::notebook::renderers::{self, Renderer};use crate::notebook::{self, CODE, MARKUP, NOTEBOOK_EDITOR_SCHEME, NotebookModel};use crate::undo_redo::Direction;use crate::webview::{ClipView, Retained, Webview};+use crate::workbench::editor_options::{FONT_FAMILY, FONT_SIZE, SCROLL_BEYOND_LAST_LINE};/// The webview ids of notebook editors, followed by the tab's model id.pub(super) const WEBVIEW_ID_PREFIX: &str = "notebook-";@@ -375,12 +376,12 @@ impl Workbench {/// notebookOptions.ts `computeWebviewOptions` and backLayerWebView.ts `_generateStyles`, `renderOptions`.fn notebook_webview_options(&self) -> Value {- let font_size = self.setting("editor.fontSize").as_f64().unwrap_or(12.);+ let font_size = self.setting(FONT_SIZE.key).as_f64().unwrap_or(12.);let setting_number = |key: &str| self.setting(key).as_f64().filter(|value| *value > 0.);let output_font_size = setting_number("notebook.output.fontSize").unwrap_or(font_size);let output_line_height = setting_number("notebook.output.lineHeight").map_or(LINE_HEIGHT as f64, |height| if height < 8. { height * output_font_size } else { height }).round();let line_limit = self.setting("notebook.output.textLineLimit").as_f64().unwrap_or(30.);- let editor_font = self.setting("editor.fontFamily");+ let editor_font = self.setting(FONT_FAMILY.key);let output_font = self.setting("notebook.output.fontFamily").as_str().filter(|font| !font.is_empty()).map(str::to_owned).or(editor_font.as_str().map(str::to_owned)).unwrap_or_default();let markup_font_size = setting_number("notebook.markup.fontSize");let markdown_line_height = setting_number("notebook.markdown.lineHeight");@@ -988,7 +989,7 @@ impl Workbench {let Some(model) = self.host.notebooks.editor(tab).and_then(|editor| self.host.notebooks.model(&editor.notebook)) else { return 0. };let content_height = self.notebook_rows(tab, model).last().map_or(layout::LIST_PADDING_TOP, |row| row.layout.top + row.layout.height);let history = self.host.notebooks.interactives.iter().any(|interactive| interactive.notebook == model.uri_string());- if history || self.setting("editor.scrollBeyondLastLine") == json!(false) {+ if history || !self.global_editor_option(&SCROLL_BEYOND_LAST_LINE) {return content_height;}let height = self.notebook_views.views.get(&tab).map_or(0., |view| f32::from(view.bounds.get().size.height));diff --git a/native/crates/app/src/workbench/notebook_editor/find.rs b/native/crates/app/src/workbench/notebook_editor/find.rsindex 312ab448de1..9de1eab1469 100644--- a/native/crates/app/src/workbench/notebook_editor/find.rs+++ b/native/crates/app/src/workbench/notebook_editor/find.rs@@ -13,6 +13,9 @@ use super::super::list_scroll::ListId;use super::super::input_box_view::{InputId, InputLook, InputView};use super::overview_ruler::RulerDecoration;use super::{CellReveal, parse_cell_id};+use crate::editor::Reveal;+use crate::workbench::editor_options::WORD_SEPARATORS;+use crate::workbench::model_events::Cursor;use crate::editor::find::controller::{Seed, selection_search_string};use crate::editor::find::model::search_params;use crate::editor::find::replace_pattern::{ReplacePattern, parse_replace_string};@@ -299,7 +302,7 @@ impl Workbench {}let Some(model) = self.host.notebooks.model(¬ebook) else { return };let filters = find.filters;- let word_separators = self.setting("editor.wordSeparators");+ let word_separators = self.setting(WORD_SEPARATORS.key);let params = search_params(&find.state, word_separators.as_str().unwrap_or(word_operations::DEFAULT_WORD_SEPARATORS));let editing = self.notebook_views.views.get(&tab).map(|view| view.editing.clone()).unwrap_or_default();let mut matches = Vec::new();@@ -490,8 +493,7 @@ impl Workbench {};if let Some(editor) = self.editors.active_mut() {editor.set_selections(vec![Selection { anchor: range.start, head: range.end }]);- let editor = self.editors.active().expect("set above");- self.host.send_selection(editor, "api");+ self.cursor_position_changed(Cursor { moved: true, source: "api", reveal: Reveal::Nothing }, cx);}self.reveal_notebook_line(tab, index, range.start.line, cx);cx.notify();@@ -568,7 +570,7 @@ impl Workbench {let text = self.notebook_find_replace_pattern().build(found.matches.as_deref(), find.state.preserve_case);let edits = vec![(found.range.clone(), text)];let uri = find.matches[cell].uri.clone();- self.notebook_find_edit_cell(&uri, edits);+ self.notebook_find_edit_cell(&uri, edits, cx);self.notebook_find_research(cx);cx.notify();}@@ -585,20 +587,19 @@ impl Workbench {.map(|cell| (cell.uri.clone(), cell.content.iter().map(|found| (found.range.clone(), pattern.build(found.matches.as_deref(), preserve_case))).collect())).collect();for (uri, edits) in cells {- self.notebook_find_edit_cell(&uri, edits);+ self.notebook_find_edit_cell(&uri, edits, cx);}self.notebook_find_research(cx);cx.notify();}/// One edit of a cell's text model, sent to the extension host as any model change.- fn notebook_find_edit_cell(&mut self, uri: &Value, edits: Vec<(Range<Position>, String)>) {+ fn notebook_find_edit_cell(&mut self, uri: &Value, edits: Vec<(Range<Position>, String)>, cx: &mut Context<Self>) {let Ok((scheme, path)) = super::uri_parts(uri) else { return };let Some(editor) = self.editors.model_mut(scheme, &path) else { return };let edits = edits.into_iter().map(|(range, text)| (range.start, range.end, text, false)).collect();let Some(change) = editor.execute_edits(edits, None, crate::editor::EditReason::Unknown("bulkEdit")) else { return };- let editor = self.editors.model(scheme, &path).expect("edited above");- self.host.send_model_change(&self.editors, editor, &change);+ self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);}/// The find matches of a cell editor: the source matches and which of them is the current onediff --git a/native/crates/app/src/workbench/notebook_editor/folding.rs b/native/crates/app/src/workbench/notebook_editor/folding.rsindex 30c451ba640..96b6f0af7e1 100644--- a/native/crates/app/src/workbench/notebook_editor/folding.rs+++ b/native/crates/app/src/workbench/notebook_editor/folding.rs@@ -9,6 +9,7 @@ use super::CellRow;use crate::commands::Outcome;use super::super::editor_view::EDITOR_FONT;use crate::notebook::{CODE, NotebookModel, layout, outline};+use crate::workbench::editor_options::FONT_SIZE;impl Workbench {/// `notebook-folding-indicator`: centered in the markdown gutter, the expanded chevron only on the hovered or@@ -49,7 +50,7 @@ impl Workbench {let label = if length == 1 { "1 cell hidden".to_owned() } else { format!("{length} cells hidden") };let font_size = match self.setting("notebook.output.fontSize").as_f64() {Some(size) if size > 0. => size,- _ => self.setting("editor.fontSize").as_f64().unwrap_or(12.),+ _ => self.setting(FONT_SIZE.key).as_f64().unwrap_or(12.),};let button = |icon: &str, id: &'static str| {self.icon(icon, 20., 16., self.color("icon.foreground"))diff --git a/native/crates/app/src/workbench/outline_pane.rs b/native/crates/app/src/workbench/outline_pane.rsindex 46cd7ba7fa7..7e2143b48d4 100644--- a/native/crates/app/src/workbench/outline_pane.rs+++ b/native/crates/app/src/workbench/outline_pane.rs@@ -11,6 +11,8 @@ use super::custom_editors::custom_navigation;use super::hover::{HoverContent, HoverOptions};use super::outline_actions::SortOrder;use super::quick_access::goto_symbol::position_of;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::editor::{Selection, VerticalReveal};use crate::outline_model::{OutlineChildren, OutlineElement, OutlineMarker, OutlineModel, Range};@@ -528,7 +530,7 @@ impl Workbench {let (start, end) = (position_of(editor, start), position_of(editor, end));editor.set_selections(vec![Selection { anchor: start, head: end }]);editor.reveal_range(start, end, VerticalReveal::NearTopIfOutsideViewport, viewport);- self.host.send_selection(self.editors.active().expect("checked above"), "code.navigation");+ self.cursor_position_changed(Cursor { moved: true, source: "code.navigation", reveal: Reveal::Nothing }, cx);self.editor_scrolled(cx);if select {window.focus(&self.editor_focus, cx);diff --git a/native/crates/app/src/workbench/output_view.rs b/native/crates/app/src/workbench/output_view.rsindex 4c27b945ba0..9ed98dee6b6 100644--- a/native/crates/app/src/workbench/output_view.rs+++ b/native/crates/app/src/workbench/output_view.rs@@ -284,10 +284,7 @@ impl Workbench {let change = model.execute_edits(vec![(end, end, text, false)], None, EditReason::ApplyEdits);model.mark_saved();if let Some(change) = change {- self.send_model_edit(OUTPUT_SCHEME, path, &change, cx);- if self.output_editor_active() {- self.links_content_changed(&change, cx);- }+ self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);}}Content::Reset(text) => {diff --git a/native/crates/app/src/workbench/parameter_hints.rs b/native/crates/app/src/workbench/parameter_hints.rsindex 9c6a8e8c954..dff5032bb6b 100644--- a/native/crates/app/src/workbench/parameter_hints.rs+++ b/native/crates/app/src/workbench/parameter_hints.rs@@ -267,7 +267,7 @@ impl Workbench {let candidate = Candidate { uri: &uri, language: &language };let (mut trigger, mut retrigger) = (false, false);for registration in self.language_features.ordered(REGISTER, &candidate) {- let metadata = registration.args.get(2).unwrap_or(&Value::Null);+ let metadata = ®istration.metadata;let has = |key: &str| metadata[key].as_array().into_iter().flatten().filter_map(Value::as_str).any(|character| character.chars().next() == Some(last));trigger |= has("triggerCharacters");retrigger |= has("triggerCharacters") || has("retriggerCharacters");diff --git a/native/crates/app/src/workbench/paste_edits.rs b/native/crates/app/src/workbench/paste_edits.rsindex c2e6e81c4ea..c6858f62923 100644--- a/native/crates/app/src/workbench/paste_edits.rs+++ b/native/crates/app/src/workbench/paste_edits.rs@@ -348,7 +348,7 @@ impl Workbench {/// `applyEditAndShowIfNeeded` after the resolve: `createCombinedWorkspaceEdit` through the bulk edit service.fn apply_paste_edit(&mut self, edit: PasteEdit, ranges: &[(Position, Position)], cx: &mut Context<Self>) {- let supports_resolve = edit.handle.and_then(|handle| self.language_features.registration(handle)).is_some_and(|registration| registration.args[2]["supportsResolve"] == true);+ let supports_resolve = edit.handle.and_then(|handle| self.language_features.registration(handle)).is_some_and(|registration| registration.metadata["supportsResolve"] == true);let resolve = (supports_resolve && !edit.cache_id.is_null()).then(|| self.host.call_cancellable("ExtHostLanguageFeatures", "$resolvePasteEdit", vec![json!(edit.handle), edit.cache_id.clone()]));let Some(resolve) = resolve else {return self.apply_resolved_paste_edit(&edit, ranges, cx);@@ -442,7 +442,7 @@ impl Workbench {}/// `DataTransferFileCache.resolveFileData`: the path of item `data_id` of the transfer of request `request_id`.- pub(super) fn transfer_file_path(&self, request_id: u64, data_id: &str) -> Result<Value, Value> {+ pub(crate) fn transfer_file_path(&self, request_id: u64, data_id: &str) -> Result<Value, Value> {let Some((_, files)) = self.paste_edits.transfer_files.as_ref().filter(|(requests, _)| (request_id as usize) < *requests) else {return Err(serialized_error("No data transfer found"));};@@ -467,7 +467,7 @@ impl Workbench {let uri = editor.document().uri();let candidate = Candidate { uri: &uri, language: &editor.document().language_id };let providers = self.language_features.ordered(REGISTER, &candidate);- providers.iter().filter(|registration| registration.args[2]["supportsPaste"] == true || registration.args[2]["supportsCopy"] == true).map(|registration| (registration.handle, registration.args[2].clone())).collect()+ providers.iter().filter(|registration| registration.metadata["supportsPaste"] == true || registration.metadata["supportsCopy"] == true).map(|registration| (registration.handle, registration.metadata.clone())).collect()}/// `mergeInDataFromCopy`: the copy's prepared data when the clipboard carries its handle, of the providers whosediff --git a/native/crates/app/src/workbench/paste_edits/drop.rs b/native/crates/app/src/workbench/paste_edits/drop.rsindex b449d4e5f54..6fab581c661 100644--- a/native/crates/app/src/workbench/paste_edits/drop.rs+++ b/native/crates/app/src/workbench/paste_edits/drop.rs@@ -37,7 +37,7 @@ impl Workbench {.ordered(REGISTER, &Candidate { uri: &uri, language: &editor.document().language_id }).into_iter().filter(|registration| {- let mimes = ®istration.args[2]["dropMimeTypes"];+ let mimes = ®istration.metadata["dropMimeTypes"];mimes.is_null() || strings(mimes).iter().any(|pattern| items.iter().any(|item| matches_mime(pattern, item[0].as_str().unwrap_or_default())))}).map(|registration| registration.handle)diff --git a/native/crates/app/src/workbench/peek_view.rs b/native/crates/app/src/workbench/peek_view.rsindex e86d080dc8d..3379e97060d 100644--- a/native/crates/app/src/workbench/peek_view.rs+++ b/native/crates/app/src/workbench/peek_view.rs@@ -5,6 +5,8 @@ use gpui::{AnyElement, Context, Div, MouseButton, MouseDownEvent, PathBuilder, Suse serde_json::{Value, json};use super::Workbench;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::editor::{OpenEditor, PeekOwner, Position, Selection, TextDocument, VERTICAL_SCROLLBAR_WIDTH, VerticalReveal, column_x};/// zoneWidget.ts: the arrow is a third of a line high; peekView.ts: the head is 1.2 lines.@@ -88,13 +90,13 @@ impl Workbench {let stored = json!({ "ratio": layout.ratio, storage.height_key: layout.height_in_lines });self.profile_storage.lock().unwrap().set(storage.key, stored.to_string());}- if let Some(editor) = self.editors.editors.iter_mut().chain(&mut self.editors.models).find(|editor| editor.model_id == layout.model_id) {+ if let Some(editor) = self.editors.all_editors_mut().find(|editor| editor.model_id == layout.model_id) {editor.remove_view_zone(layout.zone_id);}}/// `_showImpl`: the range selected and its lines and the zone revealed.- pub(super) fn reveal_peek_range(&mut self, start: Position, end: Position) {+ pub(super) fn reveal_peek_range(&mut self, start: Position, end: Position, cx: &mut Context<Self>) {let viewport = self.editors.viewport;let editor = self.editors.active_mut().expect("a peek opens in the active editor");editor.set_selections(vec![Selection { anchor: start, head: end }]);@@ -103,7 +105,7 @@ impl Workbench {true => editor.reveal_range(Position::new(last, 0), Position::new(last, 0), VerticalReveal::NearTop, viewport),false => editor.reveal_range(Position::new(start.line, 0), Position::new(end.line + 1, 0), VerticalReveal::Simple, viewport),}- self.host.send_selection(editor, "api");+ self.cursor_position_changed(Cursor { moved: true, source: "api", reveal: Reveal::Nothing }, cx);}/// The zone's position (`ZoneWidget.position`).@@ -334,7 +336,7 @@ impl Workbench {/// The file a peek previews: an open model's, else one the peek read.pub(super) fn peek_document<'a>(&'a self, uri: &str, read: &'a [TextDocument]) -> Option<PeekDocument<'a>> {- if let Some(editor) = self.editors.editors.iter().chain(&self.editors.models).find(|editor| editor.document().uri_string() == uri) {+ if let Some(editor) = self.editors.all_editors().find(|editor| editor.document().uri_string() == uri) {return Some(PeekDocument::Open(editor.document()));}read.iter().find(|document| document.uri_string() == uri).map(PeekDocument::Read)diff --git a/native/crates/app/src/workbench/preferences.rs b/native/crates/app/src/workbench/preferences.rsindex a8845762223..0ce30ecd418 100644--- a/native/crates/app/src/workbench/preferences.rs+++ b/native/crates/app/src/workbench/preferences.rs@@ -15,6 +15,8 @@ use serde_json::{Value, json};use super::Workbench;use super::host_requests::uri_parts;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::commands::Outcome;use crate::default_settings::{default_settings_content, raw_default_settings};use crate::notifications::{Notification, Severity};@@ -319,7 +321,7 @@ impl Workbench {let viewport = self.editors.viewport;let editor = self.editors.active_mut().expect("still active");editor.reveal_range(position, position, VerticalReveal::NearTop, viewport);- self.host.send_selection(editor, "api");+ self.cursor_position_changed(Cursor { moved: true, source: "api", reveal: Reveal::Nothing }, cx);self.editor_scrolled(cx);if edit {self.trigger_suggest(super::suggest_controller::TriggerOptions::new(false), cx);diff --git a/native/crates/app/src/workbench/preferences/edit_setting.rs b/native/crates/app/src/workbench/preferences/edit_setting.rsindex 33e54f4fe35..28feeedd5bb 100644--- a/native/crates/app/src/workbench/preferences/edit_setting.rs+++ b/native/crates/app/src/workbench/preferences/edit_setting.rs@@ -17,6 +17,7 @@ use super::unsupported_settings::{ParsedSetting, parse_settings, settings_file_tuse crate::commands::Outcome;use crate::editor::{EditReason, OpenEditor, Position, Selection};use crate::menus::MenuAction;+use crate::workbench::editor_options::GLYPH_MARGIN;/// `toggleEditPreferencesForMouseMoveDelayer`.const MOUSE_MOVE_DELAY: Duration = Duration::from_millis(75);@@ -103,7 +104,7 @@ impl Workbench {/// The line (1-based) of `editor`'s pencil, if one shows: the pointer's, else the cursor's unless the pointer's/// hid it (`showEditPreferencesWidget` with glyph margins on).pub(in crate::workbench) fn edit_setting_line(&self, editor: &OpenEditor) -> Option<usize> {- if self.setting("editor.glyphMargin") == json!(false) {+ if !self.editor_option(editor, &GLYPH_MARGIN) {return None;}let state = &self.edit_setting;diff --git a/native/crates/app/src/workbench/problems_quick_fix.rs b/native/crates/app/src/workbench/problems_quick_fix.rsindex ebc128cc5dc..31ec8acdf5c 100644--- a/native/crates/app/src/workbench/problems_quick_fix.rs+++ b/native/crates/app/src/workbench/problems_quick_fix.rs@@ -93,7 +93,7 @@ impl Workbench {fn request_problems_quick_fixes(&mut self, marker: &Arc<Marker>, cx: &mut Context<Self>) {let Some(index) = self.problems_quick_fixes.markers.iter().position(|fixes| Arc::ptr_eq(&fixes.marker, marker) && fixes.request.is_none()) else { return };- let Some(editor) = self.editors.editors.iter().chain(&self.editors.models).find(|editor| editor.document().uri_string() == marker.resource) else { return };+ let Some(editor) = self.editors.all_editors().find(|editor| editor.document().uri_string() == marker.resource) else { return };let request = self.request_marker_quick_fixes(editor, marker);let marker = marker.clone();self.problems_quick_fixes.markers[index].request = Some(cx.spawn(async move |workbench, cx| {diff --git a/native/crates/app/src/workbench/quick_access/goto_line.rs b/native/crates/app/src/workbench/quick_access/goto_line.rsindex 5f13f129d4b..2761c067262 100644--- a/native/crates/app/src/workbench/quick_access/goto_line.rs+++ b/native/crates/app/src/workbench/quick_access/goto_line.rs@@ -4,6 +4,8 @@use gpui::{Context, Window};use super::Accept;+use crate::editor::Reveal;+use crate::workbench::model_events::Cursor;use crate::editor::cursor::visible_column_from_column;use crate::editor::{Position, Scroll, Selection, VerticalReveal, char_column, column_from_visible};use crate::quick_input::{Button, Entry, Item};@@ -112,10 +114,10 @@ impl Workbench {let Some(editor) = self.editors.active_mut() else { return };editor.set_selections(vec![Selection { anchor: position, head: position }]);editor.reveal_range(position, position, VerticalReveal::Center, viewport);- self.host.send_selection(editor, "code.jump");if let Some(state) = self.quick_access.goto_line.as_mut().filter(|state| state.model_id == editor.model_id) {(state.selections, state.scroll) = (editor.selections.clone(), editor.scroll);}+ self.cursor_position_changed(Cursor { moved: true, source: "code.jump", reveal: Reveal::Nothing }, cx);self.editor_scrolled(cx);if !in_background {window.focus(&self.editor_focus, cx);@@ -134,11 +136,12 @@ impl Workbench {let Some(state) = self.quick_access.goto_line.take() else { return };let viewport = self.editors.viewport;let Some(editor) = self.editors.active_mut().filter(|editor| editor.model_id == state.model_id) else { return };- if editor.selections != state.selections {+ let moved = editor.selections != state.selections;+ if moved {editor.set_selections(state.selections);- self.host.send_selection(editor, "restoreState");}editor.set_scroll(state.scroll.top, state.scroll.left, viewport);+ self.cursor_position_changed(Cursor { moved, source: "restoreState", reveal: Reveal::Nothing }, cx);self.editor_scrolled(cx);}diff --git a/native/crates/app/src/workbench/quick_access/workspace_symbols.rs b/native/crates/app/src/workbench/quick_access/workspace_symbols.rsindex 177fde075a0..1e4ee49db5b 100644--- a/native/crates/app/src/workbench/quick_access/workspace_symbols.rs+++ b/native/crates/app/src/workbench/quick_access/workspace_symbols.rs@@ -89,7 +89,7 @@ impl Workbench {cx.spawn_in(window, async move |workbench, cx| {cx.background_executor().timer(TYPING_SEARCH_DELAY).await;let Ok(calls) = workbench.update(cx, |workbench, _| {- let providers: Vec<(u64, bool)> = workbench.language_features.all(REGISTER).map(|registration| (registration.handle, registration.args.get(1) == Some(&json!(true)))).collect();+ let providers: Vec<(u64, bool)> = workbench.language_features.all(REGISTER).map(|registration| (registration.handle, registration.supports_resolve)).collect();providers.into_iter().map(|(handle, resolve)| (handle, resolve, workbench.host.call_cancellable("ExtHostLanguageFeatures", "$provideWorkspaceSymbols", vec![json!(handle), json!(query)])))diff --git a/native/crates/app/src/workbench/quick_open.rs b/native/crates/app/src/workbench/quick_open.rsindex 5bd6f71fba3..94d63aff7d8 100644--- a/native/crates/app/src/workbench/quick_open.rs+++ b/native/crates/app/src/workbench/quick_open.rs@@ -13,6 +13,8 @@ use storage::Storage;use super::Workbench;use super::quick_access::Accept;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::anything_quick_access::{self, FileEntry, FilePick, TextRange};use crate::editor::{Position, Selection, VerticalReveal};use crate::editor_history::{EditorHistory, HISTORY_STORAGE_KEY};@@ -355,7 +357,7 @@ impl Workbench {if !before_layout {editor.reveal_range(selection.start(), selection.end(), reveal, viewport);}- self.host.send_selection(editor, "code.navigation");+ self.cursor_position_changed(Cursor { moved: true, source: "code.navigation", reveal: Reveal::Nothing }, cx);if before_layout {self.editors.reveal_after_layout = Some(selection.start());}diff --git a/native/crates/app/src/workbench/references_peek.rs b/native/crates/app/src/workbench/references_peek.rsindex 34a30960c3e..33203fe47d2 100644--- a/native/crates/app/src/workbench/references_peek.rs+++ b/native/crates/app/src/workbench/references_peek.rs@@ -12,6 +12,7 @@ use crate::commands::Outcome;use crate::editor::decoration_types::TextDecoration;use crate::editor::{OpenEditor, PeekOwner, Position, Selection, TextDocument, VerticalReveal, Viewport, char_column, utf16_column};use crate::references_model::{Location, ReferencesModel};+use crate::workbench::editor_options::STABLE_PEEK;/// referencesTree.ts `Delegate.getHeight`.const ROW_HEIGHT: f32 = 23.;@@ -160,7 +161,7 @@ impl Workbench {return;}let layout = self.open_peek_zone(&LAYOUT, range.start);- self.reveal_peek_range(range.start, range.end);+ self.reveal_peek_range(range.start, range.end, cx);let editor = self.editors.active().expect("the peek opens in the active editor");let uri = editor.document().uri_string();let start = (range.start.line + 1, utf16_column(&editor.document().lines[range.start.line], range.start.column) + 1);@@ -497,7 +498,7 @@ impl Workbench {let Some(reference) = workbench.focused_reference_row().or_else(|| workbench.references_peek.widget.as_ref()?.revealed) else { return };let side = modifiers.control || modifiers.platform || modifiers.alt;// `editor.stablePeek` keeps the peek open on a double click in the preview.- if side || workbench.setting("editor.stablePeek") != json!(true) {+ if side || !workbench.global_editor_option(&STABLE_PEEK) {workbench.open_peek_reference(reference, side, false, window, cx);}});diff --git a/native/crates/app/src/workbench/references_peek/tests.rs b/native/crates/app/src/workbench/references_peek/tests.rsindex 6cc4be3ad0e..74398d65437 100644--- a/native/crates/app/src/workbench/references_peek/tests.rs+++ b/native/crates/app/src/workbench/references_peek/tests.rs@@ -112,10 +112,42 @@ fn the_preview_is_a_text_editor_of_the_host(cx: &mut TestAppContext) {run(&workbench, cx, "togglePeekWidgetFocus");assert!(deltas(&receiver).iter().any(|delta| delta["newActiveEditor"] == json!(preview)));let selection = json!([{ "selectionStartLineNumber": 1, "selectionStartColumn": 2, "positionLineNumber": 1, "positionColumn": 2 }]);- workbench.update_in(cx, |workbench, window, cx| workbench.host_request("MainThreadTextEditors", "$trySetSelections", &[json!(preview), selection], window, cx)).unwrap();+ workbench.update_in(cx, |workbench, window, cx| workbench.answer_host_request("MainThreadTextEditors", "$trySetSelections", &[json!(preview), selection], window, cx)).unwrap();workbench.read_with(cx, |workbench, _| assert_eq!(workbench.editors.peek_editor(crate::editor::PeekOwner::References).unwrap().selection().head, Position::new(0, 1)));run(&workbench, cx, "closeReferenceSearch");let closed = deltas(&receiver);assert!(closed.iter().any(|delta| delta["removedEditors"] == json!([preview]) && delta["newActiveEditor"] == json!(pane)));}++/// referencesModel.ts `FileReferences.resolve` asks `ITextModelService` for the model, which holds it while any group+/// shows it: a peek previews a file shown only in another group from its open model, edits included.+#[gpui::test]+fn the_preview_of_a_file_in_another_group_is_its_open_model(cx: &mut TestAppContext) {+ let (workbench, cx, _receiver, dir) = open(cx, "peek-other-group", "foo\n");+ run(&workbench, cx, "cursorEnd");+ workbench.update_in(cx, |workbench, window, cx| _ = workbench.execute_command("type", vec![json!({ "text": "bar" })], window, cx));+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ let uri = crate::editor::uri_string("file", &dir.join("a.txt"));+ let previewed = workbench.read_with(cx, |workbench, _| match workbench.peek_document(&uri, &[]) {+ Some(crate::workbench::peek_view::PeekDocument::Open(document)) => Some(document.lines[0].clone()),+ _ => None,+ });+ assert_eq!(previewed.as_deref(), Some("foobar"));+}++/// peekView.ts `PeekViewWidget.dispose` removes its zone from the editor it lives in, whichever group shows it: a peek+/// closed from another group leaves no empty zone behind.+#[gpui::test]+fn closing_a_peek_from_another_group_removes_its_zone(cx: &mut TestAppContext) {+ let (workbench, cx, receiver, dir) = open(cx, "peek-close-other-group", "foo\nbar foo\nfoo\n");+ run(&workbench, cx, "editor.action.revealDefinition");+ answer(&receiver, "$provideDefinition", json!([link(&dir, 2, 5, 8), link(&dir, 3, 1, 4)]), cx);+ let peek_editor = workbench.read_with(cx, |workbench, _| workbench.references_peek.widget.as_ref().unwrap().layout.model_id);+ workbench.update_in(cx, |workbench, window, cx| workbench.peek_reference_selected(1, Selected::Side, window, cx));+ cx.run_until_parked();+ assert!(workbench.read_with(cx, |workbench, _| workbench.references_peek.widget.is_some()), "the peek stays open in the first group");+ run(&workbench, cx, "closeReferenceSearch");+ let zones = workbench.read_with(cx, |workbench, _| workbench.editors.all_tabs().find(|editor| editor.model_id == peek_editor).unwrap().view_zones.len());+ assert_eq!(zones, 0);+}diff --git a/native/crates/app/src/workbench/rename.rs b/native/crates/app/src/workbench/rename.rsindex c4e5456f056..cf5eab24a69 100644--- a/native/crates/app/src/workbench/rename.rs+++ b/native/crates/app/src/workbench/rename.rs@@ -15,6 +15,7 @@ use crate::host_sync::FileJob;use crate::input_box::InputBox;use crate::language_features::Candidate;use crate::notifications::{Notification, Severity};+use crate::workbench::editor_options::RENAME_ENABLE_PREVIEW;pub(super) const REGISTER: &str = "$registerRenameSupport";const EDITOR_FONT: &str = "Menlo";@@ -151,7 +152,7 @@ impl Workbench {let uri = editor.document().uri();let lines = editor.document().lines.clone();let word = editor.document().word_at(&self.languages, position.line, position.column);- let supports_resolve: Vec<bool> = handles.iter().map(|handle| self.language_features.registration(*handle).is_some_and(|registration| registration.args.get(2) == Some(&json!(true)))).collect();+ let supports_resolve: Vec<bool> = handles.iter().map(|handle| self.language_features.registration(*handle).is_some_and(|registration| registration.supports_resolve)).collect();let call = self.host.caller();let handles = handles.to_vec();async move {@@ -336,7 +337,7 @@ impl Workbench {/// `supportPreview`: the Refactor Preview handles bulk edits, so the setting decides.fn rename_supports_preview(&self) -> bool {- self.setting("editor.rename.enablePreview") == json!(true)+ self.global_editor_option(&RENAME_ENABLE_PREVIEW)}/// `rename` for `vscode.executeDocumentRenameProvider`: the edit of the first provider that answers.diff --git a/native/crates/app/src/workbench/search_actions.rs b/native/crates/app/src/workbench/search_actions.rsindex 6cc0ebfda7a..3f12b5cf051 100644--- a/native/crates/app/src/workbench/search_actions.rs+++ b/native/crates/app/src/workbench/search_actions.rs@@ -28,6 +28,7 @@ use crate::input_box::InputBox;use crate::menus::MenuId;use crate::search_editor::SearchConfiguration;use crate::search_model::{MessageLink, SearchResult, after_replace_all_message, no_results_message, replace_all_confirmation_message, result_count_message};+use crate::workbench::editor_options::{FIND_SEED_SEARCH_STRING_FROM_SELECTION, WORD_SEPARATORS};#[cfg(test)]mod tests;@@ -583,7 +584,7 @@ impl Workbench {/// `updateTextFromSelection`: the active editor's selection, or the word at the cursor, seeds the search input/// (`getSelectionTextFromEditor`); setting the value searches on type.fn update_text_from_selection(&mut self, allow_unselected_word: bool, window: &mut Window, cx: &mut Context<Self>) -> bool {- let seed = self.setting("editor.find.seedSearchStringFromSelection");+ let seed = self.setting(FIND_SEED_SEARCH_STRING_FROM_SELECTION.key);if seed == false || seed == "never" {return false;}@@ -912,7 +913,7 @@ impl Workbench {let setting = move |folder: &Path, key: &str| settings.lock().unwrap().get_value(Some(key), &Overrides { resource: Some(folder), ..Overrides::default() }).unwrap_or(Value::Null);let mut query = search_paths::expanded_text_query(&pattern, &workspace, include, exclude, &options, &setting)?;if config.only_open_editors {- let open_editors: Vec<PathBuf> = self.editors.editors.iter().filter(|editor| editor.document().scheme == "file").map(|editor| editor.document().path.clone()).collect();+ let open_editors: Vec<PathBuf> = self.editors.all_tabs().filter(|editor| editor.document().scheme == "file").map(|editor| editor.document().path.clone()).collect();search_paths::restrict_to_open_editors(&mut query, &open_editors, &workspace);}let searched = query.folder_queries.len();@@ -929,7 +930,7 @@ impl Workbench {pub(super) fn add_open_editor_matches(&self, query: &search::query::Query, only_open_editors: bool, result: &mut SearchResult) -> Vec<PathBuf> {let workspace_folders: Vec<_> = self.workspace().iter().flat_map(|workspace| &workspace.folders).map(|folder| (folder.path.clone(), folder.name.clone())).collect();let content_pattern = query.content_pattern.as_ref().expect("a text query has a content pattern");- let word_separators = self.setting("editor.wordSeparators").as_str().unwrap_or_default().to_string();+ let word_separators = self.setting(WORD_SEPARATORS.key).as_str().unwrap_or_default().to_string();let params = SearchParams { search_string: &content_pattern.pattern, is_regex: content_pattern.is_reg_exp, match_case: content_pattern.is_case_sensitive, word_separators: content_pattern.is_word_match.then_some(word_separators.as_str()) };let mut local = Vec::new();for editor in &self.editors.editors {@@ -1061,7 +1062,7 @@ impl Workbench {let Some(pattern) = self.search.pattern.as_ref() else { return };let Some(file) = self.search.result.files.iter().find(|file| file.path == path) else { return };let Some(model) = self.editors.model(scheme, path) else { return };- let word_separators = self.setting("editor.wordSeparators").as_str().unwrap_or_default().to_string();+ let word_separators = self.setting(WORD_SEPARATORS.key).as_str().unwrap_or_default().to_string();let params = SearchParams { search_string: &pattern.pattern, is_regex: pattern.is_reg_exp, match_case: pattern.is_case_sensitive, word_separators: pattern.is_word_match.then_some(word_separators.as_str()) };let folder = file.folder;self.search.result.set_model_matches(folder, path, &model.document().lines, ¶ms);diff --git a/native/crates/app/src/workbench/search_actions/tests.rs b/native/crates/app/src/workbench/search_actions/tests.rsindex 6f25b61c2c3..cfe4f9ecb13 100644--- a/native/crates/app/src/workbench/search_actions/tests.rs+++ b/native/crates/app/src/workbench/search_actions/tests.rs@@ -83,6 +83,19 @@ fn find_in_files_searches_the_folder_with_the_options(cx: &mut TestAppContext) {std::fs::remove_dir_all(dir).unwrap();}+/// queryBuilder.ts `commonQuery` with `onlyOpenEditors` takes the resources of `editorGroupsService.groups`, every+/// group's: a file open only in another group is searched.+#[gpui::test]+fn only_open_editors_searches_a_file_open_in_another_group(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = search("search-other-group", cx);+ workbench.update_in(cx, |workbench, window, cx| workbench.open_file(dir.join("a.txt"), true, window, cx));+ cx.run_until_parked();+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ run(&workbench, "workbench.action.findInFiles", vec![json!({ "query": "alpha", "triggerSearch": true, "onlyOpenEditors": true })], cx);+ assert_eq!(result_files(&workbench, &dir, cx), [("a.txt".to_string(), 2)]);+ std::fs::remove_dir_all(dir).unwrap();+}+/// searchview.css: the message is inline text, each word at its exact width, so the link starts where the text ends./// padding.css and fontRamp.css under modern UI: the count badge is 19px tall, 6px padding around label3 (10px) text.#[gpui::test]diff --git a/native/crates/app/src/workbench/search_editor_view.rs b/native/crates/app/src/workbench/search_editor_view.rsindex 6d12b261a94..434b6807929 100644--- a/native/crates/app/src/workbench/search_editor_view.rs+++ b/native/crates/app/src/workbench/search_editor_view.rs@@ -15,6 +15,8 @@ use serde_json::Value;use super::Workbench;use super::search_view::SearchField;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::commands::Outcome;use crate::host_sync::SearchTab;use crate::editor::{uri_string, ContentChanged, EditReason, OpenEditor, OpenError, Position, Selection, TextDocument, VerticalReveal, char_column, utf16_column, column_x};@@ -22,6 +24,7 @@ use crate::search_editor::{SearchConfiguration, TextRange, adjacent_match, parse_serialized_search_editor, result_block_lines, search_editor_name, serialize_search_configuration,serialize_search_result_for_editor, suggest_file_name,};+use crate::workbench::editor_options::FIND_SEED_SEARCH_STRING_FROM_SELECTION;use crate::search_model::{SearchResult, utf16_len};/// `SearchEditorConstants.SearchEditorScheme`.@@ -156,7 +159,7 @@ impl Workbench {fn open_new_search_editor(&mut self, args: &Value, window: &mut Window, cx: &mut Context<Self>) {let reuse = args["location"] == "reuse";// Upstream tests the setting for truthiness, so "never" seeds too.- let seed_setting = self.setting("editor.find.seedSearchStringFromSelection");+ let seed_setting = self.setting(FIND_SEED_SEARCH_STRING_FROM_SELECTION.key);let seed = args["location"] == "new" || !(seed_setting == false || seed_setting == "" || seed_setting.is_null());let selected = self.selected_search_text().filter(|_| seed);let mut config = SearchConfiguration { query: selected.clone().unwrap_or_default(), ..SearchConfiguration::default() }.with_args(args);@@ -548,7 +551,7 @@ impl Workbench {drop(document);editor.set_selections(vec![selection]);editor.reveal_range(selection.start(), selection.end(), VerticalReveal::CenterIfOutsideViewport, viewport);- self.host.send_selection(editor, "keyboard");+ self.cursor_position_changed(Cursor { moved: true, source: "keyboard", reveal: Reveal::Nothing }, cx);self.editor_scrolled(cx);window.focus(&self.editor_focus, cx);}@@ -562,7 +565,7 @@ impl Workbench {return;}editor.set_selections(selections);- self.host.send_selection(editor, "keyboard");+ self.cursor_position_changed(Cursor { moved: true, source: "keyboard", reveal: Reveal::Nothing }, cx);window.focus(&self.editor_focus, cx);cx.notify();}@@ -598,12 +601,7 @@ impl Workbench {editor.push_undo_stop();let change = editor.execute_edits(edits, Some(endings).filter(|endings| !endings.is_empty()), EditReason::Unknown("deleteResultBlock"));editor.push_undo_stop();- if let Some(change) = change {- let index = self.editors.active_index().expect("checked above");- self.host.send_content_change(&self.editors, self.editors.tab_model(index), &change);- let path = self.editors.editors[index].document().path.clone();- self.search_editor_edited(&path, &change);- }+ self.model_content_changed(change, crate::workbench::model_events::Cursor { moved: true, source: "api", reveal: crate::editor::Reveal::Nothing }, cx);cx.notify();}diff --git a/native/crates/app/src/workbench/selection_ranges.rs b/native/crates/app/src/workbench/selection_ranges.rsindex a3d031c4c97..d5773c38239 100644--- a/native/crates/app/src/workbench/selection_ranges.rs+++ b/native/crates/app/src/workbench/selection_ranges.rs@@ -77,7 +77,7 @@ impl Workbench {cx.spawn(async move |workbench, cx| {let answers = answers.await;let value = workbench.update(cx, |workbench, _| {- let editor = workbench.editors.editors.iter().find(|editor| editor.model_id == model_id)?;+ let editor = workbench.editors.all_editors().find(|editor| editor.model_id == model_id)?;let provided = provided_ranges(&editor.document().lines, &answers, positions.len());Some(workbench.selection_ranges_value(model_id, options, &positions, Some(&provided)))});@@ -88,7 +88,7 @@ impl Workbench {}fn selection_ranges_value(&self, model_id: u32, options: Options, positions: &[Position], provided: Option<&[Vec<Span>]>) -> Value {- let Some(editor) = self.editors.editors.iter().find(|editor| editor.model_id == model_id) else { return json!([]) };+ let Some(editor) = self.editors.all_editors().find(|editor| editor.model_id == model_id) else { return json!([]) };let one_based: Vec<Position> = positions.iter().map(|position| Position::new(position.line, position.column + 1)).collect();let lines = &editor.document().lines;let ranges = editor.provide_selection_ranges(&self.languages, options, &one_based, provided);diff --git a/native/crates/app/src/workbench/semantic_tokens.rs b/native/crates/app/src/workbench/semantic_tokens.rsindex 877f7b5f96a..1e4c392f901 100644--- a/native/crates/app/src/workbench/semantic_tokens.rs+++ b/native/crates/app/src/workbench/semantic_tokens.rs@@ -190,7 +190,7 @@ impl Workbench {let fired = |model: &SharedModel, method: &str| {let document = &model.borrow().document;let candidate = Candidate { uri: &document.uri(), language: &document.language_id };- self.language_features.ordered(method, &candidate).iter().any(|registration| registration.args.get(3) == Some(&json!(event_handle)))+ self.language_features.ordered(method, &candidate).iter().any(|registration| registration.event_handle == Some(event_handle))};let document: Vec<String> = self.semantic_tokens.watchers.iter().filter(|(_, watcher)| watcher.model.upgrade().is_some_and(|model| fired(&model, DOCUMENT_REGISTER))).map(|(uri, _)| uri.clone()).collect();let range = self.editors.active().is_some_and(|editor| fired(&editor.model, RANGE_REGISTER));@@ -232,7 +232,7 @@ impl Workbench {let uri = editor.document().uri();let language = editor.document().language_id.clone();let candidate = Candidate { uri: &uri, language: &language };- let first = |method| self.language_features.ordered(method, &candidate).first().map(|registration| (registration.handle, legend(®istration.args[2])));+ let first = |method| self.language_features.ordered(method, &candidate).first().map(|registration| (registration.handle, legend(®istration.metadata)));let (document, range) = (first(DOCUMENT_REGISTER), first(RANGE_REGISTER));let end_column = editor.document().lines[line].encode_utf16().count() + 1;let line_range = json!({ "startLineNumber": line + 1, "startColumn": 1, "endLineNumber": line + 1, "endColumn": end_column });@@ -463,7 +463,7 @@ impl Workbench {Entry::Occupied(entry) => entry.into_mut(),Entry::Vacant(entry) => {let Some(registration) = self.language_features.registration(handle) else { return Vec::new() };- entry.insert(SemanticTokensProviderStyling::new(legend(®istration.args[2])))+ entry.insert(SemanticTokensProviderStyling::new(legend(®istration.metadata)))}};let theme = &self.theme.semantic;@@ -681,7 +681,7 @@ impl Workbench {/// `getLegend()`: the legend the provider registered with.fn legend_value(&self, handle: u64) -> Value {- self.language_features.registration(handle).map_or(Value::Null, |registration| registration.args[2].clone())+ self.language_features.registration(handle).map_or(Value::Null, |registration| registration.metadata.clone())}}diff --git a/native/crates/app/src/workbench/smooth_scrolling.rs b/native/crates/app/src/workbench/smooth_scrolling.rsindex 8d42ba402d7..99e7b9856b4 100644--- a/native/crates/app/src/workbench/smooth_scrolling.rs+++ b/native/crates/app/src/workbench/smooth_scrolling.rs@@ -9,6 +9,7 @@ use gpui::{Context, Task};use super::Workbench;use crate::editor::smooth_scroll::SmoothScroll;use crate::editor::{OpenEditor, Scroll, Viewport};+use crate::workbench::editor_options::SMOOTH_SCROLLING;/// One animation frame at 120 Hz.const FRAME: Duration = Duration::from_millis(8);@@ -27,7 +28,7 @@ impl Workbench {/// Runs `scroll` on the active editor from the future scroll position and, with `editor.smoothScrolling`,/// animates from the current one to where it lands. Returns whether the editor scrolled.pub(super) fn scroll_smoothly(&mut self, cx: &mut Context<Self>, scroll: impl FnOnce(&mut OpenEditor, Viewport)) -> bool {- let smooth = self.setting("editor.smoothScrolling").as_bool().unwrap_or(false);+ let smooth = self.global_editor_option(&SMOOTH_SCROLLING);let viewport = self.editors.viewport;let running = self.smooth_scrolling.take();let editor = self.editors.active_mut().expect("an editor scrolls only while open");diff --git a/native/crates/app/src/workbench/snippet_controller.rs b/native/crates/app/src/workbench/snippet_controller.rsindex 6366d97f019..16a375843bf 100644--- a/native/crates/app/src/workbench/snippet_controller.rs+++ b/native/crates/app/src/workbench/snippet_controller.rs@@ -7,6 +7,8 @@ use serde_json::{Value, json};use super::Workbench;use super::host_requests::snippet_edits;use super::suggest_controller::TriggerOptions;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::commands::Outcome;use crate::editor::snippet_session::{Inserted, SnippetSession, starts_after_edits};use crate::editor::{EditReason, OpenEditor, Position, Selection, end_of};@@ -82,7 +84,7 @@ impl Workbench {if insert.undo_stop_after {editor.push_undo_stop();}- self.editor_edited(change, true, "snippet", cx);+ self.model_content_changed(change, Cursor { moved: true, source: "snippet", reveal: Reveal::All }, cx);}fn move_snippet(&mut self, forward: bool, cx: &mut Context<Self>) {@@ -101,9 +103,10 @@ impl Workbench {let selections = session.move_to(forward);editor.set_selections(selections);if change.is_some() {- self.editor_edited(change, true, "snippet", cx);+ self.model_content_changed(change, Cursor { moved: true, source: "snippet", reveal: Reveal::All }, cx);} else {- self.cursors_changed(before, crate::editor::Reveal::All, "keyboard", cx);+ let moved = editor.selections != before;+ self.cursor_position_changed(Cursor { moved, source: "keyboard", reveal: Reveal::All }, cx);}self.snippet_state_changed(cx);}diff --git a/native/crates/app/src/workbench/suggest_controller.rs b/native/crates/app/src/workbench/suggest_controller.rsindex 9ec7305eb96..becbbde55ef 100644--- a/native/crates/app/src/workbench/suggest_controller.rs+++ b/native/crates/app/src/workbench/suggest_controller.rs@@ -14,6 +14,8 @@ use super::host_requests::{range, uri_parts};use super::snippet_completions::SNIPPET_PROVIDER;use super::tab_completion::TAB_COMPLETION_PROVIDER;use super::snippet_controller::{SNIPPET_CHOICE_PROVIDER, SnippetInsert};+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::commands::Outcome;use crate::editor::{EditReason, OpenEditor, Position, Selection, pattern_words, utf16_column, word_definition};use crate::filters::FuzzyScoreOptions;@@ -336,7 +338,7 @@ impl Workbench {let uri = editor.document().uri();let language = editor.document().language_id.clone();let candidate = Candidate { uri: &uri, language: &language };- let supports: Vec<u64> = self.language_features.ordered("$registerCompletionsProvider", &candidate).into_iter().filter(|registration| registration.args.get(2).and_then(Value::as_array).is_some_and(|chars| chars.contains(&json!(last)))).map(|registration| registration.handle).collect();+ let supports: Vec<u64> = self.language_features.ordered("$registerCompletionsProvider", &candidate).into_iter().filter(|registration| registration.trigger_characters.contains(&last)).map(|registration| registration.handle).collect();if supports.is_empty() {return;}@@ -439,7 +441,7 @@ impl Workbench {if !options.provider_filter.is_empty() && !options.provider_filter.contains(&handle) {continue;}- let supports_resolve = registration.args.get(3) == Some(&Value::Bool(true));+ let supports_resolve = registration.supports_resolve;if handle == WORD_BASED_PROVIDER {let result = self.word_based_completions(editor, editor.selection().head);calls.push(Call::Ready(ProviderAnswer { provider: handle, supports_resolve, result }));@@ -712,7 +714,7 @@ impl Workbench {let current: Option<String> = word.clone().map(|word| text.chars().skip(word.start).take(word.len()).collect());let mut models = vec![editor];if mode != "currentDocument" {- for other in self.editors.editors.iter().chain(&self.editors.models) {+ for other in self.editors.all_editors() {if other.model_id != editor.model_id && !models.iter().any(|model| model.model_id == other.model_id) && (mode == "allDocuments" || other.document().language_id == editor.document().language_id) {models.push(other);}@@ -805,7 +807,7 @@ impl Workbench {.collect();let model_id = editor.model_id;if change.is_some() {- self.editor_edited(change, true, "suggest", cx);+ self.model_content_changed(change, Cursor { moved: true, source: "suggest", reveal: Reveal::All }, cx);}self.cancel_suggest(false, cx);let snippets: Vec<(Position, Position, &str, bool)> = ranges.into_iter().map(|(start, end)| (start, end, template.as_str(), keep_whitespace)).collect();@@ -863,7 +865,7 @@ impl Workbench {if did_type || undo_stop_after {editor.push_undo_stop();}- workbench.editor_edited(change, true, "suggest", cx);+ workbench.model_content_changed(change, Cursor { moved: true, source: "suggest", reveal: Reveal::All }, cx);});}).detach();@@ -894,7 +896,7 @@ impl Workbench {for group in self.language_features.ordered_groups("$registerCompletionsProvider", &candidate) {let mut calls = Vec::new();for registration in group {- let supports_resolve = registration.args.get(3) == Some(&Value::Bool(true));+ let supports_resolve = registration.supports_resolve;if registration.handle == WORD_BASED_PROVIDER {let (sender, receiver) = oneshot::channel();let _ = sender.send(Ok(self.word_based_completions(editor, model_position)));diff --git a/native/crates/app/src/workbench/suggest_controller/tests.rs b/native/crates/app/src/workbench/suggest_controller/tests.rsindex 0d1b3e23861..f2247375c29 100644--- a/native/crates/app/src/workbench/suggest_controller/tests.rs+++ b/native/crates/app/src/workbench/suggest_controller/tests.rs@@ -118,6 +118,20 @@ fn typing_shows_the_document_words_and_filters_them(cx: &mut TestAppContext) {assert!(shown(&workbench, cx).is_empty());}+/// editorWorkerService.ts `WordBasedCompletionItemProvider` reads the words of `modelService.getModels()`: a file of+/// the same language shown only in another group gives its words.+#[gpui::test]+fn word_suggestions_take_the_words_of_a_file_in_another_group(cx: &mut TestAppContext) {+ let (workbench, cx) = open(cx, "fable\n");+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ workbench.update_in(cx, |workbench, window, cx| window.focus(&workbench.editor_focus, cx));+ type_text(&workbench, cx, "f");+ run(&workbench, cx, "editor.action.triggerSuggest");+ cx.executor().advance_clock(Duration::from_millis(20));+ cx.run_until_parked();+ assert_eq!(shown(&workbench, cx), ["fable"]);+}+/// selectNextSuggestion moves the focus; acceptSelectedSuggestion replaces the typed word with the item.#[gpui::test]fn accepting_replaces_the_typed_prefix(cx: &mut TestAppContext) {diff --git a/native/crates/app/src/workbench/task_configure.rs b/native/crates/app/src/workbench/task_configure.rsindex 1af16bcb894..e60f4372c5d 100644--- a/native/crates/app/src/workbench/task_configure.rs+++ b/native/crates/app/src/workbench/task_configure.rs@@ -16,6 +16,7 @@ use crate::main_thread_quick_open::Owner;use crate::notifications::{Notification, Severity};use crate::quick_input::{Entry, Item, Kind, QuickInput};use crate::tasks::configuration::{CUSTOMIZED_TASK_TYPE, Task};+use crate::workbench::editor_options::{INSERT_SPACES, TAB_SIZE};/// `TaskService.requestTrust`.const TRUST_MESSAGE: &str = "Listing and running tasks requires that some of the files in this workspace be executed as code.";@@ -194,7 +195,7 @@ impl Workbench {let to_customize = Value::Object(to_customize);match file.config {None => {- let content = new_tasks_json(&to_customize, self.setting("editor.insertSpaces") == true, self.setting("editor.tabSize").as_u64().unwrap_or(4) as usize);+ let content = new_tasks_json(&to_customize, self.setting(INSERT_SPACES.key) == true, self.setting(TAB_SIZE.key).as_u64().unwrap_or(4) as usize);let parent = file.path.parent().expect("tasks.json is in a folder");if let Err(error) = std::fs::create_dir_all(parent).and_then(|()| std::fs::write(&file.path, content)) {return self.notify_error(format!("Unable to write {}: {error}", file.path.display()));@@ -264,7 +265,7 @@ impl Workbench {/// `_openEditorAtTask`: the entry found by its formatted text, its lines selected.fn open_tasks_json_at(&mut self, path: PathBuf, element: &Value, window: &mut Window, cx: &mut Context<Self>) {let content = std::fs::read_to_string(&path).unwrap_or_default();- let selection = entry_selection(&content, element, self.setting("editor.tabSize").as_u64().unwrap_or(4) as usize);+ let selection = entry_selection(&content, element, self.setting(TAB_SIZE.key).as_u64().unwrap_or(4) as usize);self.open_tasks_file(path, false, window, cx);let Some((start, end)) = selection else { return };let viewport = self.editors.viewport;diff --git a/native/crates/app/src/workbench/task_quick_pick.rs b/native/crates/app/src/workbench/task_quick_pick.rsindex 4bb3ee83048..c39d6a98c39 100644--- a/native/crates/app/src/workbench/task_quick_pick.rs+++ b/native/crates/app/src/workbench/task_quick_pick.rs@@ -16,6 +16,7 @@ use crate::main_thread_quick_open::Owner;use crate::notifications::{Notification, Severity};use crate::quick_input::{Button, Entry, Event, Item, Kind, QuickInput};use crate::tasks::configuration::{CUSTOMIZED_TASK_TYPE, Task, USER_TASKS_GROUP_KEY};+use crate::workbench::editor_options::{INSERT_SPACES, TAB_SIZE};/// `AbstractTaskService.RecentlyUsedTasks_KeyV2`, workspace storage.const RECENT_TASKS_KEY: &str = "workbench.tasks.recentlyUsedTasks2";@@ -637,8 +638,8 @@ impl Workbench {let Some(handle) = self.quick_inputs.get(id).and_then(|input| input.selected_handles().first().copied()) else { return };self.hide_quick_input_by_id(id, window, cx);let mut content = crate::tasks::templates::templates()[handle as usize].content.to_owned();- if self.setting("editor.insertSpaces") == true {- content = tabs_to_spaces(&content, self.setting("editor.tabSize").as_u64().unwrap_or(4) as usize);+ if self.setting(INSERT_SPACES.key) == true {+ content = tabs_to_spaces(&content, self.setting(TAB_SIZE.key).as_u64().unwrap_or(4) as usize);}match self.write_task_template(&path, &content) {Ok(()) => self.open_tasks_file(path, true, window, cx),diff --git a/native/crates/app/src/workbench/task_service.rs b/native/crates/app/src/workbench/task_service.rsindex 0e8147cf19a..69fbccea88d 100644--- a/native/crates/app/src/workbench/task_service.rs+++ b/native/crates/app/src/workbench/task_service.rs@@ -186,7 +186,7 @@ impl Markers for WorkbenchMarkers<'_> {}fn is_open(&self, resource: &PathBuf) -> bool {- self.0.editors.editors.iter().any(|editor| editor.document().path == *resource)+ self.0.editors.all_editors().any(|editor| editor.document().path == *resource)}}@@ -1047,4 +1047,15 @@ mod tests {assert_eq!(text.0, "Tasks");assert!(text.1.starts_with("Error: there is no registered task type 'missing'."), "{}", text.1);}++ /// problemCollectors.ts `openModels` follows `modelService.onModelAdded`: a file shown only in another group is+ /// open for `applyTo: openDocuments`.+ #[gpui::test]+ fn a_file_in_another_group_is_open_for_the_problem_collector(cx: &mut gpui::TestAppContext) {+ let (dir, workbench, cx) = crate::workbench::editor_groups::tests::workbench_with("task-open-other-group", &["a.txt"], cx);+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ let open = workbench.read_with(cx, |workbench, _| WorkbenchMarkers(workbench).is_open(&dir.join("a.txt")));+ assert!(open);+ std::fs::remove_dir_all(dir).unwrap();+ }}diff --git a/native/crates/app/src/workbench/terminal_decorations.rs b/native/crates/app/src/workbench/terminal_decorations.rsindex 9abe9e99394..93fd6b2e1c5 100644--- a/native/crates/app/src/workbench/terminal_decorations.rs+++ b/native/crates/app/src/workbench/terminal_decorations.rs@@ -11,6 +11,7 @@ use crate::commands::Outcome;use crate::main_thread_quick_open::Owner;use crate::menus::MenuAction;use crate::quick_input::{Entry, Event, Item, Kind, QuickInput};+use crate::workbench::editor_options::FONT_FAMILY;use super::terminal_view::TerminalInput;/// decorationStyles.ts `getTerminalDecorationHoverContent(command, undefined, true)` of a finished command.@@ -112,7 +113,7 @@ impl Workbench {/// The theme's ANSI colors and xterm's `fontFamily` and `fontSize` options, which the HTML copy carries.fn terminal_html_style(&self) -> (crate::terminal::colors::TerminalColors, String, f32) {- let family = Some(self.setting("terminal.integrated.fontFamily")).filter(|family| family.as_str().is_some_and(|family| !family.is_empty())).unwrap_or_else(|| self.setting("editor.fontFamily"));+ let family = Some(self.setting("terminal.integrated.fontFamily")).filter(|family| family.as_str().is_some_and(|family| !family.is_empty())).unwrap_or_else(|| self.setting(FONT_FAMILY.key));let size = self.setting("terminal.integrated.fontSize").as_f64().unwrap_or(12.) as f32;// terminalConfigurationService.ts `getFont`: the monospace and (macOS) AppleBraille fallbacks.let family = format!("{}, monospace, AppleBraille", family.as_str().unwrap_or_default());diff --git a/native/crates/app/src/workbench/terminal_editor.rs b/native/crates/app/src/workbench/terminal_editor.rsindex ff0533bf63e..c9fb44a1cf9 100644--- a/native/crates/app/src/workbench/terminal_editor.rs+++ b/native/crates/app/src/workbench/terminal_editor.rs@@ -171,8 +171,7 @@ impl Workbench {Some(id) => self.terminal_view.set_active(id),None => self.terminal_view.active_editor = None,}- let others = self.editors.other_groups.iter().flat_map(|group| &group.editors);- let open: Vec<u32> = self.editors.editors.iter().chain(others).filter_map(terminal_editor_id).collect();+ let open: Vec<u32> = self.editors.all_tabs().filter_map(terminal_editor_id).collect();self.host.terminal_tabs = open.iter().map(|id| (self.terminal_editor_path(*id), self.terminal_editor_name(&self.terminal_editor_path(*id)))).collect();let closed: Vec<u32> = self.terminal_view.editor_instances.iter().copied().filter(|id| !open.contains(id)).collect();let Some(main_window) = self.auxiliary_windows.main_window.filter(|_| !closed.is_empty()) else { return };diff --git a/native/crates/app/src/workbench/terminal_links.rs b/native/crates/app/src/workbench/terminal_links.rsindex 684f0f85c20..d6a56695d4a 100644--- a/native/crates/app/src/workbench/terminal_links.rs+++ b/native/crates/app/src/workbench/terminal_links.rs@@ -14,10 +14,13 @@ use serde_json::{Value, json};use super::Workbench;use super::hover::{HoverContent, HoverOptions};use super::terminal_view::grid;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::editor::marker_decorations::validate;use crate::editor::{Selection, VerticalReveal};use crate::link_computer::compute_links;use crate::terminal::link_parsing::detect_links;+use crate::workbench::editor_options::MULTI_CURSOR_MODIFIER;/// The element id name of a terminal link's hover.pub(super) const TERMINAL_LINK_HOVER: &str = "terminal-link";@@ -190,12 +193,12 @@ impl Workbench {pub(super) fn terminal_link_modifier(&self, modifiers: Modifiers) -> bool {// `editor.multiCursorModifier` alt (the default) makes Cmd the link modifier.- if self.setting("editor.multiCursorModifier") == "ctrlCmd" { modifiers.alt } else { modifiers.platform }+ if self.setting(MULTI_CURSOR_MODIFIER.key) == "ctrlCmd" { modifiers.alt } else { modifiers.platform }}/// `_getLinkHoverString`: "[Follow link](target) (cmd + click)", the click label after the modifier.fn terminal_link_hover_text(&self, hovered: &HoveredLink) -> String {- let click = if self.setting("editor.multiCursorModifier") == "ctrlCmd" { "option + click" } else { "cmd + click" };+ let click = if self.setting(MULTI_CURSOR_MODIFIER.key) == "ctrlCmd" { "option + click" } else { "cmd + click" };// The hover's markdown only links schemes, so a path links through its file URI. Terminal output is// untrusted: characters that could end the link and start another are percent-encoded.let (target, label) = match &hovered.link {@@ -235,7 +238,7 @@ impl Workbench {let position = validate(&editor.document().lines, line as usize, column.unwrap_or(1) as usize);editor.set_selections(vec![Selection::caret(position)]);editor.reveal_range(position, position, VerticalReveal::CenterIfOutsideViewport, viewport);- self.host.send_selection(editor, "code.jump");+ self.cursor_position_changed(Cursor { moved: true, source: "code.jump", reveal: Reveal::Nothing }, cx);self.editor_scrolled(cx);}}diff --git a/native/crates/app/src/workbench/testing_coverage_view.rs b/native/crates/app/src/workbench/testing_coverage_view.rsindex 72ca2ad310a..660d5186615 100644--- a/native/crates/app/src/workbench/testing_coverage_view.rs+++ b/native/crates/app/src/workbench/testing_coverage_view.rs@@ -8,6 +8,8 @@ use gpui::{ClickEvent, Context, Div, InteractiveElement, IntoElement, ParentElemuse serde_json::{Value, json};use super::Workbench;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::commands::Outcome;use crate::main_thread_quick_open::Owner;use crate::quick_input::{Entry, Item, Kind, QuickInput};@@ -564,7 +566,7 @@ impl Workbench {let editor = self.editors.active_mut().expect("checked above");editor.set_selections(vec![crate::editor::Selection { anchor: position, head: position }]);editor.reveal_range(position, position, crate::editor::VerticalReveal::Center, viewport);- self.host.send_selection(editor, "api");+ self.cursor_position_changed(Cursor { moved: true, source: "api", reveal: Reveal::Nothing }, cx);self.editor_scrolled(cx);cx.notify();}diff --git a/native/crates/app/src/workbench/testing_coverage_view/tests.rs b/native/crates/app/src/workbench/testing_coverage_view/tests.rsindex 8ead81fff54..ca1e07bbb4c 100644--- a/native/crates/app/src/workbench/testing_coverage_view/tests.rs+++ b/native/crates/app/src/workbench/testing_coverage_view/tests.rs@@ -488,3 +488,29 @@ fn explorer_rows_show_their_coverage(cx: &mut TestAppContext) {std::fs::remove_dir_all(dir).unwrap();std::fs::remove_dir_all(user).unwrap();}++/// codeCoverageDecorations.ts `CodeCoverageDecorations` and `CoverageToolbarWidget` are contributions of every code+/// editor: a file with coverage shown only in another group gets its inline ranges and its toolbar's zone.+#[gpui::test]+fn a_file_with_coverage_in_another_group_gets_its_inline_ranges_and_toolbar(cx: &mut TestAppContext) {+ let (workbench, cx, _host) = workbench_with_tests("coverage-other-group", TESTS, cx);+ let user = std::env::temp_dir().join(format!("vsrustium-coverage-other-group-user-{}", std::process::id()));+ let path = workbench.update_in(cx, |workbench, window, cx| {+ workbench.settings = std::sync::Arc::new(std::sync::Mutex::new(config::service::Settings::load(config::registry::Registry::with_extensions(&[]), user.clone(), None)));+ open_inline_details(workbench, window, cx);+ workbench.editors.active().expect("the test file").document().path.clone()+ });+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ workbench.update(cx, |workbench, cx| {+ workbench.settings.lock().unwrap().update_value_derived("testing.coverageToolbarEnabled", Some(&json!(true))).unwrap();+ cx.notify();+ });+ cx.run_until_parked();+ cx.update(|window, cx| drop(window.draw(cx)));+ let (ranges, zone) = workbench.read_with(cx, |workbench, _| {+ let moved = workbench.editors.model("file", &path).expect("the moved editor").model_id;+ (workbench.testing.coverage.inline.get(&moved).map_or(0, Vec::len), workbench.testing.coverage.toolbar_zones.contains_key(&moved))+ });+ assert_eq!((ranges, zone), (2, true));+ std::fs::remove_dir_all(user).unwrap();+}diff --git a/native/crates/app/src/workbench/text_file_editor_tracker.rs b/native/crates/app/src/workbench/text_file_editor_tracker.rsindex c7af5b059f1..b74f777bd5d 100644--- a/native/crates/app/src/workbench/text_file_editor_tracker.rs+++ b/native/crates/app/src/workbench/text_file_editor_tracker.rs@@ -57,9 +57,8 @@ impl Workbench {if !model.is_dirty() || self.editor_is_saving(model) {continue;}- let mut tabs = self.editors.editors.iter().chain(self.editors.other_groups.iter().flat_map(|group| &group.editors));// editorService.ts `isOpened` matches an editor's resource: a diff or merge editor's edited side.- if !tabs.any(|tab| self.editors.editor_model(tab).document().is(&scheme, &path)) {+ if !self.editors.all_tabs().any(|tab| self.editors.editor_model(tab).document().is(&scheme, &path)) {self.editors.open_inactive(&scheme, &path);}}diff --git a/native/crates/app/src/workbench/text_files.rs b/native/crates/app/src/workbench/text_files.rsindex ce45d50f017..9859730a555 100644--- a/native/crates/app/src/workbench/text_files.rs+++ b/native/crates/app/src/workbench/text_files.rs@@ -613,7 +613,7 @@ impl Workbench {pub(super) fn files_associations_changed(&mut self, cx: &mut Context<Self>) {let associations = self.settings.lock().unwrap().get_value(Some("files.associations"), &Overrides::default()).unwrap_or_default();let mut changed = Vec::new();- for model in self.editors.editors.iter().chain(&self.editors.models).filter(|model| on_disk(&model.document().scheme)) {+ for model in self.editors.all_editors().filter(|model| on_disk(&model.document().scheme)) {let document = &model.document();if self.text_files.preferred_languages.contains(&(document.scheme.clone(), document.path.clone())) {continue;@@ -712,10 +712,7 @@ impl Workbench {model.mark_saved();}let Some(change) = change.or(eol_change) else { return false };- if self.editors.active().is_some_and(|editor| editor.document().is(scheme, path)) {- self.find_editor_edited(Some(&change));- }- self.send_model_edit(scheme, path, &change, cx);+ self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);true}@@ -723,7 +720,7 @@ impl Workbench {/// outside them, and the stats of models that are gone.pub(super) fn text_files_editors_changed(&mut self) {self.host.untitled_names_from_content = self.untitled_names_from_content();- let models: HashSet<(String, PathBuf)> = self.editors.editors.iter().chain(&self.editors.models).map(|model| (model.document().scheme.clone(), model.document().path.clone())).collect();+ let models: HashSet<(String, PathBuf)> = self.editors.all_editors().map(|model| (model.document().scheme.clone(), model.document().path.clone())).collect();self.text_files.stats.retain(|key, _| models.contains(key));self.text_files.orphaned.retain(|path| models.iter().any(|(scheme, open)| on_disk(scheme) && open == path));self.text_files.preferred_languages.retain(|key| models.contains(key));diff --git a/native/crates/app/src/workbench/text_files/tests.rs b/native/crates/app/src/workbench/text_files/tests.rsindex f125e664884..0c096d358e3 100644--- a/native/crates/app/src/workbench/text_files/tests.rs+++ b/native/crates/app/src/workbench/text_files/tests.rs@@ -245,6 +245,39 @@ fn files_associations_change_the_language_of_models_without_a_picked_one(cx: &mustd::fs::remove_dir_all(dir).unwrap();}+/// textFileEditorModel.ts `onDidChangeFilesAssociation` fires for every model of the manager, whichever group shows it.+#[gpui::test]+fn files_associations_change_the_language_of_a_model_in_another_group(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = workbench_in("associations-other-group", "{}", cx);+ let a = dir.join("a.foo");+ std::fs::write(&a, "a").unwrap();+ open(&workbench, &a, cx);+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ std::fs::write(dir.join("User/settings.json"), r#"{ "files.associations": { "*.foo": "markdown" } }"#).unwrap();+ workbench.update(cx, |workbench, cx| workbench.reload_changed_settings_files(cx));+ let language = workbench.read_with(cx, |workbench, _| workbench.editors.model("file", &a).unwrap().document().language_id.clone());+ assert_eq!(language, "markdown");+ std::fs::remove_dir_all(dir).unwrap();+}++/// textFileEditorModelManager.ts keeps a model while an editor of any group holds it: its picked language and orphan+/// mark stay when its only editor is in another group.+#[gpui::test]+fn a_model_in_another_group_keeps_its_picked_language_and_orphan_mark(cx: &mut TestAppContext) {+ let (dir, workbench, cx) = workbench_in("model-state-other-group", "{}", cx);+ let a = dir.join("a.txt");+ std::fs::write(&a, "a").unwrap();+ open(&workbench, &a, cx);+ workbench.update(cx, |workbench, _| {+ workbench.text_files.preferred_languages.insert(("file".into(), a.clone()));+ workbench.text_files.orphaned.insert(a.clone());+ });+ crate::workbench::editor_groups::tests::move_active_editor_to_another_group(&workbench, cx);+ let kept = workbench.read_with(cx, |workbench, _| (workbench.text_files.preferred_languages.contains(&("file".into(), a.clone())), workbench.text_files.orphaned.contains(&a)));+ assert_eq!(kept, (true, true));+ std::fs::remove_dir_all(dir).unwrap();+}+#[cfg(unix)]#[gpui::test]fn a_write_locked_file_saves_after_overwrite(cx: &mut TestAppContext) {diff --git a/native/crates/app/src/workbench/text_files/untitled_tests.rs b/native/crates/app/src/workbench/text_files/untitled_tests.rsindex 175a4d84e9c..a1fb43c6e32 100644--- a/native/crates/app/src/workbench/text_files/untitled_tests.rs+++ b/native/crates/app/src/workbench/text_files/untitled_tests.rs@@ -53,8 +53,8 @@ impl Untitled<'_> {self.run("workbench.action.files.newUntitledFile", args);}- fn host_request(&mut self, proxy: &str, method: &str, args: &[Value]) -> Value {- self.workbench.update_in(self.cx, |workbench, window, cx| workbench.host_request(proxy, method, args, window, cx)).unwrap()+ fn host_request(&mut self, proxy: &'static str, method: &str, args: &[Value]) -> Value {+ self.workbench.update_in(self.cx, |workbench, window, cx| workbench.answer_host_request(proxy, method, args, window, cx)).unwrap()}/// `untitledTextEditorService.create({ initialValue })` as `$tryCreateDocument` asks for it.@@ -88,7 +88,7 @@ impl Untitled<'_> {}fn dirty_count(&mut self) -> usize {- self.read(|workbench| workbench.editors.editors.iter().chain(&workbench.editors.models).filter(|model| model.is_dirty()).count())+ self.read(|workbench| workbench.editors.all_editors().filter(|model| model.is_dirty()).count())}fn language(&mut self, path: &str) -> String {diff --git a/native/crates/app/src/workbench/text_input.rs b/native/crates/app/src/workbench/text_input.rsindex f818cecdd00..60444cec109 100644--- a/native/crates/app/src/workbench/text_input.rs+++ b/native/crates/app/src/workbench/text_input.rs@@ -15,9 +15,11 @@ use super::auto_save::SaveReason;use super::text_files::SaveOptions;use serde_json::json;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::editor::save_participants::SaveParticipants;use crate::editor::edit_stack::{TYPING_LABEL, UndoElement};-use crate::editor::{ContentChanged, Position, Selection, uri_string, utf16_column};+use crate::editor::{Position, Selection, uri_string, utf16_column};use crate::local_history;/// The text participants to run: all, or the ones `SaveParticipantsContribution` registers before or after@@ -42,81 +44,6 @@ impl Workbench {drop(typing(self, vec![json!({ "text": "\n" })], window, cx));}- /// Tells the host about a content change or a cursor move, and reveals the cursor (cursor.ts `revealAll`).- pub(super) fn editor_edited(&mut self, change: Option<ContentChanged>, moved: bool, source: &str, cx: &mut Context<Self>) {- self.editor_edited_revealing(change, moved, source, true, cx);- }-- /// `editor_edited`, revealing the cursor only with `reveal` (`NavigationCommandRevealType.None` leaves the scroll).- pub(super) fn editor_edited_revealing(&mut self, change: Option<ContentChanged>, moved: bool, source: &str, reveal: bool, cx: &mut Context<Self>) {- let scrolled = reveal && self.scroll_smoothly(cx, |editor, viewport| editor.reveal_cursors(source, viewport));- self.find_editor_edited(change.as_ref());- match &change {- Some(_) => self.record_navigation(Some(crate::navigation::Reason::Edit)),- None if moved => self.record_navigation(Some(crate::navigation::Reason::of_source(source))),- None => {}- }- match &change {- Some(change) => self.host.send_content_change(&self.editors, self.editors.active().expect("only the active editor is edited"), change),- None if moved => self.host.send_selection(self.editors.active().expect("still open"), source),- None => {}- }- // The edit can unfold a region or change the line count, which changes the visible lines.- if change.is_some() {- self.host.send_visible_ranges(&self.editors);- let document = self.editors.active().expect("still open").document();- let (scheme, path) = (document.scheme.clone(), document.path.clone());- drop(document);- self.search_model_changed(&scheme, &path);- self.language_detection_content_changed(&scheme, &path, cx);- self.schedule_debug_inline_values(cx);- if change.is_some() {- self.cell_status_bar_content_changed(&scheme, &path, cx);- }- if let Some(change) = &change {- self.search_editor_edited(&path, change);- self.format_on_type_content_changed(change);- self.links_content_changed(change, cx);- self.semantic_tokens_content_changed(&uri_string(&scheme, &path), cx);- }- // untitledTextEditorModel.ts `onDidChangeName`: the first line names the tab.- if scheme == "untitled" {- self.host.send_tabs(&self.editors);- }- // commentReply.ts `onDidChangeModelContent`: the comment editor grows or shrinks by its lines.- if scheme == super::comments::INPUT_SCHEME {- self.sync_comment_widgets();- }- self.schedule_keybinding_marks(cx);- self.schedule_unsupported_settings_markers(cx);- }- if scrolled {- self.editor_scrolled(cx);- }- self.snippet_state_changed(cx);- self.suggest_editor_changed(change.is_some(), source, cx);- self.parameter_hints_editor_changed(source, cx);- if moved || change.is_some() {- self.code_actions_cursor_changed(change.is_some(), cx);- self.standalone_color_picker_cursor_changed(cx);- }- if change.is_some() {- self.code_lens_content_changed(cx);- self.refresh_commenting_ranges(true, cx);- self.inlay_hints_content_changed(cx);- self.color_detector_content_changed(cx);- self.color_picker_content_changed(cx);- }- self.linked_editing_editor_changed(change.as_ref(), moved || change.is_some(), cx);- // inlineCompletionsController.ts: typing (and the keyboard's deletes and Tab) triggers, other moves stop.- match &change {- Some(change) => self.inline_completions_edited(change, source, cx),- None if moved => self.inline_completions_cursor_moved(cx),- None => {}- }- cx.notify();- }-/// fileCommands.ts `save`: the editor's model, also when clean (`force`).pub(super) fn save_editor(&mut self, index: usize, cx: &mut Context<Self>) -> oneshot::Receiver<bool> {let document = self.editors.tab_model(index).document();@@ -155,10 +82,11 @@ impl Workbench {};drop(settings);let changes = model.run_save_participants(&participants);- for change in &changes {- self.send_model_edit(scheme, path, change, cx);+ let changed = !changes.is_empty();+ for change in changes {+ self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);}- if !changes.is_empty() {+ if changed {self.host.send_visible_ranges(&self.editors);}}@@ -289,11 +217,11 @@ impl EntityInputHandler for Workbench {};let editor = self.editors.active_mut().expect("input goes to the active editor");let change = editor.type_replacing(text, previous, next, "type");- self.editor_edited(change, false, "keyboard", cx);+ self.model_content_changed(change, Cursor { moved: false, source: "keyboard", reveal: Reveal::All }, cx);if self.overtype {let editor = self.editors.active_mut().expect("input goes to the active editor");let change = editor.overtype_composed(text);- self.editor_edited(change, false, "keyboard", cx);+ self.model_content_changed(change, Cursor { moved: false, source: "keyboard", reveal: Reveal::All }, cx);}}@@ -319,7 +247,7 @@ impl EntityInputHandler for Workbench {}let marked_start = utf16_column(&editor.document().lines[start.line], start.column);self.marked_text = (!new_text.is_empty()).then(|| marked_start..marked_start + new_text.encode_utf16().count());- self.editor_edited(change, false, "keyboard", cx);+ self.model_content_changed(change, Cursor { moved: false, source: "keyboard", reveal: Reveal::All }, cx);}/// `_updateCharacterBounds`: where the chars of `range` draw, so the IME's candidate window opens below them.diff --git a/native/crates/app/src/workbench/unicode_highlight.rs b/native/crates/app/src/workbench/unicode_highlight.rsindex bb201b3f2de..092652c4aa8 100644--- a/native/crates/app/src/workbench/unicode_highlight.rs+++ b/native/crates/app/src/workbench/unicode_highlight.rs@@ -15,6 +15,7 @@ use super::editor_status::{StatusPick, label_item};use crate::editor::OpenEditor;use crate::editor::unicode_highlighter::{CodePointHighlighter, HighlightReason, UnicodeHighlighterOptions, UnicodeHighlights, compute_unicode_highlights, is_invisible_character};use crate::quick_input::{Entry, Kind, QuickInput};+use crate::workbench::editor_options::UNICODE_HIGHLIGHT_ALLOWED_CHARACTERS;#[cfg(test)]mod tests;@@ -79,7 +80,7 @@ impl Workbench {/// `ShowExcludeOptions`: the hover's "Adjust settings" picker for one character.pub(super) fn show_unicode_exclude_options(&mut self, args: &Value, window: &mut Window, cx: &mut Context<Self>) {let user_locales = self.settings.lock().unwrap().configuration.inspect("editor.unicodeHighlight.allowedLocales", &Overrides::default()).user_local.value;- let allowed_characters = self.setting("editor.unicodeHighlight.allowedCharacters");+ let allowed_characters = self.setting(UNICODE_HIGHLIGHT_ALLOWED_CHARACTERS.key);let Some(options) = unicode_exclude_options(args, user_locales, allowed_characters) else { return };let rows = options.into_iter().map(|(label, key, value)| (Entry::Item(label_item(&label)), StatusPick::UserSetting { key, value })).collect();let mut input = QuickInput::new(0, Kind::QuickPick);diff --git a/native/crates/app/src/workbench/unusual_line_terminators.rs b/native/crates/app/src/workbench/unusual_line_terminators.rsindex bf993e91216..2227d46c3ea 100644--- a/native/crates/app/src/workbench/unusual_line_terminators.rs+++ b/native/crates/app/src/workbench/unusual_line_terminators.rs@@ -104,7 +104,7 @@ impl Workbench {fn remove_unusual_line_terminators(&mut self, (scheme, path): &(String, PathBuf), cx: &mut Context<Self>) {let Some(model) = self.editors.model_mut(scheme, path) else { return };if let Some(change) = model.remove_unusual_line_terminators() {- self.send_model_edit(scheme, path, &change, cx);+ self.model_content_changed(Some(change), crate::workbench::model_events::Cursor::model_change(), cx);}}}diff --git a/native/crates/app/src/workbench/walkthrough_part.rs b/native/crates/app/src/workbench/walkthrough_part.rsindex 375e2d2db6b..bc718f67aaa 100644--- a/native/crates/app/src/workbench/walkthrough_part.rs+++ b/native/crates/app/src/workbench/walkthrough_part.rs@@ -18,6 +18,7 @@ use crate::commands::Outcome;use crate::editor::view_state::ViewStates;use crate::editor::{OpenEditor, TextDocument};use crate::markdown::{Block, Inline, MarkdownString};+use crate::workbench::editor_options::{FONT_SIZE, MULTI_CURSOR_MODIFIER};#[cfg(test)]mod tests;@@ -203,7 +204,7 @@ impl Workbench {/// walkThroughPart.ts `getArrowScrollHeight`.fn playground_arrow_scroll_height(&self) -> f32 {- let font_size = self.setting("editor.fontSize").as_f64().filter(|size| *size >= 1.).unwrap_or(12.) as f32;+ let font_size = self.setting(FONT_SIZE.key).as_f64().filter(|size| *size >= 1.).unwrap_or(12.) as f32;3. * font_size}@@ -222,7 +223,7 @@ impl Workbench {}let text = &expanded.as_ref().expect("set above").1;// walkThroughPart.ts `multiCursorModifier`: `UILabelProvider.modifierLabels[OS]` of the add-cursor modifier.- let modifier = match self.setting("editor.multiCursorModifier") == json!("ctrlCmd") {+ let modifier = match self.setting(MULTI_CURSOR_MODIFIER.key) == json!("ctrlCmd") {true => "\u{2318}",false => "\u{2325}",};diff --git a/native/crates/app/src/workbench/webview_panels.rs b/native/crates/app/src/workbench/webview_panels.rsindex 864c5fe9121..020fcf94091 100644--- a/native/crates/app/src/workbench/webview_panels.rs+++ b/native/crates/app/src/workbench/webview_panels.rs@@ -594,9 +594,8 @@ impl Workbench {/// where each panel shows (`updateWebviewViewStates`).pub(super) fn sync_webview_panels(&mut self) {let editors = &self.editors;- let group_editors = editors.editors.iter().chain(editors.other_groups.iter().flat_map(|group| &group.editors));let (open, closed): (Vec<WebviewPanel>, Vec<WebviewPanel>) =- std::mem::take(&mut self.webview_panels.panels).into_iter().partition(|panel| panel.scheme == WEBVIEW_VIEW_SCHEME || group_editors.clone().any(|editor| panel.shows(editor)));+ std::mem::take(&mut self.webview_panels.panels).into_iter().partition(|panel| panel.scheme == WEBVIEW_VIEW_SCHEME || editors.all_tabs().any(|editor| panel.shows(editor)));self.webview_panels.panels = open;self.release_hidden_webview_panels();let closed: Vec<WebviewPanel> = closed.into_iter().filter(|panel| panel.is_extensions()).collect();diff --git a/native/crates/app/src/workbench/word_wrap.rs b/native/crates/app/src/workbench/word_wrap.rsindex dbfada55688..bcb0ae7f528 100644--- a/native/crates/app/src/workbench/word_wrap.rs+++ b/native/crates/app/src/workbench/word_wrap.rs@@ -8,6 +8,7 @@ use serde_json::{Value, json};use super::Workbench;use crate::commands::Outcome;+use crate::workbench::editor_options::WORD_WRAP_INDICATOR;use gpui::{Div, ParentElement, Styled, div, px};use crate::editor::word_wrap::{BREAK_AFTER, BREAK_BEFORE, Segment, WrapOptions, WrappingIndent};@@ -65,7 +66,7 @@ impl Workbench {/// that continues on the next one.pub(super) fn word_wrap_indicator(&self, editor: &OpenEditor, segment: Segment, scroll_left: f32, char_width: f32) -> Option<Div> {let options = editor.word_wrap.options()?;- if segment.last || self.setting("editor.wordWrapIndicator") != json!(true) {+ if segment.last || !self.editor_option(editor, &WORD_WRAP_INDICATOR) {return None;}let left = options.column as f32 * char_width - scroll_left;diff --git a/native/crates/app/src/workbench/workspace_recommendations.rs b/native/crates/app/src/workbench/workspace_recommendations.rsindex 41008be5fdd..cbcfeb78abc 100644--- a/native/crates/app/src/workbench/workspace_recommendations.rs+++ b/native/crates/app/src/workbench/workspace_recommendations.rs@@ -10,6 +10,8 @@ use gpui::{Context, Window};use serde_json::{Value, json};use super::Workbench;+use super::model_events::Cursor;+use crate::editor::Reveal;use crate::commands::Outcome;use crate::editor::{Position, Selection, VerticalReveal};use crate::extension_recommendations as recommendations;@@ -267,7 +269,7 @@ impl Workbench {let Some(editor) = self.editors.active_mut() else { return };editor.set_selections(vec![Selection::caret(position)]);editor.reveal_range(position, position, VerticalReveal::CenterIfOutsideViewport, viewport);- self.host.send_selection(self.editors.active().expect("just opened"), "api");+ self.cursor_position_changed(Cursor { moved: true, source: "api", reveal: Reveal::Nothing }, cx);cx.notify();}}diff --git a/native/crates/exthost/src/lib.rs b/native/crates/exthost/src/lib.rsindex 1b4a5f77315..24da821ba1c 100644--- a/native/crates/exthost/src/lib.rs+++ b/native/crates/exthost/src/lib.rs@@ -42,6 +42,10 @@ use frame::{Frame, FrameReader, FrameType, encode_frame};#[cfg(windows)]use pipe::{Listener, Stream};+/// The test's end of an `ExtensionHost::silent` socket.+#[cfg(any(test, feature = "test-support"))]+pub type SilentPeer = Stream;+/// port/product.json's `nameLong`, the name every message shows (the app's product.rs reads the same overlay).pub fn product_name() -> &'static str {static NAME: std::sync::LazyLock<String> = std::sync::LazyLock::new(|| {@@ -258,8 +262,8 @@ impl ExtensionHost {}/// A host that never sends anything, over a socket pair whose other end is `peer`.- #[cfg(test)]- pub(crate) fn silent(inbox: Inbox) -> (Self, Stream) {+ #[cfg(any(test, feature = "test-support"))]+ pub fn silent(inbox: Inbox) -> (Self, Stream) {let (stream, peer) = Stream::pair().unwrap();let writer = Arc::new(Mutex::new(WriterState { stream: stream.try_clone().unwrap(), outgoing_id: 0, incoming_id: 0 }));let Inbox { sender, receiver: incoming } = inbox;diff --git a/native/crates/exthost/src/main_thread.rs b/native/crates/exthost/src/main_thread.rsindex 3abad97ca4a..a3fbde879b8 100644--- a/native/crates/exthost/src/main_thread.rs+++ b/native/crates/exthost/src/main_thread.rs@@ -8,10 +8,25 @@ use serde_json::{Value, json};use crate::rpc::{Arg, Reply};use crate::session::Session;+/// Who serves a host call that the session does not answer in one of its own arms.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub enum Path {+ /// The session thread waits in `MainThread::handle`.+ Blocking,+ /// Sent on as a `ForwardedRequest` and answered later by `Session::reply`.+ Forwarded,+ /// The session answers it; the workbench gets a copy (`OBSERVED_REQ`).+ Observed,+}++/// The workbench's answer to "who serves `proxy.method`"; `None` leaves the call to the session. A `fn` pointer, not a+/// `MainThread` method: `Session::serve` takes the `MainThread` out while it is busy, and a forward must not queue behind it.+pub type PathOf = fn(proxy: &str, method: &str) -> Option<Path>;+pub trait MainThread: Send {/// Answers a host request, or `None` to leave it to the session. `Err` is a `SerializedError`./// The handler may call the host through `session` while it works (a file system provider read).- fn handle(&mut self, session: &mut Session, proxy: &str, method: &str, args: &[Arg]) -> Option<Result<Reply, Value>>;+ fn handle(&mut self, session: &mut Session, proxy: &'static str, method: &str, args: &[Arg]) -> Option<Result<Reply, Value>>;/// Sends what the workbench queued for the host since the last call.fn flush(&mut self, session: &mut Session);diff --git a/native/crates/exthost/src/session.rs b/native/crates/exthost/src/session.rsindex 5e253f6366f..4bc15bc2d64 100644--- a/native/crates/exthost/src/session.rs+++ b/native/crates/exthost/src/session.rs@@ -14,7 +14,7 @@ use config::workspace::Workspace;use serde_json::{Value, json};use crate::console::format_console_entry;-use crate::main_thread::{MainThread, Waiting};+use crate::main_thread::{self, MainThread, PathOf, Waiting};use crate::main_thread_configuration::MainThreadConfiguration;use crate::main_thread_files::MainThreadFiles;use crate::main_thread_workspace::{MainThreadWorkspace, Outgoing};@@ -193,16 +193,7 @@ pub struct Session {waiting: Waiting,}-/// Host calls the session answers itself (the port log on stderr, which must keep up with the extension tests'-/// output) and also hands to the workbench as `OBSERVED_REQ`, which it answers nothing: the Window log and-/// notifications of mainThreadConsole.ts, mainThreadErrors.ts and mainThreadExtensionService.ts.-const OBSERVED: [(&str, &str); 3] = [- ("MainThreadConsole", "$logExtensionHostMessage"),- ("MainThreadErrors", "$onUnexpectedError"),- ("MainThreadExtensionService", "$onExtensionActivationError"),-];--/// The `req` of an observed call; the host numbers its requests from 1.+/// The `req` of a `Path::Observed` call's copy, which the workbench answers nothing; the host numbers its requests from 1.pub const OBSERVED_REQ: u32 = 0;/// A host request the app answers later with `Session::reply` (MainThread* shapes the workbench implements).@@ -215,7 +206,7 @@ pub struct ForwardedRequest {}struct Forward {- proxies: &'static [&'static str],+ path_of: PathOf,send: Box<dyn FnMut(ForwardedRequest) + Send>,replies: std::sync::mpsc::Receiver<(u32, Result<Value, Value>)>,/// The ids of `ask_workbench` requests, counted down from `u32::MAX`, below which the host's ids never reach.@@ -373,10 +364,10 @@ impl Session {})}- /// Hands requests to `proxies` (a proxy, or `Proxy.$method` for one method) to `send` instead of answering them here;- /// `pump` sends the answers that arrive on `replies`.- pub fn forward(&mut self, proxies: &'static [&'static str], send: impl FnMut(ForwardedRequest) + Send + 'static, replies: std::sync::mpsc::Receiver<(u32, Result<Value, Value>)>) {- self.forward = Some(Forward { proxies, send: Box::new(send), replies, asks: Vec::new(), held: Vec::new() });+ /// Hands the requests `path_of` gives `Path::Forwarded` to `send` instead of answering them here, and a copy of the+ /// `Path::Observed` ones; `pump` sends the answers that arrive on `replies`.+ pub fn forward(&mut self, path_of: PathOf, send: impl FnMut(ForwardedRequest) + Send + 'static, replies: std::sync::mpsc::Receiver<(u32, Result<Value, Value>)>) {+ self.forward = Some(Forward { path_of, send: Box::new(send), replies, asks: Vec::new(), held: Vec::new() });}/// Asks the workbench from this side (`send` with a request no host sent) and waits for the answer while@@ -611,19 +602,25 @@ impl Session {Message::Request { req, rpc_id, method, args, .. } => {self.host.send(rpc::encode(&Message::Acknowledged { req }));let proxy = proxy_name(rpc_id);- if let Some(forward) = self.forward.as_mut().filter(|_| OBSERVED.contains(&(proxy, method.as_str()))) {- let args = args.iter().cloned().map(forwarded_arg).collect();- (forward.send)(ForwardedRequest { req: OBSERVED_REQ, proxy, method: method.clone(), args });- }- let forwards = |entry: &&str| *entry == proxy || entry.strip_prefix(proxy).and_then(|rest| rest.strip_prefix('.')) == Some(method.as_str());- if let Some(forward) = self.forward.as_mut().filter(|forward| forward.proxies.iter().any(forwards)) {- *self.log.host_calls.entry(format!("{proxy}.{method}")).or_default() += 1;- if std::env::var_os("EXTHOST_TRACE").is_some() {- eprintln!("forward> {proxy}.{method} {args:?}");+ let Some(forward) = self.forward.as_mut() else {+ self.serve(req, rpc_id, method, args);+ return Ok(self.extension_tests_running());+ };+ match (forward.path_of)(proxy, &method) {+ Some(main_thread::Path::Forwarded) => {+ *self.log.host_calls.entry(format!("{proxy}.{method}")).or_default() += 1;+ if std::env::var_os("EXTHOST_TRACE").is_some() {+ eprintln!("forward> {proxy}.{method} {args:?}");+ }+ let args = args.into_iter().map(forwarded_arg).collect();+ (forward.send)(ForwardedRequest { req, proxy, method, args });+ return Ok(true);}- let args = args.into_iter().map(forwarded_arg).collect();- (forward.send)(ForwardedRequest { req, proxy, method, args });- return Ok(true);+ Some(main_thread::Path::Observed) => {+ let args = args.iter().cloned().map(forwarded_arg).collect();+ (forward.send)(ForwardedRequest { req: OBSERVED_REQ, proxy, method: method.clone(), args });+ }+ Some(main_thread::Path::Blocking) | None => {}}self.serve(req, rpc_id, method, args);}@@ -644,7 +641,11 @@ impl Session {}Message::Acknowledged { .. } => {}}- Ok(self.extension_tests_req.is_none_or(|req| !self.results.contains_key(&req)))+ Ok(self.extension_tests_running())+ }++ fn extension_tests_running(&self) -> bool {+ self.extension_tests_req.is_none_or(|req| !self.results.contains_key(&req))}/// Lets the workbench handler answer first; requests arriving while it calls the host wait for it.@@ -913,7 +914,7 @@ mod tests {let mut session = Session::new(host);let asked = std::sync::Arc::new(std::sync::Mutex::new(None));let (replies, workbench_replies) = std::sync::mpsc::channel();- session.forward(&[], { let asked = asked.clone(); move |request| *asked.lock().unwrap() = Some(request.req) }, workbench_replies);+ session.forward(|_, _| None, { let asked = asked.clone(); move |request| *asked.lock().unwrap() = Some(request.req) }, workbench_replies);session.main_thread = Some(Box::new(AnswersOnFlush { asked, replies }));let (done, answer) = std::sync::mpsc::channel();std::thread::spawn(move || done.send(session.ask_workbench("workbench", "debugMemory", Vec::new())).unwrap());@@ -926,7 +927,7 @@ mod tests {let waker = inbox.waker();let (host, _peer) = ExtensionHost::silent(inbox);let mut session = Session::new(host);- session.forward(&[], |_| {}, std::sync::mpsc::channel().1);+ session.forward(|_, _| None, |_| {}, std::sync::mpsc::channel().1);assert_eq!(session.idle_timeout(), Duration::MAX);let started = Instant::now();std::thread::spawn(move || {diff --git a/port/ledger.md b/port/ledger.mdindex 83d2600d328..7ce8b7e4394 100644--- a/port/ledger.md+++ b/port/ledger.md@@ -46,7 +46,7 @@ Status: `open`, `in progress`, `waiting on Artur`, `later` (postponed), `done`,| Milestones | M24 Windows build | in progress | Branch `worktree-m24-windows`, beside milestone 23 on the same seams: macOS and Linux code stays as it is, each Windows counterpart sits behind `cfg(target_os = "windows")` in the function where it is a few lines, in a `windows.rs` beside `macos.rs` and `linux.rs` where it is not. Scope: WebView2, the Win32 file dialogs and message boxes, the in-window menu bar and custom title bar, Credential Manager (keyring), named pipes for the extension host and single instance, ConPTY for the terminal (terminal/pty/conpty.rs, the VT backend libghostty-vt is platform-neutral), drive-letter paths and file URIs, the user-setup install path with `bin` on the user PATH (code.iss `addtopath`), `%APPDATA%\Code` settings import, an x64 and arm64 zip and a user installer, no Authenticode signing (the Windows signing decision). Cross build on the Studio (cargo-xwin, `x86_64-pc-windows-msvc` and `aarch64-pc-windows-msvc`) for compile checks and host-run unit tests; real runs on GitHub Actions `windows` runners (`.github/workflows/windows.yml`, by hand). Seams: the "M24 Windows" rows. | `cargo build --release -p app` and the area tests pass on win32-x64 and win32-arm64 runners; the app opens a folder, edits, saves, runs an extension (the exthost handshake, emmet and git activate) and shows a webview on the runner; `v1.147.0-insider` carries `VSRustium-win32-x64-1.147.0-insider.zip`, `VSRustium-win32-arm64-1.147.0-insider.zip` and both user setups; the macOS and Linux builds are unchanged (their area tests as before). || Milestones | M25 virtual workspaces | later | Artur: its own milestone after M20, not part of the gap audits. A folder of a non-file scheme (`.code-workspace` `uri` folders, `--folder-uri`, `vscode.openFolder` with an extension file system provider scheme) kept as a URI; every reader of workspace folders (173 `.folders` uses in 70 files: explorer, search, quick open, terminal cwd, tasks, git, watcher, settings layers, trust) goes through the file system providers; the workspace marked virtual, `virtualWorkspaces: false` extensions disabled with the `notSupportedInWorkspace` message (config/workspace.rs:101, port/notes.md provider entries deferred until virtual workspaces). | not started || Milestones | M26 GPUI on gpui-fast | done | Artur, 2026-12-01: the port's GPUI moved from Wu (dstrml/wu a3ced28) to gpui-fast (longbridge/gpui-fast f0a91cf952678e4d205da1ec189b6d134e975bcd, base zed a36d485, vendored in `native/vendor/gpui-fast`), a Zed GPUI fork whose Retained Mode redraws only the views that changed; `native/vendor/wu` is deleted. Reason, risks, sync, the gate's results and the open gaps (outer shadow clip, Linux `super-q`): port/notes.md "GPUI on gpui-fast". | All area tests and `port/tools/api-tests` green; `cargo test -p app corner_lab` within today's thresholds; a Retained Mode on/off differential test without differences; GUI: open a folder, edit, save, an extension (exthost handshake, emmet, git), a webview, a long list scroll, the terminal; `port/tools/bench` not worse than Wu in any column; `bun port/tools/ledger-check.ts` passes. Results: port/notes.md "GPUI on gpui-fast", "M26 gate". |-| Milestones | M27 architecture deepening | open | Artur, 2026-12-02: the six candidates of the architecture review, one per session and worktree, in the order 4, 1, 3, 5, 6, 2: one answer to who serves a MainThread call, one announcement of a model content change, one extension host start per window, editor options as a module, language feature registrations decoded once, one pass over the editors of every group (the swap of `with_group` stays, the multi-instance code editor builds on it). Every candidate is pixel-neutral and keeps the invariants of ARCHITECTURE.md; performance is M28. Plan, evidence and the picked interfaces of candidates 4 and 1: port/plans/architecture-deepening.md. | Each candidate's "Done when" of port/plans/architecture-deepening.md holds; `port/tools/pixel-check` and the area's `port/tools/ui-pair` steps show no difference from the commit before each candidate; `bun port/tools/ledger-check.ts` passes. |+| Milestones | M27 architecture deepening | open | Artur, 2026-12-02: the six candidates of the architecture review, one per session and worktree, in the order 4, 1, 3, 5, 6, 2: one answer to who serves a MainThread call, one announcement of a model content change, one extension host start per window, editor options as a module, language feature registrations decoded once, one pass over the editors of every group (the swap of `with_group` stays, the multi-instance code editor builds on it). Every candidate is pixel-neutral and keeps the invariants of ARCHITECTURE.md; performance is M28. Plan, evidence and the picked interfaces of candidates 4 and 1: port/plans/architecture-deepening.md. Done: 4, 1, 3, 5, 6, 2 (port/notes.md "Architecture deepening"). Pixel-neutral, measured once over the six from `f4d6aabdf09` to the last candidate (port/notes.md "Architecture deepening"): `port/tools/pixel-check` gives identical port images in 36 of 40 window and theme pairs, the 4 `panel` ones differing only in the checkout path the terminal prompt prints; `port/tools/ui-pair` with ONLY=port over steps-params-actions, steps-color and steps-ghost gives identical images. Open from 6: the `$provide*` calls stay built by each feature (83 `"ExtHostLanguageFeatures"` sites), not in the language features module as the plan's goal says; its "Done when" holds. Open from 5: the editor options are read under the settings lock on every call, not once per settings change (the settings service has no change counter to key a cache on; the typing and scroll gates did not move); `language_setting`, `suggest_setting`, `editor_bool_setting` and the raw `get_value` reads of word wrap, folding, paste and comments still hold their own defaults outside `workbench/editor_options.rs`. | Each candidate's "Done when" of port/plans/architecture-deepening.md holds; `port/tools/pixel-check` and the area's `port/tools/ui-pair` steps show no difference from the commit before each candidate; `bun port/tools/ledger-check.ts` passes. || Milestones | M28 Zed gate | open | Artur, 2026-12-02: the port is not behind Zed in any metric of `port/tools/bench`, time and memory. Its own track, apart from M27. Behind today (README.md, port/results/benchmark.md): peak footprint and peak RSS. The plan follows a memory profile of the peak footprint. | `port/tools/bench > run.tsv && bun port/tools/bench-check.ts run.tsv vsrustium zed` prints no `BEHIND` on a quiet machine (the run's load under `max_load` of port/budgets.json). || M23 Linux | app/src/webview/linux.rs:66 | done | [linux L] webviews through WebKitGTK: webview panels and views, editor insets, notebook outputs, extension details, release notes. | `FIXTURE=webview-tests port/tools/linux/smoke` on X11 (Xvfb): 10/10 ok; `cargo gc test -p app webview` on Linux: 19 passed || M23 Linux | app/src/webview/linux.rs:47 | open | [linux L] webviews in a Wayland session. Linux shows now: no webview under Wayland: GPUI has no X window there to hold the GTK window, so `supported()` is false and each webview surface stays empty. Needs a route that does not embed: GTK opens its own Wayland connection, and a `wl_subsurface` cannot take a surface of another client, so the reparenting X11 uses has no Wayland form; WPE WebKit rendering offscreen into a GPUI texture, with input forwarded, is the route left (not started). | |@@ -198,7 +198,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston| mainthread/MainThreadDocumentContentProviders | MainThread* shape (Rust side) | M12 | verified | | main_thread.rs keeps the registrations and opens provider URIs through $provideTextDocumentContent; host_requests.rs applies $onVirtualDocumentChange as one edit (no minimal edits): api-tests MOCHA_GREP="vscode API - workspace" 94/2/13, all 8 content provider tests pass; verified: api-tests MOCHA_GREP="vscode API - (workspace|file system|env|types|tasks)" at 44a309311e1: every workspace, workspace-fs, workspace events, workspace-watcher and file system test passes, api-workspace 4/0/0 (port/results/api-tests.md "M12 verification"), all content provider tests || mainthread/MainThreadDocuments | MainThread* shape (Rust side) | M8 | verified | | host_sync.rs, host_requests.rs: port/tools/api-tests whole folder suite, `MOCHA_GREP="vscode API - editors"` 13/0/0, `MOCHA_GREP="vscode API - workspace"` 84/2/0 (the 2 upstream skips), `workspace events` 10/0/0 (port/results/api-tests.md, milestone 20 sweep); `port/tools/settings-check preferences` (vscode://defaultsettings and vscode://schemas documents) || mainthread/MainThreadBulkEdits | MainThread* shape (Rust side) | M12 | verified | | file edits of workspace.applyEdit (api-tests: rename & ignoreIfExists, delete & ignoreIfNotExists, #111867 1/3 to 3/3, binary files pass); text edits and EOL changes through workbench/bulk_text_edits.rs, api-tests MOCHA_GREP="vscode API - workspace" 94/2/13 with every applyEdit test passing; cell edits go to the notebook models (api-tests notebook.document `workspace edit API` cases pass, milestone 17); an edit that needs confirmation waits in the Refactor Preview, `false` for no edits (port/resul [... omitted end of long line]; file edits of workspace.applyEdit (api-tests: rename & ignoreIfExists, delete & ignoreIfNotExists, #111867 1/3 to 3/3, binary files pass); text edits and EOL changes through workbench/bulk_text_edits.rs, api-tests MOCHA_GREP="vscode API - workspace" 94/2/13 with every applyEdit test passing; cell edits fail until milestone 13; an edit that needs confirmation waits in the Refactor Preview, `false` for no edits (port/results/refactor-preview.md) |-| mainthread/MainThreadTextEditors | MainThread* shape (Rust side) | M8 | verified | | host_requests.rs, workbench/editor_view/quick_diff.rs: cargo test -p app the_host_sees_the_code_editors_of_the_rendered_cells cell_list_editors_follow_the_rendered_rows set_options_apply_the_cursor_style_and_line_numbers text_editor_show_and_hide quick_diff_contributed; api-tests `MOCHA_GREP="vscode API - editors"` 13/0/0, `MOCHA_GREP="vscode API - window"` 40/0/0 (port/results/api-tests.md) |+| mainthread/MainThreadTextEditors | MainThread* shape (Rust side) | M27 | ported | [3 S] model_events.rs: the selection that follows an edit carries the wrong source for 4 paths (mainThreadEditor.ts `onDidChangeCursorSelection` passes cursor.ts's, which `TextEditorSelectionChangeKind.fromValue` reads): an editor command sends `keyboard` where coreCommands.ts sends its id (`deleteRight`), undo `keyboard` where cursor.ts `onModelContentChanged` sends `modelChange`, replace all `api` where findModel.ts sends `replaceAll`, the final newline save participant `modelChange` where saveParticipants.ts sends `insertFinalNewLine`. | host_requests.rs, workbench/editor_view/quick_diff.rs: cargo test -p app the_host_sees_the_code_editors_of_the_rendered_cells cell_list_editors_follow_the_rendered_rows set_options_apply_the_cursor_style_and_line_numbers text_editor_show_and_hide quick_diff_contributed every_path_of_an_edit_tells_the_host_first; api-tests `MOCHA_GREP="vscode API - editors"` 13/0/0, `MOCHA_GREP="vscode API - window"` 40/0/0 (port/results/api-tests.md) || mainthread/MainThreadTreeViews | MainThread* shape (Rust side) | M11 | verified | | workbench/tree_view.rs, workbench/view_containers.rs: cargo test -p app tree_view custom_tree; api-tests `MOCHA_GREP="vscode API - window|vscode API - tree"` 43/0/1 (the 1 a notebook test, milestone 17; tree.test.ts all pass); ui-pair port/fixtures/extensions/ui-tree-checkbox.json with `ARGS=--extensionDevelopmentPath=<abs>/port/fixtures/extensions/tree-checkbox`; port/results/references-view.md; scrollbars: cargo test -p app the_tree_shows_its_scrollbar_under_the_pointer (treeView.ts tree in Workbench::scrollable) || mainthread/MainThreadDownloadService | MainThread* shape (Rust side) | M18 | verified | | `_workbench.downloadResource` copies a file, fetches a URL and rejects a 404 with the upstream message: port/tools/extensions-check; session.rs answers undefined || mainthread/MainThreadErrors | MainThread* shape (Rust side) | M6 | verified | | main_thread_errors.rs: `$onUnexpectedError` goes through log.ts `createUnexpectedErrorHandler` (the stack, or `toErrorMessage`; the same text again within 1000 ms dropped) to the Window log; the session still prints it on stderr (cargo test -p app output::logger main_thread_errors: log.test.ts cases); session.rs writes `$onUnexpectedError` stacks to the port log (code-gpui stderr); seen in port/tools/api-tests api-folder.log |@@ -393,7 +393,7 @@ One row per upstream unit, generated by `bun port/tools/gen-ledger.ts`; mileston| platform/workspace | src/vs/platform | M12 | verified | | virtual workspaces (non-file folders): milestone 25; config/src/workspace.rs: folders, getFolder, toWorkspaceFolders, workspace label; cargo test -p config workspace (workspace.test.ts cases); api-workspace 4/4; verified: api-tests MOCHA_GREP="vscode API - (workspace|file system|env|types|tasks)" at 44a309311e1: every workspace, workspace-fs, workspace events, workspace-watcher and file system test passes, api-workspace 4/0/0 (port/results/api-tests.md "M12 verification"), api-workspace 4/4 || platform/workspaces | src/vs/platform | M12 | verified | | session.rs, recently_opened.rs, config/src/workspace.rs, workbench/workspace_editing.rs: cargo test -p exthost (workspaces.test.ts stable id case); cargo test -p config workspace:: 5/5; cargo test -p app recently_opened workspace_editing; ui-pair port/fixtures/ui-pair/m12/workspace-folders.json (Remove Folder from Workspace enters Untitled (Workspace)) || editor/browser | src/vs/editor | M8 | verified | | editor/view.rs, editor/folding.rs, editor/minimap.rs, editor/word_wrap.rs, editor/smooth_scroll.rs, editor/mouse_selection.rs, workbench/editor_view.rs, workbench/gutter_mouse.rs, workbench/editor_view/text_decorations.rs: cargo test -p app editor::view::tests editor::folding minimap section_headers editor_menus selection_corners whitespace control_characters gutter_presses word_wrap smooth_scroll diff_editor diff_gutter switch_side bracket_pair_guide wrapping_indent_repeats without_a_wrapping_indent file_compare char_ranges a_click_without_a_move mouse_selection text_clicks_select a_selecting_drag_below a_drag_into_the_vertical the_bottom_edge_hit a_drag_below_a_comment text_input:: outline_and_border_follow_the_css_cascade a_decoration_outline_is_drawn_outside_its_range decoration_types_set_and_remove_editor_decorations wrapping_a_padded_inlay_hint_skips_its_padding_box a_selection_over_changes_shows_the_selection_toolbar the_scrollbars_stay_shown_over_the_minimap_and_the_track; ui-pair m12/compare.json, port/fixtures/ui-pair/m8/scrollbar-hover.json (FOLDER=<reference>/src/vs/base/common FILE=strings.ts: the 14px scrollbar column matches with 0 px over 6% fuzz while the pointer is on the minimap and on the track), port/fixtures/ui-pair/menus/diff-gutter-selection.json, port/fixtures/ui-pair/m8/inlay-hint-wrap.json (port/notes.md milestones 8 and 14) |-| editor/common | src/vs/editor | M8 | verified | | app/src/editor, decorations.rs, link_computer.rs, syntax.rs, brackets/tree.rs, the diff crate: cargo test -p app editor:: decorations:: link_computer syntax:: auto_closing brackets lines_in_view_past_the_tokenized_ones the_word_at_a_column full_width_chars_take moving_down_keeps a_hyphen_next_to_a_class_escape_is_literal (13 ignored: upstream's `test.skip` cases); cargo test -p diff; typing on the 52k-line TS file under 16 ms per edit with the section headers and unicode highlights, trim and comment on it just opened under 16 ms, its bracket selection scan under 30 ms (port/notes.md "Scheduling differences"): cargo gc test --release -p app -- --ignored typing_latency_on_a_large_file. By design: the piece tree text buffer is a vector of lines (large files through workbench/large_file.rs) |+| editor/common | src/vs/editor | M27 | ported | [3 M] workbench/editor_options.rs: the editor options read through `global_editor_option` take no `[lang]` block where upstream reads them per code editor (`editor.getOption`): the find widget's options, `mouseWheelZoom`, `multiCursorModifier`, `columnSelection` (mouse), `doubleClickSelectsBlock`, `smoothScrolling`, `stickyScroll.enabled`/`maxLineCount`, the minimap's options, `contextmenu`, `definitionLinkOpensInPeek`, `mouseMiddleClickAction`, `scrollOnMiddleClick` (port/notes.md "Architecture deepening", candidate 5). | app/src/editor, decorations.rs, link_computer.rs, syntax.rs, brackets/tree.rs, the diff crate: cargo test -p app editor:: decorations:: link_computer syntax:: auto_closing brackets lines_in_view_past_the_tokenized_ones the_word_at_a_column full_width_chars_take moving_down_keeps a_hyphen_next_to_a_class_escape_is_literal (13 ignored: upstream's `test.skip` cases); cargo test -p diff; typing on the 52k-line TS file under 16 ms per edit with the section headers and unicode highlights, trim and comment on it just opened under 16 ms, its bracket selection scan under 30 ms (port/notes.md "Scheduling differences"): cargo gc test --release -p app -- --ignored typing_latency_on_a_large_file. By design: the piece tree text buffer is a vector of lines (large files through workbench/large_file.rs) || editor/standalone | src/vs/editor | | removed | | Artur: internal infrastructure or developer tool with no 1:1 counterpart in the native port || editor/test | src/vs/editor | M6 | n/a | | upstream test infrastructure; the port tests with cargo test and port/tools || editor/contrib/anchorSelect | src/vs/editor/contrib | M8 | verified | | `editor/anchor_select.rs`: the four commands with their keys and `selectionAnchorSet`, the anchor moved by edits as a `NeverGrowsWhenTypingAtEdges` marker, the bar under the word highlights: cargo test -p app anchor; ui-pair notes.txt through the Command Palette; no hover message until editor hovers |diff --git a/port/notes.md b/port/notes.mdindex ab453f0223b..d407e68200c 100644--- a/port/notes.md+++ b/port/notes.md@@ -382,7 +382,7 @@ Scope shipped so far: `workspace.fs` and file events, Seti file icons and numeri- `workbench.action.files.showOpenedFileInNewWindow` starts another app process on the active file; `code-gpui <file>` (a path that is neither a folder nor a `.code-workspace` file) opens an empty window with the file, as windowsMainService.ts does.- Command sweep of workbench/contrib/files against the port: `workbench.action.files.saveEditors` and `revertEditors` are ids of notification actions, not commands (n/a); `explorer.download` and `explorer.upload` are web and remote only (n/a). Owned by code merged in port-integrate after this branch's base (e9ae1460): Save As, Save without Formatting, Toggle Auto Save, `textFileSaveErrorHandler` and the elevated write (milestone 8 text files), the empty Explorer view (milestone 11). Wait for that code here: the compare commands (`compareFiles`, `compareSelected`, `selectForCompare`, `compareFileWith`, `compareNewUntitledTextFiles`, `compareWithClipboard`, `compareWithSaved`) need the milestone 14 diff editor; the Open Editors view (`focusOpenEditorsView`, `openEditors.closeAll`, `openEditors.newUntitledFile`, `saveAllInGroup`, `closeGroup`) needs the milestone 11 view panes. Wait for section 11 services still `todo`: `explorer.openToSide` and `toggleEditorGroupLayout` (editor groups), `explorer.openWith` (the editor resolver), the dirty files badge (the activity service), the Explorer decorations for symlinks and unresolvable roots (the decorations service), the binary, missing file and folder placeholders of textFileEditor.ts with their actions `workbench.files.action.openFolder`, `workbench.files.action.reveal` and `workbench.files.action.createMissingFile` (the editor placeholder). `workbench.files.openFile` is only a telemetry event id (n/a).- Workspace folder editing (`workbench/workspace_editing.rs`; workspaceEditingService.ts browser and electron-browser, configurationService.ts `doUpdateFolders`, workspacesManagementMainService.ts `createUntitledWorkspace`): `updateFolders`, `addFolders` and `removeFolders` write the workspace file's `folders` through jsonEdit (paths relative to the file where possible, `getStoredWorkspaceFolder`), then the window follows in place: the Explorer roots, the folder settings layers (`Settings::write_workspace_folders`), the host's `$acceptWorkspaceData` and its search folders, the file watcher, and a host restart when the first folder changed (`WorkspaceChangeExtHostRelauncher`, not while extension tests run). An edit of the workspace file on disk takes the same path. In a folder or empty window, adding (or replacing or removing the folder) creates an untitled workspace `<user data>/Workspaces/<id>/workspace.json` ("Untitled (Workspace)", not in the recent list) and enters it. Commands: `addRootFolder` and Add Folder to Workspace (dialog "Add Folder to Workspace", Add), Remove Folder from Workspace (picker "Select workspace folder"), `removeRootFolder` on the Explorer's roots, Save Workspace As (`pickNewWorkspacePath`, `rewriteWorkspaceFileForNewLocation`, trust of the new file, "Unable to save workspace" when another window has it), Duplicate Workspace (`copyWorkspaceSettings`); File menu group `3_workspace` and the Explorer context group `2_workspace`. `$updateWorkspaceFolders` shows the "Extension '{0}' added 1 folder to the workspace" status for 10 s. Closing or leaving an untitled workspace asks "Do you want to save your workspace configuration as a file?" (`window.confirmSaveUntitledWorkspace`, the "Always discard" checkbox). A dropped folder's "Add Folder to Workspace" adds it. Tests: `cargo test -p config workspace::`, `cargo test -p app workspace_editing`.-- Entering a workspace switches the window in place as nativeWorkspaceEditingService.ts `enterWorkspace`: the extension host stops, the settings read the workspace's layers, the backups move (`moveBackupFolder`), the workspace storage is copied (`storageService.switch(preserveData)`), the Explorer, trust and recently opened follow, then the host starts again. Tests count the host start without a host process (`start_extension_host` under `cfg!(test)`). A non-default profile is not associated with the new untitled workspace (`setProfileForWorkspace`), a gap on the ledger row.+- Entering a workspace switches the window in place as nativeWorkspaceEditingService.ts `enterWorkspace`: the extension host stops, the settings read the workspace's layers, the backups move (`moveBackupFolder`), the workspace storage is copied (`storageService.switch(preserveData)`), the Explorer, trust and recently opened follow, then the host starts again. Tests count the host start without a host process (a test's `Workbench` has no `host_launch`). A non-default profile is not associated with the new untitled workspace (`setProfileForWorkspace`), a gap on the ledger row.- shortcut: the folder picker of Remove Folder from Workspace shows no ROOT_FOLDER icon; Seti, the default file icon theme, has no folder icons.- An empty area Explorer press stands for the only root (`onContextMenu`): its resource keys apply, so Reveal in Finder, Open Timeline, Copy Path and Copy Relative Path show there as in the reference.- Compare commands (`workbench/file_compare.rs`, fileCommands.ts and fileActions.ts): Compare Active File with Saved (Cmd+K D; the `showModifications` side holds the file as on disk, label "{name} (in file) ↔ {name}"), Select for Compare and Compare with Selected (`resourceSelectedForCompare`), Compare Selected (two Explorer rows, `listDoubleSelection`), Compare Active File With... (Quick Open with its second item active, `ItemActivation.SECOND`; the picked file is the modified side), Compare Active File with Clipboard (Cmd+K C, `clipboardCompare<n>` side, "Clipboard ↔ {name}"), Compare New Untitled Text Files; Explorer context group `3_compare`. Test: `cargo test -p app file_compare`.@@ -443,7 +443,7 @@ Done when (first item): api-tests `vscode API - editors` passes as in the refere- Folding update delay (`trigger_folding_model_changed`, folding.ts `updateScheduler`): an edit only moves the regions and hidden lines with it (`accept_replace`); the indentation or provider ranges are computed again after the `updateDebounceInfo` delay, 300 ms (`min * 1.5`) first, then the average update time of the model clamped to 200 ms..40 s. On the 52k-line TypeScript file this took 7.6 ms off each typed char.- The scroll position truncates to whole pixels like the editor's `Scrollable` (`forceIntegerValues`), so a centered reveal in an odd height does not land on a half pixel.- Mouse cursors follow the reference CSS: text over `.view-lines` (`monaco-mouse-cursor-text`), default over line numbers, glyph margin, overview ruler, scrollbar sliders and the scroll shadow; pointer over folding icons, the `⋯` placeholder (`folding.css`), the title with tabs, close buttons and breadcrumbs (`editortabscontrol.css`, `breadcrumbsWidget.css`) and the editor actions (`actionbar.css`, the container default).-- An edit sends the host new `visibleRanges` when the visible lines changed (`editor_edited` in `workbench/text_input.rs`), so unfolding by an edit reaches the host without a scroll.+- An edit sends the host new `visibleRanges` when the visible lines changed (`editor_content_listeners` in `workbench/model_events.rs`), so unfolding by an edit reaches the host without a scroll.- Minimap (`editor/minimap.rs`, `workbench/minimap_view.rs`): `editorLayoutProvider` minimap layout, `MinimapLayout.create` with its slider, `MinimapCharRenderer` and `renderLines` into one image, with the upstream unit tests (`cargo test -p app minimap`). The text area narrows by the minimap's width. Decorations as `renderDecorations`: selections in `minimap.selectionHighlight`, word highlights in `minimap.selectionOccurrenceHighlight`, collapsed folds in `editor.foldBackground`; a hidden line's decoration lands at the end of its fold line. The slider shows on hover and for 500 ms after a scroll, fades 100 ms, drags the editor; a press off the slider reveals that line centered. The shadow shows when the text is scrolled horizontally short of its end.- Section headers (`editor/section_headers.rs`): `findSectionHeaders.ts` with its tests: `#region` labels from the folding start marker's `label` group, `MARK:` comments (`markSectionHeaderRegex`) kept only on a comment token, with the block comment end stripped. Drawn as `_renderSectionHeaders`: `500` system font at `sectionHeaderFontSize` (9px, clamped 4 to 32), `sectionHeaderLetterSpacing` canvas pixels between letters (1, clamped 0 to 5), a 70% minimap background, labels of nearby lines stacked, long labels split around an ellipsis. `showRegionSectionHeaders` and `showMarkSectionHeaders` turn each kind off; a `markSectionHeaderRegex` that does not compile falls back to the default, as `EditorMinimap.validate` does (Oniguruma compiles it, where upstream asks JavaScript's RegExp).- Minimap settings (editorOptions.ts `EditorMinimap`): every `editor.minimap.*` is read (`size`, `side`, `showSlider`, `autohide`, `renderCharacters`, `maxColumn`, `scale`, the section headers). With `side: left` the margin and the content move right by the minimap's width; `fill` and `fit` sample long files (`MinimapSamplingState`). A right press on the scrollbars or the minimap shows `_showScrollbarContextMenu` (Minimap, Render Characters, Vertical size, Slider), disabled while the minimap is off or in a diff editor. Gaps: the context menu widget has no submenus, so Vertical size and Slider show as flat `Label: Choice` groups between separators (the widget belongs to `platform/contextview`, milestone 9); scale 3 and above stretch the scale 2 character table where upstream samples the font; the sampling is computed again on each frame where upstream keeps it across edits; `autohide: scroll` reacts to scroll top changes only. View: Toggle Minimap flips `editor.minimap.enabled`; off, the minimap takes no width. Section headers are found again on the UI thread for each model version, where upstream asks the editor worker 250 ms after the last edit. Tests: `cargo test -p app minimap editor_menus`.@@ -586,7 +586,7 @@ Scope (milestone 13): diagnostics, hover, completion, go to definition and peek,- Views drag and drop (branch views-dnd; compositeBar.ts, compositeBarActions.ts, viewPaneContainer.ts, dnd.ts): a view header dropped on a bar item gets a new container before or after it by the half it is over (compositeBar.ts `drop`), a container dropped on a pane merges its views there with its first active view at the drop position, a composite dropped where it already is opens focused. Held 800 ms over a bar item, a drag opens it (`DelayedDragHandler`). The active side bar container (`workbench.sidebar.activeviewletid`) is stored at quit and on release, not on each open as compositePart.ts does: the port sets the side bar view in 14 places without one change event, and only the value at quit is read back.- Text models and editors (coordinator decision, option A): `TextModel` (document, version, undo stack, guides, markers, host reference) is shared as `SharedModel = Rc<RefCell<TextModel>>` by every editor of its resource in any group; `OpenEditor` keeps the view state (selections, scroll, folding, highlights, view zones). An edit is logged on the model (`TextModel.edits`, 1000 replaces); an editor of another group follows it in `sync_with_model` (cursors tracked as decorations are, else clamped), run each frame and on group activation.- Editor groups (`editor_grid.rs`, `workbench/editor_groups.rs`; gridview.ts, grid.ts, editorPart.ts, editorCommands.ts): `EditorGroup` holds the active group in its fields and the others in `other_groups`; `activate_group` swaps them, and another group draws through the same editor code while swapped in (`with_group`, `drawing_inactive` leaves out its focus, input handler and widgets; a press activates it first). Models, diffs, disposed models and view states are the part's. The host sees one text editor per group showing one (`editorPosition` = grid order) and every group in `$acceptEditorTabModel`; tab ids start with the group id. A tab drags within its group, onto another group's tabs, or onto a group's body, whose edges split it (editorDropTarget.ts `getSplitDirection`, `split_direction`). The grid and each group's file editors (tab order, MRU, preview) persist in the workspace memento `memento/workbench.parts.editor` under `editorpart.state` in upstream's JSON shape, saved on every editor change and restored with the workspace state (`editor_groups/part_state.rs`; the `sticky` count per group restores pinned file and notebook editors; other editor kinds and locked groups store `locked`). shortcut: `$closeTab` across several groups at once is not ported yet.-- History (`navigation.rs`, `workbench/history_actions.rs`; historyService.ts): the three navigation stacks per `workbench.editor.navigationScope` key, fed by editor changes (`editors_changed`), cursor moves (`cursors_changed`, source to reason as textEditor.ts) and edits. Reopen Closed Editor keeps file editors only (a diff or untitled editor has no reopenable input in the port). shortcut: mouse buttons 4 and 5 (`workbench.editor.mouseBackForwardToNavigate`) are not read.+- History (`navigation.rs`, `workbench/history_actions.rs`; historyService.ts): the three navigation stacks per `workbench.editor.navigationScope` key, fed by editor changes (`editors_changed`), cursor moves (`cursor_position_changed`, source to reason as textEditor.ts) and edits. Reopen Closed Editor keeps file editors only (a diff or untitled editor has no reopenable input in the port). shortcut: mouse buttons 4 and 5 (`workbench.editor.mouseBackForwardToNavigate`) are not read.- Sash settings (contrib/sash): `sash_size`, `sash_hover_size`, `sash_hover_delay` in part_grid.rs; the grippers recede after `autoHideGrippersDelay` without a mouse move. shortcut: no opacity transition (no motion support in GPUI elements here).- Panel views (`PanelView` in panel.rs: id, title, body and title actions). The Output view's code editor lives in the hidden group `PANEL_GROUP` (`u32::MAX`), outside the grid, the MRU order and `$acceptEditorTabModel`; focusing it swaps that group in as split groups do, so `editorPosition` stays the grid's. Terminal is a panel view with its own body. Its title actions (channel dropdown, filter, Clear, gear) are in the panel's title bar as upstream.- Tree views (`custom_tree.rs` model, `workbench/tree_view.rs`; mainThreadTreeViews.ts, treeView.ts): the views of `contributes.views.explorer` whose `when` holds are Explorer panes, collapsed at first (`showCollapsed`). A view's tree exists only while its pane is expanded and the Explorer shows (`$setVisible`, `onView:<id>` on the first show), as upstream creates the tree on render: a `$refresh` or `$reveal` of a hidden view fetches nothing. The root fetch is shared (AsyncDataTree), so a reveal during it does not fetch twice. Pane ids are `&'static str`; a contributed id is interned once (`static_id`). The views of the other containers (scm, debug, test, `viewsContainers.activitybar`) follow the same rule in their container (`tree_view_body_visible`, workbench/view_containers.rs); the open gaps are in the ledger rows of workbench/services/views and mainthread/MainThreadTreeViews.@@ -850,7 +850,7 @@ Scope as in the M19 Work row of port/ledger.md.- Proxy requests of MainThreadWorkspace (workbench/proxy_auth.rs): `$loadCertificates` answers the keychain certificates of `security find-certificate -a -p` (proxy-agent's `readMacCaCertificates`) without the expired ones (`filterExpiredCertificates`; the host asks only with `http.systemCertificatesNode` off, else it reads them itself), `$lookupAuthorization` answers auth.ts's credentials: an extension test run's realm, else the `http.proxy` or proxy variable user info until the proxy rejects it. Not ported: the proxy login dialog and its stored credentials (shortcut in the file). `vscode API - network proxy support`: basic auth passes on Bun and Node; custom root certificate passes on both: Bun 1.4.5's `tls.connect` builds its secure context without calling `tls.createSecureContext`, where proxy-agent adds the `_vscodeAdditionalCaCerts` of `http.systemCertificates` (and the tests' `testCertificates`), so on Bun the host's patched `tls.connect` builds that context itself (proxyResolver.ts `addBunSecureContext`, gated on `process.versions.bun`).- Tests that fail under load are ledger gaps on their rows. The accessibility test with the same symptom read the wall clock (`c58d7539460`); look for timing in them first.- `workbench.action.tasks.runTask` with a name or identifier the tasks resolve runs the task directly (`_runTaskCommand` calls `this.run(task)` without `attachProblemMatcher`); the port showed the problem matcher picker for a name, which left the CustomExecution tests started by `runTask` waiting.-- MainThread* methods answering `undefined` (exthost/session.rs fallback and the forwarded proxies' `_ =>` arms), audited against extHost.protocol.ts 1.147.0: the ones an extension observes are gap entries of their MainThread* rows in port/ledger.md. The rest by reason: proposals no built-in enables (`$createNotebookExecution`, `$beginNotebookExecution`, `$completeNotebookExecution`, kernel detection tasks and source actions, `$variablesUpdated`, debug visualizers, structural diff, new symbol names, inline completion model and option events); consumers removed by decision (canonical URI and edit session identity providers: edit sessions, Authentication, GitHub accounts, chat, language models, MCP, speech, AI search, share, tunnels, browsers, git extension service, label formatters of remote resolvers, profile content handlers, search providers); one extension host (`$activateExtension` of a host extension); the session evaluates `workspaceContains` itself (`$checkExists`); telemetry (`$logResolveTreeNodeFailure`, `$handleTelemetry`); tracked by views rows (`$setWebviewViewBadge`: workbench/contrib/webviewView; `$emitInlineValuesEvent`, evaluatable expressions: workbench/contrib/debug).+- MainThread* methods answering `undefined` (exthost/session.rs fallback and, since M27, the `not_ported` arms of app/src/main_thread_commands.rs `route`), audited against extHost.protocol.ts 1.147.0: the ones an extension observes are gap entries of their MainThread* rows in port/ledger.md. The rest by reason: proposals no built-in enables (`$createNotebookExecution`, `$beginNotebookExecution`, `$completeNotebookExecution`, kernel detection tasks and source actions, `$variablesUpdated`, debug visualizers, structural diff, new symbol names, inline completion model and option events); consumers removed by decision (canonical URI and edit session identity providers: edit sessions, Authentication, GitHub accounts, chat, language models, MCP, speech, AI search, share, tunnels, browsers, git extension service, label formatters of remote resolvers, profile content handlers, search providers); one extension host (`$activateExtension` of a host extension); the session evaluates `workspaceContains` itself (`$checkExists`); telemetry (`$logResolveTreeNodeFailure`, `$handleTelemetry`); tracked by views rows (`$setWebviewViewBadge`: workbench/contrib/webviewView; `$emitInlineValuesEvent`, evaluatable expressions: workbench/contrib/debug).- workbench/services/sharedProcess and workbench/services/utilityProcess: the port has no shared process and no utility process workers; each channel a kept feature opened to them runs in the app process, checked in its own row. `ISharedProcessService.getChannel`: `extensions` (NativeExtensionManagementService) is exthost/src/extension_management.rs (platform/extensionManagement, port/tools/extensions-check), `extensionGalleryManifest` is the Open VSX gallery (gallery/open-vsx), `extensionTipsService` is app/src/extension_recommendations.rs (platform/extensionRecommendations), `languagePacks` is exthost/src/language_packs.rs (platform/languagePacks), `checksum` is n/a (platform/checksum); `telemetryAppender`, `customEndpointTelemetry`, `userDataSync*`, `userDataAutoSync`, `mcpManagement`, `mcpGalleryManifest`, `remoteTunnel`, `sharedProcessTunnel`, `localGit`, `playwright` and `sharedWebContentExtractor` serve removed features. `IUtilityProcessWorkerWorkbenchService.createWorker`: its one kept client, the universal file watcher of diskFileSystemProvider.ts, is files/src/watcher.rs on an FSEvents thread (platform/files, api-tests `vscode API - workspace-watcher`); localTranscription is AI (removed). `notifyRestored`'s barrier (connect after the Restored phase or 2 s) has nothing to delay: no process starts.- Sticky scroll from the outline model (stickyScrollModelProvider.ts): with `editor.stickyScroll.defaultModel` `outlineModel` (the default) the active editor's scopes come from its document symbols (workbench/sticky_outline.rs, 300 ms `Delayer`, plus the 50 ms content-change scheduler), the folding regions only when the outline has no symbols. Cmd+click on a sticky line's text runs the muted Go to Definition of the projected span (Alt to the side), anchored at the span's start without moving the cursor, the peek over the span (`go_to_definition_with_location`, inlayHintsLocations.ts `goToDefinitionWithLocation`); with several candidates the clicked line is revealed first. Cmd+hover underlines a span with definitions.- Save conflict editor (textFileSaveErrorHandler.ts): Compare in the "content of the file is newer" message opens `conflictResolution:<path>` (the file on disk in the model's encoding and language, following the file while open) against the model, pinned, labeled "<name> (in file) ↔ <name> (in VSRustium) - Resolve save conflict", with the Info help message (Learn More, Don't Show Again as `neverShowAgain` `learnMoreDirtyWriteError`). `saveConflictResolutionContext` shows the title's "Use your changes and overwrite file contents" (check) and "Discard your changes and revert to file contents" (discard): they close the help messages, save with `ignoreModifiedSince` or revert, open the file's editor and close the conflict editor. A save from the conflict editor that conflicts again shows the help as an error. cargo test -p app compare_opens_the_save_conflict_editor.@@ -1172,3 +1172,34 @@ Work the port does at another time than 1.147.0, accepted with a measured same r| 78a79751093 | fix(gpui): round .5 device px up when snapping layout, as Chromium | layout | no (its hunks apply only to the dead `taffy.rs`) | `fast/taffy.rs`, `util.rs` | 5, 0 || 6c3b7094c6f | fix(gpui): shrink the background behind an opaque rounded border | quads | no | `style.rs`, `fast/layers/paint.rs` | 2, 0 || 2a560ca76e0 | build(port): vendor wu's gpui and gpui_apple through [patch] | vendor | | | |++## Architecture deepening (milestone 27, port/plans/architecture-deepening.md)++- Candidate 4, one answer to who serves a MainThread call (branch refactor/m27-host-call-paths): the forward list of `app/src/main.rs::run_extension_host`, `HOST_REQUESTS`, `Workbench::host_request`, the session's `OBSERVED` and the `_ => Outcome::done()` defaults became one private match, `app/src/main_thread_commands.rs::route`, that gives each call its `exthost::main_thread::Path` (`Blocking`, `Forwarded`, `Observed`) and its handler. `Session::forward` takes its projection `path` as a `fn` pointer, so a forward never queues behind the `MainThread` object `Session::serve` has taken out. A call the table does not name stays with the session (`Session::serve`), as before.+- Finding, fixed test first: `MainThreadLanguageFeatures` was forwarded as a whole proxy and the pump checked the forward list before `Session::serve`, so `$resolvePasteFileData` and `$resolveDocumentOnDropFileData` (mainThreadLanguageFeatures.ts) answered null instead of the file's bytes. Now `Blocking`: the workbench names the file, the session thread reads it (cargo test -p app resolve_paste_file_data).+- A proxy with a `(proxy, _)` arm answers a method it does not name with rpcProtocol.ts `_doInvokeHandler`'s error, `Unknown method $bar on actor MainThreadFoo` (cargo test -p app an_unknown_method_of_a_routed_proxy); before, it answered `undefined`. Every method of those proxies in extHost.protocol.ts 1.148.0 has its own arm, checked by script before the switch: the deliberate `undefined` answers are the `not_ported` arms (audit: "MainThread* methods answering `undefined`" above), and `$startFileSearch`, `$startTextSearch` and `$requestResourceTrust` answer null when the window has no workspace for the session's MainThreadWorkspace to serve them, as before.+- `$trySaveDocument` keeps its blocking path, but its handler returns `Outcome::Pending`; the blocking loop of `app/src/workbench/extension_host_restart.rs` awaits it.+- Candidate 1, one announcement of a model content change (branch refactor/m27-model-content-changed): `ContentChanged` names its model and every edit and cursor move goes through `app/src/workbench/model_events.rs::Workbench::model_content_changed` or `cursor_position_changed`, which send `$acceptModelChanged` and the shown editor's selection before any listener runs. `editor_edited`, `editor_edited_revealing`, `cursors_changed`, `send_model_edit` and `HostSync::send_content_change` are gone; `app/src/workbench/model_events/tests.rs::every_path_of_an_edit_tells_the_host_first_and_wakes_the_shown_editor` makes one edit by each of 10 paths.+- Skips closed test first (model_events/tests.rs): a bulk, host or save participant edit of the shown model now asks code lens, inlay hints and colors again (codelensController.ts, inlayHintsController.ts, colorDetector.ts); a cursor move wakes code actions, parameter hints and linked editing (codeActionModel.ts, parameterHintsModel.ts, linkedEditing.ts); a click in the output view locks its scroll (outputView.ts `onDidChangeCursorPosition`, reason `Explicit`). The selection after an edit takes the cursor's source instead of a fixed `keyboard` (cursor.ts `onModelContentChanged` sends `modelChange`); 4 paths still send another source than upstream, a gap of the `mainthread/MainThreadTextEditors` row.+- Trap: with one announcement, the find widget's own Replace All reached `find_editor_edited` and reset its match position; `ignore_own_change` skips it as findModel.ts `_ignoreModelContentChanged` does. Language detection lost its own `edited` channel and runs from the model listeners.+- Candidate 3, one extension host start per window (branch refactor/m27-host-start): `app/src/extension_host_start.rs`. Three interfaces, on one axis, where the start reads the window state the host needs (extensions, settings, storage, trust, workspace, runtime, user data): (a) from the caller, one free function over a 16-field struct both callers fill; (b) from a `HostStarter` object the workbench keeps, holding the channels and the process kind; (c) from the `Workbench` itself, `Workbench::spawn_extension_host(HostStart, HostLaunch, development)`, with only what `open_window` alone knows (`HostLaunch`: the process and `--user-data-dir`) stored once on the workbench. Picked (c): (a) leaves both callers gathering the same list, the place the copies drifted; (b) is a class beside state the workbench already owns. `HostStart::new` makes the channels and queues the color theme and language ids before `Workbench::new`, which takes the `HostSync`.+- The seam has two adapters, `HostProcess::Runtime` (Bun, or Node with `--node`) and, in tests, `HostProcess::Silent` over `ExtensionHost::silent`, which hands the test the init data and its end of the socket. The restart's `cfg!(test)` return is gone: a test's `Workbench` has no `host_launch` and only counts the start; `app/src/workbench/extension_host_restart/tests.rs::a_host_restart_starts_the_host_as_the_window_did` sets one and checks the host the restart opens.+- Drift confirmed and closed test first: the restart read the runtime again from `std::env::args()` and derived the user data folder from the settings path (`user_home().parent()`), where `open_window` used `--user-data-dir`. Both agree in the app today (the profile's files sit apart from `user_home`), so no visible bug; the test fails with the derivation back. The restart now also runs the status loop's eager-activation step; `code/didLoadExtensions` stays a mark of the first start.+- `port/tools/bench` on the Studio (vscode-ref-1.148.0, `chat.disableAIFeatures`), medians before and after candidate 3: `window_s` 1.10 and 1.09, `ready_s` 1.67 and 1.66. `window_s` is over its 0.66 budget on the commit before too (b110e96a688), so not this change's; a finding for M28.+- Candidate 5, editor options as a module (branch refactor/m27-editor-options): `app/src/workbench/editor_options.rs`. Three interfaces, on one axis, how a call site names an option: (a) a typed constant per option, `EditorOption<T>` with its key and its `validate` (editorOptions.ts `IEditorOption`), read by `Workbench::editor_option(editor, &OPTION)` with the editor's `[lang]` block or `global_editor_option(&OPTION)` outside a code editor; (b) the key string, read by a getter per type (`editor_bool(editor, "editor.find.loop")`) over a table of defaults and validators keyed by the string; (c) a field of an `EditorOptions` snapshot struct the workbench keeps per language and rebuilds on a settings change. Picked (a): jump to definition reaches the default and the validation, a misspelled option does not compile, and nothing is cached; (b) keeps a misspelling a runtime miss and adds string-keyed dispatch; (c) needs a settings change signal the settings service does not have (no revision counter) and rebuilds about 70 fields per language.+- Every `self.setting("editor.…")` read moved: through the module where upstream reads an editor option, and as `self.setting(OPTION.key)`, raw as upstream, where upstream reads the configuration itself (notebookOptions.ts `editor.fontSize` and `editor.fontFamily`, walkThroughPart.ts, the terminal's font and link modifier, the task templates' `editor.tabSize` and `editor.insertSpaces`, the search view's seed and word separators, accessibilityService's `editor.accessibilitySupport`). The defaults and validators are editorOptions.ts's; the options that are not editor options take their schema's default (`editor.codeActions.triggerOnFocusChange`, `editor.rename.enablePreview`, `editor.stablePeek`, `editor.tabSize`, `editor.insertSpaces`); `editor.fontSize` and `editor.fontFamily` default per platform as fontInfo.ts `EDITOR_FONT_DEFAULTS`.+- Closed test first (`app/src/workbench/editor_options/tests.rs`): a value of the wrong type no longer reaches a site raw (`EditorFind.validate` reads `seedSearchStringFromSelection: false` as `never`, the port read it as `always`; `clampedInt` parses `"42px"`; `stringSet` falls back to the default), and `editor.renderWhitespace`, `renderControlCharacters`, `roundedSelection`, `cursorStyle`, `overtypeCursorStyle`, `showUnused`, `showDeprecated`, `glyphMargin`, `wordWrapIndicator`, `selectionHighlight*`, `occurrencesHighlightFromAllProviders`, `dragAndDrop`, `columnSelection` and `folding` (context keys), `stickyScroll.scrollWithEditor`, `ariaLabel`, `accessibilityPageSize` and `accessibilitySupport` (the aria label) now take the editor's `[lang]` block, as `editor.guides.*` and `editor.cursorBlinking` did.+- Open, written back to the M27 row: the module reads under the settings lock on every call, not once per settings change; the reads that stay global take no `[lang]` block (a class 3 gap of the editor/common row, moved to M27); three more per-editor readers (`format.rs::language_setting`, `suggest_controller.rs::suggest_setting`, `editor_commands.rs::editor_bool_setting`) and the raw `get_value` reads of word wrap, folding, paste and comments keep their own defaults.+- Gates on the Studio before and after candidate 5: `typing_latency_on_a_large_file` p95 at line 100, 25000 and 49000 10.06, 10.59, 11.57 ms and 10.03, 10.62, 11.80 ms; `scroll_frame_time` editor (20000 lines) median 4.15 and 4.15 ms, p95 7.97 and 7.95 ms.+- Pixel check for candidate 5: `port/tools/pixel-check` stops before and after on `ref-screenshot` timing out, so the port's own screenshots (file, main, find, folded in Dark Modern and High Contrast) were compared before and after with `pixeldiff`: file, main and folded match to the pixel; find differs by as many pixels between two runs of the same build, so the difference is run noise.+- Candidate 6, language feature registrations decoded once (branch refactor/m27-language-registrations): `app/src/language_features.rs::Registration::decode`. Three interfaces, on one axis, the form a feature reads a decoded registration in: (a) an enum with one variant per `$register*` method and its fields (`Provider::DocumentLink { supports_resolve }`), matched at each site; (b) one flat struct whose fields carry the protocol's names (`supports_resolve`, `event_handle`, `extension_id`, `metadata`, `trigger_characters`, ...), filled by one table keyed by the method in `register`, a field the method lacks keeping its default; (c) accessor methods over the kept wire tuple (`registration.supports_resolve()`), each knowing its position per method. Picked (b): every site already picks its registrations by method, so (a) makes each read a `let ... else` with an unreachable arm, and (c) decodes on every read and keeps the tuple for the next positional read. `register(method, args)` keeps its signature, so the callers and tests that register stay as they were.+- Every positional read moved, the 30 of the plan's check and 5 sites its pattern misses: `provided_kinds(®istration.args)` (code actions, 3 sites), `format.rs::formatter` (`args[2..4]` through a local) and `inline_completions.rs::inline_completion_handles`, which handed the whole tuple to the debounce (`debounceDelayMs`, position 8). `format.rs::extension_id` moved into the decode. No difference from upstream found: each field sits where extHost.protocol.ts `MainThreadLanguageFeaturesShape` puts it (`app/src/language_features/tests.rs::register_decodes_each_method_at_its_protocol_positions`).+- Not done from the plan's goal: the `$provide*` calls stay built by each feature (`"ExtHostLanguageFeatures"`, 83 sites). Their arguments are the feature's own request (a URI, a position, a context), not a shape the features repeat, so one builder per call would be a wrapper over `vec![...]` with nothing hidden; the plan's "Done when" does not ask for it.+- Pixel and gates for candidate 6: no render, key context, list row, tokenization or startup code changed beyond the field a value is read from; each decoded field holds the value the site read before (the folding provider compares the `ExtensionIdentifier` string where it compared `["value"]`; the host always sends the object), so render output cannot change and `pixel-check` was not run. `port/tools/api-tests` before and after: api-folder 320 passing, 46 pending, 42 failing with the same failing titles, api-workspace 4/0/0; `port/tools/extension-tests` configuration-editing 18, emmet 176, markdown-language-features 217 and 2 pending, typescript-language-features (unit) 60 and 8 pending, both times.+- Candidate 2, one pass over the editors of every group (branch refactor/m27-group-editors): `app/src/editor.rs::EditorGroup::all_tabs` and `all_editors`, each with a `_mut`; `model` and `model_mut` go through `all_editors`. Three interfaces, on one axis, how a call site names its reach: (a) by the method, `all_tabs` (the tabs of every group) and `all_editors` (those plus the models without a tab), the active group's first; (b) by an argument, one `editors(Reach)` with `Reach::Tabs` or `Reach::TabsAndModels`; (c) by taking the raw lists away, `editors`, `models` and `other_groups` private, so every site goes through a named accessor. Picked (a): the name says the reach where the site reads it, as `code_editors` already does. (b) puts the reach in a value a reader has to look up and still needs two methods for `&mut`; (c) moves the about 70 sites that use the active group's tabs on purpose (an open or activate in the active group, as editorGroupView.ts `openEditor` does) and the `with_group` swap that M20's multi-instance code editor builds on.+- Every `editors.editors.iter().chain(&editors.models)` moved (the plan's check finds none; it found 2 in `workbench/configuration.rs` alone on the commit before), and the hand-built chains over `other_groups` became `all_tabs` or `all_editors`. 27 sites reached only the active group where upstream reaches every editor or model; each is closed test first with the file moved to another group (`editor_groups/tests.rs::move_active_editor_to_another_group`), 27 tests that fail without their fix: `editor_groups/tests.rs` (tab size, column breakpoint, stack frame column, dirty breakpoint, marker decoration, model commands, `dirtyWorkingCopies`, selection ranges, marker navigation, exception and breakpoint widget close), `text_files/tests.rs` (orphan mark and picked language, `files.associations`), `testing_coverage_view`, `host_requests` (first casing), `hierarchy_peek`, `references_peek` (preview, peek close), `suggest_controller` (word completions), `debug_inline_values`, `linked_editing`, `explorer_actions` (dirty delete), `search_actions` (`onlyOpenEditors`), `task_service` (problem collector), `goto_symbol` (definition preview), `code_actions` (problems quick fix), `inlay_hints`. Each test cites its upstream file (modelService.ts `getModels`, debugModel.ts `textFileService.isDirty`, contextkeys.ts `dirtyWorkingCopiesContext`, queryBuilder.ts `onlyOpenEditors`, problemCollectors.ts `openModels`, fileActions.ts `getDirty`, zoneWidget.ts `dispose`, among others).+- Kept on the active group's tabs, as upstream: opening or activating an editor (editorGroupView.ts `openEditor` finds the editor in its own group), `workbench/custom_editors.rs::show_open_with_picker_for` (openWithEditorPicker.ts `activeGroup.findEditors`), `workbench/actions.rs::tab_is_opened_in_other_group` (editorGroupView.ts `isOpenedInOtherGroup`, other groups by name), and the controllers the port runs for the active editor only (code lens, debug inline values, peek and marker zone layout), whose results are asked again when the active model changes. `workbench/editor_view/quick_diff_widget.rs::close_quick_diff` removes its zone from the tab of every group as well (zoneWidget.ts `dispose`): quick_diff_widget.rs `closing_the_quick_diff_in_another_group_removes_its_zone`, on the harness of its other tests.+- Gates on the Studio before and after candidate 2, same hour, load 2 to 4: `scroll_frame_time` editor (20000 lines) median 4.25 and 4.17 ms, p95 8.07 and 7.97 ms (the commit before fails its 8 ms gate on this run, so the p95 sits at the line on both sides); explorer, extensions, settings and terminal typing within 0.05 ms; `typing_latency_on_a_large_file` p95 at line 100, 25000 and 49000 10.09, 10.61, 11.77 ms and 11.22, 11.39, 12.09 ms, under 16 ms. The three render-time syncs (`sync_stack_frame_columns`, `sync_inline_breakpoints`, `sync_inline_coverage`) now visit the tabs of every group, in proportion to the open tabs, not to a document.+- Pixel check for candidate 2: `port/tools/pixel-check` stops before and after on `ref-screenshot` timing out, so the port's own screenshots (file, split, main in Dark Modern and High Contrast) were compared before and after with `pixeldiff`: 0 different pixels in all six, as between two runs of the same build.+- `ref-screenshot` timing out was the Studio's locked screen: with `loginwindow` in front no app becomes key, so the reference title bar stays `.inactive` and the wait for it (`capture`, 10 s) fails; the bare reference reaches its status bar in 1 s. Check before a GUI run: `ioreg -n Root -d1 -a | rg -A1 CGSSessionScreenIsLocked`.+- Milestone check, once over the six (base `f4d6aabdf09`, the commit before candidate 4, against the last candidate), unlocked screen: `port/tools/pixel-check` port images compared with `magick compare -metric AE -fuzz 2%` are identical in 36 of 40 window and theme pairs; the 4 `panel` pairs differ by 1010 to 1437 px, the checkout path in the terminal prompt (`port-src` against `port-src-m27-group-editors`). The `different` counts against the reference move between runs because the reference capture does (main, split, panel). `port/tools/ui-pair` with ONLY=port, FOLDER=port/fixtures/language-features: steps-params-actions (FILE=a.ts), steps-color (FILE=a.ts, the inlay hint SETTINGS of port/results/inlay-hints.md) and steps-ghost (FILE=a.html, `emmet.useInlineCompletions`) give AE 0 on all six shots; the base's first params run showed the Explorer title actions and the editor scrollbar from the pointer's place, and two reruns of the base match the last candidate at AE 0. Not run: one pixel-check per candidate; identical ends make a change that one candidate adds and a later one undoes the only case missed.diff --git a/port/plans/architecture-deepening.md b/port/plans/architecture-deepening.mdindex efade0e3d64..02803f7e2f9 100644--- a/port/plans/architecture-deepening.md+++ b/port/plans/architecture-deepening.md@@ -16,6 +16,8 @@ Every count below is `rg` over `native/crates/app/src` without `tests.rs` files,## 4. One answer to "who serves this MainThread call"+**Status.** Done on branch `refactor/m27-host-call-paths`: `app/src/main_thread_commands.rs::route`; findings in port/notes.md, "Architecture deepening".+**Evidence.** Five places decide the path of a call, and they must agree by hand:- `app/src/main.rs::run_extension_host`: a list of 42 strings (`"MainThreadFoo"` or `"MainThreadFoo.$bar"`) handed to `exthost/src/session.rs::Session::forward`.@@ -70,6 +72,8 @@ impl Workbench {## 1. One announcement of a model content change+**Status.** Done on branch `refactor/m27-model-content-changed`: `app/src/workbench/model_events.rs`; findings in port/notes.md, "Architecture deepening"; the selection sources still off upstream are a gap of the `mainthread/MainThreadTextEditors` ledger row.+**Evidence.** A model is edited at 42 `.execute_edits(` sites in 26 files. What happens next depends on which of four functions the site calls: `.editor_edited(` or `.editor_edited_revealing(` (20 sites in 13 files), `.send_model_edit(` (11 in 9), `.cursors_changed(` (11 in 6), `.editor_command_ran(` (10 in 1). Four more sites tell the host by hand (`host.send_content_change(` or `host.send_model_change(`: 7 sites in 6 files), and `host.send_selection(` has 23 sites in 18 files. Each function runs a different list of reactions.Skips three independent readings agreed on (read, not run):@@ -130,6 +134,8 @@ Inside, two flat private lists, one line per feature: reactions to any model (ho**Tests that survive.** `extension_host_restart` tests at the `Workbench`. New: restart sends the host the same opening sequence as the first start.+**Status.** Done on branch `refactor/m27-host-start`: `app/src/extension_host_start.rs`; variants, pick and findings in port/notes.md, "Architecture deepening".+**Done when.** `rg -c 'run_extension_host\(' app/src` is one call; `rg 'cfg!\(test\)' app/src/workbench/extension_host_restart.rs` finds nothing in the start path; the new test passes; `window_s` and `ready_s` of `port/tools/bench` stay within budget.## 5. Editor options as a module@@ -140,6 +146,8 @@ Inside, two flat private lists, one line per feature: reactions to any model (ho**Tests that survive.** The settings tests of each feature. New: tests per option at the module (default, invalid value, `[lang]`), against editorOptions.ts.+**Status.** Done on branch `refactor/m27-editor-options`: `app/src/workbench/editor_options.rs`; variants, pick and findings in port/notes.md, "Architecture deepening". Still open, in the M27 ledger row: the read once per settings change, and the global reads without `[lang]` (a gap of the editor/common row).+**Done when.** `rg 'self\.setting\("editor\.' app/src -g '!**/tests.rs'` finds matches only in the module; `app/src/workbench/scroll_frame_time.rs` and the typing gate report before and after.## 6. Language feature registrations decoded once@@ -148,6 +156,8 @@ Inside, two flat private lists, one line per feature: reactions to any model (ho**Goal.** One module knows the shape of each `$register*` and `$provide*`: named fields in, a call out.+**Status.** Done on branch `refactor/m27-language-registrations`: `app/src/language_features.rs::Registration::decode`; variants, pick and findings in port/notes.md, "Architecture deepening". Still open, in the M27 ledger row: the `$provide*` calls stay built by each feature.+**Done when.** `rg 'registration\.args(\[|\.get\()|\.args\.get\(\d\)' app/src/workbench -g '!**/tests.rs'` finds nothing; `port/tools/api-tests` gives the counts of the commit before.## 2. One pass over the editors of every group@@ -171,6 +181,8 @@ The check of "Done when" below finds 38 sites in 24 files (5 of them fixed by th**Goal.** Two named traversals, each with its reach in the name: the tabs of the active group, and every open editor and model. `&mut` included, which `all_editors` lacks today.+**Status.** Done on branch `refactor/m27-group-editors`: `app/src/editor.rs::EditorGroup::all_tabs` and `all_editors`, each with a `_mut`; every row of the table above and the other suspects closed test first (27 tests with the file in another group); variants, pick, the sites kept on the active group and findings in port/notes.md, "Architecture deepening". Still open, in the M27 ledger row: the quick diff widget's close.+**Done when.** `rg -U 'editors\s*\.editors\s*\.iter(_mut)?\(\)\s*\.chain\(' app/src -g '!**/tests.rs' -g '!editor.rs'` finds nothing; each row of the table has a test with the file in another group, or a line here on why upstream skips it too.## Not in this plan