bible/src/main.rs
Oliver Atkinson 8a7804e780 formatting
2025-04-08 13:04:34 -06:00

468 lines
18 KiB
Rust

#![feature(iter_map_windows)]
use iced::keyboard::key::Named;
use iced::keyboard::{Key, Modifiers};
use iced::{event, Event, Subscription};
use iced::widget::scrollable;
use iced::{
Element, Length, Task, Theme, clipboard, color,
widget::{
button, column, combo_box, row,
scrollable::{Direction, Scrollbar},
text, text_input,
},
};
use std::{env, fs, path::PathBuf};
use texts::*;
mod texts;
pub const BIBLE_DIRECTORY: &str = "./Holy-Bible-XML-Format";
fn main() -> iced::Result {
// CLI
let arg = env::args().collect::<Vec<String>>();
if let Some(query) = arg.get(1) {
if query.starts_with("H") | query.starts_with("h") {
if let Some(found) = strong::get(query) {
print!("{found}");
return Ok(());
}
}
if let Some(second_query) = arg.get(2) {
if let Ok(contents) = fs::read_to_string(&format!("{BIBLE_DIRECTORY}/EnglishNASBBible.xml")) {
if let Ok(bible) = quick_xml::de::from_str::<bible::Bible>(&contents) {
if let Ok(f) = bible::get(
query,
second_query,
vec![&bible],
) {
println!("{}", f);
}
}
}
return Ok(());
}
}
// THEMES
// Dark - KanagawaDragon
// Default - Nord
// Light - TokyoNightLight
// GUI
iced::application("Bible Study", State::update, State::view)
.subscription(State::subscription)
.theme(|_| Theme::Nord)
.run()
}
#[derive(Debug, Clone)]
enum Message {
BibleSearchInput(usize, String),
BibleSelected(usize, String),
BibleSearchSubmit(usize),
CopyText(usize),
Clear(usize),
WordSearchInput(usize, String),
SubmitWordSearch(usize),
QuickSearch(usize, String, usize),
AddColRight,
DeleteColumn(usize),
SetErrorMessage(usize, String),
RecievedEvent(Event),
}
struct ColState {
selected_file: Option<String>,
bible_selected: Option<bible::Bible>,
bible_search: String,
scripture_body: Option<String>,
word_search: String,
word_search_results: Option<Vec<(String, bool)>>,
error: Option<String>,
}
impl Default for ColState {
fn default() -> Self {
Self {
selected_file: None,
bible_selected: None,
bible_search: String::new(),
scripture_body: None,
word_search: String::new(),
word_search_results: None,
error: None,
}
}
}
struct State {
files: combo_box::State<String>,
states: Vec<ColState>,
cols: usize,
tab_index: Option<i32>,
}
impl Default for State {
fn default() -> Self {
let files = if let Ok(contents) = fs::read_dir(BIBLE_DIRECTORY) {
let paths = contents
.into_iter()
.filter_map(|f| f.ok())
.map(|f| (f.path(), f.file_type()))
.filter(|(_, f)| f.is_ok())
.map(|(a, b)| (a, b.unwrap()))
.filter(|(_, f)| f.is_file())
.map(|(f, _)| f)
.filter(|f| f.extension().is_some())
.filter(|f| f.extension().unwrap() == "xml")
.collect::<Vec<PathBuf>>();
paths
} else {
todo!()
};
let files = files
.iter()
.filter_map(|f| f.to_str())
.map(|f| f.to_owned())
.collect::<Vec<String>>();
Self {
files: combo_box::State::new(files),
states: vec![ColState::default()],
cols: 1,
tab_index: None,
}
}
}
impl State {
fn subscription(&self) -> Subscription<Message> {
event::listen().map(Message::RecievedEvent)
}
fn update(&mut self, msg: Message) -> Task<Message> {
// match normal messages
match msg {
Message::RecievedEvent(event) => {
if let Event::Keyboard(kbd) = event {
if let iced::keyboard::Event::KeyReleased {key, modifiers, ..} = kbd {
if let Key::Named(n) = key {
if let Named::Tab = n {
if let Some(idx) = self.tab_index {
let new_idx = if modifiers == Modifiers::SHIFT { idx-1 } else { idx+1 };
// 2 because two buttons on each col
let new_idx = new_idx.clamp(0, (self.cols*2) as i32 -1);
self.tab_index = Some(new_idx);
let id = format!("tabId-{}", new_idx);
return text_input::focus(id);
} else {
if self.cols > 0 {
self.tab_index = Some(0);
return text_input::focus("tabId-0");
}
}
}
}
}
}
}
Message::SetErrorMessage(i, m) => {
self.states[i].error = Some(m);
}
Message::DeleteColumn(idx) => {
self.cols -= 1;
self.states.remove(idx);
}
Message::AddColRight => {
self.cols += 1;
// clone this state into the new one
// self.states.push(self.states.into_iter().last().unwrap().clone())
self.states.push(ColState::default())
}
Message::BibleSelected(i, file) => {
match fs::read_to_string(&file) {
Ok(contents) => {
match quick_xml::de::from_str::<bible::Bible>(&contents) {
Ok(bible) => {
// State is held technically in this variable, although
// the Bible is held in memory in it's own variable.
self.states[i].selected_file = Some(format!("{bible}"));
self.states[i].bible_selected = Some(bible);
self.states[i].error = None;
}
Err(err) => {
eprintln!("{}", err);
return self.update(Message::SetErrorMessage(i, err.to_string()));
},
}
},
Err(err) => {
eprintln!("{}", err);
return self.update(Message::SetErrorMessage(i, err.to_string()));
}
}
}
Message::QuickSearch(i, s, result_index) => {
self.states[i].bible_search = s;
if let Some(wsr) = &mut self.states[i].word_search_results {
// set "visited" for this link
wsr[result_index].1 = true;
}
return self.update(Message::BibleSearchSubmit(i));
}
Message::BibleSearchInput(i, query) => self.states[i].bible_search = query,
Message::WordSearchInput(i, query) => self.states[i].word_search = query,
Message::BibleSearchSubmit(i) => {
let mut splits = self.states[i].bible_search.split_whitespace();
let book = splits.next();
let location = splits.next();
if let (Some(book), Some(chap_and_ver), Some(bible)) =
(book, location, &self.states[i].bible_selected)
{
self.states[i].scripture_body = match bible::get(book, chap_and_ver, vec![bible]) {
Ok(s) => {
self.states[i].error = None;
Some(s)
},
Err(s) => {
return self.update(Message::SetErrorMessage(i, s));
},
};
} else {
if let None = book {
return self.update(Message::SetErrorMessage(i, format!("Error selecting book {:?}", book)));
}
if let None = location {
return self.update(Message::SetErrorMessage(i, format!("Error getting chapter and/or verse {:?}", location)));
}
if let None = &self.states[i].bible_selected {
return self.update(Message::SetErrorMessage(i, format!("Error getting selected bible")));
}
}
}
Message::SubmitWordSearch(i) => {
if let Some(bible) = &self.states[i].bible_selected {
let res = bible::search_for_word(&self.states[i].word_search, bible);
self.states[i].word_search_results = Some(
res
.into_iter()
.map(|f| (f, false))
.collect()
);
}
}
Message::CopyText(i) => {
if let Some(text) = &self.states[i].scripture_body {
return clipboard::write::<Message>(parse(text));
}
}
Message::Clear(i) => {
self.states[i].scripture_body = None;
self.states[i].word_search_results = None;
self.states[i].bible_search = String::new();
self.states[i].word_search = String::new();
}
};
Task::none()
}
fn view(&self) -> Element<Message> {
//TODO error message
scrollable(
row![
row((0..self.cols).map(|col_index| {
column![
// header
combo_box(
&self.files,
"Select Bible",
self.states[col_index].selected_file.as_ref(),
move |s| Message::BibleSelected(col_index, s)
),
text_input("Search query, ie: Gen 1:1", &self.states[col_index].bible_search)
.id(format!("tabId-{}", (col_index*2)+0))
.on_input(move |s| Message::BibleSearchInput(col_index, s))
.on_submit(Message::BibleSearchSubmit(col_index)),
text_input("Word Search", &self.states[col_index].word_search)
.id(format!("tabId-{}", (col_index*2)+1))
.on_input(move |s| Message::WordSearchInput(col_index, s))
.on_submit(Message::SubmitWordSearch(col_index)),
row![
button("Clear All")
.on_press_with(move || Message::Clear(col_index))
.style(button::secondary),
button("Copy Scripture")
.on_press_with(move || Message::CopyText(col_index))
.style(button::primary),
button("Delete Column")
.on_press_with(move || Message::DeleteColumn(col_index))
.style(button::danger),
text(format!("{:?}", self.states[col_index].error))
.style(text::danger),
]
.spacing(5),
row![
// Word search results
scrollable(
column(
self.states[col_index]
.word_search_results
.clone()
.unwrap_or(Vec::new())
.into_iter()
.enumerate()
.map(|(idx,i)| {
let style = if i.1 {
button::secondary
} else {
button::primary
};
button(text(i.0.clone()))
.style(style)
.on_press_with(move || Message::QuickSearch(
col_index,
i.0.to_owned(),
idx
))
.into()
})
)
.padding([5, 5])
)
.spacing(5),
// Body
scrollable(
if let Some(body) = &self.states[col_index].scripture_body {
column(body.split("\n").enumerate().map(|(i, msg)| {
let msg = parse(msg);
if i & 1 == 0 {
text(msg.to_owned()).color(color![0xFFFFFF]).into()
} else {
text(msg.to_owned()).color(color![0xAAAAAA]).into()
}
}))
} else {
column(
Vec::<String>::new()
.iter()
.map(|_| text(String::new()).into()),
)
}
)
.spacing(5)
],
]
.spacing(5)
.width(800.)
.into()
})),
button(text("+").center())
.height(Length::Fixed(200.))
.style(button::primary)
.on_press(Message::AddColRight)
]
// 5 pixles css-like padding
.padding([5, 5])
// space elements inside this 5 pixels apart
.spacing(5),
)
.direction(Direction::Horizontal(Scrollbar::new()))
.into()
}
}
// parse out terminal style codes
fn parse(input: &str) -> String {
let magic_start_indices = input
.bytes()
.into_iter()
.enumerate()
.map_windows(|[(ai, a), (_, b)]| {
// 27 91 is the start sequence for a color/style
if *a == 27 && *b == 91 {
Some(*ai)
} else {
None
}
})
.filter_map(|f| f)
.collect::<Vec<usize>>();
let mut to_remove = Vec::new();
for start in magic_start_indices {
let range = &input[start..];
// "m" is the end of sequence
if let Some(end) = range.find("m") {
let end = start + end;
let code = &input[start..=end];
match code {
"\x1B[1m" => {} //style_bold
"\x1B[4m" => {} //style_underline
"\x1B[0m" => {} //style_reset
"\x1B[30m" => {} //color_black
"\x1B[31m" => {} //color_red
"\x1B[32m" => {} //color_green
"\x1B[33m" => {} //color_yellow
"\x1B[34m" => {} //color_blue
"\x1B[35m" => {} //color_magenta
"\x1B[36m" => {} //color_cyan
"\x1B[37m" => {} //color_white
"\x1B[90m" => {} //color_bright_black
"\x1B[91m" => {} //color_bright_red
"\x1B[92m" => {} //color_bright_green
"\x1B[93m" => {} //color_bright_yellow
"\x1B[94m" => {} //color_bright_blue
"\x1B[95m" => {} //color_bright_magenta
"\x1B[96m" => {} //color_bright_cyan
"\x1B[97m" => {} //color_bright_white
"\x1B[39m" => {} //color_reset
"\x1B[40m" => {} //bg_black
"\x1B[41m" => {} //bg_red
"\x1B[42m" => {} //bg_green
"\x1B[43m" => {} //bg_yellow
"\x1B[44m" => {} //bg_blue
"\x1B[45m" => {} //bg_magenta
"\x1B[46m" => {} //bg_cyan
"\x1B[47m" => {} //bg_white
"\x1B[100m" => {} //bg_bright_black
"\x1B[101m" => {} //bg_bright_red
"\x1B[102m" => {} //bg_bright_green
"\x1B[103m" => {} //bg_bright_yellow
"\x1B[104m" => {} //bg_bright_blue
"\x1B[105m" => {} //bg_bright_magenta
"\x1B[106m" => {} //bg_bright_cyan
"\x1B[107m" => {} //bg_bright_white
"\x1B[49m" => {} //bg_reset
_ => {}
}
to_remove.push((start, end));
}
}
to_remove.reverse();
let mut modified = input.to_owned();
for (s, e) in to_remove {
let front = modified[..s].to_string();
let back = modified[e + 1..].to_string();
modified = front + &back;
}
modified
}