1mod native_kernel;
2use std::{fmt::Debug, future::Future, path::PathBuf};
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, 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>>> {
83 let python_language = LanguageName::new("Python");
84 let toolchains = project
85 .read(cx)
86 .available_toolchains(worktree_id, python_language, cx);
87 let background_executor = cx.background_executor().clone();
88
89 async move {
90 let toolchains = if let Some(toolchains) = toolchains.await {
91 toolchains
92 } else {
93 return Ok(Vec::new());
94 };
95
96 let kernelspecs = toolchains.toolchains.into_iter().map(|toolchain| {
97 background_executor.spawn(async move {
98 let python_path = toolchain.path.to_string();
99
100 // Check if ipykernel is installed
101 let ipykernel_check = util::command::new_smol_command(&python_path)
102 .args(&["-c", "import ipykernel"])
103 .output()
104 .await;
105
106 if ipykernel_check.is_ok() && ipykernel_check.unwrap().status.success() {
107 // Create a default kernelspec for this environment
108 let default_kernelspec = JupyterKernelspec {
109 argv: vec![
110 python_path.clone(),
111 "-m".to_string(),
112 "ipykernel_launcher".to_string(),
113 "-f".to_string(),
114 "{connection_file}".to_string(),
115 ],
116 display_name: toolchain.name.to_string(),
117 language: "python".to_string(),
118 interrupt_mode: None,
119 metadata: None,
120 env: None,
121 };
122
123 Some(KernelSpecification::PythonEnv(LocalKernelSpecification {
124 name: toolchain.name.to_string(),
125 path: PathBuf::from(&python_path),
126 kernelspec: default_kernelspec,
127 }))
128 } else {
129 None
130 }
131 })
132 });
133
134 let kernel_specs = futures::future::join_all(kernelspecs)
135 .await
136 .into_iter()
137 .flatten()
138 .collect();
139
140 anyhow::Ok(kernel_specs)
141 }
142}
143
144pub trait RunningKernel: Send + Debug {
145 fn request_tx(&self) -> mpsc::Sender<JupyterMessage>;
146 fn working_directory(&self) -> &PathBuf;
147 fn execution_state(&self) -> &ExecutionState;
148 fn set_execution_state(&mut self, state: ExecutionState);
149 fn kernel_info(&self) -> Option<&KernelInfoReply>;
150 fn set_kernel_info(&mut self, info: KernelInfoReply);
151 fn force_shutdown(&mut self, window: &mut Window, cx: &mut App) -> Task<anyhow::Result<()>>;
152}
153
154#[derive(Debug, Clone)]
155pub enum KernelStatus {
156 Idle,
157 Busy,
158 Starting,
159 Error,
160 ShuttingDown,
161 Shutdown,
162 Restarting,
163}
164
165impl KernelStatus {
166 pub fn is_connected(&self) -> bool {
167 match self {
168 KernelStatus::Idle | KernelStatus::Busy => true,
169 _ => false,
170 }
171 }
172}
173
174impl ToString for KernelStatus {
175 fn to_string(&self) -> String {
176 match self {
177 KernelStatus::Idle => "Idle".to_string(),
178 KernelStatus::Busy => "Busy".to_string(),
179 KernelStatus::Starting => "Starting".to_string(),
180 KernelStatus::Error => "Error".to_string(),
181 KernelStatus::ShuttingDown => "Shutting Down".to_string(),
182 KernelStatus::Shutdown => "Shutdown".to_string(),
183 KernelStatus::Restarting => "Restarting".to_string(),
184 }
185 }
186}
187
188#[derive(Debug)]
189pub enum Kernel {
190 RunningKernel(Box<dyn RunningKernel>),
191 StartingKernel(Shared<Task<()>>),
192 ErroredLaunch(String),
193 ShuttingDown,
194 Shutdown,
195 Restarting,
196}
197
198impl From<&Kernel> for KernelStatus {
199 fn from(kernel: &Kernel) -> Self {
200 match kernel {
201 Kernel::RunningKernel(kernel) => match kernel.execution_state() {
202 ExecutionState::Idle => KernelStatus::Idle,
203 ExecutionState::Busy => KernelStatus::Busy,
204 },
205 Kernel::StartingKernel(_) => KernelStatus::Starting,
206 Kernel::ErroredLaunch(_) => KernelStatus::Error,
207 Kernel::ShuttingDown => KernelStatus::ShuttingDown,
208 Kernel::Shutdown => KernelStatus::Shutdown,
209 Kernel::Restarting => KernelStatus::Restarting,
210 }
211 }
212}
213
214impl Kernel {
215 pub fn status(&self) -> KernelStatus {
216 self.into()
217 }
218
219 pub fn set_execution_state(&mut self, status: &ExecutionState) {
220 if let Kernel::RunningKernel(running_kernel) = self {
221 running_kernel.set_execution_state(status.clone());
222 }
223 }
224
225 pub fn set_kernel_info(&mut self, kernel_info: &KernelInfoReply) {
226 if let Kernel::RunningKernel(running_kernel) = self {
227 running_kernel.set_kernel_info(kernel_info.clone());
228 }
229 }
230
231 pub fn is_shutting_down(&self) -> bool {
232 match self {
233 Kernel::Restarting | Kernel::ShuttingDown => true,
234 Kernel::RunningKernel(_)
235 | Kernel::StartingKernel(_)
236 | Kernel::ErroredLaunch(_)
237 | Kernel::Shutdown => false,
238 }
239 }
240}