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            env.extend(spawn_task.env);
 48            // Activate minimal Python virtual environment
 49            if let Some(python_settings) = &python_settings.as_option() {
 50                self.set_python_venv_path_for_tasks(python_settings, venv_base_directory, &mut env);
 51            }
 52            (
 53                Some(TaskState {
 54                    id: spawn_task.id,
 55                    label: spawn_task.label,
 56                    status: TaskStatus::Running,
 57                    completion_rx,
 58                }),
 59                Shell::WithArguments {
 60                    program: spawn_task.command,
 61                    args: spawn_task.args,
 62                },
 63            )
 64        } else {
 65            (None, settings.shell.clone())
 66        };
 67
 68        let terminal = TerminalBuilder::new(
 69            working_directory.clone(),
 70            spawn_task,
 71            shell,
 72            env,
 73            Some(settings.blinking.clone()),
 74            settings.alternate_scroll,
 75            settings.max_scroll_history_lines,
 76            window,
 77            completion_tx,
 78        )
 79        .map(|builder| {
 80            let terminal_handle = cx.new_model(|cx| builder.subscribe(cx));
 81
 82            self.terminals
 83                .local_handles
 84                .push(terminal_handle.downgrade());
 85
 86            let id = terminal_handle.entity_id();
 87            cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
 88                let handles = &mut project.terminals.local_handles;
 89
 90                if let Some(index) = handles
 91                    .iter()
 92                    .position(|terminal| terminal.entity_id() == id)
 93                {
 94                    handles.remove(index);
 95                    cx.notify();
 96                }
 97            })
 98            .detach();
 99
100            // if the terminal is not a task, activate full Python virtual environment
101            if is_terminal {
102                if let Some(python_settings) = &python_settings.as_option() {
103                    if let Some(activate_script_path) =
104                        self.find_activate_script_path(python_settings, venv_base_directory)
105                    {
106                        self.activate_python_virtual_environment(
107                            Project::get_activate_command(python_settings),
108                            activate_script_path,
109                            &terminal_handle,
110                            cx,
111                        );
112                    }
113                }
114            }
115            terminal_handle
116        });
117
118        terminal
119    }
120
121    pub fn find_activate_script_path(
122        &mut self,
123        settings: &VenvSettingsContent,
124        venv_base_directory: &Path,
125    ) -> Option<PathBuf> {
126        let activate_script_name = match settings.activate_script {
127            terminal_settings::ActivateScript::Default => "activate",
128            terminal_settings::ActivateScript::Csh => "activate.csh",
129            terminal_settings::ActivateScript::Fish => "activate.fish",
130            terminal_settings::ActivateScript::Nushell => "activate.nu",
131        };
132
133        settings
134            .directories
135            .into_iter()
136            .find_map(|virtual_environment_name| {
137                let path = venv_base_directory
138                    .join(virtual_environment_name)
139                    .join("bin")
140                    .join(activate_script_name);
141                path.exists().then_some(path)
142            })
143    }
144
145    pub fn set_python_venv_path_for_tasks(
146        &mut self,
147        settings: &VenvSettingsContent,
148        venv_base_directory: &Path,
149        env: &mut HashMap<String, String>,
150    ) {
151        let activate_path = settings
152            .directories
153            .into_iter()
154            .find_map(|virtual_environment_name| {
155                let path = venv_base_directory.join(virtual_environment_name);
156                path.exists().then_some(path)
157            });
158
159        if let Some(path) = activate_path {
160            // Some tools use VIRTUAL_ENV to detect the virtual environment
161            env.insert(
162                "VIRTUAL_ENV".to_string(),
163                path.to_string_lossy().to_string(),
164            );
165
166            let path_bin = path.join("bin");
167            // We need to set the PATH to include the virtual environment's bin directory
168            if let Some(paths) = std::env::var_os("PATH") {
169                let paths = std::iter::once(path_bin).chain(std::env::split_paths(&paths));
170                if let Some(new_path) = std::env::join_paths(paths).log_err() {
171                    env.insert("PATH".to_string(), new_path.to_string_lossy().to_string());
172                }
173            } else {
174                env.insert(
175                    "PATH".to_string(),
176                    path.join("bin").to_string_lossy().to_string(),
177                );
178            }
179        }
180    }
181
182    fn get_activate_command(settings: &VenvSettingsContent) -> &'static str {
183        match settings.activate_script {
184            terminal_settings::ActivateScript::Nushell => "overlay use",
185            _ => "source",
186        }
187    }
188
189    fn activate_python_virtual_environment(
190        &mut self,
191        activate_command: &'static str,
192        activate_script: PathBuf,
193        terminal_handle: &Model<Terminal>,
194        cx: &mut ModelContext<Project>,
195    ) {
196        // Paths are not strings so we need to jump through some hoops to format the command without `format!`
197        let mut command = Vec::from(activate_command.as_bytes());
198        command.push(b' ');
199        // Wrapping path in double quotes to catch spaces in folder name
200        command.extend_from_slice(b"\"");
201        command.extend_from_slice(activate_script.as_os_str().as_encoded_bytes());
202        command.extend_from_slice(b"\"");
203        command.push(b'\n');
204
205        terminal_handle.update(cx, |this, _| this.input_bytes(command));
206    }
207
208    pub fn local_terminal_handles(&self) -> &Vec<WeakModel<terminal::Terminal>> {
209        &self.terminals.local_handles
210    }
211}
212
213// TODO: Add a few tests for adding and removing terminal tabs