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