Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
55 changes: 28 additions & 27 deletions frontends/rioterm/src/context/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -51,9 +51,7 @@ pub struct Context<T: EventListener> {
pub renderable_content: RenderableContent,
pub messenger: Messenger,
#[cfg(not(target_os = "windows"))]
pub main_fd: Arc<i32>,
#[cfg(not(target_os = "windows"))]
pub shell_pid: u32,
pty: Option<(i32, u32)>,
pub rich_text_id: usize,
pub dimension: ContextDimension,
pub title: ContextTitle,
Expand All @@ -63,19 +61,32 @@ pub struct Context<T: EventListener> {

impl<T: rio_backend::event::EventListener> Drop for Context<T> {
fn drop(&mut self) {
// Shutdown the terminal's PTY.
// The performer owns the PTY and terminates its child when it shuts down.
let _ = self.messenger.channel.send(Msg::Shutdown);

// `create_dead_context` uses 1 as a placeholder PID, so guard against
// signalling init (1) or our own process group (0).
#[cfg(not(target_os = "windows"))]
if self.shell_pid > 1 {
teletypewriter::kill_pid(self.shell_pid as i32);
}
}
}

impl<T: EventListener> Context<T> {
fn foreground_process_name(&self) -> Option<String> {
#[cfg(not(target_os = "windows"))]
return self.pty.as_ref().map(|(main_fd, shell_pid)| {
teletypewriter::foreground_process_name(*main_fd, *shell_pid)
});

#[cfg(target_os = "windows")]
None
}

pub(crate) fn foreground_process_path(&self) -> Option<std::path::PathBuf> {
#[cfg(not(target_os = "windows"))]
return self.pty.as_ref().and_then(|(main_fd, shell_pid)| {
teletypewriter::foreground_process_path(*main_fd, *shell_pid).ok()
});

#[cfg(target_os = "windows")]
None
}

#[inline]
pub fn set_selection(&mut self, selection_range: Option<SelectionRange>) {
let old_selection = self.renderable_content.selection_range;
Expand Down Expand Up @@ -163,9 +174,7 @@ pub fn create_dead_context<T: rio_backend::event::EventListener>(
Context {
route_id,
#[cfg(not(target_os = "windows"))]
main_fd: Arc::new(-1),
#[cfg(not(target_os = "windows"))]
shell_pid: 1,
pty: None,
messenger: Messenger::new(sender),
renderable_content: RenderableContent::new(Cursor::default()),
terminal,
Expand Down Expand Up @@ -296,9 +305,9 @@ impl<T: EventListener + Clone + std::marker::Send + 'static> ContextManager<T> {
}

#[cfg(not(target_os = "windows"))]
let main_fd = pty.child.id.clone();
let main_fd = pty.child.id;
#[cfg(not(target_os = "windows"))]
let shell_pid = *pty.child.pid.clone() as u32;
let shell_pid = pty.child.pid as u32;

#[cfg(target_os = "windows")]
{
Expand Down Expand Up @@ -337,9 +346,7 @@ impl<T: EventListener + Clone + std::marker::Send + 'static> ContextManager<T> {
Ok(Context {
route_id,
#[cfg(not(target_os = "windows"))]
main_fd,
#[cfg(not(target_os = "windows"))]
shell_pid,
pty: Some((main_fd, shell_pid)),
messenger,
terminal,
rich_text_id,
Expand Down Expand Up @@ -1001,10 +1008,7 @@ impl<T: EventListener + Clone + std::marker::Send + 'static> ContextManager<T> {
#[cfg(not(target_os = "windows"))]
{
let current_context = self.current();
if let Ok(path) = teletypewriter::foreground_process_path(
*current_context.main_fd,
current_context.shell_pid,
) {
if let Some(path) = current_context.foreground_process_path() {
working_dir = Some(path.to_string_lossy().to_string());
}
}
Expand Down Expand Up @@ -1121,10 +1125,7 @@ impl<T: EventListener + Clone + std::marker::Send + 'static> ContextManager<T> {
#[cfg(not(target_os = "windows"))]
{
let current_context = self.current();
if let Ok(path) = teletypewriter::foreground_process_path(
*current_context.main_fd,
current_context.shell_pid,
) {
if let Some(path) = current_context.foreground_process_path() {
working_dir = Some(path.to_string_lossy().to_string());
}
}
Expand Down
193 changes: 50 additions & 143 deletions frontends/rioterm/src/context/title.rs
Original file line number Diff line number Diff line change
Expand Up @@ -22,13 +22,7 @@ impl Default for ContextTitle {
pub fn create_title_extra_from_context<T: rio_backend::event::EventListener>(
context: &Context<T>,
) -> Option<ContextTitleExtra> {
#[cfg(unix)]
let program =
teletypewriter::foreground_process_name(*context.main_fd, context.shell_pid);

#[cfg(not(unix))]
let program = String::default();

let program = context.foreground_process_name()?;
Some(ContextTitleExtra { program })
}

Expand Down Expand Up @@ -79,6 +73,41 @@ fn shorten_path(absolute: &str) -> String {
}
}

fn current_path<T: rio_backend::event::EventListener>(
context: &Context<T>,
) -> Option<String> {
context
.terminal
.lock()
.current_directory
.clone()
.and_then(|path| path.into_os_string().into_string().ok())
.or_else(|| {
context
.foreground_process_path()
.map(|path| path.to_string_lossy().into_owned())
})
}

fn variable_value<T: rio_backend::event::EventListener>(
variable: &str,
context: &Context<T>,
) -> Option<String> {
match variable.trim().to_ascii_lowercase().as_str() {
"columns" => Some(context.dimension.columns.to_string()),
"lines" => Some(context.dimension.lines.to_string()),
"title" => Some(context.terminal.lock().title.clone()),
"program" => Some(context.foreground_process_name().unwrap_or_default()),
"absolute_path" => Some(current_path(context).unwrap_or_default()),
"relative_path" => Some(
current_path(context)
.map(|path| shorten_path(&path))
.unwrap_or_default(),
),
_ => None,
}
}

#[inline]
pub fn update_title<T: rio_backend::event::EventListener>(
template: &str,
Expand All @@ -92,144 +121,17 @@ pub fn update_title<T: rio_backend::event::EventListener>(

let re = regex::Regex::new(r"\{\{(.*?)\}\}").unwrap();
for (to_replace_str, [variable]) in re.captures_iter(template).map(|c| c.extract()) {
let variables = if to_replace_str.contains("||") {
variable.split("||").collect()
} else {
vec![variable]
};

let mut matched = false;
for (i, scoped_variable) in variables.iter().enumerate() {
if matched {
break;
let mut variables = variable.split("||").peekable();
while let Some(variable) = variables.next() {
let Some(value) = variable_value(variable, context) else {
continue;
};
if value.is_empty() && variables.peek().is_some() {
continue;
}

let var = scoped_variable.to_owned().trim().to_lowercase();
match var.as_str() {
"columns" => {
new_template = new_template
.replace(to_replace_str, &context.dimension.columns.to_string());
matched = true;
}
"lines" => {
new_template = new_template
.replace(to_replace_str, &context.dimension.lines.to_string());
matched = true;
}
"title" => {
let terminal_title = {
let terminal = context.terminal.lock();
terminal.title.to_string()
};

// In case it has a fallback and title is empty
// or
// In case is the last then we need to erase variables either way
let is_only_one = variables.len() == 1;
let is_last = i == variables.len() - 1;
if is_only_one || is_last {
new_template =
new_template.replace(to_replace_str, &terminal_title);
continue;
}

if !terminal_title.is_empty() {
new_template =
new_template.replace(to_replace_str, &terminal_title);
matched = true;
}
}
"program" => {
#[cfg(unix)]
{
let program = teletypewriter::foreground_process_name(
*context.main_fd,
context.shell_pid,
);

new_template = new_template.replace(to_replace_str, &program);
matched = true;
}
}
"absolute_path" => {
{
let terminal = context.terminal.lock();
if let Some(current_directory) = &terminal.current_directory {
if let Ok(dir_str) =
current_directory.clone().into_os_string().into_string()
{
new_template =
new_template.replace(to_replace_str, &dir_str);
matched = true;
continue;
}
};
}

#[cfg(unix)]
{
let path = teletypewriter::foreground_process_path(
*context.main_fd,
context.shell_pid,
)
.map(|p| p.to_string_lossy().to_string())
.unwrap_or_default();

// In case it has a fallback and path is empty
// or
// In case is the last then we need to erase variables either way
let is_only_one = variables.len() == 1;
let is_last = i == variables.len() - 1;
if is_only_one || is_last {
new_template = new_template.replace(to_replace_str, &path);
continue;
}

if !path.is_empty() {
new_template = new_template.replace(to_replace_str, &path);
matched = true;
}
}
}
"relative_path" => {
{
let terminal = context.terminal.lock();
if let Some(current_directory) = &terminal.current_directory {
if let Ok(dir_str) =
current_directory.clone().into_os_string().into_string()
{
new_template = new_template
.replace(to_replace_str, &shorten_path(&dir_str));
matched = true;
continue;
}
};
}

#[cfg(unix)]
{
let path = teletypewriter::foreground_process_path(
*context.main_fd,
context.shell_pid,
)
.map(|p| shorten_path(&p.to_string_lossy()))
.unwrap_or_default();

let is_only_one = variables.len() == 1;
let is_last = i == variables.len() - 1;
if is_only_one || is_last {
new_template = new_template.replace(to_replace_str, &path);
continue;
}

if !path.is_empty() {
new_template = new_template.replace(to_replace_str, &path);
matched = true;
}
}
}
_ => {}
}
new_template = new_template.replace(to_replace_str, &value);
break;
}
}

Expand Down Expand Up @@ -348,6 +250,11 @@ pub mod test {
String::from("64")
);

assert_eq!(
update_title("{{ program || columns }}", &context),
String::from("64")
);

assert_eq!(
update_title("{{ title || title }}", &context),
String::from("")
Expand Down
24 changes: 5 additions & 19 deletions frontends/rioterm/src/screen/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2339,25 +2339,11 @@ impl Screen<'_> {
I: IntoIterator<Item = S> + Debug + Copy,
S: AsRef<OsStr>,
{
#[cfg(unix)]
{
let main_fd = *self.ctx().current().main_fd;
let shell_pid = &self.ctx().current().shell_pid;
match teletypewriter::spawn_daemon(program, args, main_fd, *shell_pid) {
Ok(_) => tracing::debug!("Launched {} with args {:?}", program, args),
Err(_) => {
tracing::warn!("Unable to launch {} with args {:?}", program, args)
}
}
}

#[cfg(windows)]
{
match teletypewriter::spawn_daemon(program, args) {
Ok(_) => tracing::debug!("Launched {} with args {:?}", program, args),
Err(_) => {
tracing::warn!("Unable to launch {} with args {:?}", program, args)
}
let cwd = self.ctx().current().foreground_process_path();
match teletypewriter::spawn_daemon(program, args, cwd.as_deref()) {
Ok(_) => tracing::debug!("Launched {} with args {:?}", program, args),
Err(_) => {
tracing::warn!("Unable to launch {} with args {:?}", program, args)
}
}
}
Expand Down
Loading
Loading