Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions fcitx5-engine/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -22,6 +22,11 @@ add_library(path_utils_obj OBJECT src/path_utils.cpp)
target_include_directories(path_utils_obj PUBLIC src)
set_target_properties(path_utils_obj PROPERTIES POSITION_INDEPENDENT_CODE ON)

# seen_apps — apps typed in, for the settings app's Per-app page
add_library(seen_apps_obj OBJECT src/seen_apps.cpp)
target_include_directories(seen_apps_obj PUBLIC src)
set_target_properties(seen_apps_obj PROPERTIES POSITION_INDEPENDENT_CODE ON)

# corpus_collector compiled once; reused by the addon and the test binary
add_library(corpus_collector_obj OBJECT src/corpus_collector.cpp)
target_include_directories(corpus_collector_obj PUBLIC src)
Expand Down Expand Up @@ -49,6 +54,7 @@ target_include_directories(xtype-fcitx5 PRIVATE src)
target_link_libraries(xtype-fcitx5 PRIVATE
context_buffer_obj
path_utils_obj
seen_apps_obj
corpus_collector_obj
style_profile_obj
prompt_builder_obj
Expand Down
153 changes: 153 additions & 0 deletions fcitx5-engine/src/seen_apps.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,153 @@
#include "seen_apps.h"

#include <algorithm>
#include <cinttypes>
#include <cstdio>
#include <cstdlib>
#include <fstream>
#include <iterator>
#include <vector>

namespace {

std::string escape(std::string_view s) {
std::string out;
out.reserve(s.size());
for (char c : s) {
switch (c) {
case '"': out += "\\\""; break;
case '\\': out += "\\\\"; break;
case '\n': out += "\\n"; break;
case '\r': out += "\\r"; break;
case '\t': out += "\\t"; break;
default:
if (static_cast<unsigned char>(c) < 0x20) continue; // drop other controls
out += c;
}
}
return out;
}

// Reads the JSON string starting at json[pos] == '"'. On success returns true,
// stores the unescaped text and leaves pos just past the closing quote.
bool readString(std::string_view json, size_t& pos, std::string& out) {
if (pos >= json.size() || json[pos] != '"') return false;
out.clear();
for (++pos; pos < json.size(); ++pos) {
char c = json[pos];
if (c == '"') { ++pos; return true; }
if (c == '\\' && pos + 1 < json.size()) {
char e = json[++pos];
switch (e) {
case 'n': out += '\n'; break;
case 'r': out += '\r'; break;
case 't': out += '\t'; break;
default: out += e; // \" \\ \/
}
} else {
out += c;
}
}
return false;
}

// Value of `"key": <string|number>` inside json[begin, end).
bool findString(std::string_view json, size_t begin, size_t end,
std::string_view key, std::string& out) {
std::string needle = "\"" + std::string(key) + "\"";
size_t k = json.find(needle, begin);
if (k == std::string_view::npos || k >= end) return false;
size_t p = json.find_first_not_of(" \t\r\n:", k + needle.size());
return p != std::string_view::npos && p < end && readString(json, p, out);
}

bool findNumber(std::string_view json, size_t begin, size_t end,
std::string_view key, long long& out) {
std::string needle = "\"" + std::string(key) + "\"";
size_t k = json.find(needle, begin);
if (k == std::string_view::npos || k >= end) return false;
size_t p = json.find_first_not_of(" \t\r\n:", k + needle.size());
if (p == std::string_view::npos || p >= end) return false;
std::string digits(json.substr(p, std::min<size_t>(20, end - p)));
char* stop = nullptr;
out = std::strtoll(digits.c_str(), &stop, 10);
return stop != digits.c_str();
}

} // namespace

void SeenApps::parse(std::string_view json) {
_apps.clear();
// Each app is one flat {...} object. Strings are stepped over as JSON
// strings while looking for the closing brace, so a brace inside a name
// doesn't end the object early.
size_t pos = json.find('[');
while (pos != std::string_view::npos) {
size_t open = json.find('{', pos);
if (open == std::string_view::npos) break;
std::string name;
size_t end = open + 1;
// Find the object's closing brace, stepping over strings.
while (end < json.size() && json[end] != '}') {
if (json[end] == '"') {
std::string skipped;
if (!readString(json, end, skipped)) return;
} else {
++end;
}
}
if (end >= json.size()) break;
long long ts = 0;
if (findString(json, open, end, "name", name) && !name.empty()) {
findNumber(json, open, end, "last_seen", ts);
_apps[name] = static_cast<std::time_t>(ts);
}
pos = end + 1;
}
}

std::string SeenApps::toJson() const {
// Most recent first, which is also the order the settings app shows.
std::vector<std::pair<std::string, std::time_t>> list(_apps.begin(), _apps.end());
std::stable_sort(list.begin(), list.end(),
[](const auto& a, const auto& b) { return a.second > b.second; });
std::string out = "{\"apps\":[";
for (size_t i = 0; i < list.size(); ++i) {
char ts[32];
std::snprintf(ts, sizeof(ts), "%" PRId64, static_cast<int64_t>(list[i].second));
out += i ? ",\n " : "\n ";
out += "{\"name\":\"" + escape(list[i].first) + "\",\"last_seen\":" + ts + "}";
}
out += "\n]}\n";
return out;
}

bool SeenApps::touch(const std::string& name, std::time_t now) {
if (name.empty()) return false;
auto it = _apps.find(name);
if (it != _apps.end() && now - it->second < kRefreshSec) return false;
_apps[name] = now;
while (_apps.size() > kMaxApps) {
auto oldest = std::min_element(_apps.begin(), _apps.end(),
[](const auto& a, const auto& b) { return a.second < b.second; });
_apps.erase(oldest);
}
return true;
}

void SeenApps::load(const std::string& path) {
std::ifstream in(path);
if (!in) { _apps.clear(); return; }
std::string content((std::istreambuf_iterator<char>(in)), std::istreambuf_iterator<char>());
parse(content);
}

bool SeenApps::save(const std::string& path) const {
const std::string tmp = path + ".tmp";
FILE* f = std::fopen(tmp.c_str(), "w");
if (!f) return false;
const std::string json = toJson();
bool ok = std::fputs(json.c_str(), f) >= 0;
ok = (std::fclose(f) == 0) && ok;
return ok && std::rename(tmp.c_str(), path.c_str()) == 0;
}
41 changes: 41 additions & 0 deletions fcitx5-engine/src/seen_apps.h
Original file line number Diff line number Diff line change
@@ -0,0 +1,41 @@
#pragma once

// Apps the user has typed in, with when each was last used, so the settings
// app can list them on its Per-app page instead of a fixed list.
//
// Persisted as ~/.local/share/xtype/active_apps.json:
// {"apps":[{"name":"com.t3tools.T3Code","last_seen":1792023274}, ...]}
// `name` is the program name Fcitx5 reports (InputContext::program()), the
// same key [apps."<name>"] uses in config.toml.
//
// Main-thread only. Approach after K-Sugar's active_apps.json (094cb35).

#include <cstddef>
#include <ctime>
#include <map>
#include <string>
#include <string_view>

class SeenApps {
public:
// Re-stamp a known app at most this often, to keep file writes rare.
static constexpr std::time_t kRefreshSec = 600;
// Oldest apps are dropped beyond this many.
static constexpr std::size_t kMaxApps = 200;

// Replaces the contents with what `json` holds; unparseable parts are skipped.
void parse(std::string_view json);
std::string toJson() const;

// Records `name` as used at `now`. True when the stored list changed
// enough to be worth saving: a new app, or a stamp older than kRefreshSec.
bool touch(const std::string& name, std::time_t now);

void load(const std::string& path); // missing/unreadable file → empty
bool save(const std::string& path) const; // atomic (tmp + rename)

const std::map<std::string, std::time_t>& apps() const { return _apps; }

private:
std::map<std::string, std::time_t> _apps;
};
11 changes: 11 additions & 0 deletions fcitx5-engine/src/xtype.cpp
Original file line number Diff line number Diff line change
Expand Up @@ -88,6 +88,14 @@ XTypeEngine::XTypeEngine(fcitx::AddonManager *manager)

_phraseBlock.load(_cfg.behaviour.blocked_phrases);
dbg("XTypeEngine loaded, model=%s", _cfg.inference.model.c_str());

{
auto dir = path_utils::expandTilde("~/.local/share/xtype");
std::error_code ec;
std::filesystem::create_directories(dir, ec);
_seenAppsPath = (dir / "active_apps.json").string();
_seenApps.load(_seenAppsPath);
}
if (_debugVerbose)
dbg("[debug] verbose mode ON — sentence content will be written to debug.log");
if (_profileRefreshSec != kProfileRefreshSec)
Expand Down Expand Up @@ -181,6 +189,9 @@ void XTypeEngine::activate(const fcitx::InputMethodEntry &,
_lastProg = prog;
if (appChanged)
applyPrompt(); // re-apply prompt addendum for the new app

if (_seenApps.touch(prog, std::time(nullptr)) && !_seenApps.save(_seenAppsPath))
dbg("[apps] could not write %s", _seenAppsPath.c_str());
}

void XTypeEngine::deactivate(const fcitx::InputMethodEntry &,
Expand Down
3 changes: 3 additions & 0 deletions fcitx5-engine/src/xtype.h
Original file line number Diff line number Diff line change
Expand Up @@ -23,6 +23,7 @@
#include "inference_client.h"
#include "phrase_blocklist.h"
#include "recent_events.h"
#include "seen_apps.h"
#include "style_profile.h"

class XTypeEngine : public fcitx::InputMethodEngineV2 {
Expand Down Expand Up @@ -75,6 +76,8 @@ class XTypeEngine : public fcitx::InputMethodEngineV2 {
std::unique_ptr<fcitx::EventSourceTime> _debounceTimer;
uint64_t _gen{0};
std::string _lastProg;
SeenApps _seenApps; // for the settings app's Per-app page
std::string _seenAppsPath;

// Personalization state (Session 17). Populated only when learning enabled.
std::unique_ptr<StyleProfile> _profile; // main-thread only
Expand Down
7 changes: 7 additions & 0 deletions fcitx5-engine/tests/CMakeLists.txt
Original file line number Diff line number Diff line change
Expand Up @@ -8,6 +8,13 @@ target_link_libraries(test_context_buffer PRIVATE

catch_discover_tests(test_context_buffer)

add_executable(test_seen_apps test_seen_apps.cpp)
target_link_libraries(test_seen_apps PRIVATE
seen_apps_obj
Catch2::Catch2WithMain
)
catch_discover_tests(test_seen_apps)

add_executable(test_corpus_collector test_corpus_collector.cpp)
target_link_libraries(test_corpus_collector PRIVATE
corpus_collector_obj
Expand Down
76 changes: 76 additions & 0 deletions fcitx5-engine/tests/test_seen_apps.cpp
Original file line number Diff line number Diff line change
@@ -0,0 +1,76 @@
#include <catch2/catch_test_macros.hpp>

#include <cstdio>
#include <filesystem>
#include <string>

#include "seen_apps.h"

TEST_CASE("touch records a new app and asks for a save", "[seen_apps]") {
SeenApps s;
CHECK(s.touch("omawrite", 1000));
CHECK(s.apps().at("omawrite") == 1000);
}

TEST_CASE("touch ignores empty names", "[seen_apps]") {
SeenApps s;
CHECK_FALSE(s.touch("", 1000));
CHECK(s.apps().empty());
}

TEST_CASE("touch re-stamps a known app only after kRefreshSec", "[seen_apps]") {
SeenApps s;
s.touch("omawrite", 1000);
CHECK_FALSE(s.touch("omawrite", 1000 + SeenApps::kRefreshSec - 1));
CHECK(s.apps().at("omawrite") == 1000);
CHECK(s.touch("omawrite", 1000 + SeenApps::kRefreshSec));
CHECK(s.apps().at("omawrite") == 1000 + SeenApps::kRefreshSec);
}

TEST_CASE("touch drops the oldest app beyond kMaxApps", "[seen_apps]") {
SeenApps s;
for (std::size_t i = 0; i < SeenApps::kMaxApps; ++i)
s.touch("app" + std::to_string(i), static_cast<std::time_t>(100 + i));
s.touch("newest", 100000);
CHECK(s.apps().size() == SeenApps::kMaxApps);
CHECK(s.apps().count("app0") == 0);
CHECK(s.apps().count("newest") == 1);
}

TEST_CASE("toJson / parse round-trip, most recent first", "[seen_apps]") {
SeenApps s;
s.touch("omawrite", 1000);
s.touch("com.t3tools.T3Code", 2000);
s.touch("we\"ird\\na{me}", 1500);
const std::string json = s.toJson();
CHECK(json.find("com.t3tools.T3Code") < json.find("omawrite"));

SeenApps r;
r.parse(json);
CHECK(r.apps() == s.apps());
}

TEST_CASE("parse tolerates garbage and missing fields", "[seen_apps]") {
SeenApps s;
s.parse("not json at all");
CHECK(s.apps().empty());
s.parse(R"({"apps":[{"name":"a"},{"last_seen":5},{"name":"b","last_seen":7}]})");
CHECK(s.apps().size() == 2);
CHECK(s.apps().at("a") == 0);
CHECK(s.apps().at("b") == 7);
}

TEST_CASE("save / load through a file", "[seen_apps]") {
auto path = (std::filesystem::temp_directory_path() / "xtype_seen_apps_test.json").string();
SeenApps s;
s.touch("kate", 42);
REQUIRE(s.save(path));
SeenApps r;
r.load(path);
CHECK(r.apps() == s.apps());
std::remove(path.c_str());

SeenApps missing;
missing.load(path);
CHECK(missing.apps().empty());
}
9 changes: 5 additions & 4 deletions settings/qt6-app/qml/pages/PageBlockList.qml
Original file line number Diff line number Diff line change
Expand Up @@ -149,17 +149,18 @@ Item {
height: parent.height - 60
clip: true
model: {
const all = AppsKnown.knownApps()
return all.filter(a => Config.blocklistApps.indexOf(a.canonical) < 0)
const all = AppsKnown.appList(Config.apps, AppsKnown.seenApps)
return all.filter(a => Config.blocklistApps.indexOf(a.name) < 0)
}
spacing: 4
delegate: XAppRow {
required property var modelData
appLabel: modelData.label
iconCls: modelData.iconCls
appSub: modelData.name
iconName: modelData.iconName
width: parent ? parent.width : 0
onClicked: {
Config.blocklistApps = Config.blocklistApps.concat([modelData.canonical])
Config.blocklistApps = Config.blocklistApps.concat([modelData.name])
appPickerOverlay.visible = false
}
}
Expand Down
Loading