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 _: &mut AsyncApp,
138 ) -> Result<Option<serde_json::Value>> {
139 Ok(Some(json!({
140 "provideFormatter": true
141 })))
142 }
143
144 async fn workspace_configuration(
145 self: Arc<Self>,
146 delegate: &Arc<dyn LspAdapterDelegate>,
147 _: Option<Toolchain>,
148 _: Option<Uri>,
149 cx: &mut AsyncApp,
150 ) -> Result<serde_json::Value> {
151 let mut default_config = json!({
152 "css": {
153 "lint": {}
154 },
155 "less": {
156 "lint": {}
157 },
158 "scss": {
159 "lint": {}
160 }
161 });
162
163 let project_options = cx.update(|cx| {
164 language_server_settings(delegate.as_ref(), &self.name(), cx)
165 .and_then(|s| s.settings.clone())
166 });
167
168 if let Some(override_options) = project_options {
169 merge_json_value_into(override_options, &mut default_config);
170 }
171
172 Ok(default_config)
173 }
174}
175
176async fn get_cached_server_binary(
177 container_dir: PathBuf,
178 node: &NodeRuntime,
179) -> Option<LanguageServerBinary> {
180 maybe!(async {
181 let server_path = container_dir.join(SERVER_PATH);
182 anyhow::ensure!(
183 server_path.exists(),
184 "missing executable in directory {server_path:?}"
185 );
186 Ok(LanguageServerBinary {
187 path: node.binary_path().await?,
188 env: None,
189 arguments: server_binary_arguments(&server_path),
190 })
191 })
192 .await
193 .log_err()
194}
195
196#[cfg(test)]
197mod tests {
198 use gpui::{AppContext as _, TestAppContext};
199 use unindent::Unindent;
200
201 #[gpui::test]
202 async fn test_outline(cx: &mut TestAppContext) {
203 let language = crate::language("css", tree_sitter_css::LANGUAGE.into());
204
205 let text = r#"
206 /* Import statement */
207 @import './fonts.css';
208
209 /* multiline list of selectors with nesting */
210 .test-class,
211 div {
212 .nested-class {
213 color: red;
214 }
215 }
216
217 /* descendant selectors */
218 .test .descendant {}
219
220 /* pseudo */
221 .test:not(:hover) {}
222
223 /* media queries */
224 @media screen and (min-width: 3000px) {
225 .desktop-class {}
226 }
227 "#
228 .unindent();
229
230 let buffer = cx.new(|cx| language::Buffer::local(text, cx).with_language(language, cx));
231 let outline = buffer.read_with(cx, |buffer, _| buffer.snapshot().outline(None));
232 assert_eq!(
233 outline
234 .items
235 .iter()
236 .map(|item| (item.text.as_str(), item.depth))
237 .collect::<Vec<_>>(),
238 &[
239 ("@import './fonts.css'", 0),
240 (".test-class, div", 0),
241 (".nested-class", 1),
242 (".test .descendant", 0),
243 (".test:not(:hover)", 0),
244 ("@media screen and (min-width: 3000px)", 0),
245 (".desktop-class", 1),
246 ]
247 );
248 }
249}