use std::ops::Range;
use std::sync::{Arc, Mutex};
use std::time::Duration;
use bigtext::jobs::{self, CancelToken, Throttle};
use bigtext::search::{self, Matcher, Query, SearchEnd};
use bigtext::text::TextBuf;
use super::filter_panel::fmt_count;
use super::i18n::{tr, trf};
use super::{BigTextApp, Msg};
const MARK_EVERY: u64 = 4096;
const MARK_GAP: u64 = 4 << 20;
pub struct MatchCount {
pub query: Query,
pub version: u64,
pub len: u64,
pub data: Arc<Mutex<CountData>>,
pub cancel: CancelToken,
pub asked: Option<(u64, u64)>,
pub number: Option<((u64, u64), Option<u64>)>,
}
#[derive(Default)]
pub struct CountData {
pub total: u64,
pub done: bool,
pub marks: Vec<(u64, u64)>,
}
fn count(
buf: &TextBuf,
m: &Matcher,
range: Range<u64>,
data: &Mutex<CountData>,
cancel: &CancelToken,
mut wake: impl FnMut(),
) -> SearchEnd {
let mut total = 0u64;
let mut marks = Vec::new();
let mut last: Option<(u64, u64)> = None;
let mut throttle = Throttle::new(Duration::from_millis(100));
let end = search::search_forward_par(buf, m, range, cancel, None, |s, _| {
if last.is_none_or(|(at, n)| total - n >= MARK_EVERY || s - at >= MARK_GAP) {
marks.push((s, total));
last = Some((s, total));
}
total += 1;
if throttle.ready() {
let mut g = data.lock().unwrap();
g.total = total;
g.marks.append(&mut marks);
drop(g);
wake();
}
true
});
let mut g = data.lock().unwrap();
g.total = total;
g.marks.append(&mut marks);
g.done = end == SearchEnd::Completed;
end
}
fn number_of(
buf: &TextBuf,
m: &Matcher,
marks: &[(u64, u64)],
sel: (u64, u64),
cancel: &CancelToken,
) -> Option<u64> {
let (s, e) = sel;
let i = marks.partition_point(|&(at, _)| at <= s).checked_sub(1)?;
let (from, mut n) = marks[i];
let mut number = None;
let end = (e + m.overlap()).min(buf.len());
search::search_forward(buf, m, from..end, cancel, None, |a, b| {
if a < s {
n += 1;
return true;
}
if (a, b) == sel {
number = Some(n + 1);
}
false
});
number.filter(|_| !cancel.is_cancelled())
}
impl BigTextApp {
pub(super) fn start_match_count(&mut self) {
let query = self.search.query.clone();
let Some(d) = self.docs.get(self.active) else {
return;
};
if !self.search.open
|| query.pattern.is_empty()
|| !d.is_ready()
|| d.remote_ssh.is_some()
|| d.buf.source.is_remote()
|| d.growing.is_some()
{
return;
}
let (version, len) = (d.version, d.buf.len());
if d.match_count
.as_ref()
.is_some_and(|c| c.query == query && c.version == version && c.len == len)
|| self.complete_results().is_some()
{
return;
}
let Ok(m) = self.search.matcher(d.buf.codec) else {
return;
};
let d = &mut self.docs[self.active];
if let Some(c) = d.match_count.take() {
c.cancel.cancel();
}
let data = Arc::new(Mutex::new(CountData::default()));
let cancel = CancelToken::new();
d.match_count = Some(MatchCount {
query,
version,
len,
data: data.clone(),
cancel: cancel.clone(),
asked: None,
number: None,
});
let snap = d.buf.snapshot();
let waker = self.waker.clone();
jobs::spawn("match-count", move || {
count(&snap, &m, 0..len, &data, &cancel, || waker());
waker();
});
}
fn complete_results(&self) -> Option<Arc<Mutex<super::search_panel::ResultsData>>> {
let d = self.docs.get(self.active)?;
let r = d.results.as_ref()?;
let g = r.data.lock().unwrap();
(g.done
&& !g.capped
&& g.end == Some(SearchEnd::Completed)
&& r.query == self.search.query
&& r.version == d.version
&& r.range == (0..d.buf.len()))
.then(|| r.data.clone())
}
pub(super) fn match_count_tick(&mut self) {
let query = &self.search.query;
for d in &mut self.docs {
let stale = d.match_count.as_ref().is_some_and(|c| {
c.query != *query || c.version != d.version || c.len != d.buf.len()
});
if stale {
if let Some(c) = d.match_count.take() {
c.cancel.cancel();
}
}
}
let Some(d) = self.docs.get_mut(self.active) else {
return;
};
let Some(sel) = d.last_found.filter(|&f| f == d.selection()) else {
return;
};
let Some(c) = d.match_count.as_mut() else {
return;
};
if c.asked == Some(sel) || !c.data.lock().unwrap().done {
return;
}
c.asked = Some(sel);
let Ok(m) = self.search.matcher(d.buf.codec) else {
return;
};
let d = &self.docs[self.active];
let c = d.match_count.as_ref().unwrap();
let (data, cancel, snap) = (c.data.clone(), c.cancel.clone(), d.buf.snapshot());
let (doc, version, tx, waker) = (d.id, d.version, self.tx.clone(), self.waker.clone());
jobs::spawn("match-number", move || {
let marks = data.lock().unwrap().marks.clone();
let number = number_of(&snap, &m, &marks, sel, &cancel);
if !cancel.is_cancelled() {
let _ = tx.send(Msg::MatchNumber {
doc,
version,
sel,
number,
});
waker();
}
});
}
pub(super) fn on_match_number(
&mut self,
doc: u64,
version: u64,
sel: (u64, u64),
number: Option<u64>,
) {
let Some(d) = self.docs.iter_mut().find(|d| d.id == doc) else {
return;
};
if let Some(c) = d.match_count.as_mut().filter(|_| d.version == version) {
c.number = Some((sel, number));
}
}
pub(crate) fn match_counter(&self) -> Option<(String, String)> {
let d = self.docs.get(self.active)?;
if self.search.query.pattern.is_empty() {
return None;
}
let sel = d.selection();
let on_found = d.last_found == Some(sel);
let tip = tr("Matches of the pattern in the whole file, counted in the background");
let text = |i: Option<u64>, n: String| {
let i = i.map_or_else(|| "?".to_string(), fmt_count);
trf("{i} of {n}", &[("i", &i), ("n", &n)])
};
if let Some(r) = self.complete_results() {
let v = &r.lock().unwrap().matches;
if v.is_empty() {
return Some((tr("No matches").into(), tip.into()));
}
let i = v.partition_point(|&(s, _)| s < sel.0);
let i = (on_found && v.get(i) == Some(&sel)).then_some(i as u64 + 1);
return Some((text(i, fmt_count(v.len() as u64)), tip.into()));
}
let c = d.match_count.as_ref()?;
let g = c.data.lock().unwrap();
if g.done && g.total == 0 {
return Some((tr("No matches").into(), tip.into()));
}
let mut n = fmt_count(g.total);
if !g.done {
n.push('…');
}
let i = match c.number {
Some((at, i)) if on_found && at == sel => i,
_ => None,
};
Some((text(i, n), tip.into()))
}
}
#[cfg(test)]
mod tests {
use super::*;
use bigtext::encoding::Codec;
use std::io::Write;
fn buf_with(data: &[u8]) -> (tempfile::NamedTempFile, TextBuf) {
let mut f = tempfile::NamedTempFile::new().unwrap();
f.write_all(data).unwrap();
f.flush().unwrap();
let src =
Arc::new(bigtext::file::Source::open(f.path(), bigtext::file::OpenMode::Auto).unwrap());
let idx = bigtext::index::build_blocking(&src, Codec::utf8());
let mut t = TextBuf::new(src, idx, Codec::utf8());
t.blocking = true;
(f, t)
}
fn matcher(pattern: &str, regex: bool) -> Matcher {
let q = Query {
pattern: pattern.into(),
regex,
..Query::default()
};
Matcher::new(&q, Codec::utf8()).unwrap()
}
#[test]
fn counts_and_numbers_every_match() {
let mut data = Vec::new();
for i in 0..10_000 {
writeln!(data, "line {i} foo").unwrap();
}
data.extend(std::iter::repeat_n(b'.', 9 << 20));
data.extend_from_slice(b"\nfoo at the end foo\n");
let (_f, t) = buf_with(&data);
let m = matcher("foo", false);
let cd = Mutex::new(CountData::default());
let cancel = CancelToken::new();
let end = count(&t, &m, 0..t.len(), &cd, &cancel, || {});
let g = cd.lock().unwrap();
assert_eq!((end, g.done, g.total), (SearchEnd::Completed, true, 10_002));
assert_eq!(
g.marks[0],
(data.windows(3).position(|w| w == b"foo").unwrap() as u64, 0)
);
assert!(g.marks.windows(2).all(|w| w[1].1 - w[0].1 <= MARK_EVERY));
let mut all = Vec::new();
search::search_forward(&t, &m, 0..t.len(), &cancel, None, |s, e| {
all.push((s, e));
true
});
for (i, &sel) in all
.iter()
.enumerate()
.step_by(97)
.chain(all.iter().enumerate().rev().take(3))
{
assert_eq!(
number_of(&t, &m, &g.marks, sel, &cancel),
Some(i as u64 + 1),
"{sel:?}"
);
}
let (s, e) = all[5];
assert_eq!(number_of(&t, &m, &g.marks, (s + 1, e), &cancel), None);
assert_eq!(number_of(&t, &m, &g.marks, (0, 3), &cancel), None);
}
#[test]
fn a_match_inside_a_counted_one_has_no_number() {
let (_f, t) = buf_with(b"aaaa\n");
let m = matcher("aa", false);
let cd = Mutex::new(CountData::default());
let cancel = CancelToken::new();
count(&t, &m, 0..t.len(), &cd, &cancel, || {});
let g = cd.lock().unwrap();
assert_eq!(g.total, 2);
assert_eq!(number_of(&t, &m, &g.marks, (2, 4), &cancel), Some(2));
assert_eq!(number_of(&t, &m, &g.marks, (1, 3), &cancel), None);
let m = matcher("a+", true);
let cd = Mutex::new(CountData::default());
count(&t, &m, 0..t.len(), &cd, &cancel, || {});
let g = cd.lock().unwrap();
assert_eq!(number_of(&t, &m, &g.marks, (0, 4), &cancel), Some(1));
}
#[test]
fn a_cancelled_count_is_not_done() {
let (_f, t) = buf_with(b"foo foo foo\n");
let m = matcher("foo", false);
let cd = Mutex::new(CountData::default());
let cancel = CancelToken::new();
cancel.cancel();
count(&t, &m, 0..t.len(), &cd, &cancel, || {});
assert!(!cd.lock().unwrap().done);
}
}