Skip to content

Commit c380ec8

Browse files
committed
refactor: chewing_new3 compatible constructor
1 parent c1013fa commit c380ec8

File tree

3 files changed

+78
-73
lines changed

3 files changed

+78
-73
lines changed

capi/src/io.rs

Lines changed: 17 additions & 60 deletions
Original file line numberDiff line numberDiff line change
@@ -13,13 +13,10 @@ use std::{
1313

1414
use chewing::{
1515
conversion::{ChewingEngine, FuzzyChewingEngine, Interval, SimpleEngine, Symbol},
16-
dictionary::{
17-
DEFAULT_DICT_NAMES, Dictionary, Layered, LookupStrategy, SystemDictionaryLoader, Trie,
18-
UserDictionaryLoader,
19-
},
16+
dictionary::{DEFAULT_DICT_NAMES, LookupStrategy},
2017
editor::{
21-
AbbrevTable, BasicEditor, CharacterForm, ConversionEngineKind, Editor, EditorKeyBehavior,
22-
LanguageMode, LaxUserFreqEstimate, SymbolSelector, UserPhraseAddDirection,
18+
BasicEditor, CharacterForm, ConversionEngineKind, Editor, EditorKeyBehavior, LanguageMode,
19+
UserPhraseAddDirection,
2320
zhuyin_layout::{
2421
DaiChien26, Et, Et26, GinYieh, Hsu, Ibm, KeyboardLayoutCompat, Pinyin, Standard,
2522
SyllableEditor,
@@ -37,7 +34,7 @@ use chewing::{
3734
},
3835
zhuyin::Syllable,
3936
};
40-
use tracing::{debug, error, info, level_filters::LevelFilter};
37+
use tracing::{debug, info, level_filters::LevelFilter};
4138
use tracing_subscriber::{filter::Targets, layer::SubscriberExt, util::SubscriberInitExt};
4239

4340
use crate::{
@@ -184,13 +181,7 @@ pub unsafe extern "C" fn chewing_new3(
184181
.with(targets)
185182
.try_init();
186183
let _logger_guard = init_scoped_logging_subscriber(logger_fn, logger_data);
187-
let mut sys_loader = SystemDictionaryLoader::new();
188184
let mut dict_names: Vec<String> = DEFAULT_DICT_NAMES.iter().map(|&n| n.to_owned()).collect();
189-
if !syspath.is_null() {
190-
if let Ok(search_path) = unsafe { CStr::from_ptr(syspath).to_str() } {
191-
sys_loader = sys_loader.sys_path(search_path);
192-
}
193-
}
194185
if !enabled_dicts.is_null() {
195186
if let Ok(enabled_dicts) = unsafe { CStr::from_ptr(enabled_dicts).to_str() } {
196187
dict_names = enabled_dicts
@@ -199,56 +190,22 @@ pub unsafe extern "C" fn chewing_new3(
199190
.collect();
200191
}
201192
}
202-
let system_dicts = match sys_loader.load(&dict_names) {
203-
Ok(d) => d,
204-
Err(e) => {
205-
let builtin = Trie::new(&include_bytes!("../data/mini.dat")[..]);
206-
error!("Failed to load system dict: {e}");
207-
error!("Loading builtin minimum dictionary...");
208-
// NB: we can unwrap because the built-in dictionary should always
209-
// be valid.
210-
vec![Box::new(builtin.unwrap()) as Box<dyn Dictionary>]
211-
}
212-
};
213-
let abbrev = sys_loader.load_abbrev();
214-
let abbrev = match abbrev {
215-
Ok(abbr) => abbr,
216-
Err(e) => {
217-
error!("Failed to load abbrev table: {e}");
218-
error!("Loading empty table...");
219-
AbbrevTable::new()
220-
}
221-
};
222-
let sym_sel = sys_loader.load_symbol_selector();
223-
let sym_sel = match sym_sel {
224-
Ok(sym_sel) => sym_sel,
225-
Err(e) => {
226-
error!("Failed to load symbol table: {e}");
227-
error!("Loading empty table...");
228-
// NB: we can unwrap here because empty table is always valid.
229-
SymbolSelector::new(b"".as_slice()).unwrap()
230-
}
193+
let syspath = if syspath.is_null() {
194+
None
195+
} else {
196+
unsafe { CStr::from_ptr(syspath).to_str() }
197+
.ok()
198+
.map(|p| p.to_owned())
231199
};
232-
let mut user_dictionary = UserDictionaryLoader::new();
233-
if !userpath.is_null() {
234-
if let Ok(data_path) = unsafe { CStr::from_ptr(userpath).to_str() } {
235-
user_dictionary = user_dictionary.userphrase_path(data_path);
236-
}
237-
}
238-
let user_dictionary = match user_dictionary.load() {
239-
Ok(d) => d,
240-
Err(e) => {
241-
error!("Failed to load user dict: {e}");
242-
UserDictionaryLoader::in_memory()
243-
}
200+
let userpath = if userpath.is_null() {
201+
None
202+
} else {
203+
unsafe { CStr::from_ptr(userpath).to_str() }
204+
.ok()
205+
.map(|p| p.to_owned())
244206
};
245-
246-
let estimate = LaxUserFreqEstimate::max_from(user_dictionary.as_ref());
247-
248-
let dict = Layered::new(system_dicts, user_dictionary);
249-
let conversion_engine = Box::new(ChewingEngine::new());
250207
let kb_compat = KeyboardLayoutCompat::Default;
251-
let editor = Editor::new(conversion_engine, dict, estimate, abbrev, sym_sel);
208+
let editor = Editor::chewing(syspath, userpath, &dict_names);
252209
let context = Box::new(ChewingContext {
253210
kb_compat,
254211
keymap: &QWERTY_MAP,

src/editor/mod.rs

Lines changed: 59 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -23,8 +23,8 @@ use crate::{
2323
special_symbol_input,
2424
},
2525
dictionary::{
26-
DEFAULT_DICT_NAMES, Dictionary, Layered, LookupStrategy, SystemDictionaryLoader,
27-
UpdateDictionaryError, UserDictionaryLoader,
26+
Dictionary, Layered, LookupStrategy, SystemDictionaryLoader, Trie, UpdateDictionaryError,
27+
UserDictionaryLoader,
2828
},
2929
input::{KeyState, KeyboardEvent, keysym::*},
3030
zhuyin::Syllable,
@@ -106,7 +106,7 @@ impl Default for EditorOptions {
106106
/// An editor can react to KeyEvents and change its state.
107107
pub trait BasicEditor {
108108
/// Handles a KeyEvent
109-
fn process_keyevent(&mut self, key_event: KeyboardEvent) -> EditorKeyBehavior;
109+
fn process_keyevent(&mut self, evt: KeyboardEvent) -> EditorKeyBehavior;
110110
}
111111

112112
/// The internal state of the editor.
@@ -188,17 +188,64 @@ pub(crate) struct SharedState {
188188
}
189189

190190
impl Editor {
191-
pub fn chewing() -> Result<Editor, Box<dyn Error>> {
192-
let sys_loader = SystemDictionaryLoader::new();
193-
let system_dict = sys_loader.load(DEFAULT_DICT_NAMES)?;
194-
let user_dict = UserDictionaryLoader::new().load()?;
195-
let estimate = LaxUserFreqEstimate::max_from(user_dict.as_ref());
196-
let dict = Layered::new(system_dict, user_dict);
191+
pub fn chewing<T>(
192+
syspath: Option<String>,
193+
userpath: Option<String>,
194+
enabled_dicts: &[T],
195+
) -> Editor
196+
where
197+
T: AsRef<str>,
198+
{
199+
let mut sys_loader = SystemDictionaryLoader::new();
200+
if let Some(syspath) = syspath {
201+
sys_loader = sys_loader.sys_path(syspath);
202+
}
203+
let system_dicts = match sys_loader.load(enabled_dicts) {
204+
Ok(d) => d,
205+
Err(e) => {
206+
let builtin = Trie::new(&include_bytes!("../../capi/data/mini.dat")[..]);
207+
error!("Failed to load system dict: {e}");
208+
error!("Loading builtin minimum dictionary...");
209+
// NB: we can unwrap because the built-in dictionary should always
210+
// be valid.
211+
vec![Box::new(builtin.unwrap()) as Box<dyn Dictionary>]
212+
}
213+
};
214+
let abbrev = sys_loader.load_abbrev();
215+
let abbrev = match abbrev {
216+
Ok(abbr) => abbr,
217+
Err(e) => {
218+
error!("Failed to load abbrev table: {e}");
219+
error!("Loading empty table...");
220+
AbbrevTable::new()
221+
}
222+
};
223+
let sym_sel = sys_loader.load_symbol_selector();
224+
let sym_sel = match sym_sel {
225+
Ok(sym_sel) => sym_sel,
226+
Err(e) => {
227+
error!("Failed to load symbol table: {e}");
228+
error!("Loading empty table...");
229+
// NB: we can unwrap here because empty table is always valid.
230+
SymbolSelector::new(b"".as_slice()).unwrap()
231+
}
232+
};
233+
let mut user_dict_loader = UserDictionaryLoader::new();
234+
if let Some(userpath) = userpath {
235+
user_dict_loader = user_dict_loader.userphrase_path(userpath);
236+
}
237+
let user_dictionary = match user_dict_loader.load() {
238+
Ok(d) => d,
239+
Err(e) => {
240+
error!("Failed to load user dict: {e}");
241+
UserDictionaryLoader::in_memory()
242+
}
243+
};
244+
let estimate = LaxUserFreqEstimate::max_from(user_dictionary.as_ref());
245+
let dict = Layered::new(system_dicts, user_dictionary);
197246
let conversion_engine = Box::new(ChewingEngine::new());
198-
let abbrev = sys_loader.load_abbrev()?;
199-
let sym_sel = sys_loader.load_symbol_selector()?;
200247
let editor = Editor::new(conversion_engine, dict, estimate, abbrev, sym_sel);
201-
Ok(editor)
248+
editor
202249
}
203250

204251
pub fn new(

src/lib.rs

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -34,8 +34,9 @@
3434
//! use chewing::editor::{BasicEditor, Editor};
3535
//! use chewing::input::{keycode, keysym, KeyboardEvent};
3636
//! use chewing::input::keymap::{map_ascii, QWERTY_MAP};
37+
//! use chewing::dictionary::DEFAULT_DICT_NAMES;
3738
//!
38-
//! let mut editor = Editor::chewing()?;
39+
//! let mut editor = Editor::chewing(None, None, &DEFAULT_DICT_NAMES);
3940
//!
4041
//! editor.process_keyevent(map_ascii(&QWERTY_MAP, b'd'));
4142
//! editor.process_keyevent(map_ascii(&QWERTY_MAP, b'j'));

0 commit comments

Comments
 (0)