terminals.rs

  1use crate::Project;
  2use gpui::{AnyWindowHandle, Context, Entity, Model, ModelContext, WeakModel};
  3use settings::Settings;
  4use std::path::{Path, PathBuf};
  5use terminal::{
  6    terminal_settings::{self, TerminalSettings, VenvSettingsContent},
  7    Terminal, TerminalBuilder,
  8};
  9
 10#[cfg(target_os = "macos")]
 11use std::os::unix::ffi::OsStrExt;
 12
 13pub struct Terminals {
 14    pub(crate) local_handles: Vec<WeakModel<terminal::Terminal>>,
 15}
 16
 17impl Project {
 18    pub fn create_terminal(
 19        &mut self,
 20        working_directory: Option<PathBuf>,
 21        window: AnyWindowHandle,
 22        cx: &mut ModelContext<Self>,
 23    ) -> anyhow::Result<Model<Terminal>> {
 24        if self.is_remote() {
 25            return Err(anyhow::anyhow!(
 26                "creating terminals as a guest is not supported yet"
 27            ));
 28        } else {
 29            let settings = TerminalSettings::get_global(cx);
 30            let python_settings = settings.detect_venv.clone();
 31            let shell = settings.shell.clone();
 32
 33            let terminal = TerminalBuilder::new(
 34                working_directory.clone(),
 35                shell.clone(),
 36                settings.env.clone(),
 37                Some(settings.blinking.clone()),
 38                settings.alternate_scroll,
 39                window,
 40                |_, _| todo!("color_for_index"),
 41            )
 42            .map(|builder| {
 43                let terminal_handle = cx.build_model(|cx| builder.subscribe(cx));
 44
 45                self.terminals
 46                    .local_handles
 47                    .push(terminal_handle.downgrade());
 48
 49                let id = terminal_handle.entity_id();
 50                cx.observe_release(&terminal_handle, move |project, _terminal, cx| {
 51                    let handles = &mut project.terminals.local_handles;
 52
 53                    if let Some(index) = handles
 54                        .iter()
 55                        .position(|terminal| terminal.entity_id() == id)
 56                    {
 57                        handles.remove(index);
 58                        cx.notify();
 59                    }
 60                })
 61                .detach();
 62
 63                if let Some(python_settings) = &python_settings.as_option() {
 64                    let activate_script_path =
 65                        self.find_activate_script_path(&python_settings, working_directory);
 66                    self.activate_python_virtual_environment(
 67                        activate_script_path,
 68                        &terminal_handle,
 69                        cx,
 70                    );
 71                }
 72                terminal_handle
 73            });
 74
 75            terminal
 76        }
 77    }
 78
 79    pub fn find_activate_script_path(
 80        &mut self,
 81        settings: &VenvSettingsContent,
 82        working_directory: Option<PathBuf>,
 83    ) -> Option<PathBuf> {
 84        // When we are unable to resolve the working directory, the terminal builder
 85        // defaults to '/'. We should probably encode this directly somewhere, but for
 86        // now, let's just hard code it here.
 87        let working_directory = working_directory.unwrap_or_else(|| Path::new("/").to_path_buf());
 88        let activate_script_name = match settings.activate_script {
 89            terminal_settings::ActivateScript::Default => "activate",
 90            terminal_settings::ActivateScript::Csh => "activate.csh",
 91            terminal_settings::ActivateScript::Fish => "activate.fish",
 92            terminal_settings::ActivateScript::Nushell => "activate.nu",
 93        };
 94
 95        for virtual_environment_name in settings.directories {
 96            let mut path = working_directory.join(virtual_environment_name);
 97            path.push("bin/");
 98            path.push(activate_script_name);
 99
100            if path.exists() {
101                return Some(path);
102            }
103        }
104
105        None
106    }
107
108    fn activate_python_virtual_environment(
109        &mut self,
110        activate_script: Option<PathBuf>,
111        terminal_handle: &Model<Terminal>,
112        cx: &mut ModelContext<Project>,
113    ) {
114        if let Some(activate_script) = activate_script {
115            // Paths are not strings so we need to jump through some hoops to format the command without `format!`
116            let mut command = Vec::from("source ".as_bytes());
117            command.extend_from_slice(activate_script.as_os_str().as_bytes());
118            command.push(b'\n');
119
120            terminal_handle.update(cx, |this, _| this.input_bytes(command));
121        }
122    }
123
124    pub fn local_terminal_handles(&self) -> &Vec<WeakModel<terminal::Terminal>> {
125        &self.terminals.local_handles
126    }
127}
128
129// TODO: Add a few tests for adding and removing terminal tabs