-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathpython_simple_filter.cc
More file actions
61 lines (48 loc) · 1.71 KB
/
Copy pathpython_simple_filter.cc
File metadata and controls
61 lines (48 loc) · 1.71 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
#include <pybind11/embed.h>
#include <rime/candidate.h>
#include <rime/segmentation.h>
#include "python_simple_filter.h"
namespace pythonext {
// PythonSimpleFilter
PythonSimpleFilter::PythonSimpleFilter( const rime::Ticket& ticket, py::function py_entry )
: Filter { ticket }, py_entry { py_entry } {}
rime::an<rime::Translation> PythonSimpleFilter::Apply( rime::an<rime::Translation> translation, rime::CandidateList* candidates ) {
return rime::New<PythonSimpleFilterTranslation>( this, translation );
}
bool PythonSimpleFilter::FilterFunc( rime::an<rime::Candidate> cand ) noexcept {
const std::string& text { cand->text() };
try {
return py_entry( text ).cast<bool>();
} catch ( const py::error_already_set& e ) {
LOG( ERROR ) << e.what();
}
return true;
}
// PythonSimpleFilterTranslation
PythonSimpleFilterTranslation::PythonSimpleFilterTranslation( PythonSimpleFilter* filter, rime::an<rime::Translation> translation )
: filter_ { filter }, translation_ { translation } {
LocateNextCandidate();
}
bool PythonSimpleFilterTranslation::Next() {
if ( exhausted() )
return false;
if ( !translation_->Next() ) {
set_exhausted( true );
return false;
}
return LocateNextCandidate();
}
rime::an<rime::Candidate> PythonSimpleFilterTranslation::Peek() {
return translation_->Peek();
}
bool PythonSimpleFilterTranslation::LocateNextCandidate() {
while ( !translation_->exhausted() ) {
const rime::an<rime::Candidate> cand { translation_->Peek() };
if ( cand && filter_->FilterFunc( cand ) )
return true;
translation_->Next();
}
set_exhausted( true );
return false;
}
} // namespace pythonext