1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
//! Tab profile and title tracking methods.
//!
//! Provides methods for auto-updating tab titles from OSC sequences, tracking
//! hostname/CWD changes for automatic profile switching, and managing the
//! auto-profile lifecycle.
use crate::tab::Tab;
use crate::ui_constants::VISUAL_BELL_FLASH_DURATION_MS;
impl Tab {
/// Check if the visual bell is currently active (within flash duration)
pub fn is_bell_active(&self) -> bool {
// Use active_bell() to route through the focused pane in split-pane mode.
if let Some(flash_start) = self.active_bell().visual_flash {
flash_start.elapsed().as_millis() < VISUAL_BELL_FLASH_DURATION_MS
} else {
false
}
}
/// Update tab title from terminal OSC sequences or shell integration data.
///
/// Priority when on a **remote** host (hostname detected via OSC 7):
/// 1. Explicit OSC title (`\033]0;...\007`) if `remote_osc_priority` is true
/// 2. `remote_format` — formatted from hostname/username/cwd
///
/// Priority when **local**:
/// 1. Explicit OSC title
/// 2. Last CWD component (only in `TabTitleMode::Auto`)
///
/// User-named tabs are never auto-updated.
pub fn update_title(
&mut self,
title_mode: par_term_config::TabTitleMode,
remote_format: par_term_config::RemoteTabTitleFormat,
remote_osc_priority: bool,
) {
// User-named tabs are static — never auto-update
if self.user_named {
return;
}
// try_write: intentional — called every frame from the render path; blocking would
// stall rendering. On miss: title is not updated this frame. No data loss.
if let Ok(term) = self.terminal.try_write() {
// Collect all values in a single lock acquisition
let osc_title = term.get_title();
let hostname = term.shell_integration_hostname();
let username = term.shell_integration_username();
let cwd = term.shell_integration_cwd();
drop(term); // release lock before mutating self
// A terminal is "remote" only when the OSC 7 hostname differs from the
// local machine's hostname. `shell_integration_hostname()` returns
// `Some(local_hostname)` for ordinary local shells with shell integration
// enabled, so we must not treat every non-None value as a remote host.
//
// If we cannot determine the local hostname (hostname::get() error or
// non-UTF-8 result), we conservatively assume the tab is local.
let is_remote = if let Some(reported_host) = &hostname {
hostname::get()
.ok()
.and_then(|h| h.into_string().ok())
.map(|local| !reported_host.eq_ignore_ascii_case(&local))
.unwrap_or(false)
} else {
false
};
if is_remote {
if remote_osc_priority && !osc_title.is_empty() {
self.title = osc_title;
self.has_default_title = false;
} else {
self.title = format_remote_title(hostname, username, cwd, remote_format);
self.has_default_title = false;
}
} else if !osc_title.is_empty() {
self.title = osc_title;
self.has_default_title = false;
} else if title_mode == par_term_config::TabTitleMode::Auto
&& let Some(cwd) = cwd
{
// Abbreviate home directory to ~
let abbreviated = if let Some(home) = dirs::home_dir() {
cwd.replace(&home.to_string_lossy().to_string(), "~")
} else {
cwd
};
// Use just the last component for brevity (original pattern)
if let Some(last) = abbreviated.rsplit('/').next() {
if !last.is_empty() {
self.title = last.to_string();
} else {
self.title = abbreviated;
}
} else {
self.title = abbreviated;
}
self.has_default_title = false;
}
// else: keep existing title
}
}
/// Set the tab's default title based on its position
pub fn set_default_title(&mut self, tab_number: usize) {
if self.has_default_title {
self.title = format!("Tab {}", tab_number);
}
}
/// Explicitly set the tab title (for tmux window names, etc.)
///
/// This overrides any default title and marks the tab as having a custom title.
pub fn set_title(&mut self, title: &str) {
self.title = title.to_string();
self.has_default_title = false;
}
/// Check if the terminal in this tab is still running
pub fn is_running(&self) -> bool {
if let Ok(term) = self.terminal.try_write() {
term.is_running()
} else {
true // Assume running if locked
}
}
/// Get the current working directory of this tab's shell
pub fn get_cwd(&self) -> Option<String> {
if let Ok(term) = self.terminal.try_write() {
term.shell_integration_cwd()
} else {
self.working_directory.clone()
}
}
/// Set a custom color for this tab
pub fn set_custom_color(&mut self, color: [u8; 3]) {
self.custom_color = Some(color);
}
/// Clear the custom color for this tab (reverts to default config colors)
pub fn clear_custom_color(&mut self) {
self.custom_color = None;
}
/// Check if this tab has a custom color set
pub fn has_custom_color(&self) -> bool {
self.custom_color.is_some()
}
/// Parse hostname from an OSC 7 file:// URL
///
/// OSC 7 format: `file://hostname/path` or `file:///path` (localhost)
/// Returns the hostname if present and not localhost, None otherwise.
pub fn parse_hostname_from_osc7_url(url: &str) -> Option<String> {
let path = url.strip_prefix("file://")?;
if path.starts_with('/') {
// file:///path - localhost implicit
None
} else {
// file://hostname/path - extract hostname
let hostname = path.split('/').next()?;
if hostname.is_empty() || hostname == "localhost" {
None
} else {
Some(hostname.to_string())
}
}
}
/// Check if hostname has changed and update tracking
///
/// Returns Some(hostname) if a new remote hostname was detected,
/// None if hostname hasn't changed or is local.
///
/// This uses the hostname extracted from OSC 7 sequences by the terminal emulator.
pub fn check_hostname_change(&mut self) -> Option<String> {
let current_hostname = if let Ok(term) = self.terminal.try_write() {
term.shell_integration_hostname()
} else {
return None;
};
// Check if hostname has changed
if current_hostname != self.detected_hostname {
let old_hostname = self.detected_hostname.take();
self.detected_hostname = current_hostname.clone();
crate::debug_info!(
"PROFILE",
"Hostname changed: {:?} -> {:?}",
old_hostname,
current_hostname
);
// Return the new hostname if it's a remote host (not None/localhost)
current_hostname
} else {
None
}
}
/// Check if CWD has changed and update tracking
///
/// Returns Some(cwd) if the CWD has changed, None otherwise.
/// Uses the CWD reported via OSC 7 by the terminal emulator.
pub fn check_cwd_change(&mut self) -> Option<String> {
let current_cwd = self.get_cwd();
if current_cwd != self.detected_cwd {
let old_cwd = self.detected_cwd.take();
self.detected_cwd = current_cwd.clone();
crate::debug_info!("PROFILE", "CWD changed: {:?} -> {:?}", old_cwd, current_cwd);
current_cwd
} else {
None
}
}
/// Clear auto-applied profile tracking
///
/// Call this when manually switching profiles or when the hostname
/// returns to local, or when disconnecting from tmux.
pub fn clear_auto_profile(&mut self) {
self.profile.auto_applied_profile_id = None;
self.profile.auto_applied_dir_profile_id = None;
self.profile.profile_icon = None;
if let Some(original) = self.profile.pre_profile_title.take() {
self.title = original;
}
self.profile.badge_override = None;
}
}
/// Format a tab title for a remote host based on the configured format.
///
/// Uses the remote username to abbreviate the home directory in `HostAndCwd` mode
/// (e.g. `/home/alice/projects` → `~/projects`) rather than the local `$HOME`,
/// which never matches remote paths.
fn format_remote_title(
hostname: Option<String>,
username: Option<String>,
cwd: Option<String>,
format: par_term_config::RemoteTabTitleFormat,
) -> String {
use par_term_config::RemoteTabTitleFormat;
let host = hostname.unwrap_or_default();
match format {
RemoteTabTitleFormat::UserAtHost => {
if let Some(user) = username {
format!("{}@{}", user, host)
} else {
host
}
}
RemoteTabTitleFormat::Host => host,
RemoteTabTitleFormat::HostAndCwd => {
if let Some(cwd) = cwd {
let abbrev = if let Some(ref user) = username {
let linux_home = format!("/home/{}", user);
let macos_home = format!("/Users/{}", user);
let abbrev_with = |home: &str| -> Option<String> {
if cwd == home {
Some("~".to_string())
} else if cwd.starts_with(&format!("{}/", home)) {
Some(format!("~{}", &cwd[home.len()..]))
} else {
None
}
};
if let Some(a) = abbrev_with(&linux_home) {
a
} else if let Some(a) = abbrev_with(&macos_home) {
a
} else {
cwd
}
} else {
cwd
};
format!("{}:{}", host, abbrev)
} else {
host
}
}
}
}
#[cfg(test)]
mod format_remote_title_tests {
use super::format_remote_title;
use par_term_config::RemoteTabTitleFormat;
#[test]
fn user_at_host_with_both() {
let result = format_remote_title(
Some("server".into()),
Some("alice".into()),
None,
RemoteTabTitleFormat::UserAtHost,
);
assert_eq!(result, "alice@server");
}
#[test]
fn user_at_host_no_username_falls_back_to_host() {
let result = format_remote_title(
Some("server".into()),
None,
None,
RemoteTabTitleFormat::UserAtHost,
);
assert_eq!(result, "server");
}
#[test]
fn host_only() {
let result = format_remote_title(
Some("mybox".into()),
Some("bob".into()),
Some("/home/bob/projects".into()),
RemoteTabTitleFormat::Host,
);
assert_eq!(result, "mybox");
}
#[test]
fn host_and_cwd_abbreviates_linux_home() {
let result = format_remote_title(
Some("server".into()),
Some("alice".into()),
Some("/home/alice/projects/foo".into()),
RemoteTabTitleFormat::HostAndCwd,
);
assert_eq!(result, "server:~/projects/foo");
}
#[test]
fn host_and_cwd_abbreviates_macos_home() {
let result = format_remote_title(
Some("mac".into()),
Some("alice".into()),
Some("/Users/alice/dev".into()),
RemoteTabTitleFormat::HostAndCwd,
);
assert_eq!(result, "mac:~/dev");
}
#[test]
fn host_and_cwd_no_cwd_falls_back_to_host() {
let result = format_remote_title(
Some("server".into()),
Some("alice".into()),
None,
RemoteTabTitleFormat::HostAndCwd,
);
assert_eq!(result, "server");
}
#[test]
fn host_and_cwd_unknown_path_no_abbreviation() {
let result = format_remote_title(
Some("server".into()),
Some("alice".into()),
Some("/var/log".into()),
RemoteTabTitleFormat::HostAndCwd,
);
assert_eq!(result, "server:/var/log");
}
#[test]
fn host_and_cwd_does_not_abbreviate_partial_username_match() {
let result = format_remote_title(
Some("server".into()),
Some("alice".into()),
Some("/home/alice2/projects".into()),
RemoteTabTitleFormat::HostAndCwd,
);
assert_eq!(result, "server:/home/alice2/projects");
}
#[test]
fn host_and_cwd_exact_home_dir_shows_tilde() {
let result = format_remote_title(
Some("server".into()),
Some("alice".into()),
Some("/home/alice".into()),
RemoteTabTitleFormat::HostAndCwd,
);
assert_eq!(result, "server:~");
}
}
#[cfg(test)]
mod tests {
use crate::tab::Tab;
#[test]
fn test_parse_hostname_from_osc7_url_localhost() {
// file:///path - localhost implicit, should return None
assert_eq!(Tab::parse_hostname_from_osc7_url("file:///home/user"), None);
assert_eq!(Tab::parse_hostname_from_osc7_url("file:///"), None);
assert_eq!(
Tab::parse_hostname_from_osc7_url("file:///var/log/syslog"),
None
);
}
#[test]
fn test_parse_hostname_from_osc7_url_remote() {
// file://hostname/path - should extract hostname
assert_eq!(
Tab::parse_hostname_from_osc7_url("file://server.example.com/home/user"),
Some("server.example.com".to_string())
);
assert_eq!(
Tab::parse_hostname_from_osc7_url("file://myhost/tmp"),
Some("myhost".to_string())
);
assert_eq!(
Tab::parse_hostname_from_osc7_url("file://192.168.1.100/var/log"),
Some("192.168.1.100".to_string())
);
}
#[test]
fn test_parse_hostname_from_osc7_url_localhost_explicit() {
// file://localhost/path - localhost should return None
assert_eq!(
Tab::parse_hostname_from_osc7_url("file://localhost/home/user"),
None
);
}
#[test]
fn test_parse_hostname_from_osc7_url_invalid() {
// Invalid URLs should return None
assert_eq!(Tab::parse_hostname_from_osc7_url(""), None);
assert_eq!(
Tab::parse_hostname_from_osc7_url("http://example.com"),
None
);
assert_eq!(Tab::parse_hostname_from_osc7_url("/home/user"), None);
assert_eq!(Tab::parse_hostname_from_osc7_url("file://"), None);
}
#[test]
fn test_parse_hostname_from_osc7_url_edge_cases() {
// Empty hostname after file://
assert_eq!(Tab::parse_hostname_from_osc7_url("file:///"), None);
// Hostname with no path (unusual but valid)
assert_eq!(
Tab::parse_hostname_from_osc7_url("file://host"),
Some("host".to_string())
);
}
}