use serde::Serialize;
use crate::document_core::queries::grep::GrepMatch;
use crate::service::open::OpenedDocument;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct SearchOptions {
pub case_sensitive: bool,
pub limit: Option<usize>,
pub offset: usize,
pub context_paragraphs: Option<usize>,
}
impl Default for SearchOptions {
fn default() -> Self {
SearchOptions {
case_sensitive: true,
limit: None,
offset: 0,
context_paragraphs: None,
}
}
}
impl SearchOptions {
pub fn new() -> Self {
SearchOptions::default()
}
pub fn case_sensitive(mut self, case_sensitive: bool) -> Self {
self.case_sensitive = case_sensitive;
self
}
pub fn with_limit(mut self, limit: usize) -> Self {
self.limit = Some(limit);
self
}
pub fn with_offset(mut self, offset: usize) -> Self {
self.offset = offset;
self
}
pub fn with_context_paragraphs(mut self, context: usize) -> Self {
self.context_paragraphs = Some(context);
self
}
}
#[derive(Debug, Clone, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct SearchOutcome {
pub query: String,
pub case_sensitive: bool,
pub match_count: usize,
pub total_match_count: usize,
pub truncated: bool,
pub omitted_count: usize,
pub offset: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub next_offset: Option<usize>,
pub matches: Vec<GrepMatch>,
}
impl SearchOutcome {
pub fn is_empty(&self) -> bool {
self.total_match_count == 0
}
}
#[derive(Debug, Clone, Default, PartialEq, Eq)]
pub struct TextExportOptions {
pub pages: Option<Vec<u32>>,
pub max_chars: Option<usize>,
pub char_offset: usize,
}
impl TextExportOptions {
pub fn new() -> Self {
TextExportOptions::default()
}
pub fn with_pages(mut self, pages: Vec<u32>) -> Self {
self.pages = Some(pages);
self
}
pub fn with_max_chars(mut self, max_chars: usize) -> Self {
self.max_chars = Some(max_chars);
self
}
pub fn with_char_offset(mut self, char_offset: usize) -> Self {
self.char_offset = char_offset;
self
}
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct PageText {
pub page: u32,
pub text: String,
#[serde(skip_serializing_if = "std::ops::Not::not")]
pub truncated: bool,
#[serde(skip_serializing_if = "is_zero")]
pub omitted_count: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub extract_error: Option<String>,
}
#[allow(clippy::trivially_copy_pass_by_ref)]
fn is_zero(value: &usize) -> bool {
*value == 0
}
#[derive(Debug, Clone, PartialEq, Serialize)]
#[serde(rename_all = "camelCase")]
pub struct TextExport {
pub page_count: usize,
pub truncated: bool,
pub omitted_count: usize,
pub char_offset: usize,
#[serde(skip_serializing_if = "Option::is_none")]
pub next_offset: Option<usize>,
pub out_of_range: Vec<u32>,
pub pages: Vec<PageText>,
}
impl TextExport {
pub fn concatenated(&self) -> String {
let mut out = String::new();
for page in &self.pages {
if !out.is_empty() {
out.push('\n');
}
out.push_str(&page.text);
}
out
}
pub fn has_failures(&self) -> bool {
self.pages.iter().any(|p| p.extract_error.is_some())
}
}
impl OpenedDocument {
pub fn search(&self, query: &str, opts: &SearchOptions) -> SearchOutcome {
let all =
self.core
.grep_with_context(query, opts.case_sensitive, None, opts.context_paragraphs);
let total = all.len();
let skipped = all.into_iter().skip(opts.offset);
let matches: Vec<GrepMatch> = match opts.limit {
Some(limit) => skipped.take(limit).collect(),
None => skipped.collect(),
};
let consumed = opts.offset.saturating_add(matches.len());
SearchOutcome {
query: query.to_string(),
case_sensitive: opts.case_sensitive,
match_count: matches.len(),
total_match_count: total,
truncated: matches.len() < total,
omitted_count: total.saturating_sub(matches.len()),
offset: opts.offset,
next_offset: if consumed < total {
Some(consumed)
} else {
None
},
matches,
}
}
pub fn export_text(&self, opts: &TextExportOptions) -> TextExport {
let page_count = self.page_count();
let (selected, out_of_range): (Vec<u32>, Vec<u32>) = match &opts.pages {
Some(requested) => requested.iter().copied().partition(|p| *p < page_count),
None => ((0..page_count).collect(), Vec::new()),
};
let mut extracted: Vec<(u32, String, Option<String>)> = Vec::with_capacity(selected.len());
for page in selected {
match self.core.extract_page_text_native(page) {
Ok(text) => extracted.push((page, text, None)),
Err(error) => extracted.push((page, String::new(), Some(error.to_string()))),
}
}
let total_chars: usize = extracted.iter().map(|(_, t, _)| t.chars().count()).sum();
let mut skip = opts.char_offset;
let windowed: Vec<(u32, String, Option<String>)> = extracted
.into_iter()
.map(|(page, text, failure)| {
if skip == 0 {
return (page, text, failure);
}
let len = text.chars().count();
if skip >= len {
skip -= len;
(page, String::new(), failure)
} else {
let tail = text.chars().skip(skip).collect();
skip = 0;
(page, tail, failure)
}
})
.collect();
let mut budget = opts.max_chars;
let mut omitted_total = 0usize;
let mut shown_chars = 0usize;
let mut pages = Vec::with_capacity(windowed.len());
for (page, text, extract_error) in windowed {
let total = text.chars().count();
let keep = match budget {
Some(remaining) => remaining.min(total),
None => total,
};
if let Some(remaining) = budget.as_mut() {
*remaining -= keep;
}
let omitted = total - keep;
omitted_total += omitted;
shown_chars += keep;
let kept: String = if omitted == 0 {
text
} else {
text.chars().take(keep).collect()
};
pages.push(PageText {
page,
text: kept,
truncated: omitted > 0,
omitted_count: omitted,
extract_error,
});
}
let consumed = opts.char_offset.saturating_add(shown_chars);
TextExport {
page_count: pages.len(),
truncated: omitted_total > 0,
omitted_count: omitted_total,
char_offset: opts.char_offset,
next_offset: if consumed < total_chars {
Some(consumed)
} else {
None
},
out_of_range,
pages,
}
}
}