|
| 1 | +#include "chromepanel.h" |
| 2 | +#include <emscripten.h> |
| 3 | +#include <fcitx/inputpanel.h> |
| 4 | +#include <nlohmann/json.hpp> |
| 5 | + |
| 6 | +using json = nlohmann::json; |
| 7 | + |
| 8 | +namespace fcitx { |
| 9 | + |
| 10 | +struct Candidate { |
| 11 | + std::string text; |
| 12 | + std::string label; |
| 13 | + std::string comment; |
| 14 | + |
| 15 | + friend void to_json(json &j, const Candidate &c) { |
| 16 | + j = json{{"label", c.label}, {"text", c.text}, {"comment", c.comment}}; |
| 17 | + } |
| 18 | +}; |
| 19 | + |
| 20 | +ChromePanel::ChromePanel(Instance *instance) : instance_(instance) {} |
| 21 | + |
| 22 | +void ChromePanel::update(UserInterfaceComponent component, |
| 23 | + InputContext *inputContext) { |
| 24 | + switch (component) { |
| 25 | + case UserInterfaceComponent::InputPanel: { |
| 26 | + const InputPanel &inputPanel = inputContext->inputPanel(); |
| 27 | + std::vector<Candidate> candidates; |
| 28 | + int highlighted = -1; |
| 29 | + if (const auto &list = inputPanel.candidateList()) { |
| 30 | + auto size = list->size(); |
| 31 | + candidates.reserve(size); |
| 32 | + for (int i = 0; i < size; ++i) { |
| 33 | + const auto &candidate = list->candidate(i); |
| 34 | + auto label = list->label(i).toString(); |
| 35 | + // HACK: fcitx5's Linux UI concatenates label and text and |
| 36 | + // expects engine to append a ' ' to label. |
| 37 | + auto length = label.length(); |
| 38 | + if (length && label[length - 1] == ' ') { |
| 39 | + label = label.substr(0, length - 1); |
| 40 | + } |
| 41 | + candidates.push_back( |
| 42 | + {instance_->outputFilter(inputContext, candidate.text()) |
| 43 | + .toString(), |
| 44 | + label, |
| 45 | + instance_->outputFilter(inputContext, candidate.comment()) |
| 46 | + .toString()}); |
| 47 | + highlighted = list->cursorIndex(); |
| 48 | + } |
| 49 | + } |
| 50 | + auto str = |
| 51 | + json{{"candidates", candidates}, {"highlighted", highlighted}} |
| 52 | + .dump(); |
| 53 | + EM_ASM(fcitx.chrome.setCandidates(UTF8ToString($0)), str.c_str()); |
| 54 | + break; |
| 55 | + } |
| 56 | + } |
| 57 | +} |
| 58 | +} // namespace fcitx |
| 59 | + |
| 60 | +FCITX_ADDON_FACTORY_V2(chromepanel, fcitx::ChromePanelFactory); |
0 commit comments