forked from rime/librime
-
Notifications
You must be signed in to change notification settings - Fork 0
/
reverse_lookup_filter.cc
91 lines (82 loc) · 2.53 KB
/
reverse_lookup_filter.cc
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
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
//
// Copyright RIME Developers
// Distributed under the BSD License
//
// 2013-11-05 GONG Chen <chen.sst@gmail.com>
//
#include <rime/candidate.h>
#include <rime/engine.h>
#include <rime/schema.h>
#include <rime/translation.h>
#include <rime/dict/reverse_lookup_dictionary.h>
#include <rime/gear/reverse_lookup_filter.h>
#include <rime/gear/translator_commons.h>
namespace rime {
class ReverseLookupFilterTranslation : public CacheTranslation {
public:
ReverseLookupFilterTranslation(an<Translation> translation,
ReverseLookupFilter* filter)
: CacheTranslation(translation), filter_(filter) {}
virtual an<Candidate> Peek();
protected:
ReverseLookupFilter* filter_;
};
an<Candidate> ReverseLookupFilterTranslation::Peek() {
auto cand = CacheTranslation::Peek();
if (cand) {
filter_->Process(cand);
}
return cand;
}
ReverseLookupFilter::ReverseLookupFilter(const Ticket& ticket)
: Filter(ticket), TagMatching(ticket) {
if (ticket.name_space == "filter") {
name_space_ = "reverse_lookup";
}
}
void ReverseLookupFilter::Initialize() {
initialized_ = true;
if (!engine_)
return;
Ticket ticket(engine_, name_space_);
if (auto c = ReverseLookupDictionary::Require("reverse_lookup_dictionary")) {
rev_dict_.reset(c->Create(ticket));
if (rev_dict_ && !rev_dict_->Load()) {
rev_dict_.reset();
}
}
if (Config* config = engine_->schema()->config()) {
config->GetBool(name_space_ + "/overwrite_comment", &overwrite_comment_);
config->GetBool(name_space_ + "/append_comment", &append_comment_);
comment_formatter_.Load(config->GetList(name_space_ + "/comment_format"));
}
}
an<Translation> ReverseLookupFilter::Apply(an<Translation> translation,
CandidateList* candidates) {
if (!initialized_) {
Initialize();
}
if (!rev_dict_) {
return translation;
}
return New<ReverseLookupFilterTranslation>(translation, this);
}
void ReverseLookupFilter::Process(const an<Candidate>& cand) {
if (!cand->comment().empty() && !(overwrite_comment_ || append_comment_))
return;
auto phrase = As<Phrase>(Candidate::GetGenuineCandidate(cand));
if (!phrase)
return;
string codes;
if (rev_dict_->ReverseLookup(phrase->text(), &codes)) {
comment_formatter_.Apply(&codes);
if (!codes.empty()) {
if (overwrite_comment_ || cand->comment().empty()) {
phrase->set_comment(codes);
} else {
phrase->set_comment(cand->comment() + " " + codes);
}
}
}
}
} // namespace rime