1mod native_kernel;
2use std::{fmt::Debug, future::Future, path::PathBuf, sync::Arc};
3
4use futures::{
5 channel::mpsc::{self, Receiver},
6 future::Shared,
7 stream,
8};
9use gpui::{App, Entity, Task, Window};
10use language::LanguageName;
11pub use native_kernel::*;
12
13mod remote_kernels;
14use project::{Project, ProjectPath, WorktreeId};
15pub use remote_kernels::*;
16
17use anyhow::Result;
18use jupyter_protocol::JupyterKernelspec;
19use runtimelib::{ExecutionState, JupyterMessage, KernelInfoReply};
20use ui::{Icon, IconName, SharedString};
21
22pub type JupyterMessageChannel = stream::SelectAll<Receiver<JupyterMessage>>;
23
24#[derive(Debug, Clone, PartialEq, Eq)]
25pub enum KernelSpecification {
26 Remote(RemoteKernelSpecification),
27 Jupyter(LocalKernelSpecification),
28 PythonEnv(LocalKernelSpecification),
29}
30
31impl KernelSpecification {
32 pub fn name(&self) -> SharedString {
33 match self {
34 Self::Jupyter(spec) => spec.name.clone().into(),
35 Self::PythonEnv(spec) => spec.name.clone().into(),
36 Self::Remote(spec) => spec.name.clone().into(),
37 }
38 }
39
40 pub fn type_name(&self) -> SharedString {
41 match self {
42 Self::Jupyter(_) => "Jupyter".into(),
43 Self::PythonEnv(_) => "Python Environment".into(),
44 Self::Remote(_) => "Remote".into(),
45 }
46 }
47
48 pub fn path(&self) -> SharedString {
49 SharedString::from(match self {
50 Self::Jupyter(spec) => spec.path.to_string_lossy().to_string(),
51 Self::PythonEnv(spec) => spec.path.to_string_lossy().to_string(),
52 Self::Remote(spec) => spec.url.to_string(),
53 })
54 }
55
56 pub fn language(&self) -> SharedString {
57 SharedString::from(match self {
58 Self::Jupyter(spec) => spec.kernelspec.language.clone(),
59 Self::PythonEnv(spec) => spec.kernelspec.language.clone(),
60 Self::Remote(spec) => spec.kernelspec.language.clone(),
61 })
62 }
63
64 pub fn icon(&self, cx: &App) -> Icon {
65 let lang_name = match self {
66 Self::Jupyter(spec) => spec.kernelspec.language.clone(),
67 Self::PythonEnv(spec) => spec.kernelspec.language.clone(),
68 Self::Remote(spec) => spec.kernelspec.language.clone(),
69 };
70
71 file_icons::FileIcons::get(cx)
72 .get_icon_for_type(&lang_name.to_lowercase(), cx)
73 .map(Icon::from_path)
74 .unwrap_or(Icon::new(IconName::ReplNeutral))
75 }
76}
77
78pub fn python_env_kernel_specifications(
79 project: &Entity<Project>,
80 worktree_id: WorktreeId,
81 cx: &mut App,
82) -> impl Future<Output = Result<Vec<KernelSpecification>>> + use<> {
83 let python_language = LanguageName::new("Python");
84 let toolchains = project.read(cx).available_toolchains(
85 ProjectPath {
86 worktree_id,
87 path: Arc::from("".as_ref()),
88 },
89 python_language,
90 cx,
91 );
92 let background_executor = cx.background_executor().clone();
93
94 async move {
95 let toolchains = if let Some((toolchains, _)) = toolchains.await {
96 toolchains
97 } else {
98 return Ok(Vec::new());
99 };
100
101 let kernelspecs = toolchains.toolchains.into_iter().map(|toolchain| {
102 background_executor.spawn(async move {
103 let python_path = toolchain.path.to_string();
104
105 // Check if ipykernel is installed
106 let ipykernel_check = util::command::new_smol_command(&python_path)
107 .args(&["-c", "import ipykernel"])
108 .output()
109 .await;
110
111 if ipykernel_check.is_ok() && ipykernel_check.unwrap().status.success() {
112 // Create a default kernelspec for this environment
113 let default_kernelspec = JupyterKernelspec {
114 argv: vec![
115 python_path.clone(),
116 "-m".to_string(),
117 "ipykernel_launcher".to_string(),
118 "-f".to_string(),
119 "{connection_file}".to_string(),
120 ],
121 display_name: toolchain.name.to_string(),
122 language: "python".to_string(),
123 interrupt_mode: None,
124 metadata: None,
125 env: None,
126 };
127
128 Some(KernelSpecification::PythonEnv(LocalKernelSpecification {
129 name: toolchain.name.to_string(),
130 path: PathBuf::from(&python_path),
131 kernelspec: default_kernelspec,
132 }))
133 } else {
134 None
135 }
136 })
137 });
138
139 let kernel_specs = futures::future::join_all(kernelspecs)
140 .await
141 .into_iter()
142 .flatten()
143 .collect();
144
145 anyhow::Ok(kernel_specs)
146 }
147}
148
149pub trait RunningKernel: Send + Debug {
150 fn request_tx(&self) -> mpsc::Sender<JupyterMessage>;
151 fn working_directory(&self) -> &PathBuf;
152 fn execution_state(&self) -> &ExecutionState;
153 fn set_execution_state(&mut self, state: ExecutionState);
154 fn kernel_info(&self) -> Option<&KernelInfoReply>;
155 fn set_kernel_info(&mut self, info: KernelInfoReply);
156 fn force_shutdown(&mut self, window: &mut Window, cx: &mut App) -> Task<anyhow::Result<()>>;
157}
158
159#[derive(Debug, Clone)]
160pub enum KernelStatus {
161 Idle,
162 Busy,
163 Starting,
164 Error,
165 ShuttingDown,
166 Shutdown,
167 Restarting,
168}
169
170impl KernelStatus {
171 pub fn is_connected(&self) -> bool {
172 matches!(self, KernelStatus::Idle | KernelStatus::Busy)
173 }
174}
175
176impl ToString for KernelStatus {
177 fn to_string(&self) -> String {
178 match self {
179 KernelStatus::Idle => "Idle".to_string(),
180 KernelStatus::Busy => "Busy".to_string(),
181 KernelStatus::Starting => "Starting".to_string(),
182 KernelStatus::Error => "Error".to_string(),
183 KernelStatus::ShuttingDown => "Shutting Down".to_string(),
184 KernelStatus::Shutdown => "Shutdown".to_string(),
185 KernelStatus::Restarting => "Restarting".to_string(),
186 }
187 }
188}
189
190#[derive(Debug)]
191pub enum Kernel {
192 RunningKernel(Box<dyn RunningKernel>),
193 StartingKernel(Shared<Task<()>>),
194 ErroredLaunch(String),
195 ShuttingDown,
196 Shutdown,
197 Restarting,
198}
199
200impl From<&Kernel> for KernelStatus {
201 fn from(kernel: &Kernel) -> Self {
202 match kernel {
203 Kernel::RunningKernel(kernel) => match kernel.execution_state() {
204 ExecutionState::Idle => KernelStatus::Idle,
205 ExecutionState::Busy => KernelStatus::Busy,
206 },
207 Kernel::StartingKernel(_) => KernelStatus::Starting,
208 Kernel::ErroredLaunch(_) => KernelStatus::Error,
209 Kernel::ShuttingDown => KernelStatus::ShuttingDown,
210 Kernel::Shutdown => KernelStatus::Shutdown,
211 Kernel::Restarting => KernelStatus::Restarting,
212 }
213 }
214}
215
216impl Kernel {
217 pub fn status(&self) -> KernelStatus {
218 self.into()
219 }
220
221 pub fn set_execution_state(&mut self, status: &ExecutionState) {
222 if let Kernel::RunningKernel(running_kernel) = self {
223 running_kernel.set_execution_state(status.clone());
224 }
225 }
226
227 pub fn set_kernel_info(&mut self, kernel_info: &KernelInfoReply) {
228 if let Kernel::RunningKernel(running_kernel) = self {
229 running_kernel.set_kernel_info(kernel_info.clone());
230 }
231 }
232
233 pub fn is_shutting_down(&self) -> bool {
234 match self {
235 Kernel::Restarting | Kernel::ShuttingDown => true,
236 Kernel::RunningKernel(_)
237 | Kernel::StartingKernel(_)
238 | Kernel::ErroredLaunch(_)
239 | Kernel::Shutdown => false,
240 }
241 }
242}