Skip to content

Commit

Permalink
doc
Browse files Browse the repository at this point in the history
  • Loading branch information
pythonbrad committed Oct 18, 2023
1 parent 1fc714a commit 0663904
Show file tree
Hide file tree
Showing 16 changed files with 191 additions and 25 deletions.
2 changes: 2 additions & 0 deletions config/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Clafrica Config Manager
Manage the configuration of the clafrica input method.
16 changes: 16 additions & 0 deletions config/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,22 +1,34 @@
//! Library to manage the configuration of the clafrica input method.
//!

#![deny(missing_docs)]

use rhai::{Engine, AST};
use serde::Deserialize;
use std::result::Result;
use std::{collections::HashMap, error, fs, path::Path};
use toml::{self};

/// Hold information about a configuration.
#[derive(Deserialize, Debug, Clone)]
pub struct Config {
/// The core config.
pub core: Option<CoreConfig>,
data: Option<HashMap<String, Data>>,
translators: Option<HashMap<String, Data>>,
translation: Option<HashMap<String, Data>>,
}

/// Core information about a configuration.
#[derive(Deserialize, Debug, Clone)]
pub struct CoreConfig {
/// The size of the memory (history).
/// The number of elements that should be tracked.
pub buffer_size: Option<usize>,
auto_capitalize: Option<bool>,
/// The max numbers of predicates to display.
pub page_size: Option<usize>,
/// Whether the predicate should be automatically committed.
pub auto_commit: Option<bool>,
}

Expand Down Expand Up @@ -60,6 +72,7 @@ macro_rules! insert_with_auto_capitalize {
}

