use std::ops::Range;
use rusqlite::Connection;
use super::analyzer;
use super::read::{Asked, Prefix, begins_a_word, halfway, held, long_enough, prefixes};
use crate::{Error, Result};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) enum Layout {
En,
Ru,
}
const EN: [&str; 2] =
["`1234567890-=qwertyuiop[]\\asdfghjkl;'zxcvbnm,./", "~!@#$%^&*()_+QWERTYUIOP{}|ASDFGHJKL:\"ZXCVBNM<>?"];
const RU: [&str; 2] =
["ё1234567890-=йцукенгшщзхъ\\фывапролджэячсмитьбю.", "Ё!\"№;%:?*()_+ЙЦУКЕНГШЩЗХЪ/ФЫВАПРОЛДЖЭЯЧСМИТЬБЮ,"];
impl Layout {
pub(crate) fn named(name: &str) -> Result<Layout> {
match name {
"en" => Ok(Layout::En),
"ru" => Ok(Layout::Ru),
name => Err(Error::invalid(format!("a layout {name:?}: the layouts known are ru and en"))),
}
}
pub(crate) fn name(self) -> &'static str {
match self {
Layout::En => "en",
Layout::Ru => "ru",
}
}
fn keys(self) -> [&'static str; 2] {
match self {
Layout::En => EN,
Layout::Ru => RU,
}
}
fn place(self, c: char) -> Option<(usize, usize)> {
let keys = self.keys();
(0..keys.len()).find_map(|level| keys[level].chars().position(|key| key == c).map(|key| (level, key)))
}
fn types(self, piece: &str) -> bool {
piece.chars().all(|c| self.place(c).is_some()) && piece.chars().any(char::is_alphabetic)
}
fn retyped(self, piece: &str, other: Layout) -> String {
let at = |(level, key): (usize, usize)| other.keys()[level].chars().nth(key);
piece.chars().map(|c| self.place(c).and_then(at).unwrap_or(c)).collect()
}
}
pub(crate) fn layouts<S: AsRef<str>>(names: &[S]) -> Result<Vec<Layout>> {
let mut layouts = Vec::with_capacity(names.len());
for name in names {
let layout = Layout::named(name.as_ref())?;
if layouts.contains(&layout) {
return Err(Error::invalid(format!("layout {} is given twice", layout.name())));
}
layouts.push(layout);
}
if layouts.len() == 1 {
return Err(Error::invalid("a single layout: a word typed in one is read in another, so name two"));
}
Ok(layouts)
}
fn readings(piece: &str, layouts: &[Layout]) -> Vec<String> {
let Some(typed) = layouts.iter().copied().find(|layout| layout.types(piece)) else { return Vec::new() };
layouts.iter().copied().filter(|other| *other != typed).map(|other| typed.retyped(piece, other)).collect()
}
fn pieces(text: &str) -> Vec<Range<usize>> {
let mut pieces = Vec::new();
let mut start = None;
for (at, c) in text.char_indices() {
match (c.is_whitespace(), start) {
(false, None) => start = Some(at),
(true, Some(from)) => {
pieces.push(from..at);
start = None;
}
_ => {}
}
}
if let Some(from) = start {
pieces.push(from..text.len());
}
pieces
}
pub(super) fn swap(connection: &Connection, asked: &mut Asked<'_>) -> Result<bool> {
if asked.settings.layouts.is_empty() {
return Ok(false);
}
let query = &asked.query;
let mut swaps: Vec<(Range<usize>, String)> = Vec::new();
for piece in pieces(&query.normal) {
let inside = |at: &usize| piece.start <= query.words[*at].at.start && query.words[*at].at.end <= piece.end;
let typed: Vec<usize> = (0..query.words.len()).filter(inside).collect();
if typed.is_empty() || finds_typed(connection, asked, &typed)? {
continue;
}
let last = piece.end == query.normal.len();
for reading in readings(&query.normal[piece.clone()], &asked.settings.layouts) {
let reading = analyzer::normalize(&reading);
if finds_read(connection, asked, &reading, last)? {
swaps.push((piece.clone(), reading));
break;
}
}
}
if swaps.is_empty() {
return Ok(false);
}
let normal = rewritten(&asked.query.normal, swaps);
asked.query.words = super::index::words_read(&normal);
asked.query.normal = normal;
Ok(true)
}
fn finds_typed(connection: &Connection, asked: &Asked<'_>, typed: &[usize]) -> Result<bool> {
let prefixes = prefixes(&asked.query);
for &at in typed {
let word = &asked.query.words[at];
if held(connection, asked, word)? > 0 {
return Ok(true);
}
if prefixes.contains(&at) && begins_a_word(connection, asked, &word.text)? {
return Ok(true);
}
}
Ok(false)
}
fn finds_read(connection: &Connection, asked: &Asked<'_>, reading: &str, last: bool) -> Result<bool> {
let words = analyzer::words_of(reading);
if words.is_empty() {
return Ok(false);
}
for (at, word) in words.iter().enumerate() {
if held(connection, asked, word)? > 0 {
continue;
}
let prefix = match asked.query.prefix {
Prefix::Whole => false,
Prefix::Last => last && at == words.len() - 1 && halfway(word, reading),
Prefix::Every => long_enough(word),
};
if !(prefix && begins_a_word(connection, asked, &word.text)?) {
return Ok(false);
}
}
Ok(true)
}
fn rewritten(text: &str, swaps: Vec<(Range<usize>, String)>) -> String {
let mut written = String::with_capacity(text.len() * 2);
let mut from = 0;
for (piece, reading) in swaps {
written.push_str(&text[from..piece.start]);
written.push_str(&reading);
from = piece.end;
}
written.push_str(&text[from..]);
written
}
#[cfg(test)]
#[path = "layouts_tests.rs"]
mod tests;