use super::input::ENTERED_ENGLISH_WORD_WEIGHT;
use super::Session;
use crate::assets;
use crate::diagnostics;
use crate::pinyin::segment::is_complete_pinyin_input;
use crate::types::{Command, KeyResult, LocalInputMode};
use crate::user_dictionary::removal::learn_entered_english_word;
impl Session {
pub(super) fn commit_raw_without_learning(&mut self) -> KeyResult {
let before = self.snapshot();
if !before.dedicated_english {
return self.dispatch_command(Command::CommitRaw);
}
let raw = before.preedit;
self.dispatch_command(Command::Cancel);
KeyResult::committed(raw)
}
pub(super) fn commit_raw_learning_typed_spellings(&mut self) -> KeyResult {
let grid_composing = self.grid_composing();
let before = self.snapshot();
let chinese_scheme = before.scheme.learns_english_words();
let complete_pure_pinyin = chinese_scheme && {
let segmentation = if before.normalized_segmentation.is_empty() {
&before.raw_segmentation
} else {
&before.normalized_segmentation
};
!segmentation.is_empty() && is_complete_pinyin_input(segmentation)
};
let should_learn = self.input.learn_english_on_enter
&& before.conversion.is_empty()
&& !grid_composing
&& !before.local_mode.generates_text()
&& before.local_mode != LocalInputMode::Url
&& (before.dedicated_english
|| before.local_mode != LocalInputMode::None
|| (chinese_scheme && !complete_pure_pinyin));
let mut result = self.dispatch_command(Command::CommitRaw);
if !should_learn || !self.input.can_learn_english_words() {
return result;
}
if let Some(commit) = result.commit.as_deref() {
let text = before.local_mode.without_entry_marker(commit);
if !text.is_empty() {
let word = if before.local_mode == LocalInputMode::TemporaryJapanese {
temporary_japanese_word(text)
} else {
text.to_owned()
};
let paths = &self.input.paths;
if learn_entered_english_word(
&paths.dictionary(assets::ENGLISH_DICTIONARY),
&paths.user(assets::USER_JOURNAL),
&word,
ENTERED_ENGLISH_WORD_WEIGHT,
)
.is_err()
{
result.diagnostic = Some(diagnostics::ENGLISH_WORD_NOT_LEARNED.to_owned());
}
}
}
result
}
}
fn temporary_japanese_word(commit: &str) -> String {
let mut word = String::with_capacity(1 + commit.len());
word.push('R');
word.push_str(commit);
word
}
#[cfg(test)]
mod tests {
use super::temporary_japanese_word;
#[test]
fn temporary_japanese_word_allocates_only_result_bytes() {
let word = temporary_japanese_word("かな");
assert_eq!(word, "Rかな");
assert_eq!(word.capacity(), word.len());
}
}