Download src/ai-kana.cpp from WariHima/OsakanaIME: direct link, hf CLI and curl.
- Browser
- Download file 30.4 kB
-
https://huggingface.co/WariHima/OsakanaIME/resolve/main/src/ai-kana.cpp
- Command line
-
hf download hf://WariHima/OsakanaIME/src/ai-kana.cpp
-
curl -L -o ai-kana.cpp https://huggingface.co/WariHima/OsakanaIME/resolve/main/src/ai-kana.cpp
30.4 kB
| // fcitx5-ai-kana: 薄い C++ クライアント + Python デーモン | |
| using json = nlohmann::json; | |
| namespace fc = fcitx; | |
| static std::string socketPath() { | |
| const char *xdg = std::getenv("XDG_RUNTIME_DIR"); | |
| if (xdg && *xdg) { | |
| return std::string(xdg) + "/fcitx5-ai-kana.sock"; | |
| } | |
| return "/tmp/fcitx5-ai-kana-" + std::to_string(getuid()) + ".sock"; | |
| } | |
| class Daemon { | |
| public: | |
| bool call(const json &req, json &res, int timeoutMs = 1500) { | |
| int fd = ::socket(AF_UNIX, SOCK_STREAM, 0); | |
| if (fd < 0) return false; | |
| sockaddr_un addr{}; | |
| addr.sun_family = AF_UNIX; | |
| auto path = socketPath(); | |
| if (path.size() >= sizeof(addr.sun_path)) { ::close(fd); return false; } | |
| std::strncpy(addr.sun_path, path.c_str(), sizeof(addr.sun_path) - 1); | |
| if (::connect(fd, reinterpret_cast<sockaddr *>(&addr), sizeof(addr)) < 0) { | |
| ::close(fd); return false; | |
| } | |
| std::string out = req.dump() + "\n"; | |
| size_t sent = 0; | |
| while (sent < out.size()) { | |
| pollfd p{fd, POLLOUT, 0}; | |
| if (::poll(&p, 1, timeoutMs) <= 0) { ::close(fd); return false; } | |
| ssize_t n = ::send(fd, out.data() + sent, out.size() - sent, MSG_NOSIGNAL); | |
| if (n <= 0) { ::close(fd); return false; } | |
| sent += static_cast<size_t>(n); | |
| } | |
| std::string buf; | |
| while (buf.size() < (1u << 20)) { | |
| pollfd p{fd, POLLIN, 0}; | |
| if (::poll(&p, 1, timeoutMs) <= 0) break; | |
| char tmp[4096]; | |
| ssize_t n = ::recv(fd, tmp, sizeof(tmp), 0); | |
| if (n <= 0) break; | |
| buf.append(tmp, static_cast<size_t>(n)); | |
| if (buf.find('\n') != std::string::npos) break; | |
| } | |
| ::close(fd); | |
| auto pos = buf.find('\n'); | |
| if (pos == std::string::npos) return false; | |
| try { res = json::parse(buf.substr(0, pos)); return true; } | |
| catch (...) { return false; } | |
| } | |
| }; | |
| static size_t utf8Len(const std::string &s) { | |
| size_t n = 0; | |
| for (unsigned char c : s) if ((c & 0xC0) != 0x80) ++n; | |
| return n; | |
| } | |
| static void utf8Pop(std::string &s) { | |
| if (s.empty()) return; | |
| size_t i = s.size() - 1; | |
| while (i > 0 && (static_cast<unsigned char>(s[i]) & 0xC0) == 0x80) --i; | |
| s.erase(i); | |
| } | |
| static const char *jpPunct(char ch) { | |
| switch (ch) { | |
| case ',': return "、"; | |
| case '.': return "。"; | |
| case '-': return "ー"; | |
| case '[': return "「"; | |
| case ']': return "」"; | |
| case '?': return "?"; | |
| case '!': return "!"; | |
| case '~': return "〜"; | |
| default: return nullptr; | |
| } | |
| } | |
| static std::string utf8Clip(const std::string &s, size_t maxCp, bool tail) { | |
| std::vector<size_t> idx; | |
| for (size_t i = 0; i < s.size(); ++i) { | |
| if ((static_cast<unsigned char>(s[i]) & 0xC0) != 0x80) idx.push_back(i); | |
| } | |
| if (idx.size() <= maxCp) return s; | |
| return tail ? s.substr(idx[idx.size() - maxCp]) : s.substr(0, idx[maxCp]); | |
| } | |
| static std::vector<std::string> splitLines(const std::string &s) { | |
| std::vector<std::string> out; | |
| size_t start = 0; | |
| while (start <= s.size()) { | |
| size_t end = s.find('\n', start); | |
| if (end == std::string::npos) end = s.size(); | |
| std::string line = s.substr(start, end - start); | |
| size_t b = line.find_first_not_of(" \t\r"); | |
| size_t e = line.find_last_not_of(" \t\r"); | |
| if (b != std::string::npos) out.push_back(line.substr(b, e - b + 1)); | |
| if (end == s.size()) break; | |
| start = end + 1; | |
| } | |
| return out; | |
| } | |
| struct Segment { | |
| std::string reading; | |
| std::vector<std::string> cands; | |
| size_t idx = 0; | |
| std::string aiTop; | |
| double aiProb = 0.0; | |
| }; | |
| class AiKanaEngine; // ★ 前方宣言は候補クラスより前 | |
| class AiCandidate : public fc::CandidateWord { | |
| public: | |
| AiCandidate(AiKanaEngine *engine, std::string text, size_t idx) | |
| : fc::CandidateWord(fc::Text(std::move(text))), engine_(engine), idx_(idx) {} | |
| void select(fc::InputContext *ic) const override; | |
| private: | |
| AiKanaEngine *engine_; | |
| size_t idx_; | |
| }; | |
| class ChatLineCandidate : public fc::CandidateWord { | |
| public: | |
| ChatLineCandidate(AiKanaEngine *e, std::string line) | |
| : fc::CandidateWord(fc::Text(line)), engine_(e), line_(std::move(line)) {} | |
| void select(fc::InputContext *ic) const override; | |
| private: | |
| AiKanaEngine *engine_; | |
| std::string line_; | |
| }; | |
| class AiKanaEngine : public fc::InputMethodEngine { | |
| public: | |
| explicit AiKanaEngine(fc::Instance *instance) : instance_(instance) {} | |
| void activate(const fc::InputMethodEntry &, fc::InputContextEvent &event) override { | |
| refresh(event.inputContext()); | |
| } | |
| void deactivate(const fc::InputMethodEntry &, fc::InputContextEvent &event) override { | |
| if (chat_) { exitChat(event.inputContext()); return; } | |
| commitCurrent(event.inputContext()); | |
| } | |
| void reset(const fc::InputMethodEntry &, fc::InputContextEvent &event) override { | |
| if (chat_) { exitChat(event.inputContext()); return; } | |
| clearState(); | |
| refresh(event.inputContext()); | |
| } | |
| void keyEvent(const fc::InputMethodEntry &entry, fc::KeyEvent &keyEvent) override; | |
| void selectCandidate(fc::InputContext *ic, size_t idx) { | |
| if (mode_ != Mode::Convert || segs_.empty()) return; | |
| auto &seg = segs_[focus_]; | |
| if (idx < seg.cands.size()) { seg.idx = idx; updateConvert(ic); } | |
| } | |
| void commitChatLine(fc::InputContext *ic, const std::string &line) { | |
| ic->commitString(line); | |
| updateChatIdle(ic); | |
| } | |
| private: | |
| enum class Mode { Input, Convert }; | |
| fc::Instance *instance_; | |
| Daemon daemon_; | |
| Mode mode_ = Mode::Input; | |
| std::string buf_; | |
| std::string baseKana_; | |
| std::string origKana_; | |
| std::vector<Segment> segs_; | |
| size_t focus_ = 0; | |
| bool progressive_ = false; | |
| size_t revealed_ = 0; | |
| static constexpr bool kSepInPreedit = true; | |
| bool kata_ = false; | |
| std::string note_; | |
| static constexpr int kPageSize = 9; | |
| bool chat_ = false; | |
| bool chatPending_ = false; | |
| std::string chatJob_; | |
| std::string chatReply_; | |
| std::unique_ptr<fc::EventSourceTime> chatTimer_; | |
| std::string lastCommit_; | |
| std::string lastReading_; | |
| bool composing() const { | |
| return !buf_.empty() || !baseKana_.empty() || mode_ == Mode::Convert; | |
| } | |
| void clearState() { | |
| mode_ = Mode::Input; | |
| buf_.clear(); baseKana_.clear(); origKana_.clear(); | |
| segs_.clear(); focus_ = 0; note_.clear(); | |
| progressive_ = false; revealed_ = 0; | |
| } | |
| std::string segText(size_t i) const { | |
| const auto &s = segs_[i]; | |
| if (progressive_ && i > revealed_) return s.reading; | |
| if (s.cands.empty()) return s.reading; | |
| return s.cands[std::min(s.idx, s.cands.size() - 1)]; | |
| } | |
| std::string composed() const { | |
| std::string s; | |
| for (size_t i = 0; i < segs_.size(); ++i) s += segText(i); | |
| return s; | |
| } | |
| void clearUI(fc::InputContext *ic) { | |
| ic->inputPanel().reset(); | |
| ic->updatePreedit(); | |
| ic->updateUserInterface(fc::UserInterfaceComponent::InputPanel); | |
| } | |
| void commit(fc::InputContext *ic, const std::string &s) { | |
| if (!s.empty()) { | |
| ic->commitString(s); | |
| lastCommit_ = s; | |
| lastReading_ = (mode_ == Mode::Convert) ? origKana_ : s; // ← 再 flush 不要 | |
| } | |
| clearState(); | |
| clearUI(ic); | |
| } | |
| void commitCurrent(fc::InputContext *ic) { | |
| if (mode_ == Mode::Convert) commit(ic, composed()); | |
| else if (composing()) commit(ic, flushKana(kata_)); | |
| } | |
| std::string flushKana(bool kata) { | |
| json req{{"cmd", "flush"}, {"buf", buf_}, {"base", baseKana_}, {"kata", kata}}; | |
| json res; | |
| if (daemon_.call(req, res, 500)) return res.value("kana", baseKana_ + buf_); | |
| return baseKana_ + buf_; | |
| } | |
| void refresh(fc::InputContext *ic) { | |
| if (mode_ == Mode::Convert) updateConvert(ic); | |
| else updateInput(ic); | |
| } | |
| void updateInput(fc::InputContext *ic) { | |
| if (!composing()) { clearUI(ic); return; } | |
| json req{{"cmd", "romaji"}, {"buf", buf_}, {"base", baseKana_}, {"kata", kata_}}; | |
| json res; | |
| std::string shown; | |
| std::string aux = std::string(chat_ ? "CHAT> " : "") + (kata_ ? "カナ" : "かな"); | |
| if (daemon_.call(req, res, 300)) { | |
| shown = res.value("kana", "") + res.value("pending", ""); | |
| } else { | |
| shown = baseKana_ + buf_; | |
| aux = "daemon 未起動"; | |
| } | |
| fc::Text text; | |
| text.append(shown, fc::TextFormatFlag::Underline); | |
| text.setCursor(static_cast<int>(utf8Len(shown))); | |
| ic->inputPanel().setClientPreedit(text); | |
| ic->inputPanel().setPreedit(fc::Text(shown)); | |
| ic->inputPanel().setAuxUp(fc::Text(aux)); | |
| ic->inputPanel().setAuxDown(fc::Text("")); | |
| ic->inputPanel().setCandidateList(nullptr); | |
| ic->updatePreedit(); | |
| ic->updateUserInterface(fc::UserInterfaceComponent::InputPanel); | |
| } | |
| void updateConvert(fc::InputContext *ic) { | |
| if (segs_.empty()) { clearUI(ic); return; } | |
| fc::Text text; | |
| int cursor = 0; | |
| for (size_t i = 0; i < segs_.size(); ++i) { | |
| if (kSepInPreedit && i) text.append(" ", fc::TextFormatFlag::Underline); | |
| std::string s = segText(i); | |
| if (i == focus_) { | |
| text.append(s, {fc::TextFormatFlag::Underline, fc::TextFormatFlag::HighLight}); | |
| cursor = static_cast<int>(utf8Len(text.toString())); | |
| } else { | |
| text.append(s, fc::TextFormatFlag::Underline); | |
| } | |
| } | |
| text.setCursor(cursor); | |
| ic->inputPanel().setClientPreedit(text); | |
| ic->inputPanel().setPreedit(fc::Text(text.toString())); | |
| const auto &seg = segs_[focus_]; | |
| auto cl = std::make_unique<fc::CommonCandidateList>(); | |
| cl->setPageSize(kPageSize); | |
| cl->setSelectionKey(fc::Key::keyListFromString("1 2 3 4 5 6 7 8 9")); | |
| for (size_t i = 0; i < seg.cands.size(); ++i) { | |
| cl->append(std::make_unique<AiCandidate>(this, seg.cands[i], i)); | |
| } | |
| cl->setGlobalCursorIndex(static_cast<int>(seg.idx)); | |
| ic->inputPanel().setCandidateList(std::move(cl)); | |
| std::string aux = "[" + std::to_string(focus_ + 1) + "/" + | |
| std::to_string(segs_.size()) + "] " + seg.reading; | |
| if (!seg.aiTop.empty()) { | |
| char tmp[64]; | |
| std::snprintf(tmp, sizeof(tmp), " AI: %s (%.2f)", seg.aiTop.c_str(), seg.aiProb); | |
| aux += tmp; | |
| } | |
| if (!note_.empty()) aux += " " + note_; | |
| ic->inputPanel().setAuxUp(fc::Text(aux)); | |
| std::string breakdown; | |
| for (size_t i = 0; i < segs_.size(); ++i) { | |
| if (i) breakdown += "|"; | |
| if (i == focus_) breakdown += "【"; | |
| breakdown += segText(i); | |
| if (i == focus_) breakdown += "】"; | |
| } | |
| ic->inputPanel().setAuxDown(fc::Text(breakdown)); | |
| ic->updatePreedit(); | |
| ic->updateUserInterface(fc::UserInterfaceComponent::InputPanel); | |
| } | |
| void doConvert(fc::InputContext *ic, bool progressive) { | |
| json req{{"cmd", "convert"}, {"buf", buf_}, {"base", baseKana_}}; | |
| json res; | |
| if (!daemon_.call(req, res, 2000) || !res.contains("segments")) { | |
| note_ = "daemon 応答なし"; | |
| updateInput(ic); | |
| return; | |
| } | |
| origKana_ = res.value("kana", ""); | |
| segs_.clear(); | |
| for (const auto &j : res["segments"]) { | |
| Segment s; | |
| s.reading = j.value("reading", ""); | |
| for (const auto &c : j["cands"]) s.cands.push_back(c.get<std::string>()); | |
| if (s.cands.empty()) s.cands.push_back(s.reading); | |
| if (j.contains("ai") && !j["ai"].empty()) { | |
| s.aiTop = j["ai"][0][0].get<std::string>(); | |
| s.aiProb = j["ai"][0][1].get<double>(); | |
| } | |
| segs_.push_back(std::move(s)); | |
| } | |
| if (segs_.empty()) return; | |
| progressive_ = progressive; | |
| revealed_ = 0; | |
| mode_ = Mode::Convert; | |
| focus_ = 0; | |
| note_ = res.value("note", ""); | |
| updateConvert(ic); | |
| } | |
| void backToInput(fc::InputContext *ic, bool dropLast) { | |
| mode_ = Mode::Input; | |
| baseKana_ = origKana_; | |
| if (dropLast) utf8Pop(baseKana_); | |
| buf_.clear(); segs_.clear(); note_.clear(); | |
| progressive_ = false; revealed_ = 0; | |
| updateInput(ic); | |
| } | |
| void handleInput(fc::KeyEvent &keyEvent, fc::KeySym sym, char ch) { | |
| auto *ic = keyEvent.inputContext(); | |
| if (sym == FcitxKey_space || sym == FcitxKey_Henkan) { | |
| if (composing()) { | |
| doConvert(ic, keyEvent.key().states().test(fc::KeyState::Shift)); | |
| keyEvent.filterAndAccept(); | |
| } | |
| return; | |
| } | |
| if (sym == FcitxKey_Return || sym == FcitxKey_KP_Enter || sym == FcitxKey_Muhenkan) { | |
| if (composing()) { | |
| if (chat_) chatSend(ic, flushKana(kata_)); | |
| else commit(ic, flushKana(kata_)); | |
| keyEvent.filterAndAccept(); | |
| } | |
| return; | |
| } | |
| if (sym == FcitxKey_F6) { | |
| if (composing()) { | |
| if (chat_) chatSend(ic, flushKana(false)); | |
| else commit(ic, flushKana(false)); | |
| keyEvent.filterAndAccept(); | |
| } | |
| return; | |
| } | |
| if (sym == FcitxKey_F7) { | |
| if (composing()) { | |
| if (chat_) chatSend(ic, flushKana(true)); | |
| else commit(ic, flushKana(true)); | |
| keyEvent.filterAndAccept(); | |
| } | |
| return; | |
| } | |
| if (sym == FcitxKey_Escape) { | |
| if (composing()) { | |
| clearState(); | |
| if (chat_) updateChatIdle(ic); | |
| else clearUI(ic); | |
| keyEvent.filterAndAccept(); | |
| } | |
| return; | |
| } | |
| if (sym == FcitxKey_BackSpace) { | |
| if (!buf_.empty()) { | |
| buf_.pop_back(); | |
| updateInput(ic); | |
| keyEvent.filterAndAccept(); | |
| } else if (!baseKana_.empty()) { | |
| utf8Pop(baseKana_); | |
| updateInput(ic); | |
| keyEvent.filterAndAccept(); | |
| } | |
| return; | |
| } | |
| if (sym == FcitxKey_Katakana || sym == FcitxKey_Hiragana || | |
| sym == FcitxKey_Hiragana_Katakana) { | |
| if (sym == FcitxKey_Katakana) kata_ = true; | |
| else if (sym == FcitxKey_Hiragana) kata_ = false; | |
| else kata_ = !kata_; | |
| updateInput(ic); | |
| keyEvent.filterAndAccept(); | |
| return; | |
| } | |
| if (!composing() && ch) { | |
| if (const char *p = jpPunct(ch)) { | |
| ic->commitString(p); | |
| keyEvent.filterAndAccept(); | |
| return; | |
| } | |
| } | |
| if (ch && ch != ' ') { | |
| if (composing() || std::isalpha(static_cast<unsigned char>(ch))) { | |
| if (std::isalpha(static_cast<unsigned char>(ch))) { | |
| ch = static_cast<char>(std::tolower(static_cast<unsigned char>(ch))); | |
| } | |
| buf_.push_back(ch); | |
| updateInput(ic); | |
| keyEvent.filterAndAccept(); | |
| } | |
| } | |
| } | |
| void handleConvert(fc::KeyEvent &keyEvent, fc::KeySym sym, char ch) { | |
| auto *ic = keyEvent.inputContext(); | |
| if (segs_.empty()) { clearState(); clearUI(ic); return; } | |
| if (sym == FcitxKey_Return || sym == FcitxKey_KP_Enter) { | |
| if (chat_) chatSend(ic, composed()); | |
| else commit(ic, composed()); | |
| keyEvent.filterAndAccept(); | |
| return; | |
| } | |
| if (sym == FcitxKey_Escape) { backToInput(ic, false); keyEvent.filterAndAccept(); return; } | |
| if (sym == FcitxKey_BackSpace) { backToInput(ic, true); keyEvent.filterAndAccept(); return; } | |
| if (sym == FcitxKey_space || sym == FcitxKey_Down || sym == FcitxKey_Henkan) { | |
| auto &seg = segs_[focus_]; | |
| seg.idx = (seg.idx + 1) % seg.cands.size(); | |
| updateConvert(ic); keyEvent.filterAndAccept(); return; | |
| } | |
| if (sym == FcitxKey_Up) { | |
| auto &seg = segs_[focus_]; | |
| seg.idx = (seg.idx + seg.cands.size() - 1) % seg.cands.size(); | |
| updateConvert(ic); keyEvent.filterAndAccept(); return; | |
| } | |
| if (sym == FcitxKey_Page_Down || sym == FcitxKey_Page_Up) { | |
| auto &seg = segs_[focus_]; | |
| int delta = (sym == FcitxKey_Page_Down) ? kPageSize : -kPageSize; | |
| int next = static_cast<int>(seg.idx) + delta; | |
| next = std::max(0, std::min(next, static_cast<int>(seg.cands.size()) - 1)); | |
| seg.idx = static_cast<size_t>(next); | |
| updateConvert(ic); keyEvent.filterAndAccept(); return; | |
| } | |
| if (sym == FcitxKey_Right || sym == FcitxKey_Tab) { | |
| focus_ = (focus_ + 1) % segs_.size(); | |
| revealed_ = std::max(revealed_, focus_); | |
| updateConvert(ic); keyEvent.filterAndAccept(); return; | |
| } | |
| if (sym == FcitxKey_Left || sym == FcitxKey_ISO_Left_Tab) { | |
| focus_ = (focus_ + segs_.size() - 1) % segs_.size(); | |
| updateConvert(ic); keyEvent.filterAndAccept(); return; | |
| } | |
| if (sym == FcitxKey_Home) { focus_ = 0; updateConvert(ic); keyEvent.filterAndAccept(); return; } | |
| if (sym == FcitxKey_End) { | |
| focus_ = segs_.size() - 1; revealed_ = focus_; | |
| updateConvert(ic); keyEvent.filterAndAccept(); return; | |
| } | |
| if (sym == FcitxKey_F6 || sym == FcitxKey_Muhenkan) { | |
| commit(ic, origKana_); keyEvent.filterAndAccept(); return; | |
| } | |
| if (sym == FcitxKey_F7) { | |
| json req{{"cmd", "flush"}, {"buf", ""}, {"base", origKana_}, {"kata", true}}; | |
| json res; | |
| std::string kata = origKana_; | |
| if (daemon_.call(req, res, 300)) kata = res.value("kana", origKana_); | |
| commit(ic, kata); keyEvent.filterAndAccept(); return; | |
| } | |
| if (ch >= '1' && ch <= '9') { | |
| auto &seg = segs_[focus_]; | |
| size_t page = seg.idx / kPageSize; | |
| size_t i = page * kPageSize + static_cast<size_t>(ch - '1'); | |
| if (i < seg.cands.size()) { seg.idx = i; updateConvert(ic); } | |
| keyEvent.filterAndAccept(); return; | |
| } | |
| if (ch && ch != ' ') { | |
| if (chat_) chatSend(ic, composed()); | |
| else commit(ic, composed()); | |
| handleInput(keyEvent, sym, ch); | |
| return; | |
| } | |
| } | |
| // ---- tts ---- | |
| void ttsSay(const std::string &text, const std::string &reading) { | |
| json req{{"cmd", "tts_say"}, {"text", text}}; | |
| if (!reading.empty()) req["reading"] = reading; | |
| json res; | |
| daemon_.call(req, res, 300); // デーモンは enqueue だけなので即返る | |
| } | |
| void ttsSpeak(fc::InputContext *ic) { | |
| if (chat_ && !chatReply_.empty()) { | |
| ttsSay(chatReply_, ""); // 漢字 → 任意の pyopenjtalk 経路 | |
| } else if (mode_ == Mode::Convert && !segs_.empty()) { | |
| ttsSay(composed(), origKana_); // 変換中は読みを持っている | |
| } else if (composing()) { | |
| ttsSay("", flushKana(false)); // 入力中のかなをそのまま | |
| } else if (!lastCommit_.empty()) { | |
| ttsSay(lastCommit_, lastReading_); // 直前の確定をリプレイ | |
| } | |
| } | |
| void ttsStop() { json res; daemon_.call({{"cmd", "tts_stop"}}, res, 200); } | |
| void ttsClipboard() { json res; daemon_.call({{"cmd", "tts_clipboard"}}, res, 2500); } | |
| // ---- chat(すべてクラス直下のメンバー) ---- | |
| void toggleChat(fc::InputContext *ic) { | |
| if (chat_) { exitChat(ic); return; } | |
| if (composing()) commitCurrent(ic); | |
| chat_ = true; | |
| chatReply_.clear(); chatJob_.clear(); chatPending_ = false; | |
| updateChatIdle(ic); | |
| } | |
| void exitChat(fc::InputContext *ic) { | |
| if (chatPending_) { | |
| json res; daemon_.call({{"cmd", "chat_cancel"}}, res, 200); | |
| } | |
| chat_ = false; chatPending_ = false; | |
| chatJob_.clear(); chatReply_.clear(); | |
| clearState(); | |
| clearUI(ic); | |
| } | |
| void chatReset(fc::InputContext *ic) { | |
| json res; daemon_.call({{"cmd", "chat_reset"}}, res, 300); | |
| chatPending_ = false; chatJob_.clear(); chatReply_.clear(); | |
| updateChatIdle(ic); | |
| } | |
| void chatSend(fc::InputContext *ic, const std::string &msg) { | |
| if (msg.empty()) return; | |
| json res; | |
| if (!daemon_.call({{"cmd", "chat_send"}, {"msg", msg}}, res, 500) || | |
| !res.value("ok", false)) { | |
| chatReply_ = "(daemon 応答なし / chat_gguf 未設定)"; | |
| clearState(); | |
| updateChatIdle(ic); | |
| return; | |
| } | |
| chatJob_ = res.value("job", ""); | |
| chatReply_.clear(); | |
| chatPending_ = true; | |
| clearState(); | |
| startChatTimer(); | |
| updateChatIdle(ic); | |
| } | |
| void startChatTimer() { | |
| if (!chatTimer_) { | |
| chatTimer_ = instance_->eventLoop().addTimeEvent( | |
| CLOCK_MONOTONIC, fcitx::now(CLOCK_MONOTONIC) + 80000, 0, | |
| [this](fc::EventSourceTime *ev, uint64_t) { | |
| chatPoll(); | |
| if (!chatPending_) return false; | |
| ev->setNextInterval(80000); | |
| ev->setOneShot(); | |
| return true; | |
| }); | |
| chatTimer_->setOneShot(); | |
| } else { | |
| chatTimer_->setNextInterval(80000); | |
| chatTimer_->setOneShot(); | |
| chatTimer_->setEnabled(true); | |
| } | |
| } | |
| void chatPoll() { | |
| if (!chatPending_ || chatJob_.empty()) return; | |
| json res; | |
| if (!daemon_.call({{"cmd", "chat_poll"}, {"job", chatJob_}}, res, 100)) return; | |
| chatReply_ = res.value("text", chatReply_); | |
| if (res.contains("error") && res["error"].is_string()) { | |
| chatReply_ = "[error] " + res["error"].get<std::string>(); | |
| } | |
| if (res.value("done", false)) chatPending_ = false; | |
| auto *ic = instance_->mostRecentInputContext(); | |
| if (chat_ && ic && ic->hasFocus() && !composing()) updateChatIdle(ic); | |
| } | |
| void updateChatIdle(fc::InputContext *ic) { | |
| if (!chat_ || composing()) return; | |
| std::string shown = chatReply_.empty() ? "(メッセージを入力)" : chatReply_; | |
| std::replace(shown.begin(), shown.end(), '\n', ' '); | |
| shown = utf8Clip(shown, 100, chatPending_); | |
| fc::Text text; | |
| text.append((chatPending_ ? "[生成中] " : "[AI] ") + shown, | |
| fc::TextFormatFlag::Underline); | |
| text.setCursor(static_cast<int>(utf8Len(text.toString()))); | |
| ic->inputPanel().setClientPreedit(text); | |
| ic->inputPanel().setPreedit(fc::Text(shown)); | |
| ic->inputPanel().setAuxUp(fc::Text( | |
| "CHAT Enter=回答 C-Enter=ログ C-r=リセット Esc=終了")); | |
| ic->inputPanel().setAuxDown(fc::Text(chatPending_ | |
| ? "生成中… " + std::to_string(utf8Len(chatReply_)) + "文字 (Enterで途中確定)" | |
| : "1-9=行だけ確定 / 英字で次のメッセージ")); | |
| auto lines = splitLines(chatReply_); | |
| if (!lines.empty()) { | |
| auto cl = std::make_unique<fc::CommonCandidateList>(); | |
| cl->setPageSize(kPageSize); | |
| cl->setSelectionKey(fc::Key::keyListFromString("1 2 3 4 5 6 7 8 9")); | |
| for (size_t i = 0; i < lines.size() && i < 27; ++i) { | |
| cl->append(std::make_unique<ChatLineCandidate>(this, lines[i])); | |
| } | |
| cl->setGlobalCursorIndex(-1); | |
| ic->inputPanel().setCandidateList(std::move(cl)); | |
| } else { | |
| ic->inputPanel().setCandidateList(nullptr); | |
| } | |
| ic->updatePreedit(); | |
| ic->updateUserInterface(fc::UserInterfaceComponent::InputPanel); | |
| } | |
| void commitChatReply(fc::InputContext *ic) { | |
| if (chatPending_) { | |
| json res; daemon_.call({{"cmd", "chat_cancel"}}, res, 300); | |
| chatPending_ = false; | |
| if (!chatJob_.empty() && | |
| daemon_.call({{"cmd", "chat_poll"}, {"job", chatJob_}}, res, 200)) { | |
| chatReply_ = res.value("text", chatReply_); | |
| } | |
| } | |
| if (!chatReply_.empty()) { | |
| lastCommit_ = chatReply_; lastReading_.clear(); | |
| ic->commitString(chatReply_); | |
| chatReply_.clear(); | |
| } | |
| updateChatIdle(ic); | |
| } | |
| void commitChatLog(fc::InputContext *ic) { | |
| if (chatPending_) { | |
| json res; daemon_.call({{"cmd", "chat_cancel"}}, res, 300); | |
| chatPending_ = false; | |
| } | |
| json res; | |
| if (daemon_.call({{"cmd", "chat_log"}}, res, 500)) { | |
| std::string md = res.value("markdown", ""); | |
| if (!md.empty()) { | |
| ic->commitString(md); | |
| chatReply_.clear(); | |
| updateChatIdle(ic); | |
| } | |
| } | |
| } | |
| void handleChatIdle(fc::KeyEvent &keyEvent, fc::KeySym sym, char ch) { | |
| auto *ic = keyEvent.inputContext(); | |
| if (sym == FcitxKey_Return || sym == FcitxKey_KP_Enter) { | |
| commitChatReply(ic); keyEvent.filterAndAccept(); return; | |
| } | |
| if (sym == FcitxKey_Escape) { | |
| if (chatPending_) { | |
| json res; daemon_.call({{"cmd", "chat_cancel"}}, res, 300); | |
| chatPending_ = false; | |
| } else if (!chatReply_.empty()) { | |
| chatReply_.clear(); | |
| } else { | |
| exitChat(ic); keyEvent.filterAndAccept(); return; | |
| } | |
| updateChatIdle(ic); keyEvent.filterAndAccept(); return; | |
| } | |
| if (sym == FcitxKey_BackSpace) { | |
| chatReply_.clear(); updateChatIdle(ic); keyEvent.filterAndAccept(); return; | |
| } | |
| if (ch >= '1' && ch <= '9') { | |
| auto lines = splitLines(chatReply_); | |
| size_t i = static_cast<size_t>(ch - '1'); | |
| if (i < lines.size()) commitChatLine(ic, lines[i]); | |
| keyEvent.filterAndAccept(); return; | |
| } | |
| if (ch && ch != ' ') { | |
| chatReply_.clear(); | |
| if (std::isalpha(static_cast<unsigned char>(ch))) { | |
| handleInput(keyEvent, sym, ch); | |
| } else { | |
| buf_.push_back(ch); | |
| updateInput(ic); | |
| keyEvent.filterAndAccept(); | |
| } | |
| return; | |
| } | |
| // それ以外のキーはアプリに素通し | |
| } | |
| void keyEventImpl(fc::KeyEvent &keyEvent) { | |
| if (keyEvent.isRelease()) return; | |
| const auto &key = keyEvent.key(); | |
| auto sym = key.sym(); | |
| auto states = key.states(); | |
| if (states.test(fc::KeyState::Alt) || states.test(fc::KeyState::Super)) return; | |
| if (states.test(fc::KeyState::Ctrl)) { | |
| if (sym == FcitxKey_slash) { | |
| toggleChat(keyEvent.inputContext()); | |
| keyEvent.filterAndAccept(); | |
| } else if (chat_ && (sym == FcitxKey_Return || sym == FcitxKey_KP_Enter)) { | |
| commitChatLog(keyEvent.inputContext()); | |
| keyEvent.filterAndAccept(); | |
| } else if (chat_ && (sym == FcitxKey_r || sym == FcitxKey_R)) { | |
| chatReset(keyEvent.inputContext()); | |
| keyEvent.filterAndAccept(); | |
| } else if (sym == FcitxKey_j || sym == FcitxKey_J) { | |
| kata_ = false; refresh(keyEvent.inputContext()); keyEvent.filterAndAccept(); | |
| } else if (sym == FcitxKey_k || sym == FcitxKey_K) { | |
| kata_ = true; refresh(keyEvent.inputContext()); keyEvent.filterAndAccept(); | |
| } else if (sym == FcitxKey_s || sym == FcitxKey_S) { | |
| if (states.test(fc::KeyState::Shift)) ttsClipboard(); | |
| else ttsSpeak(keyEvent.inputContext()); | |
| keyEvent.filterAndAccept(); | |
| } else if (sym == FcitxKey_x || sym == FcitxKey_X) { | |
| ttsStop(); | |
| keyEvent.filterAndAccept(); | |
| } | |
| return; | |
| } | |
| char ch = (sym >= 0x20 && sym <= 0x7e) ? static_cast<char>(sym) : 0; | |
| if (chat_ && !composing()) { | |
| handleChatIdle(keyEvent, sym, ch); | |
| } else if (mode_ == Mode::Convert) { | |
| handleConvert(keyEvent, sym, ch); | |
| } else { | |
| handleInput(keyEvent, sym, ch); | |
| } | |
| } | |
| }; | |
| void AiKanaEngine::keyEvent(const fc::InputMethodEntry &, fc::KeyEvent &keyEvent) { | |
| keyEventImpl(keyEvent); | |
| } | |
| void AiCandidate::select(fc::InputContext *ic) const { | |
| engine_->selectCandidate(ic, idx_); | |
| } | |
| void ChatLineCandidate::select(fc::InputContext *ic) const { | |
| engine_->commitChatLine(ic, line_); | |
| } | |
| class AiKanaFactory : public fc::AddonFactory { | |
| fc::AddonInstance *create(fc::AddonManager *manager) override { | |
| return new AiKanaEngine(manager->instance()); | |
| } | |
| }; | |
| FCITX_ADDON_FACTORY(AiKanaFactory); | |