Skip to main content

matrixcode_core/lsp/
manager.rs

1//! LSP Manager
2//!
3//! 管理多个 LSP 服务器连接
4
5use std::collections::HashMap;
6use std::sync::{Arc, RwLock};
7
8use super::types::{LspServerConfig, LspServerInfo, LspServerStatus, LspConfig};
9
10/// LSP 管理器
11///
12/// 管理多个语言服务器的连接状态
13pub struct LspManager {
14    /// 服务器配置(按名称索引)
15    configs: HashMap<String, LspServerConfig>,
16    /// 服务器状态(按名称索引)
17    statuses: Arc<RwLock<HashMap<String, LspServerStatus>>>,
18}
19
20impl LspManager {
21    /// 创建新的 LSP 管理器
22    pub fn new() -> Self {
23        Self {
24            configs: HashMap::new(),
25            statuses: Arc::new(RwLock::new(HashMap::new())),
26        }
27    }
28
29    /// 从配置创建 LSP 管理器
30    pub fn from_config(config: &LspConfig) -> Self {
31        let configs: HashMap<String, LspServerConfig> = config
32            .servers
33            .iter()
34            .filter(|s| s.enabled)
35            .map(|s| (s.language.clone(), s.clone()))
36            .collect();
37
38        // 初始化所有状态为 NotStarted
39        let statuses = configs
40            .keys()
41            .map(|k| (k.clone(), LspServerStatus::NotStarted))
42            .collect();
43
44        Self {
45            configs,
46            statuses: Arc::new(RwLock::new(statuses)),
47        }
48    }
49
50    /// 添加服务器配置
51    pub fn add_server(&mut self, config: LspServerConfig) {
52        let name = config.language.clone();
53        self.configs.insert(name.clone(), config);
54        if let Ok(mut statuses) = self.statuses.write() {
55            statuses.insert(name, LspServerStatus::NotStarted);
56        }
57    }
58
59    /// 移除服务器配置
60    pub fn remove_server(&mut self, name: &str) {
61        self.configs.remove(name);
62        if let Ok(mut statuses) = self.statuses.write() {
63            statuses.remove(name);
64        }
65    }
66
67    /// 获取所有服务器信息(用于 TUI 显示)
68    pub fn server_infos(&self) -> Vec<LspServerInfo> {
69        if let Ok(statuses) = self.statuses.read() {
70            self.configs
71                .iter()
72                .map(|(name, config)| {
73                    let status = statuses.get(name).cloned().unwrap_or(LspServerStatus::NotStarted);
74                    LspServerInfo {
75                        name: config.command.clone(),
76                        language: config.language.clone(),
77                        status,
78                    }
79                })
80                .collect()
81        } else {
82            // 返回默认状态
83            self.configs
84                .iter()
85                .map(|(_name, config)| {
86                    LspServerInfo {
87                        name: config.command.clone(),
88                        language: config.language.clone(),
89                        status: LspServerStatus::NotStarted,
90                    }
91                })
92                .collect()
93        }
94    }
95
96    /// 获取服务器状态
97    pub fn get_status(&self, name: &str) -> LspServerStatus {
98        self.statuses
99            .read()
100            .map(|s| s.get(name).cloned().unwrap_or(LspServerStatus::NotStarted))
101            .unwrap_or(LspServerStatus::NotStarted)
102    }
103
104    /// 更新服务器状态
105    pub fn set_status(&self, name: &str, status: LspServerStatus) {
106        if let Ok(mut statuses) = self.statuses.write() {
107            statuses.insert(name.to_string(), status);
108        }
109    }
110
111    /// 标记服务器已连接
112    pub fn mark_connected(&self, name: &str) {
113        self.set_status(name, LspServerStatus::Connected);
114    }
115
116    /// 标记服务器错误
117    pub fn mark_error(&self, name: &str, msg: impl Into<String>) {
118        self.set_status(name, LspServerStatus::Error(msg.into()));
119    }
120
121    /// 获取服务器配置
122    pub fn get_config(&self, name: &str) -> Option<&LspServerConfig> {
123        self.configs.get(name)
124    }
125
126    /// 获取所有服务器名称
127    pub fn server_names(&self) -> Vec<&String> {
128        self.configs.keys().collect()
129    }
130
131    /// 获取已连接的服务器数量
132    pub fn connected_count(&self) -> usize {
133        self.statuses
134            .read()
135            .map(|s| s.values().filter(|s| s.is_ok()).count())
136            .unwrap_or(0)
137    }
138
139    /// 获取有错误的服务器数量
140    pub fn error_count(&self) -> usize {
141        self.statuses
142            .read()
143            .map(|s| s.values().filter(|s| s.is_error()).count())
144            .unwrap_or(0)
145    }
146
147    /// 是否有任何服务器配置
148    pub fn has_servers(&self) -> bool {
149        !self.configs.is_empty()
150    }
151
152    /// 重置所有状态为未启动
153    pub fn reset_all(&self) {
154        if let Ok(mut statuses) = self.statuses.write() {
155            for name in self.configs.keys() {
156                statuses.insert(name.clone(), LspServerStatus::NotStarted);
157            }
158        }
159    }
160}
161
162impl Default for LspManager {
163    fn default() -> Self {
164        Self::new()
165    }
166}
167
168/// 查找 LSP 配置文件
169///
170/// 在当前目录或用户主目录查找 `lsp.toml`
171pub fn find_lsp_config(start_dir: &std::path::Path) -> Option<std::path::PathBuf> {
172    // 当前目录
173    let local_config = start_dir.join("lsp.toml");
174    if local_config.exists() {
175        return Some(local_config);
176    }
177
178    // 用户主目录
179    if let Some(home) = dirs::home_dir() {
180        let home_config = home.join(".config").join("matrixcode").join("lsp.toml");
181        if home_config.exists() {
182            return Some(home_config);
183        }
184    }
185
186    None
187}
188
189/// 加载 LSP 配置
190///
191/// 自动查找配置文件,找不到则返回默认配置
192pub fn load_lsp_config(start_dir: &std::path::Path) -> LspConfig {
193    find_lsp_config(start_dir)
194        .and_then(|p| LspConfig::from_file(&p).ok())
195        .unwrap_or_default()
196}