use std::{fmt::Display, ops::Deref};
use crossterm::event::KeyModifiers;
use xdg::BaseDirectories;
pub mod app;
pub mod config;
pub mod storage;
pub fn base_dirs() -> Result<BaseDirectories, xdg::BaseDirectoriesError> {
BaseDirectories::with_prefix("mantra")
}
pub fn value_from_modifiers(modifiers: KeyModifiers) -> i32 {
let mut value = 10;
if modifiers.contains(KeyModifiers::SHIFT) {
value = 1;
}
if modifiers.contains(KeyModifiers::CONTROL) {
value *= 5;
}
if modifiers.contains(KeyModifiers::ALT) {
value *= 20;
}
value
}
#[derive(Default)]
pub struct CursoredString {
buf: String,
index: usize,
pub inserting: bool,
}
impl CursoredString {
pub fn new() -> Self {
Self::default()
}
pub fn as_str(&self) -> &str {
self
}
pub fn cursor_index(&self) -> usize {
self.index
}
pub fn next(&mut self) {
self.index = self.index.saturating_add(1).clamp(0, self.buf.len())
}
pub fn prev(&mut self) {
self.index = self.index.saturating_sub(1).clamp(0, self.buf.len())
}
pub fn remove_behind(&mut self) {
if self.index > 0 {
let old_len = self.buf.len();
let mut index = 0;
self.buf.retain(|_| {
index += 1;
index != self.index
});
if self.buf.len() < old_len {
self.index -= 1;
};
}
}
pub fn remove_ahead(&mut self) {
if self.index < self.buf.chars().count() {
let mut index = 0;
self.buf.retain(|_| {
index += 1;
if index - 1 == self.index {
return false;
}
true
})
}
}
pub fn insert(&mut self, value: char) {
if self.inserting {
self.remove_ahead();
}
let byte_index = self
.buf
.char_indices()
.map(|(i, _)| i)
.nth(self.index)
.unwrap_or(self.buf.len());
self.buf.insert(byte_index, value);
self.index += 1
}
}
impl Display for CursoredString {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
self.buf.fmt(f)
}
}
impl From<CursoredString> for String {
fn from(value: CursoredString) -> Self {
value.buf
}
}
impl Deref for CursoredString {
type Target = str;
fn deref(&self) -> &Self::Target {
self.buf.as_str()
}
}
impl From<String> for CursoredString {
fn from(value: String) -> Self {
Self {
buf: value,
index: 0,
inserting: false,
}
}
}