Visual Studio Code, rebuilt in Rust
Rust
//! The workbench side of configurationService.ts's file watchers: settings files edited outside the port reach
//! the extension host (mainThreadConfiguration.ts), the color theme (ThemeService) and the text models
//! (modelService.ts `_updateModelOptions`).
use std::collections::{BTreeSet, HashMap};
use std::path::PathBuf;
use config::indentation::{CreationOptions, creation_options};
use config::model::Change;
use files::watcher::Watcher;
use futures::StreamExt;
use futures::channel::mpsc;
use gpui::{Context, Window};
use crate::editor::{Indentation, guess_indentation};
use crate::workbench::Workbench;
/// The watches of the settings files' folders, by folder.
#[derive(Default)]
pub(super) struct SettingsWatcher {
watcher: Option<Watcher>,
watched: HashMap<PathBuf, u64>,
next_watch: u64,
}
impl Workbench {
/// `FileUserDataProvider.watch` and the workspace watcher of configuration.ts: the folders of the settings, tasks,
/// launch and mcp files are watched and a change reloads the files that changed. Started from main.rs only: the
/// watcher's thread wakes the window from outside the test scheduler.
pub fn watch_settings_files(&mut self, window: &mut Window, cx: &mut Context<Self>) {
let (sender, mut receiver) = mpsc::unbounded();
let watcher = match Watcher::new(move |changes| drop(sender.unbounded_send(changes))) {
Ok(watcher) => watcher,
Err(error) => return eprintln!("[Configuration] {error}"),
};
self.settings_watcher.watcher = Some(watcher);
self.sync_settings_watches();
cx.spawn_in(window, async move |workbench, cx| {
while receiver.next().await.is_some() {
let reloaded = workbench.update_in(cx, |workbench, window, cx| {
workbench.sync_settings_watches();
workbench.reload_settings_files(Some(window), cx);
});
if reloaded.is_err() {
return;
}
}
})
.detach();
}
/// Watches the folder of each settings file, or the folder above it while it is missing (a folder's `.vscode`), so
/// its creation is seen; runs again when a profile switch or a folder change moves the files.
pub(super) fn sync_settings_watches(&mut self) {
let files = self.settings.lock().unwrap().watched_files();
let mut folders = BTreeSet::new();
for file in &files {
let folder = file.parent().expect("a settings file has a folder");
folders.insert(if folder.exists() { folder } else { folder.parent().unwrap_or(folder) }.to_path_buf());
}
let state = &mut self.settings_watcher;
let Some(watcher) = state.watcher.as_mut() else { return };
state.watched.retain(|folder, id| {
let keep = folders.remove(folder);
if !keep {
watcher.unwatch(*id);
}
keep
});
for folder in folders {
state.next_watch += 1;
match watcher.watch(state.next_watch, &folder, false, &[]) {
Ok(()) => drop(state.watched.insert(folder, state.next_watch)),
Err(error) => eprintln!("[Configuration] {}: {error}", folder.display()),
}
}
}
/// nativePolicyService.ts `_onDidPolicyChange`: a managed preferences change reads the policies again and applies
/// the ones that changed.
pub fn watch_policies(&self, cx: &mut Context<Self>) {
let (sender, mut receiver) = futures::channel::mpsc::unbounded();
crate::policy::watch_policy_changes(crate::policy::WATCHED_PATH, move || {
let _ = sender.unbounded_send(());
});
cx.spawn(async move |workbench, cx| {
while futures::StreamExt::next(&mut receiver).await.is_some() {
if workbench.update(cx, |workbench, cx| workbench.reload_policies(cx)).is_err() {
return;
}
}
})
.detach();
}
pub(super) fn reload_policies(&mut self, cx: &mut Context<Self>) {
let before = self.model_creation_options();
let mut settings = self.settings.lock().unwrap();
let values = crate::policy::read_native_policies(&settings.registry, crate::policy::BUNDLE_IDENTIFIER);
let change = settings.set_policy_values(values);
drop(settings);
if !change.is_empty() {
self.configuration_changed(&change, before, cx);
}
}
/// Reloads the settings files that changed on disk and applies the change.
pub fn reload_changed_settings_files(&mut self, cx: &mut Context<Self>) {
self.reload_settings_files(None, cx);
}
/// `reload_changed_settings_files`; a workspace file whose folders changed changes the window's folders, the
/// extension host restarting with `window`.
fn reload_settings_files(&mut self, window: Option<&mut Window>, cx: &mut Context<Self>) {
let before = self.model_creation_options();
let change = self.settings.lock().unwrap().reload_changed_files();
let folders_changed = self.settings.lock().unwrap().workspace.as_ref().map(|workspace| &workspace.folders) != self.workspace().map(|workspace| &workspace.folders);
if folders_changed {
return self.workspace_folders_changed(&change.unwrap_or_default(), before, window, cx);
}
if let Some(change) = change {
self.configuration_changed(&change, before, cx);
}
}
/// `restoreFileIconTheme`.
pub(super) fn restore_file_icon_theme(&mut self) {
match crate::settings_file_icons(&self.extensions, &self.settings.lock().unwrap()) {
Ok(file_icons) => self.file_icons = file_icons,
Err(error) => eprintln!("loading the file icon theme: {error:#}"),
}
}
/// `restoreProductIconTheme`.
pub(super) fn restore_product_icon_theme(&mut self) {
self.product_icons = crate::product_icons::settings_product_icons(&self.extensions, &self.settings.lock().unwrap());
}
/// `onDidChangeConfiguration` listeners of the workbench for a change already in the settings model.
pub(super) fn configuration_changed(&mut self, change: &Change, before: Vec<CreationOptions>, cx: &mut Context<Self>) {
self.host.send_configuration_change(&self.settings.lock().unwrap(), change);
let theme_keys = ["workbench.colorTheme", "workbench.preferredDarkColorTheme", "workbench.preferredLightColorTheme", "workbench.preferredHighContrastColorTheme", "workbench.preferredHighContrastLightColorTheme", "window.autoDetectColorScheme", "window.autoDetectHighContrast"];
if theme_keys.iter().any(|key| affects(change, key)) {
self.restore_color_theme(cx);
}
if affects(change, "workbench.iconTheme") {
self.restore_file_icon_theme();
}
if affects(change, "workbench.productIconTheme") {
self.restore_product_icon_theme();
}
if ["workbench.colorCustomizations", "editor.tokenColorCustomizations", "editor.semanticTokenColorCustomizations"].iter().any(|key| affects(change, key)) {
self.customize_theme();
self.semantic_tokens_settings_changed(true, cx);
// themeService.ts fires `onDidColorThemeChange` for customizations too.
self.host.send_color_theme(self.theme.kind);
self.host.send_syntax_highlighting_theme_changed();
}
// webviewElement.ts restyles on `onDidChangeReducedMotion`.
if affects(change, "workbench.editor.enablePreview") {
self.editors.set_previews_disabled(self.setting("workbench.editor.enablePreview") == false);
}
if affects(change, "scm.repositories.selectionMode") {
self.scm_selection_mode_changed();
}
if affects(change, "scm.repositories.explorer") || affects(change, "scm.repositories.selectionMode") {
self.scm_explorer_changed(cx);
}
if affects(change, "notebook.variablesView") {
self.init_notebook_variables_view(None, cx);
}
if affects(change, "notebook.undoRedoPerCell") {
self.update_cell_undo_redo_comparison_key();
}
if affects(change, "window.appIcon") {
self.sync_app_icon();
}
if affects(change, "workbench.reduceMotion") {
self.restyle_webviews();
}
if super::editor_view::cursor_blink::EDITOR_OPTION_NAMES.iter().any(|name| affects(change, &format!("editor.{name}"))) {
*self.cursor_blink.borrow_mut() = super::editor_view::cursor_blink::CursorBlink::default();
}
let active_indentation = self.editors.active().map(|editor| editor.document().indentation);
self.update_model_options(before);
// mainThreadEditor.ts `_updatePropertiesNow` on the model's options or the code editor's configuration changing.
if let Some(editor) = self.editors.active()
&& (active_indentation != Some(editor.document().indentation) || affects(change, "editor.cursorStyle") || affects(change, "editor.lineNumbers"))
{
let options = self.host_editor_options(editor);
self.host.send_options(editor, options);
}
if ["editor.folding", "editor.foldingStrategy", "editor.foldingMaximumRegions", "editor.defaultFoldingRangeProvider"].iter().any(|key| affects(change, key)) {
self.trigger_folding_model_changed(cx);
}
// commentsController.ts shows the threads again in the other style.
if affects(change, "comments.thread.experimental.style") {
self.sync_comment_widgets();
}
if affects(change, "editor.stickyScroll") {
self.sticky_outline_providers_changed(cx);
}
if affects(change, "editor.semanticHighlighting.enabled") {
self.semantic_tokens_settings_changed(false, cx);
}
if affects(change, "editor.linkedEditing") || affects(change, "editor.renameOnType") {
self.linked_editing_reinitialize(false, cx);
}
if affects(change, "problems.visibility") || affects(change, "problems.decorations.enabled") {
self.update_markers_file_decorations();
self.refresh_language_status(cx);
}
if ["editor.colorDecorators", "editor.defaultColorDecorators", "editor.colorDecoratorsLimit"].iter().any(|key| affects(change, key)) {
self.color_providers_changed(cx);
}
if affects(change, "editor.inlayHints") {
self.inlay_hints_registrations_changed(cx);
}
if affects(change, "workbench.localHistory.enabled") {
self.update_local_history_timeline_registration();
let source = crate::timeline::LOCAL_HISTORY_SOURCE.to_string();
self.load_timeline(true, Some(vec![source]), super::timeline_view::TRIGGER_AUTOMATIC, cx);
}
if affects(change, "editor.defaultFormatter") {
self.refresh_language_status(cx);
}
if affects(change, "files.associations") {
self.files_associations_changed(cx);
}
if ["http.proxy", "http.noProxy", "http.proxyAuthorization"].iter().any(|key| affects(change, key)) {
self.apply_proxy_settings();
}
self.settings_editor_configuration_changed(cx);
cx.notify();
}
/// windowImpl.ts `onConfigurationUpdated` for `http.proxy` and `http.noProxy`, and the user-local
/// `http.proxyAuthorization` the electron-browser requestService adds to each request.
pub fn apply_proxy_settings(&self) {
let settings = self.settings.lock().unwrap();
let inspect = |key: &str| settings.configuration.inspect(key, &Default::default());
let user_local = |key: &str| inspect(key).user_local.value;
let user_proxy = user_local("http.proxy").and_then(|value| value.as_str().map(str::to_owned)).unwrap_or_default();
let no_proxy: Vec<String> = inspect("http.noProxy").value.and_then(|value| serde_json::from_value(value).ok()).unwrap_or_default();
let env = |key: &str| std::env::var(key).ok();
if let Some(proxy) = exthost::request::session_proxy(&user_proxy, &no_proxy, &env, exthost::request::current_session_proxy().as_ref()) {
exthost::request::set_session_proxy(proxy);
}
exthost::request::set_proxy_authorization(user_local("http.proxyAuthorization").and_then(|value| value.as_str().map(str::to_owned)));
}
pub(super) fn model_creation_options(&self) -> Vec<CreationOptions> {
let settings = self.settings.lock().unwrap();
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();
for ((model, old), new) in self.editors.all_editors_mut().zip(before).zip(after) {
if old == new {
continue;
}
let indentation = match new.detect_indentation {
true => guess_indentation(&model.document().lines, Indentation { tab_size: new.tab_size, indent_size: None, insert_spaces: new.insert_spaces }),
false => Indentation { tab_size: new.tab_size, indent_size: new.indent_size, insert_spaces: new.insert_spaces },
};
model.set_indentation(indentation);
}
}
}
/// `IConfigurationChangeEvent.affectsConfiguration(key)` for a key without overrides: the key, a parent or a child changed.
fn affects(change: &Change, key: &str) -> bool {
let touches = |changed: &str| changed == key || key.starts_with(&format!("{changed}.")) || changed.starts_with(&format!("{key}."));
change.keys.iter().any(|changed| touches(changed))
}
#[cfg(test)]
mod tests;