Merge branch 'main' into elevations

This commit is contained in:
K Simmons
2022-10-18 12:47:15 -07:00
273 changed files with 26504 additions and 15624 deletions
+14 -3
View File
@@ -7,6 +7,7 @@ use std::{borrow::Cow, str, sync::Arc};
mod c;
mod elixir;
mod go;
mod html;
mod installation;
mod json;
mod language_plugin;
@@ -46,6 +47,11 @@ pub async fn init(languages: Arc<LanguageRegistry>, _executor: Arc<Background>)
tree_sitter_cpp::language(),
Some(CachedLspAdapter::new(c::CLspAdapter).await),
),
(
"css",
tree_sitter_css::language(),
None, //
),
(
"elixir",
tree_sitter_elixir::language(),
@@ -96,8 +102,13 @@ pub async fn init(languages: Arc<LanguageRegistry>, _executor: Arc<Background>)
tree_sitter_typescript::language_tsx(),
Some(CachedLspAdapter::new(typescript::TypeScriptLspAdapter).await),
),
(
"html",
tree_sitter_html::language(),
Some(CachedLspAdapter::new(html::HtmlLspAdapter).await),
),
] {
languages.add(Arc::new(language(name, grammar, lsp_adapter)));
languages.add(language(name, grammar, lsp_adapter));
}
}
@@ -105,7 +116,7 @@ pub(crate) fn language(
name: &str,
grammar: tree_sitter::Language,
lsp_adapter: Option<Arc<CachedLspAdapter>>,
) -> Language {
) -> Arc<Language> {
let config = toml::from_slice(
&LanguageDir::get(&format!("{}/config.toml", name))
.unwrap()
@@ -142,7 +153,7 @@ pub(crate) fn language(
if let Some(lsp_adapter) = lsp_adapter {
language = language.with_lsp_adapter(lsp_adapter)
}
language
Arc::new(language)
}
fn load_query(name: &str, filename_prefix: &str) -> Option<Cow<'static, str>> {
+3 -4
View File
@@ -112,7 +112,7 @@ impl super::LspAdapter for CLspAdapter {
async fn label_for_completion(
&self,
completion: &lsp::CompletionItem,
language: &Language,
language: &Arc<Language>,
) -> Option<CodeLabel> {
let label = completion
.label
@@ -190,7 +190,7 @@ impl super::LspAdapter for CLspAdapter {
&self,
name: &str,
kind: lsp::SymbolKind,
language: &Language,
language: &Arc<Language>,
) -> Option<CodeLabel> {
let (text, filter_range, display_range) = match kind {
lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
@@ -251,7 +251,6 @@ mod tests {
use gpui::MutableAppContext;
use language::{AutoindentMode, Buffer};
use settings::Settings;
use std::sync::Arc;
#[gpui::test]
fn test_c_autoindent(cx: &mut MutableAppContext) {
@@ -262,7 +261,7 @@ mod tests {
let language = crate::languages::language("c", tree_sitter_c::language(), None);
cx.add_model(|cx| {
let mut buffer = Buffer::new(0, "", cx).with_language(Arc::new(language), cx);
let mut buffer = Buffer::new(0, "", cx).with_language(language, cx);
// empty function
buffer.edit([(0..0, "int main() {}")], None, cx);
+1 -1
View File
@@ -86,7 +86,7 @@
(identifier) @variable
((identifier) @constant
(#match? @constant "^[A-Z][A-Z\\d_]*$"))
(#match? @constant "^_*[A-Z][A-Z\\d_]*$"))
(call_expression
function: (identifier) @function)
+2 -2
View File
@@ -37,11 +37,11 @@
(type_identifier) @type
((identifier) @constant
(#match? @constant "^[A-Z][A-Z\\d_]*$"))
(#match? @constant "^_*[A-Z][A-Z\\d_]*$"))
(field_identifier) @property
(statement_identifier) @label
(this) @variable.builtin
(this) @variable.special
[
"break"
@@ -0,0 +1,3 @@
("(" @open ")" @close)
("[" @open "]" @close)
("{" @open "}" @close)
+9
View File
@@ -0,0 +1,9 @@
name = "CSS"
path_suffixes = ["css"]
autoclose_before = ";:.,=}])>"
brackets = [
{ start = "{", end = "}", close = true, newline = true },
{ start = "[", end = "]", close = true, newline = true },
{ start = "(", end = ")", close = true, newline = true },
{ start = "\"", end = "\"", close = true, newline = false }
]
@@ -0,0 +1,78 @@
(comment) @comment
[
(tag_name)
(nesting_selector)
(universal_selector)
] @tag
[
"~"
">"
"+"
"-"
"*"
"/"
"="
"^="
"|="
"~="
"$="
"*="
"and"
"or"
"not"
"only"
] @operator
(attribute_selector (plain_value) @string)
(attribute_name) @attribute
(pseudo_element_selector (tag_name) @attribute)
(pseudo_class_selector (class_name) @attribute)
[
(class_name)
(id_name)
(namespace_name)
(property_name)
(feature_name)
] @property
(function_name) @function
(
[
(property_name)
(plain_value)
] @variable.special
(#match? @variable.special "^--")
)
[
"@media"
"@import"
"@charset"
"@namespace"
"@supports"
"@keyframes"
(at_keyword)
(to)
(from)
(important)
] @keyword
(string_value) @string
(color_value) @string.special
[
(integer_value)
(float_value)
] @number
(unit) @type
[
","
":"
] @punctuation.delimiter
+1
View File
@@ -0,0 +1 @@
(_ "{" "}" @end) @indent
+2 -2
View File
@@ -113,7 +113,7 @@ impl LspAdapter for ElixirLspAdapter {
async fn label_for_completion(
&self,
completion: &lsp::CompletionItem,
language: &Language,
language: &Arc<Language>,
) -> Option<CodeLabel> {
match completion.kind.zip(completion.detail.as_ref()) {
Some((_, detail)) if detail.starts_with("(function)") => {
@@ -168,7 +168,7 @@ impl LspAdapter for ElixirLspAdapter {
&self,
name: &str,
kind: SymbolKind,
language: &Language,
language: &Arc<Language>,
) -> Option<CodeLabel> {
let (text, filter_range, display_range) = match kind {
SymbolKind::METHOD | SymbolKind::FUNCTION => {
+2 -2
View File
@@ -134,7 +134,7 @@ impl super::LspAdapter for GoLspAdapter {
async fn label_for_completion(
&self,
completion: &lsp::CompletionItem,
language: &Language,
language: &Arc<Language>,
) -> Option<CodeLabel> {
let label = &completion.label;
@@ -235,7 +235,7 @@ impl super::LspAdapter for GoLspAdapter {
&self,
name: &str,
kind: lsp::SymbolKind,
language: &Language,
language: &Arc<Language>,
) -> Option<CodeLabel> {
let (text, filter_range, display_range) = match kind {
lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
+101
View File
@@ -0,0 +1,101 @@
use super::installation::{npm_install_packages, npm_package_latest_version};
use anyhow::{anyhow, Context, Result};
use async_trait::async_trait;
use client::http::HttpClient;
use futures::StreamExt;
use language::{LanguageServerName, LspAdapter};
use serde_json::json;
use smol::fs;
use std::{any::Any, path::PathBuf, sync::Arc};
use util::ResultExt;
pub struct HtmlLspAdapter;
impl HtmlLspAdapter {
const BIN_PATH: &'static str =
"node_modules/vscode-langservers-extracted/bin/vscode-html-language-server";
}
#[async_trait]
impl LspAdapter for HtmlLspAdapter {
async fn name(&self) -> LanguageServerName {
LanguageServerName("vscode-html-language-server".into())
}
async fn server_args(&self) -> Vec<String> {
vec!["--stdio".into()]
}
async fn fetch_latest_server_version(
&self,
_: Arc<dyn HttpClient>,
) -> Result<Box<dyn 'static + Any + Send>> {
Ok(Box::new(npm_package_latest_version("vscode-langservers-extracted").await?) as Box<_>)
}
async fn fetch_server_binary(
&self,
version: Box<dyn 'static + Send + Any>,
_: Arc<dyn HttpClient>,
container_dir: PathBuf,
) -> Result<PathBuf> {
let version = version.downcast::<String>().unwrap();
let version_dir = container_dir.join(version.as_str());
fs::create_dir_all(&version_dir)
.await
.context("failed to create version directory")?;
let binary_path = version_dir.join(Self::BIN_PATH);
if fs::metadata(&binary_path).await.is_err() {
npm_install_packages(
[("vscode-langservers-extracted", version.as_str())],
&version_dir,
)
.await?;
if let Some(mut entries) = fs::read_dir(&container_dir).await.log_err() {
while let Some(entry) = entries.next().await {
if let Some(entry) = entry.log_err() {
let entry_path = entry.path();
if entry_path.as_path() != version_dir {
fs::remove_dir_all(&entry_path).await.log_err();
}
}
}
}
}
Ok(binary_path)
}
async fn cached_server_binary(&self, container_dir: PathBuf) -> Option<PathBuf> {
(|| async move {
let mut last_version_dir = None;
let mut entries = fs::read_dir(&container_dir).await?;
while let Some(entry) = entries.next().await {
let entry = entry?;
if entry.file_type().await?.is_dir() {
last_version_dir = Some(entry.path());
}
}
let last_version_dir = last_version_dir.ok_or_else(|| anyhow!("no cached binary"))?;
let bin_path = last_version_dir.join(Self::BIN_PATH);
if bin_path.exists() {
Ok(bin_path)
} else {
Err(anyhow!(
"missing executable in directory {:?}",
last_version_dir
))
}
})()
.await
.log_err()
}
async fn initialization_options(&self) -> Option<serde_json::Value> {
Some(json!({
"provideFormatter": true
}))
}
}
@@ -0,0 +1,2 @@
("<" @open ">" @close)
("\"" @open "\"" @close)
+12
View File
@@ -0,0 +1,12 @@
name = "HTML"
path_suffixes = ["html"]
autoclose_before = ">})"
brackets = [
{ start = "<", end = ">", close = true, newline = true },
{ start = "{", end = "}", close = true, newline = true },
{ start = "(", end = ")", close = true, newline = true },
{ start = "\"", end = "\"", close = true, newline = false },
{ start = "!--", end = " --", close = true, newline = false },
]
block_comment = ["<!-- ", " -->"]
@@ -0,0 +1,15 @@
(tag_name) @keyword
(erroneous_end_tag_name) @keyword
(doctype) @constant
(attribute_name) @property
(attribute_value) @string
(comment) @comment
"=" @operator
[
"<"
">"
"</"
"/>"
] @punctuation.bracket
@@ -0,0 +1,6 @@
(start_tag ">" @end) @indent
(self_closing_tag "/>" @end) @indent
(element
(start_tag) @start
(end_tag)? @end) @indent
@@ -0,0 +1,7 @@
(script_element
(raw_text) @content
(#set! "language" "javascript"))
(style_element
(raw_text) @content
(#set! "language" "css"))
@@ -51,12 +51,12 @@
(shorthand_property_identifier)
(shorthand_property_identifier_pattern)
] @constant
(#match? @constant "^[A-Z_][A-Z\\d_]+$"))
(#match? @constant "^_*[A-Z_][A-Z\\d_]*$"))
; Literals
(this) @variable.builtin
(super) @variable.builtin
(this) @variable.special
(super) @variable.special
[
(true)
+3 -4
View File
@@ -90,7 +90,7 @@ impl LspAdapter for PythonLspAdapter {
async fn label_for_completion(
&self,
item: &lsp::CompletionItem,
language: &language::Language,
language: &Arc<language::Language>,
) -> Option<language::CodeLabel> {
let label = &item.label;
let grammar = language.grammar()?;
@@ -112,7 +112,7 @@ impl LspAdapter for PythonLspAdapter {
&self,
name: &str,
kind: lsp::SymbolKind,
language: &language::Language,
language: &Arc<language::Language>,
) -> Option<language::CodeLabel> {
let (text, filter_range, display_range) = match kind {
lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
@@ -149,7 +149,6 @@ mod tests {
use gpui::{ModelContext, MutableAppContext};
use language::{AutoindentMode, Buffer};
use settings::Settings;
use std::sync::Arc;
#[gpui::test]
fn test_python_autoindent(cx: &mut MutableAppContext) {
@@ -160,7 +159,7 @@ mod tests {
cx.set_global(settings);
cx.add_model(|cx| {
let mut buffer = Buffer::new(0, "", cx).with_language(Arc::new(language), cx);
let mut buffer = Buffer::new(0, "", cx).with_language(language, cx);
let append = |buffer: &mut Buffer, text: &str, cx: &mut ModelContext<Buffer>| {
let ix = buffer.len();
buffer.edit([(ix..ix, text)], Some(AutoindentMode::EachLine), cx);
@@ -21,7 +21,7 @@
(#match? @type "^[A-Z]"))
((identifier) @constant
(#match? @constant "^[A-Z][A-Z_]*$"))
(#match? @constant "^_*[A-Z][A-Z\\d_]*$"))
; Builtin functions
+3 -3
View File
@@ -119,7 +119,7 @@ impl LspAdapter for RustLspAdapter {
async fn label_for_completion(
&self,
completion: &lsp::CompletionItem,
language: &Language,
language: &Arc<Language>,
) -> Option<CodeLabel> {
match completion.kind {
Some(lsp::CompletionItemKind::FIELD) if completion.detail.is_some() => {
@@ -196,7 +196,7 @@ impl LspAdapter for RustLspAdapter {
&self,
name: &str,
kind: lsp::SymbolKind,
language: &Language,
language: &Arc<Language>,
) -> Option<CodeLabel> {
let (text, filter_range, display_range) = match kind {
lsp::SymbolKind::METHOD | lsp::SymbolKind::FUNCTION => {
@@ -439,7 +439,7 @@ mod tests {
cx.set_global(settings);
cx.add_model(|cx| {
let mut buffer = Buffer::new(0, "", cx).with_language(Arc::new(language), cx);
let mut buffer = Buffer::new(0, "", cx).with_language(language, cx);
// indent between braces
buffer.set_text("fn a() {}", cx);
+4 -13
View File
@@ -1,6 +1,6 @@
(type_identifier) @type
(primitive_type) @type.builtin
(self) @variable.builtin
(self) @variable.special
(field_identifier) @property
(call_expression
@@ -27,22 +27,13 @@
; Identifier conventions
; Assume uppercase names are enum constructors
((identifier) @variant
(#match? @variant "^[A-Z]"))
; Assume that uppercase names in paths are types
((scoped_identifier
path: (identifier) @type)
(#match? @type "^[A-Z]"))
((scoped_identifier
path: (scoped_identifier
name: (identifier) @type))
; Assume uppercase names are types/enum-constructors
((identifier) @type
(#match? @type "^[A-Z]"))
; Assume all-caps names are constants
((identifier) @constant
(#match? @constant "^[A-Z][A-Z\\d_]+$"))
(#match? @constant "^_*[A-Z][A-Z\\d_]*$"))
[
"("
+3 -5
View File
@@ -115,7 +115,7 @@ impl LspAdapter for TypeScriptLspAdapter {
async fn label_for_completion(
&self,
item: &lsp::CompletionItem,
language: &language::Language,
language: &Arc<language::Language>,
) -> Option<language::CodeLabel> {
use lsp::CompletionItemKind as Kind;
let len = item.label.len();
@@ -144,7 +144,6 @@ impl LspAdapter for TypeScriptLspAdapter {
#[cfg(test)]
mod tests {
use std::sync::Arc;
use gpui::MutableAppContext;
use unindent::Unindent;
@@ -172,9 +171,8 @@ mod tests {
"#
.unindent();
let buffer = cx.add_model(|cx| {
language::Buffer::new(0, text, cx).with_language(Arc::new(language), cx)
});
let buffer =
cx.add_model(|cx| language::Buffer::new(0, text, cx).with_language(language, cx));
let outline = buffer.read(cx).snapshot().outline(None).unwrap();
assert_eq!(
outline
@@ -51,12 +51,12 @@
(shorthand_property_identifier)
(shorthand_property_identifier_pattern)
] @constant
(#match? @constant "^[A-Z_][A-Z\\d_]+$"))
(#match? @constant "^_*[A-Z_][A-Z\\d_]*$"))
; Literals
(this) @variable.builtin
(super) @variable.builtin
(this) @variable.special
(super) @variable.special
[
(true)
+42 -35
View File
@@ -14,32 +14,32 @@ use client::{
http::{self, HttpClient},
UserStore, ZED_SECRET_CLIENT_TOKEN,
};
use fs::OpenOptions;
use futures::{
channel::{mpsc, oneshot},
FutureExt, SinkExt, StreamExt,
};
use gpui::{executor::Background, App, AssetSource, AsyncAppContext, Task, ViewContext};
use isahc::{config::Configurable, AsyncBody, Request};
use isahc::{config::Configurable, Request};
use language::LanguageRegistry;
use log::LevelFilter;
use parking_lot::Mutex;
use project::{Fs, ProjectStore};
use serde_json::json;
use settings::{self, KeymapFileContent, Settings, SettingsFileContent, WorkingDirectory};
use settings::{
self, settings_file::SettingsFile, KeymapFileContent, Settings, SettingsFileContent,
WorkingDirectory,
};
use smol::process::Command;
use std::{env, ffi::OsStr, fs, panic, path::PathBuf, sync::Arc, thread, time::Duration};
use std::fs::OpenOptions;
use std::{env, ffi::OsStr, panic, path::PathBuf, sync::Arc, thread, time::Duration};
use terminal::terminal_container_view::{get_working_directory, TerminalContainer};
use fs::RealFs;
use settings::watched_json::{watch_keymap_file, watch_settings_file, WatchedJsonFile};
use theme::ThemeRegistry;
use util::{ResultExt, TryFutureExt};
use workspace::{self, AppState, ItemHandle, NewFile, OpenPaths, Workspace};
use zed::{
self, build_window_options,
fs::RealFs,
initialize_workspace, languages, menus,
settings_file::{watch_keymap_file, watch_settings_file, WatchedJsonFile},
};
use zed::{self, build_window_options, initialize_workspace, languages, menus};
fn main() {
let http = http::client();
@@ -88,7 +88,7 @@ fn main() {
});
app.run(move |cx| {
let client = client::Client::new(http.clone());
let client = client::Client::new(http.clone(), cx);
let mut languages = LanguageRegistry::new(login_shell_env_loaded);
languages.set_language_server_download_dir(zed::paths::LANGUAGES_DIR.clone());
let languages = Arc::new(languages);
@@ -97,10 +97,15 @@ fn main() {
.spawn(languages::init(languages.clone(), cx.background().clone()));
let user_store = cx.add_model(|cx| UserStore::new(client.clone(), http.clone(), cx));
let (settings_file, keymap_file) = cx.background().block(config_files).unwrap();
let (settings_file_content, keymap_file) = cx.background().block(config_files).unwrap();
//Setup settings global before binding actions
watch_settings_file(default_settings, settings_file, themes.clone(), cx);
cx.set_global(SettingsFile::new(
&*zed::paths::SETTINGS,
settings_file_content.clone(),
fs.clone(),
));
watch_settings_file(default_settings, settings_file_content, themes.clone(), cx);
watch_keymap_file(keymap_file, cx);
context_menu::init(cx);
@@ -111,7 +116,6 @@ fn main() {
editor::init(cx);
go_to_line::init(cx);
file_finder::init(cx);
contacts_panel::init(cx);
outline::init(cx);
project_symbols::init(cx);
project_panel::init(cx);
@@ -121,7 +125,6 @@ fn main() {
terminal::init(cx);
theme_testbench::init(cx);
let db = cx.background().block(db);
cx.spawn(|cx| watch_themes(fs.clone(), themes.clone(), cx))
.detach();
@@ -139,7 +142,11 @@ fn main() {
})
.detach();
let project_store = cx.add_model(|_| ProjectStore::new(db.clone()));
let project_store = cx.add_model(|_| ProjectStore::new());
let db = cx.background().block(db);
client.start_telemetry(db.clone());
client.report_event("start app", Default::default());
let app_state = Arc::new(AppState {
languages,
themes,
@@ -156,6 +163,7 @@ fn main() {
journal::init(app_state.clone(), cx);
theme_selector::init(app_state.clone(), cx);
zed::init(&app_state, cx);
collab_ui::init(app_state.clone(), cx);
cx.set_menus(menus::menus());
@@ -197,23 +205,23 @@ fn main() {
}
fn init_paths() {
fs::create_dir_all(&*zed::paths::CONFIG_DIR).expect("could not create config path");
fs::create_dir_all(&*zed::paths::LANGUAGES_DIR).expect("could not create languages path");
fs::create_dir_all(&*zed::paths::DB_DIR).expect("could not create database path");
fs::create_dir_all(&*zed::paths::LOGS_DIR).expect("could not create logs path");
std::fs::create_dir_all(&*zed::paths::CONFIG_DIR).expect("could not create config path");
std::fs::create_dir_all(&*zed::paths::LANGUAGES_DIR).expect("could not create languages path");
std::fs::create_dir_all(&*zed::paths::DB_DIR).expect("could not create database path");
std::fs::create_dir_all(&*zed::paths::LOGS_DIR).expect("could not create logs path");
// Copy setting files from legacy locations. TODO: remove this after a few releases.
thread::spawn(|| {
if fs::metadata(&*zed::paths::legacy::SETTINGS).is_ok()
&& fs::metadata(&*zed::paths::SETTINGS).is_err()
if std::fs::metadata(&*zed::paths::legacy::SETTINGS).is_ok()
&& std::fs::metadata(&*zed::paths::SETTINGS).is_err()
{
fs::copy(&*zed::paths::legacy::SETTINGS, &*zed::paths::SETTINGS).log_err();
std::fs::copy(&*zed::paths::legacy::SETTINGS, &*zed::paths::SETTINGS).log_err();
}
if fs::metadata(&*zed::paths::legacy::KEYMAP).is_ok()
&& fs::metadata(&*zed::paths::KEYMAP).is_err()
if std::fs::metadata(&*zed::paths::legacy::KEYMAP).is_ok()
&& std::fs::metadata(&*zed::paths::KEYMAP).is_err()
{
fs::copy(&*zed::paths::legacy::KEYMAP, &*zed::paths::KEYMAP).log_err();
std::fs::copy(&*zed::paths::legacy::KEYMAP, &*zed::paths::KEYMAP).log_err();
}
});
}
@@ -228,9 +236,10 @@ fn init_logger() {
const KIB: u64 = 1024;
const MIB: u64 = 1024 * KIB;
const MAX_LOG_BYTES: u64 = MIB;
if fs::metadata(&*zed::paths::LOG).map_or(false, |metadata| metadata.len() > MAX_LOG_BYTES)
if std::fs::metadata(&*zed::paths::LOG)
.map_or(false, |metadata| metadata.len() > MAX_LOG_BYTES)
{
let _ = fs::rename(&*zed::paths::LOG, &*zed::paths::OLD_LOG);
let _ = std::fs::rename(&*zed::paths::LOG, &*zed::paths::OLD_LOG);
}
let log_file = OpenOptions::new()
@@ -280,15 +289,13 @@ fn init_panic_hook(app_version: String, http: Arc<dyn HttpClient>, background: A
"token": ZED_SECRET_CLIENT_TOKEN,
}))
.unwrap();
let request = Request::builder()
.uri(&panic_report_url)
.method(http::Method::POST)
let request = Request::post(&panic_report_url)
.redirect_policy(isahc::config::RedirectPolicy::Follow)
.header("Content-Type", "application/json")
.body(AsyncBody::from(body))?;
.body(body.into())?;
let response = http.send(request).await.context("error sending panic")?;
if response.status().is_success() {
fs::remove_file(child_path)
std::fs::remove_file(child_path)
.context("error removing panic after sending it successfully")
.log_err();
} else {
@@ -337,7 +344,7 @@ fn init_panic_hook(app_version: String, http: Arc<dyn HttpClient>, background: A
};
let panic_filename = chrono::Utc::now().format("%Y_%m_%d %H_%M_%S").to_string();
fs::write(
std::fs::write(
zed::paths::LOGS_DIR.join(format!("zed-{}-{}.panic", app_version, panic_filename)),
&message,
)
@@ -394,7 +401,7 @@ fn stdout_is_a_pty() -> bool {
fn collect_path_args() -> Vec<PathBuf> {
env::args()
.skip(1)
.filter_map(|arg| match fs::canonicalize(arg) {
.filter_map(|arg| match std::fs::canonicalize(arg) {
Ok(path) => Some(path),
Err(error) => {
log::error!("error parsing path argument: {}", error);
+5 -4
View File
@@ -244,10 +244,6 @@ pub fn menus() -> Vec<Menu<'static>> {
name: "Project Panel",
action: Box::new(project_panel::ToggleFocus),
},
MenuItem::Action {
name: "Contacts Panel",
action: Box::new(contacts_panel::ToggleFocus),
},
MenuItem::Action {
name: "Command Palette",
action: Box::new(command_palette::Toggle),
@@ -332,6 +328,11 @@ pub fn menus() -> Vec<Menu<'static>> {
action: Box::new(command_palette::Toggle),
},
MenuItem::Separator,
MenuItem::Action {
name: "View Telemetry Log",
action: Box::new(crate::OpenTelemetryLog),
},
MenuItem::Separator,
MenuItem::Action {
name: "Documentation",
action: Box::new(crate::OpenBrowser {
-215
View File
@@ -1,215 +0,0 @@
use futures::StreamExt;
use gpui::{executor, MutableAppContext};
use postage::sink::Sink as _;
use postage::{prelude::Stream, watch};
use project::Fs;
use serde::Deserialize;
use settings::{parse_json_with_comments, KeymapFileContent, Settings, SettingsFileContent};
use std::{path::Path, sync::Arc, time::Duration};
use theme::ThemeRegistry;
use util::ResultExt;
#[derive(Clone)]
pub struct WatchedJsonFile<T>(pub watch::Receiver<T>);
impl<T> WatchedJsonFile<T>
where
T: 'static + for<'de> Deserialize<'de> + Clone + Default + Send + Sync,
{
pub async fn new(
fs: Arc<dyn Fs>,
executor: &executor::Background,
path: impl Into<Arc<Path>>,
) -> Self {
let path = path.into();
let settings = Self::load(fs.clone(), &path).await.unwrap_or_default();
let mut events = fs.watch(&path, Duration::from_millis(500)).await;
let (mut tx, rx) = watch::channel_with(settings);
executor
.spawn(async move {
while events.next().await.is_some() {
if let Some(settings) = Self::load(fs.clone(), &path).await {
if tx.send(settings).await.is_err() {
break;
}
}
}
})
.detach();
Self(rx)
}
///Loads the given watched JSON file. In the special case that the file is
///empty (ignoring whitespace) or is not a file, this will return T::default()
async fn load(fs: Arc<dyn Fs>, path: &Path) -> Option<T> {
if !fs.is_file(path).await {
return Some(T::default());
}
fs.load(path).await.log_err().and_then(|data| {
if data.trim().is_empty() {
Some(T::default())
} else {
parse_json_with_comments(&data).log_err()
}
})
}
}
pub fn watch_settings_file(
defaults: Settings,
mut file: WatchedJsonFile<SettingsFileContent>,
theme_registry: Arc<ThemeRegistry>,
cx: &mut MutableAppContext,
) {
settings_updated(&defaults, file.0.borrow().clone(), &theme_registry, cx);
cx.spawn(|mut cx| async move {
while let Some(content) = file.0.recv().await {
cx.update(|cx| settings_updated(&defaults, content, &theme_registry, cx));
}
})
.detach();
}
pub fn keymap_updated(content: KeymapFileContent, cx: &mut MutableAppContext) {
cx.clear_bindings();
settings::KeymapFileContent::load_defaults(cx);
content.add_to_cx(cx).log_err();
}
pub fn settings_updated(
defaults: &Settings,
content: SettingsFileContent,
theme_registry: &Arc<ThemeRegistry>,
cx: &mut MutableAppContext,
) {
let mut settings = defaults.clone();
settings.set_user_settings(content, theme_registry, cx.font_cache());
cx.set_global(settings);
cx.refresh_windows();
}
pub fn watch_keymap_file(mut file: WatchedJsonFile<KeymapFileContent>, cx: &mut MutableAppContext) {
cx.spawn(|mut cx| async move {
while let Some(content) = file.0.recv().await {
cx.update(|cx| keymap_updated(content, cx));
}
})
.detach();
}
#[cfg(test)]
mod tests {
use super::*;
use project::FakeFs;
use settings::{EditorSettings, SoftWrap};
#[gpui::test]
async fn test_watch_settings_files(cx: &mut gpui::TestAppContext) {
let executor = cx.background();
let fs = FakeFs::new(executor.clone());
let font_cache = cx.font_cache();
fs.save(
"/settings.json".as_ref(),
&r#"
{
"buffer_font_size": 24,
"soft_wrap": "editor_width",
"tab_size": 8,
"language_overrides": {
"Markdown": {
"tab_size": 2,
"preferred_line_length": 100,
"soft_wrap": "preferred_line_length"
}
}
}
"#
.into(),
Default::default(),
)
.await
.unwrap();
let source = WatchedJsonFile::new(fs.clone(), &executor, "/settings.json".as_ref()).await;
let default_settings = cx.read(Settings::test).with_language_defaults(
"JavaScript",
EditorSettings {
tab_size: Some(2.try_into().unwrap()),
..Default::default()
},
);
cx.update(|cx| {
watch_settings_file(
default_settings.clone(),
source,
ThemeRegistry::new((), font_cache),
cx,
)
});
cx.foreground().run_until_parked();
let settings = cx.read(|cx| cx.global::<Settings>().clone());
assert_eq!(settings.buffer_font_size, 24.0);
assert_eq!(settings.soft_wrap(None), SoftWrap::EditorWidth);
assert_eq!(
settings.soft_wrap(Some("Markdown")),
SoftWrap::PreferredLineLength
);
assert_eq!(
settings.soft_wrap(Some("JavaScript")),
SoftWrap::EditorWidth
);
assert_eq!(settings.preferred_line_length(None), 80);
assert_eq!(settings.preferred_line_length(Some("Markdown")), 100);
assert_eq!(settings.preferred_line_length(Some("JavaScript")), 80);
assert_eq!(settings.tab_size(None).get(), 8);
assert_eq!(settings.tab_size(Some("Markdown")).get(), 2);
assert_eq!(settings.tab_size(Some("JavaScript")).get(), 8);
fs.save(
"/settings.json".as_ref(),
&"(garbage)".into(),
Default::default(),
)
.await
.unwrap();
// fs.remove_file("/settings.json".as_ref(), Default::default())
// .await
// .unwrap();
cx.foreground().run_until_parked();
let settings = cx.read(|cx| cx.global::<Settings>().clone());
assert_eq!(settings.buffer_font_size, 24.0);
assert_eq!(settings.soft_wrap(None), SoftWrap::EditorWidth);
assert_eq!(
settings.soft_wrap(Some("Markdown")),
SoftWrap::PreferredLineLength
);
assert_eq!(
settings.soft_wrap(Some("JavaScript")),
SoftWrap::EditorWidth
);
assert_eq!(settings.preferred_line_length(None), 80);
assert_eq!(settings.preferred_line_length(Some("Markdown")), 100);
assert_eq!(settings.preferred_line_length(Some("JavaScript")), 80);
assert_eq!(settings.tab_size(None).get(), 8);
assert_eq!(settings.tab_size(Some("Markdown")).get(), 2);
assert_eq!(settings.tab_size(Some("JavaScript")).get(), 8);
fs.remove_file("/settings.json".as_ref(), Default::default())
.await
.unwrap();
cx.foreground().run_until_parked();
let settings = cx.read(|cx| cx.global::<Settings>().clone());
assert_eq!(settings.buffer_font_size, default_settings.buffer_font_size);
}
}
+95 -32
View File
@@ -2,7 +2,6 @@ mod feedback;
pub mod languages;
pub mod menus;
pub mod paths;
pub mod settings_file;
#[cfg(any(test, feature = "test-support"))]
pub mod test;
@@ -10,11 +9,11 @@ use anyhow::{anyhow, Context, Result};
use assets::Assets;
use breadcrumbs::Breadcrumbs;
pub use client;
use collab_ui::{CollabTitlebarItem, ToggleCollaborationMenu};
use collections::VecDeque;
pub use contacts_panel;
use contacts_panel::ContactsPanel;
pub use editor;
use editor::{Editor, MultiBuffer};
use gpui::{
actions,
geometry::vector::vec2f,
@@ -24,7 +23,7 @@ use gpui::{
};
use language::Rope;
pub use lsp;
pub use project::{self, fs};
pub use project;
use project_panel::ProjectPanel;
use search::{BufferSearchBar, ProjectSearchBar};
use serde::Deserialize;
@@ -56,6 +55,7 @@ actions!(
DebugElements,
OpenSettings,
OpenLog,
OpenTelemetryLog,
OpenKeymap,
OpenDefaultSettings,
OpenDefaultKeymap,
@@ -94,6 +94,22 @@ pub fn init(app_state: &Arc<AppState>, cx: &mut gpui::MutableAppContext) {
cx.toggle_full_screen();
},
);
cx.add_action(
|workspace: &mut Workspace,
_: &ToggleCollaborationMenu,
cx: &mut ViewContext<Workspace>| {
if let Some(item) = workspace
.titlebar_item()
.and_then(|item| item.downcast::<CollabTitlebarItem>())
{
cx.as_mut().defer(move |cx| {
item.update(cx, |item, cx| {
item.toggle_contacts_popover(&Default::default(), cx);
});
});
}
},
);
cx.add_global_action(quit);
cx.add_global_action(move |action: &OpenBrowser, cx| cx.platform().open_url(&action.url));
cx.add_global_action(move |_: &IncreaseBufferFontSize, cx| {
@@ -146,6 +162,12 @@ pub fn init(app_state: &Arc<AppState>, cx: &mut gpui::MutableAppContext) {
open_log_file(workspace, app_state.clone(), cx);
}
});
cx.add_action({
let app_state = app_state.clone();
move |workspace: &mut Workspace, _: &OpenTelemetryLog, cx: &mut ViewContext<Workspace>| {
open_telemetry_log_file(workspace, app_state.clone(), cx);
}
});
cx.add_action({
let app_state = app_state.clone();
move |_: &mut Workspace, _: &OpenKeymap, cx: &mut ViewContext<Workspace>| {
@@ -207,15 +229,9 @@ pub fn init(app_state: &Arc<AppState>, cx: &mut gpui::MutableAppContext) {
workspace.toggle_sidebar_item_focus(SidebarSide::Left, 0, cx);
},
);
cx.add_action(
|workspace: &mut Workspace,
_: &contacts_panel::ToggleFocus,
cx: &mut ViewContext<Workspace>| {
workspace.toggle_sidebar_item_focus(SidebarSide::Right, 0, cx);
},
);
activity_indicator::init(cx);
call::init(app_state.client.clone(), app_state.user_store.clone(), cx);
settings::KeymapFileContent::load_defaults(cx);
}
@@ -224,7 +240,8 @@ pub fn initialize_workspace(
app_state: &Arc<AppState>,
cx: &mut ViewContext<Workspace>,
) {
cx.subscribe(&cx.handle(), {
let workspace_handle = cx.handle();
cx.subscribe(&workspace_handle, {
move |_, _, event, cx| {
if let workspace::Event::PaneAdded(pane) = event {
pane.update(cx, |pane, cx| {
@@ -278,16 +295,11 @@ pub fn initialize_workspace(
}));
});
let project_panel = ProjectPanel::new(workspace.project().clone(), cx);
let contact_panel = cx.add_view(|cx| {
ContactsPanel::new(
app_state.user_store.clone(),
app_state.project_store.clone(),
workspace.weak_handle(),
cx,
)
});
let collab_titlebar_item =
cx.add_view(|cx| CollabTitlebarItem::new(&workspace_handle, &app_state.user_store, cx));
workspace.set_titlebar_item(collab_titlebar_item, cx);
let project_panel = ProjectPanel::new(workspace.project().clone(), cx);
workspace.left_sidebar().update(cx, |sidebar, cx| {
sidebar.add_item(
"icons/folder_tree_16.svg",
@@ -296,14 +308,6 @@ pub fn initialize_workspace(
cx,
)
});
workspace.right_sidebar().update(cx, |sidebar, cx| {
sidebar.add_item(
"icons/user_group_16.svg",
"Contacts Panel".to_string(),
contact_panel,
cx,
)
});
let diagnostic_summary =
cx.add_view(|cx| diagnostics::items::DiagnosticIndicator::new(workspace.project(), cx));
@@ -356,7 +360,9 @@ fn quit(_: &Quit, cx: &mut gpui::MutableAppContext) {
// If the user cancels any save prompt, then keep the app open.
for workspace in workspaces {
if !workspace
.update(&mut cx, |workspace, cx| workspace.prepare_to_close(cx))
.update(&mut cx, |workspace, cx| {
workspace.prepare_to_close(true, cx)
})
.await?
{
return Ok(());
@@ -504,6 +510,62 @@ fn open_log_file(
});
}
fn open_telemetry_log_file(
workspace: &mut Workspace,
app_state: Arc<AppState>,
cx: &mut ViewContext<Workspace>,
) {
workspace.with_local_workspace(cx, app_state.clone(), |_, cx| {
cx.spawn_weak(|workspace, mut cx| async move {
let workspace = workspace.upgrade(&cx)?;
let path = app_state.client.telemetry_log_file_path()?;
let log = app_state.fs.load(&path).await.log_err()?;
const MAX_TELEMETRY_LOG_LEN: usize = 5 * 1024 * 1024;
let mut start_offset = log.len().saturating_sub(MAX_TELEMETRY_LOG_LEN);
if let Some(newline_offset) = log[start_offset..].find('\n') {
start_offset += newline_offset + 1;
}
let log_suffix = &log[start_offset..];
workspace.update(&mut cx, |workspace, cx| {
let project = workspace.project().clone();
let buffer = project
.update(cx, |project, cx| project.create_buffer("", None, cx))
.expect("creating buffers on a local workspace always succeeds");
buffer.update(cx, |buffer, cx| {
buffer.set_language(app_state.languages.get_language("JSON"), cx);
buffer.edit(
[(
0..0,
concat!(
"// Zed collects anonymous usage data to help us understand how people are using the app.\n",
"// After the beta release, we'll provide the ability to opt out of this telemetry.\n",
"// Here is the data that has been reported for the current session:\n",
"\n"
),
)],
None,
cx,
);
buffer.edit([(buffer.len()..buffer.len(), log_suffix)], None, cx);
});
let buffer = cx.add_model(|cx| {
MultiBuffer::singleton(buffer, cx).with_title("Telemetry Log".into())
});
workspace.add_item(
Box::new(cx.add_view(|cx| Editor::for_multibuffer(buffer, Some(project), cx))),
cx,
);
});
Some(())
})
.detach();
});
}
fn open_bundled_config_file(
workspace: &mut Workspace,
app_state: Arc<AppState>,
@@ -1070,7 +1132,7 @@ mod tests {
assert!(!editor.is_dirty(cx));
assert_eq!(editor.title(cx), "untitled");
assert!(Arc::ptr_eq(
editor.language_at(0, cx).unwrap(),
&editor.language_at(0, cx).unwrap(),
&languages::PLAIN_TEXT
));
editor.handle_input("hi", cx);
@@ -1157,7 +1219,7 @@ mod tests {
editor.update(cx, |editor, cx| {
assert!(Arc::ptr_eq(
editor.language_at(0, cx).unwrap(),
&editor.language_at(0, cx).unwrap(),
&languages::PLAIN_TEXT
));
editor.handle_input("hi", cx);
@@ -1709,6 +1771,7 @@ mod tests {
let state = Arc::get_mut(&mut app_state).unwrap();
state.initialize_workspace = initialize_workspace;
state.build_window_options = build_window_options;
call::init(app_state.client.clone(), app_state.user_store.clone(), cx);
workspace::init(app_state.clone(), cx);
editor::init(cx);
pane::init(cx);