Compare commits

...

2 Commits

Author SHA1 Message Date
e64aee2b31 checkpoint 2025-03-27 00:54:58 -06:00
3e7509a9c7 improved search and focus 2025-03-26 23:35:07 -06:00
2 changed files with 179 additions and 77 deletions

View File

@ -1,7 +1,7 @@
#![feature(iter_map_windows)] #![feature(iter_map_windows)]
use iced::{ use iced::{
Element, Element, Task, clipboard,
widget::{self, column, combo_box}, widget::{self, button, column, combo_box, row, scrollable, text, text_input},
}; };
use std::{env, fs, path::PathBuf}; use std::{env, fs, path::PathBuf};
use texts::*; use texts::*;
@ -11,6 +11,7 @@ mod texts;
pub const BIBLE_DIRECTORY: &str = "./Holy-Bible-XML-Format"; pub const BIBLE_DIRECTORY: &str = "./Holy-Bible-XML-Format";
fn main() -> iced::Result { fn main() -> iced::Result {
// CLI
let arg = env::args().collect::<Vec<String>>(); let arg = env::args().collect::<Vec<String>>();
if let Some(query) = arg.get(1) { if let Some(query) = arg.get(1) {
if query.starts_with("H") | query.starts_with("h") { if query.starts_with("H") | query.starts_with("h") {
@ -20,33 +21,43 @@ fn main() -> iced::Result {
} }
} }
if let Some(second_query) = arg.get(2) { if let Some(second_query) = arg.get(2) {
if let Some(f) = bible::get( // if let Some(f) = bible::get( query, second_query, vec![format!("{BIBLE_DIRECTORY}/EnglishNASBBible.xml").into()],
query, // ) {
second_query, // println!("{}", f);
vec![format!("{BIBLE_DIRECTORY}/EnglishNASBBible.xml").into()], // }
) { return Ok(());
println!("{}", f);
}
return Ok(())
} }
} }
// GUI
iced::run("Bible Search", State::update, State::view) iced::run("Bible Search", State::update, State::view)
} }
#[derive(Debug, Clone)] #[derive(Debug, Clone)]
enum Message { enum Message {
InputChange(String), BibleSearchInput(String),
BibleSelected(String), BibleSelected(String),
SubmitQuery, BibleSearchSubmit,
CopyText,
Clear,
WordSearchInput(String),
SubmitWordSearch,
QuickSearch(String),
AddColRight,
} }
struct State { struct State {
files: combo_box::State<String>, files: combo_box::State<String>,
file_selected: Option<String>, selected_file: Option<String>,
bible_selected: Option<bible::Bible>,
query: String, bible_search: String,
body: Option<String>, scripture_body: Option<String>,
word_search: String,
word_search_results: Option<Vec<String>>,
cols: usize,
} }
impl Default for State { impl Default for State {
fn default() -> Self { fn default() -> Self {
@ -74,57 +85,127 @@ impl Default for State {
Self { Self {
files: combo_box::State::new(files), files: combo_box::State::new(files),
file_selected: None, selected_file: None,
bible_selected: None,
query: String::new(), bible_search: String::new(),
body: None, scripture_body: None,
word_search: String::new(),
word_search_results: None,
cols: 1,
} }
} }
} }
impl State { impl State {
fn update(&mut self, msg: Message) { fn update(&mut self, msg: Message) -> Task<Message> {
match msg { match msg {
Message::AddColRight => self.cols += 1,
Message::BibleSelected(file) => { Message::BibleSelected(file) => {
self.file_selected = Some(file); if let Ok(contents) = fs::read_to_string(&file) {
if let Ok(bible) = quick_xml::de::from_str::<bible::Bible>(&contents) {
// State is held technically in this variable, although
// the Bible is held in memory in it's own variable.
self.selected_file = Some(format!("{bible}"));
self.bible_selected = Some(bible);
// automatically focus the search bar when done here
return text_input::focus("bible-search");
}
}
} }
Message::InputChange(query) => { Message::QuickSearch(s) => {
// update self's state self.bible_search = s;
self.query = query; return self.update(Message::BibleSearchSubmit);
} }
Message::SubmitQuery => { Message::BibleSearchInput(query) => self.bible_search = query,
let mut splits = self.query.split_whitespace(); Message::WordSearchInput(query) => self.word_search = query,
Message::BibleSearchSubmit => {
let mut splits = self.bible_search.split_whitespace();
let book = splits.next(); let book = splits.next();
let location = splits.next(); let location = splits.next();
if let (Some(book), Some(chap_and_ver), Some(file)) = if let (Some(book), Some(chap_and_ver), Some(bible)) =
(book, location, &self.file_selected) (book, location, &self.bible_selected)
{ {
self.body = bible::get(book, chap_and_ver, vec![file.into()]); self.scripture_body = bible::get(book, chap_and_ver, vec![bible]);
} }
} }
} Message::SubmitWordSearch => {
if let Some(bible) = &self.bible_selected {
let res = bible::search_for_word(&self.word_search, bible);
self.word_search_results = Some(res);
}
}
Message::CopyText => {
if let Some(text) = &self.scripture_body {
return clipboard::write::<Message>(parse(text));
}
}
Message::Clear => {
self.scripture_body = None;
self.word_search_results = None;
self.bible_search = String::new();
self.word_search = String::new();
return text_input::focus("bible-search");
}
};
Task::none()
} }
fn view(&self) -> Element<Message> { fn view(&self) -> Element<Message> {
let msg = if let Some(body) = self.body.clone() { let body = if let Some(body) = self.scripture_body.clone() {
parse(&body) parse(&body)
} else { } else {
"None".to_string() String::new()
}; };
column![ scrollable(row((0..self.cols).map(|_| {
widget::combo_box( row![
&self.files, button("-"),
"Select Bible", column![
self.file_selected.as_ref(), combo_box(
Message::BibleSelected &self.files,
), "Select Bible",
widget::text_input("Search query, ie: Gen 1:1", &self.query) self.selected_file.as_ref(),
.on_input(Message::InputChange) Message::BibleSelected
.on_submit(Message::SubmitQuery), ),
widget::text(msg), text_input("Search query, ie: Gen 1:1", &self.bible_search)
] .on_input(Message::BibleSearchInput)
.on_submit(Message::BibleSearchSubmit)
.id("bible-search"),
widget::text_input("Word Search", &self.word_search)
.on_input(Message::WordSearchInput)
.on_submit(Message::SubmitWordSearch)
.id("word-search"),
row![
button("Clear All").on_press(Message::Clear),
button("Copy Scripture").on_press(Message::CopyText),
],
row![
scrollable(column(
self.word_search_results
.clone()
.unwrap_or(Vec::new())
.into_iter()
.map(|i| button(text(i.clone()))
.on_press_with(move || Message::QuickSearch(i.to_owned()))
.into())
)),
scrollable(text(body.clone()))
],
],
button(text("+").center())
.height(iced::Length::FillPortion(1))
.on_press(Message::AddColRight)
]
.into()
})))
.direction(scrollable::Direction::Both {
vertical: scrollable::Scrollbar::new(),
horizontal: scrollable::Scrollbar::new(),
})
.into() .into()
} }
} }
@ -135,7 +216,7 @@ fn parse(input: &str) -> String {
.bytes() .bytes()
.into_iter() .into_iter()
.enumerate() .enumerate()
.map_windows(|[(ai, a), (bi, b)]| { .map_windows(|[(ai, a), (_, b)]| {
// 27 91 is the start sequence for a color/style // 27 91 is the start sequence for a color/style
if *a == 27 && *b == 91 { if *a == 27 && *b == 91 {
Some(*ai) Some(*ai)
@ -200,11 +281,11 @@ fn parse(input: &str) -> String {
to_remove.reverse(); to_remove.reverse();
let mut modified = input.to_owned(); let mut modified = input.to_owned();
for (s,e) in to_remove { for (s, e) in to_remove {
let front = modified[..s].to_string(); let front = modified[..s].to_string();
let back = modified[e+1..].to_string(); let back = modified[e + 1..].to_string();
modified = front + &back; modified = front + &back;
} }
modified modified
} }

View File

@ -1,7 +1,6 @@
use inline_colorization::*; use inline_colorization::*;
use std::{fmt::Display, fs, path::PathBuf}; use std::fmt::Display;
use quick_xml::de::from_str;
use serde::Deserialize; use serde::Deserialize;
pub const BOOKS_IN_ORDER: [&str; 66] = [ pub const BOOKS_IN_ORDER: [&str; 66] = [
@ -13,12 +12,12 @@ pub const BOOKS_IN_ORDER: [&str; 66] = [
"Joshua", "Joshua",
"Judges", "Judges",
"Ruth", "Ruth",
"1 Samuel", "1-Samuel",
"2 Samuel", "2-Samuel",
"1 Kings", "1-Kings",
"2 Kings", "2-Kings",
"1 Chronicles", "1-Chronicles",
"2 Chronicles", "2-Chronicles",
"Ezra", "Ezra",
"Nehemiah", "Nehemiah",
"Esther", "Esther",
@ -26,7 +25,7 @@ pub const BOOKS_IN_ORDER: [&str; 66] = [
"Psalms", "Psalms",
"Proverbs", "Proverbs",
"Ecclesiastes", "Ecclesiastes",
"Song of Solomon", "Song-of-Solomon",
"Isaiah", "Isaiah",
"Jeremiah", "Jeremiah",
"Lamentations", "Lamentations",
@ -50,30 +49,46 @@ pub const BOOKS_IN_ORDER: [&str; 66] = [
"John", "John",
"Acts", "Acts",
"Romans", "Romans",
"1 Corinthians", "1-Corinthians",
"2 Corinthians", "2-Corinthians",
"Galations", "Galations",
"Ephesians", "Ephesians",
"Philippians", "Philippians",
"Colossians", "Colossians",
"1 Thessalonians", "1-Thessalonians",
"2 Thessalonians", "2-Thessalonians",
"1 Timothy", "1-Timothy",
"2 Timothy", "2-Timothy",
"Titus", "Titus",
"Philemon", "Philemon",
"Hebrews", "Hebrews",
"James", "James",
"1 Peter", "1-Peter",
"2 Peter", "2-Peter",
"1 John", "1-John",
"2 John", "2-John",
"3 John", "3-John",
"Jude", "Jude",
"Revelation", "Revelation",
]; ];
pub fn get(book: &str, chap_and_ver: &str, from_files: Vec<PathBuf>) -> Option<String> { pub fn search_for_word(word: &str, from_files: &Bible) -> Vec<String> {
let mut found = Vec::new();
for test in &from_files.testaments {
for book in &test.books {
for chapter in &book.chapters {
for verse in &chapter.verses {
if verse.text.contains(word) {
found.push(format!("{} {}:{}", BOOKS_IN_ORDER[book.number-1], chapter.number, verse.number));
}
}
}
}
}
found
}
pub fn get(book: &str, chap_and_ver: &str, bibles: Vec<&Bible>) -> Option<String> {
// expecting query to be in format: // expecting query to be in format:
// Gen 1:2 // Gen 1:2
// Gen 1:2-5 // Gen 1:2-5
@ -89,7 +104,14 @@ pub fn get(book: &str, chap_and_ver: &str, from_files: Vec<PathBuf>) -> Option<S
let res = BOOKS_IN_ORDER let res = BOOKS_IN_ORDER
.iter() .iter()
.enumerate() .enumerate()
.filter(|(_, lbook)| lbook.to_lowercase().contains(&book.trim().to_lowercase())) .filter(|(_, lbook)| lbook
.to_lowercase()
.starts_with(&book
.trim()
.replace(" ", "-")
.to_lowercase()
)
)
.collect::<Vec<(usize, &&str)>>(); .collect::<Vec<(usize, &&str)>>();
let (book_idx, book_name) = match res.len() { let (book_idx, book_name) = match res.len() {
@ -107,19 +129,13 @@ pub fn get(book: &str, chap_and_ver: &str, from_files: Vec<PathBuf>) -> Option<S
} }
}; };
// Load Bibles into memory
let bibles = from_files
.iter()
.filter_map(|path| fs::read_to_string(path).ok())
.filter_map(|contents| from_str::<Bible>(&contents).ok())
.collect::<Vec<Bible>>();
// Select the book in each Bible // Select the book in each Bible
let books = bibles let books = bibles
.iter() .iter()
// Book are 1 indexed in the xml spec // Book are 1 indexed in the xml spec
.map(|bible| (bible, bible.get_book_by_index(book_idx + 1))) .map(|bible| (bible, bible.get_book_by_index(book_idx + 1)))
.filter(|(_,e)| e.is_some()) .filter(|(_,e)| e.is_some())
.map(|(bible,book)| (bible,book.unwrap())) .map(|(bible,book)| (*bible,book.unwrap()))
.collect::<Vec<(&Bible,&Book)>>(); .collect::<Vec<(&Bible,&Book)>>();
// Select the chapter in each Bible // Select the chapter in each Bible
@ -237,12 +253,17 @@ impl Chapter {
} }
#[derive(Deserialize)] #[derive(Deserialize)]
struct Bible { pub struct Bible {
#[serde(rename = "@translation")] #[serde(rename = "@translation")]
translation_name: String, translation_name: String,
#[serde(rename = "testament")] #[serde(rename = "testament")]
testaments: Vec<Testament>, testaments: Vec<Testament>,
} }
impl Display for Bible {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
write!(f, "{}",self.translation_name)
}
}
#[derive(Deserialize)] #[derive(Deserialize)]
struct Testament { struct Testament {