terminals.rs

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