1use anyhow::Result;
2use async_trait::async_trait;
3use gpui::AsyncApp;
4use language::{LspAdapter, LspAdapterDelegate, LspInstaller, Toolchain};
5use lsp::{LanguageServerBinary, LanguageServerName};
6use node_runtime::{NodeRuntime, VersionStrategy};
7use project::lsp_store::language_server_settings;
8use serde_json::json;
9use std::{
10 ffi::OsString,
11 path::{Path, PathBuf},
12 sync::Arc,
13};
14use util::{ResultExt, maybe, merge_json_value_into};
15
16const SERVER_PATH: &str =
17 "node_modules/vscode-langservers-extracted/bin/vscode-css-language-server";
18
19fn server_binary_arguments(server_path: &Path) -> Vec<OsString> {
20 vec![server_path.into(), "--stdio".into()]
21}
22
23pub struct CssLspAdapter {
24 node: NodeRuntime,
25}
26
27impl CssLspAdapter {
28 const PACKAGE_NAME: &str = "vscode-langservers-extracted";
29 pub fn new(node: NodeRuntime) -> Self {
30 CssLspAdapter { node }
31 }
32}
33
34impl LspInstaller for CssLspAdapter {
35 type BinaryVersion = String;
36
37 async fn fetch_latest_server_version(
38 &self,
39 _: &dyn LspAdapterDelegate,
40 _: bool,
41 _: &mut AsyncApp,
42 ) -> Result<String> {
43 self.node
44 .npm_package_latest_version("vscode-langservers-extracted")
45 .await
46 }
47
48 async fn check_if_user_installed(
49 &self,
50 delegate: &dyn LspAdapterDelegate,
51 _: Option<Toolchain>,
52 _: &AsyncApp,
53 ) -> Option<LanguageServerBinary> {
54 let path = delegate
55 .which("vscode-css-language-server".as_ref())
56 .await?;
57 let env = delegate.shell_env().await;
58
59 Some(LanguageServerBinary {
60 path,
61 env: Some(env),
62 arguments: vec!["--stdio".into()],
63 })
64 }
65
66 async fn fetch_server_binary(
67 &self,
68 latest_version: String,
69 container_dir: PathBuf,
70 _: &dyn LspAdapterDelegate,
71 ) -> Result<LanguageServerBinary> {
72 let server_path = container_dir.join(SERVER_PATH);
73
74 self.node
75 .npm_install_packages(
76 &container_dir,
77 &[(Self::PACKAGE_NAME, latest_version.as_str())],
78 )
79 .await?;
80
81 Ok(LanguageServerBinary {
82 path: self.node.binary_path().await?,
83 env: None,
84 arguments: server_binary_arguments(&server_path),
85 })
86 }
87
88 async fn check_if_version_installed(
89 &self,
90 version: &String,
91 container_dir: &PathBuf,
92 _: &dyn LspAdapterDelegate,
93 ) -> Option<LanguageServerBinary> {
94 let server_path = container_dir.join(SERVER_PATH);
95
96 let should_install_language_server = self
97 .node
98 .should_install_npm_package(
99 Self::PACKAGE_NAME,
100 &server_path,
101 container_dir,
102 VersionStrategy::Latest(version),
103 )
104 .await;
105
106 if should_install_language_server {
107 None
108 } else {
109 Some(LanguageServerBinary {
110 path: self.node.binary_path().await.ok()?,
111 env: None,
112 arguments: server_binary_arguments(&server_path),
113 })
114 }
115 }
116
117 async fn cached_server_binary(
118 &self,
119 container_dir: PathBuf,
120 _: &dyn LspAdapterDelegate,
121 ) -> Option<LanguageServerBinary> {
122 get_cached_server_binary(container_dir, &self.node).await
123 }
124}
125
126#[async_trait(?Send)]
127impl LspAdapter for CssLspAdapter {
128 fn name(&self) -> LanguageServerName {
129 LanguageServerName("vscode-css-language-server".into())
130 }
131
132 async fn initialization_options(
133 self: Arc<Self>,
134 _: &Arc<dyn LspAdapterDelegate>,
135 ) -> Result<Option<serde_json::Value>> {
136 Ok(Some(json!({
137 "provideFormatter": true
138 })))
139 }
140
141 async fn workspace_configuration(
142 self: Arc<Self>,
143 delegate: &Arc<dyn LspAdapterDelegate>,
144 _: Option<Toolchain>,
145 cx: &mut AsyncApp,
146 ) -> Result<serde_json::Value> {
147 let mut default_config = json!({
148 "css": {
149 "lint": {}
150 },
151 "less": {
152 "lint": {}
153 },
154 "scss": {
155 "lint": {}
156 }
157 });
158
159 let project_options = cx.update(|cx| {
160 language_server_settings(delegate.as_ref(), &self.name(), cx)
161 .and_then(|s| s.settings.clone())
162 })?;
163
164 if let Some(override_options) = project_options {
165 merge_json_value_into(override_options, &mut default_config);
166 }
167
168 Ok(default_config)
169 }
170}
171
172async fn get_cached_server_binary(
173 container_dir: PathBuf,
174 node: &NodeRuntime,
175) -> Option<LanguageServerBinary> {
176 maybe!(async {
177 let server_path = container_dir.join(SERVER_PATH);
178 anyhow::ensure!(
179 server_path.exists(),
180 "missing executable in directory {server_path:?}"
181 );
182 Ok(LanguageServerBinary {
183 path: node.binary_path().await?,
184 env: None,
185 arguments: server_binary_arguments(&server_path),
186 })
187 })
188 .await
189 .log_err()
190}
191
192#[cfg(test)]
193mod tests {
194 use gpui::{AppContext as _, TestAppContext};
195 use unindent::Unindent;
196
197 #[gpui::test]
198 async fn test_outline(cx: &mut TestAppContext) {
199 let language = crate::language("css", tree_sitter_css::LANGUAGE.into());
200
201 let text = r#"
202 /* Import statement */
203 @import './fonts.css';
204
205 /* multiline list of selectors with nesting */
206 .test-class,
207 div {
208 .nested-class {
209 color: red;
210 }
211 }
212
213 /* descendant selectors */
214 .test .descendant {}
215
216 /* pseudo */
217 .test:not(:hover) {}
218
219 /* media queries */
220 @media screen and (min-width: 3000px) {
221 .desktop-class {}
222 }
223 "#
224 .unindent();
225
226 let buffer = cx.new(|cx| language::Buffer::local(text, cx).with_language(language, cx));
227 let outline = buffer.read_with(cx, |buffer, _| buffer.snapshot().outline(None));
228 assert_eq!(
229 outline
230 .items
231 .iter()
232 .map(|item| (item.text.as_str(), item.depth))
233 .collect::<Vec<_>>(),
234 &[
235 ("@import './fonts.css'", 0),
236 (".test-class, div", 0),
237 (".nested-class", 1),
238 (".test .descendant", 0),
239 (".test:not(:hover)", 0),
240 ("@media screen and (min-width: 3000px)", 0),
241 (".desktop-class", 1),
242 ]
243 );
244 }
245}