terminals.rs

  1use crate::Project;
  2use collections::HashMap;
  3use gpui::{AnyWindowHandle, Context, Entity, Model, ModelContext, WeakModel};
  4use settings::Settings;
  5use smol::channel::bounded;
  6use std::path::{Path, PathBuf};
  7use terminal::{
  8    terminal_settings::{self, Shell, TerminalSettings, VenvSettingsContent},
  9    SpawnTask, TaskState, TaskStatus, Terminal, TerminalBuilder,
 10};
 11use util::ResultExt;
 12
 13// #[cfg(target_os = "macos")]
 14// use std::os::unix::ffi::OsStrExt;
 15
 16pub struct Terminals {
 17    pub(crate) local_handles: Vec<WeakModel<terminal::Terminal>>,
 18}
 19
 20impl Project {
 21    pub fn create_terminal(
 22        &mut self,
 23        working_directory: Option<PathBuf>,
 24        spawn_task: Option<SpawnTask>,
 25        window: AnyWindowHandle,
 26        cx: &mut ModelContext<Self>,
 27    ) -> anyhow::Result<Model<Terminal>> {
 28        anyhow::ensure!(
 29            !self.is_remote(),
 30            "creating terminals as a guest is not supported yet"
 31        );
 32
 33        let is_terminal = spawn_task.is_none();
 34        let settings = TerminalSettings::get_global(cx);
 35        let python_settings = settings.detect_venv.clone();
 36        let (completion_tx, completion_rx) = bounded(1);
 37
 38        let mut env = settings.env.clone();
 39        // Alacritty uses parent project's working directory when no working directory is provided
 40        // https://github.com/alacritty/alacritty/blob/fd1a3cc79192d1d03839f0fd8c72e1f8d0fce42e/extra/man/alacritty.5.scd?plain=1#L47-L52
 41
 42        let venv_base_directory = working_directory
 43            .as_deref()
 44            .unwrap_or_else(|| Path::new(""));
 45
 46        let (spawn_task, shell) = if let Some(spawn_task) = spawn_task {
 47            log::debug!("Spawning task: {spawn_task:?}");
 48            env.extend(spawn_task.env);
 49            // Activate minimal Python virtual environment
 50            if let Some(python_settings) = &python_settings.as_option() {
 51                self.set_python_venv_path_for_tasks(python_settings, venv_base_directory, &mut env);
 52            }
 53            (
 54                Some(TaskState {
 55                    id: spawn_task.id,
 56                    full_label: spawn_task.full_label,
 57                    label: spawn_task.label,
 58                    status: TaskStatus::Running,
 59                    completion_rx,
 60                }),
 61                Shell::WithArguments {
 62                    program: spawn_task.command,
 63                    args: spawn_task.args,
 64                },
 65            )
 66        } else {
 67            (None, settings.shell.clone())
 68        };
 69
 70        let terminal = TerminalBuilder::new(
 71            working_directory.clone(),
 72            spawn_task,
 73            shell,
 74            env,
 75            Some(settings.blinking.clone()),
 76            settings.alternate_scroll,
 77            settings.max_scroll_history_lines,
 78            window,
 79            completion_tx,
 80        )
 81        .map(|builder| {
 82            let terminal_handle = cx.new_model(|cx| builder.subscribe(cx));
 83
 84            self.terminals
 85                .local_handles
 86                .push(terminal_handle.downgrade());
 87
 88            let id = terminal_handle.entity_id();
 89            cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
 90                let handles = &mut project.terminals.local_handles;
 91
 92                if let Some(index) = handles
 93                    .iter()
 94                    .position(|terminal| terminal.entity_id() == id)
 95                {
 96                    handles.remove(index);
 97                    cx.notify();
 98                }
 99            })
100            .detach();
101
102            // if the terminal is not a task, activate full Python virtual environment
103            if is_terminal {
104                if let Some(python_settings) = &python_settings.as_option() {
105                    if let Some(activate_script_path) =
106                        self.find_activate_script_path(python_settings, venv_base_directory)
107                    {
108                        self.activate_python_virtual_environment(
109                            Project::get_activate_command(python_settings),
110                            activate_script_path,
111                            &terminal_handle,
112                            cx,
113                        );
114                    }
115                }
116            }
117            terminal_handle
118        });
119
120        terminal
121    }
122
123    pub fn find_activate_script_path(
124        &mut self,
125        settings: &VenvSettingsContent,
126        venv_base_directory: &Path,
127    ) -> Option<PathBuf> {
128        let activate_script_name = match settings.activate_script {
129            terminal_settings::ActivateScript::Default => "activate",
130            terminal_settings::ActivateScript::Csh => "activate.csh",
131            terminal_settings::ActivateScript::Fish => "activate.fish",
132            terminal_settings::ActivateScript::Nushell => "activate.nu",
133        };
134
135        settings
136            .directories
137            .into_iter()
138            .find_map(|virtual_environment_name| {
139                let path = venv_base_directory
140                    .join(virtual_environment_name)
141                    .join("bin")
142                    .join(activate_script_name);
143                path.exists().then_some(path)
144            })
145    }
146
147    pub fn set_python_venv_path_for_tasks(
148        &mut self,
149        settings: &VenvSettingsContent,
150        venv_base_directory: &Path,
151        env: &mut HashMap<String, String>,
152    ) {
153        let activate_path = settings
154            .directories
155            .into_iter()
156            .find_map(|virtual_environment_name| {
157                let path = venv_base_directory.join(virtual_environment_name);
158                path.exists().then_some(path)
159            });
160
161        if let Some(path) = activate_path {
162            // Some tools use VIRTUAL_ENV to detect the virtual environment
163            env.insert(
164                "VIRTUAL_ENV".to_string(),
165                path.to_string_lossy().to_string(),
166            );
167
168            let path_bin = path.join("bin");
169            // We need to set the PATH to include the virtual environment's bin directory
170            if let Some(paths) = std::env::var_os("PATH") {
171                let paths = std::iter::once(path_bin).chain(std::env::split_paths(&paths));
172                if let Some(new_path) = std::env::join_paths(paths).log_err() {
173                    env.insert("PATH".to_string(), new_path.to_string_lossy().to_string());
174                }
175            } else {
176                env.insert(
177                    "PATH".to_string(),
178                    path.join("bin").to_string_lossy().to_string(),
179                );
180            }
181        }
182    }
183
184    fn get_activate_command(settings: &VenvSettingsContent) -> &'static str {
185        match settings.activate_script {
186            terminal_settings::ActivateScript::Nushell => "overlay use",
187            _ => "source",
188        }
189    }
190
191    fn activate_python_virtual_environment(
192        &mut self,
193        activate_command: &'static str,
194        activate_script: PathBuf,
195        terminal_handle: &Model<Terminal>,
196        cx: &mut ModelContext<Project>,
197    ) {
198        // Paths are not strings so we need to jump through some hoops to format the command without `format!`
199        let mut command = Vec::from(activate_command.as_bytes());
200        command.push(b' ');
201        // Wrapping path in double quotes to catch spaces in folder name
202        command.extend_from_slice(b"\"");
203        command.extend_from_slice(activate_script.as_os_str().as_encoded_bytes());
204        command.extend_from_slice(b"\"");
205        command.push(b'\n');
206
207        terminal_handle.update(cx, |this, _| this.input_bytes(command));
208    }
209
210    pub fn local_terminal_handles(&self) -> &Vec<WeakModel<terminal::Terminal>> {
211        &self.terminals.local_handles
212    }
213}
214
215// TODO: Add a few tests for adding and removing terminal tabs