impl Config {
/// Load the configuration from a file.
pub fn from_file(filepath: &Path) -> Result<Self, Box<dyn error::Error>> {
let content = fs::read_to_string(filepath)
.map_err(|err| format!("Couldn't open file `{filepath:?}`.\nCaused by:\n\t{err}."))?;
Expand Down Expand Up @@ -155,6 +168,7 @@ impl Config {
Ok(config)
}

/// Extract the data from the configuration.
pub fn extract_data(&self) -> HashMap<String, String> {
let empty = HashMap::default();

Expand All @@ -172,6 +186,7 @@ impl Config {
.collect()
}

/// Extract the translators from the configuration.
pub fn extract_translators(&self) -> Result<HashMap<String, AST>, Box<dyn error::Error>> {
let empty = HashMap::default();
let mut engine = Engine::new();
Expand Down Expand Up @@ -204,6 +219,7 @@ impl Config {
.collect()
}

/// Extract the translation from the configuration.
pub fn extract_translation(&self) -> HashMap<String, Vec<String>> {
let empty = HashMap::new();

Expand Down
2 changes: 1 addition & 1 deletion engine/preprocessor/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name = "clafrica-preprocessor"
version = "0.5.0"
edition = "2021"
description = "A preprocessor for processing key input of an input method."
description = "A preprocessor to process keyboard events for an input method."
keywords = ["ime", "processor", "keyboard"]
repository = "https://github.com/pythonbrad/name"
license = "MIT"
Expand Down
2 changes: 2 additions & 0 deletions engine/preprocessor/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Clafrica Preprocessor
It generate a sequence of command to be perform to execute a particular task.
56 changes: 55 additions & 1 deletion engine/preprocessor/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,3 +1,46 @@
//! Preprocessor of keyboard events for an input method.
//!
//! Example
//!
//! ```rust
//! use clafrica_preprocessor::{utils, Command, Preprocessor};
//! use keyboard_types::{
//! webdriver::{self, Event},
//! Key::*,
//! };
//! use std::collections::VecDeque;
//!
//! // We build initiate our preprocessor
//! let data = utils::load_data("cc ç");
//! let map = utils::build_map(data);
//! let mut preprocessor = Preprocessor::new(map, 8);
//!
//! // We trigger a sequence
//! webdriver::send_keys("cc")
//! .into_iter()
//! .for_each(|e| {
//! match e {
//! Event::Keyboard(e) => preprocessor.process(e),
//! _ => unimplemented!(),
//! };
//! });
//!
//! // We got the generated command
//! let mut expecteds = VecDeque::from(vec![
//! Command::Pause,
//! Command::KeyClick(Backspace),
//! Command::KeyClick(Backspace),
//! Command::CommitText("ç".to_owned()),
//! Command::Resume,
//! ]);
//!
//! while let Some(command) = preprocessor.pop_stack() {
//! assert_eq!(command, expecteds.pop_front().unwrap());
//! }
//! ```

#![deny(missing_docs)]

mod message;

pub use crate::message::Command;
Expand All @@ -6,20 +49,23 @@ use clafrica_memory::{Cursor, Node};
pub use keyboard_types::{Key, KeyState, KeyboardEvent};
use std::collections::VecDeque;

/// The main structure of the preprocessor.
#[derive(Debug)]
pub struct Preprocessor {
cursor: Cursor,
stack: VecDeque<Command>,
}

impl Preprocessor {
/// Initiate a new preprocessor.
pub fn new(map: Node, buffer_size: usize) -> Self {
let cursor = Cursor::new(map, buffer_size);
let stack = VecDeque::with_capacity(15);

Self { cursor, stack }
}

/// Cancel the previous operation.
fn rollback(&mut self) -> bool {
self.stack.push_back(Command::KeyRelease(Key::Backspace));

Expand All @@ -42,6 +88,7 @@ impl Preprocessor {
}
}

/// Process the key event.
pub fn process(&mut self, event: KeyboardEvent) -> (bool, bool) {
let (mut changed, mut committed) = (false, false);

Expand Down Expand Up @@ -97,6 +144,7 @@ impl Preprocessor {
(changed, committed)
}

/// Commit a text.
pub fn commit(&mut self, text: &str) {
self.pause();

Expand All @@ -110,14 +158,17 @@ impl Preprocessor {
self.cursor.clear();
}

/// Pause the keyboard event listerner.
fn pause(&mut self) {
self.stack.push_back(Command::Pause);
}

/// Resume the keyboard event listener.
fn resume(&mut self) {
self.stack.push_back(Command::Resume);
}

/// Return the sequence present in the memory.
pub fn get_input(&self) -> String {
self.cursor
.to_sequence()
Expand All @@ -126,10 +177,12 @@ impl Preprocessor {
.collect::<String>()
}

/// Return the next command to be executed.
pub fn pop_stack(&mut self) -> Option<Command> {
self.stack.pop_front()
}

/// Clear the stack.
pub fn clear_stack(&mut self) {
self.stack.clear();
}
Expand All @@ -145,7 +198,6 @@ mod tests {
Key::*,
};
use std::collections::VecDeque;
use std::fs;

#[test]
fn test_process() {
Expand Down Expand Up @@ -248,6 +300,8 @@ mod tests {

#[test]
fn test_advanced() {
use std::fs;

let data = fs::read_to_string("./data/sample.txt").unwrap();
let data = utils::load_data(&data);
let map = utils::build_map(data);
Expand Down
9 changes: 9 additions & 0 deletions engine/preprocessor/src/message.rs
Original file line number Diff line number Diff line change
@@ -1,11 +1,20 @@
#![deny(missing_docs)]

use keyboard_types::Key;

/// Possible commands that can be generated.
#[derive(Clone, Debug, Eq, PartialEq)]
pub enum Command {
/// Request to commit a text.
CommitText(String),
/// Request to pause the listener.
Pause,
/// Request to resume the listener.
Resume,
/// Request to press a key.
KeyPress(Key),
/// Request to release a key.
KeyRelease(Key),
/// Request to toggle a key.
KeyClick(Key),
}
2 changes: 2 additions & 0 deletions engine/translator/README.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,2 @@
# Clafrica Translator
Handle the predication system of the clafrica input method.
50 changes: 47 additions & 3 deletions engine/translator/src/lib.rs
Original file line number Diff line number Diff line change
@@ -1,13 +1,57 @@
use rhai::{Array, Engine, Scope, AST};
//! Engine to generate predicates based on a particular input.
//!
//! Example
//! ```rust
//! use clafrica_translator::{Engine, Translator};
//! use std::collections::HashMap;
//!
//! // Translation via scripting
//! let engine = Engine::new();
//! let hi = engine.compile(r#"
//! fn translate(input) {
//! if input == "hi" {
//! ["hi", "", "hello", true]
//! }
//! }
//! "#).unwrap();
//! let mut translators = HashMap::new();
//! translators.insert("hi".to_string(), hi);
//!
//! // Translation via dictionary
//! let mut dictionary = HashMap::new();
//! dictionary.insert("halo".to_string(), ["hello".to_string()].to_vec());
//! dictionary.insert("nihao".to_string(), ["hello".to_string()].to_vec());
//!
//! // We build the translator.
//! let translator = Translator::new(dictionary, translators, true);
//!
//! assert_eq!(
//! translator.translate("hi"),
//! vec![(
//! "hi".to_owned(),
//! "".to_owned(),
//! vec!["hello".to_owned()],
//! true
//! )]
//! );
//! ```
//!

#![deny(missing_docs)]

pub use rhai::Engine;
use rhai::{Array, Scope, AST};
use std::collections::HashMap;

/// Core structure of the translator.
pub struct Translator {
dictionary: HashMap<String, Vec<String>>,
translators: HashMap<String, AST>,
auto_commit: bool,
}

impl Translator {
/// Initiate a new translator.
pub fn new(
dictionary: HashMap<String, Vec<String>>,
translators: HashMap<String, AST>,
Expand All @@ -20,6 +64,7 @@ impl Translator {
}
}

/// Generate a list of predicates based on the input.
pub fn translate(&self, input: &str) -> Vec<(String, String, Vec<String>, bool)> {
let mut scope = Scope::new();
let engine = Engine::new();
Expand Down Expand Up @@ -73,8 +118,7 @@ impl Translator {
mod tests {
#[test]
fn test_translate() {
use crate::Translator;
use rhai::Engine;
use crate::{Translator, Engine};
use std::collections::HashMap;

let engine = Engine::new();
Expand Down
2 changes: 1 addition & 1 deletion memory/Cargo.toml
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,7 @@
name = "clafrica-memory"
version = "0.3.2"
edition = "2021"
description = "This library manage the memory of an input method."
description = "Make the handle of sequential codes easier for an input method."
keywords = ["ime", "memory", "data-structure"]
repository = "https://github.com/pythonbrad/name"
license = "MIT"
Expand Down
Loading

0 comments on commit 0663904

Please sign in to comment.