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
//! Prettify relay trigger processing for WindowState.
//!
//! Handles `Prettify` triggers that are relayed through the core MarkLine
//! system. Responsible for:
//! - Regex cache pre-population
//! - Command filter matching
//! - Scope range computation (Line, CommandOutput, Block)
//! - ContentBlock construction and pipeline dispatch
use std::collections::HashMap;
use std::time::SystemTime;
use crate::app::window_state::WindowState;
use crate::config::automation::{PrettifyRelayPayload, PrettifyScope};
use crate::prettifier::types::ContentBlock;
/// Output of [`WindowState::read_terminal_context`].
pub(super) struct TerminalContext {
/// Map from absolute scrollback line index to line text.
pub lines_by_abs: HashMap<usize, String>,
/// The command that preceded the first matched line (if any).
pub preceding_command: Option<String>,
/// Per-pending-event `(start_abs, end_abs)` scope range.
pub scope_ranges: Vec<(usize, usize)>,
}
use crate::tab::Tab;
impl WindowState {
/// Process collected prettify relay events.
///
/// Each event is a `(trigger_id, matched_grid_row, payload)` tuple relayed
/// through the core MarkLine system. This method:
/// 1. Checks the master prettifier toggle
/// 2. Handles `command_filter` scoping
/// 3. Routes `format: "none"` to suppression
/// 4. Builds `ContentBlock`s based on scope and dispatches to the pipeline
pub(super) fn apply_prettify_triggers(
&mut self,
pending: Vec<(u64, usize, PrettifyRelayPayload)>,
current_scrollback_len: usize,
) {
// Pre-populate the regex cache with all patterns from pending events.
// This is done before borrowing `tab` to avoid borrow-checker conflicts.
// Patterns that are already cached are skipped; invalid patterns are logged once.
for (trigger_id, _row, payload) in &pending {
if let Some(ref filter) = payload.command_filter
&& !self
.trigger_state
.trigger_regex_cache
.contains_key(filter.as_str())
{
match regex::Regex::new(filter) {
Ok(re) => {
self.trigger_state
.trigger_regex_cache
.insert(filter.clone(), re);
}
Err(e) => {
log::error!(
"Trigger {} prettify: invalid command_filter regex '{}': {}",
trigger_id,
filter,
e
);
}
}
}
if let Some(ref block_end) = payload.block_end
&& !self
.trigger_state
.trigger_regex_cache
.contains_key(block_end.as_str())
{
match regex::Regex::new(block_end) {
Ok(re) => {
self.trigger_state
.trigger_regex_cache
.insert(block_end.clone(), re);
}
Err(e) => {
log::error!(
"Trigger {} prettify: invalid block_end regex '{}': {}",
trigger_id,
block_end,
e
);
}
}
}
}
let tab = if let Some(t) = self.tab_manager.active_tab_mut() {
t
} else {
return;
};
// Check master toggle — if prettifier is disabled, skip all.
if let Some(ref pipeline) = tab.prettifier {
if !pipeline.is_enabled() {
return;
}
} else {
// No pipeline configured — nothing to do.
return;
}
// Read terminal content and metadata we need for scope handling.
// We lock the terminal once and extract everything we need.
let TerminalContext {
lines_by_abs,
preceding_command,
scope_ranges,
} = Self::read_terminal_context(tab, current_scrollback_len, &pending);
for (idx, (trigger_id, _grid_row, payload)) in pending.into_iter().enumerate() {
// Check command_filter: if set, only fire when the preceding command matches.
if let Some(ref filter) = payload.command_filter {
// Use the pre-compiled regex from the cache (populated before this loop).
// If the pattern was invalid it was logged above and not inserted — skip.
if let Some(re) = self.trigger_state.trigger_regex_cache.get(filter.as_str()) {
match preceding_command.as_deref() {
Some(cmd) if re.is_match(cmd) => {}
_ => {
log::debug!(
"Trigger {} prettify: command_filter '{}' did not match, skipping",
trigger_id,
filter
);
continue;
}
}
} else {
// Pattern was invalid (logged during pre-compilation above).
continue;
}
}
// Get the pre-computed scope range; narrow for Block scope if block_end is set.
let (start_abs, end_abs) = if let Some(&range) = scope_ranges.get(idx) {
if payload.scope == PrettifyScope::Block {
// Look up the pre-compiled block_end regex from the cache.
let block_end_re = payload
.block_end
.as_deref()
.and_then(|pat| self.trigger_state.trigger_regex_cache.get(pat));
Self::narrow_block_scope(range.0, range.1, block_end_re, &lines_by_abs)
} else {
range
}
} else {
continue;
};
log::info!(
"Trigger {} prettify: format='{}' scope={:?} rows={}..{}",
trigger_id,
payload.format,
payload.scope,
start_abs,
end_abs,
);
// Handle "none" format — suppress auto-detection for this range.
if payload.format == "none" {
if let Some(ref mut pipeline) = tab.prettifier {
pipeline.suppress_detection(start_abs..end_abs);
log::debug!(
"Trigger {} prettify: suppressed auto-detection for rows {}..{}",
trigger_id,
start_abs,
end_abs,
);
}
continue;
}
// Build the ContentBlock from the determined range.
let content_lines: Vec<String> = (start_abs..end_abs)
.filter_map(|abs| lines_by_abs.get(&abs).cloned())
.collect();
if content_lines.is_empty() {
log::debug!(
"Trigger {} prettify: no content in range {}..{}, skipping",
trigger_id,
start_abs,
end_abs,
);
continue;
}
let content = ContentBlock {
lines: content_lines,
preceding_command: preceding_command.clone(),
start_row: start_abs,
end_row: end_abs,
timestamp: SystemTime::now(),
};
// Dispatch to the pipeline, bypassing confidence scoring.
if let Some(ref mut pipeline) = tab.prettifier {
pipeline.trigger_prettify(&payload.format, content);
}
}
}
/// Read terminal content and metadata needed for prettify scope handling.
///
/// `scope_ranges` maps each pending index to its `(start_abs, end_abs)` range.
/// We read all needed lines in one lock acquisition to avoid contention.
pub(super) fn read_terminal_context(
tab: &Tab,
current_scrollback_len: usize,
pending: &[(u64, usize, PrettifyRelayPayload)],
) -> TerminalContext {
let mut lines_by_abs: HashMap<usize, String> = HashMap::new();
let mut scope_ranges: Vec<(usize, usize)> = Vec::with_capacity(pending.len());
let preceding_command;
// try_lock: intentional — prettify trigger processing in about_to_wait (sync loop).
// On miss: prettify is skipped this frame; the pending events are reprocessed next poll.
if let Ok(term) = tab.terminal.try_write() {
// Compute scope ranges for each pending event using scrollback metadata.
let max_readable = current_scrollback_len + 200; // generous upper bound for visible grid
for (_trigger_id, grid_row, payload) in pending {
let matched_abs = current_scrollback_len + grid_row;
let range = match payload.scope {
PrettifyScope::Line => (matched_abs, matched_abs + 1),
PrettifyScope::CommandOutput => {
// Use previous_mark/next_mark to find command output boundaries.
let output_start = term
.scrollback_previous_mark(matched_abs)
.map(|p| p + 1) // output starts after the prompt line
.unwrap_or(0);
let output_end = term
.scrollback_next_mark(matched_abs + 1)
.unwrap_or(max_readable);
(output_start, output_end)
}
PrettifyScope::Block => {
// For block scope, read from match to a reasonable limit.
// Actual block_end matching is done after reading.
(matched_abs, matched_abs + 500)
}
};
scope_ranges.push(range);
}
// Find the widest range we need to read.
let min_abs = scope_ranges.iter().map(|(s, _)| *s).min().unwrap_or(0);
let max_abs = scope_ranges.iter().map(|(_, e)| *e).max().unwrap_or(0);
// Read the lines in the determined range.
for abs_line in min_abs..max_abs {
if let Some(text) = term.line_text_at_absolute(abs_line) {
lines_by_abs.insert(abs_line, text);
}
}
// Get preceding command from the most recent mark before the first match.
let first_matched_abs = pending
.iter()
.map(|(_, row, _)| current_scrollback_len + row)
.min()
.unwrap_or(0);
preceding_command = term
.scrollback_previous_mark(first_matched_abs)
.and_then(|mark_line| term.scrollback_metadata_for_line(mark_line))
.and_then(|m| m.command);
} else {
return TerminalContext {
lines_by_abs,
preceding_command: None,
scope_ranges: Vec::new(),
};
}
TerminalContext {
lines_by_abs,
preceding_command,
scope_ranges,
}
}
/// Narrow a block scope range by scanning for a block_end regex match.
///
/// If `block_end_re` is set and matches a line in `lines_by_abs`, the range
/// is narrowed to `start..match+1`. Otherwise returns the original range.
///
/// Accepts a pre-compiled `Regex` reference to avoid hot-path recompilation.
pub(super) fn narrow_block_scope(
start_abs: usize,
end_abs: usize,
block_end_re: Option<®ex::Regex>,
lines_by_abs: &HashMap<usize, String>,
) -> (usize, usize) {
if let Some(re) = block_end_re {
for abs in (start_abs + 1)..end_abs {
if let Some(text) = lines_by_abs.get(&abs)
&& re.is_match(text)
{
return (start_abs, abs + 1); // Include the end line.
}
}
}
// No block_end found or no pattern — use original range capped to available content.
let max_available = lines_by_abs.keys().max().copied().unwrap_or(start_abs) + 1;
(start_abs, end_abs.min(max_available))
}
}