diff --git a/fcitx5-engine/CMakeLists.txt b/fcitx5-engine/CMakeLists.txt index 8326f18..bec5715 100644 --- a/fcitx5-engine/CMakeLists.txt +++ b/fcitx5-engine/CMakeLists.txt @@ -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) @@ -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 diff --git a/fcitx5-engine/src/seen_apps.cpp b/fcitx5-engine/src/seen_apps.cpp new file mode 100644 index 0000000..92d2a53 --- /dev/null +++ b/fcitx5-engine/src/seen_apps.cpp @@ -0,0 +1,153 @@ +#include "seen_apps.h" + +#include +#include +#include +#include +#include +#include +#include + +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(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": ` 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(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(ts); + } + pos = end + 1; + } +} + +std::string SeenApps::toJson() const { + // Most recent first, which is also the order the settings app shows. + std::vector> 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(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(in)), std::istreambuf_iterator()); + 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; +} diff --git a/fcitx5-engine/src/seen_apps.h b/fcitx5-engine/src/seen_apps.h new file mode 100644 index 0000000..1664d9c --- /dev/null +++ b/fcitx5-engine/src/seen_apps.h @@ -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.""] uses in config.toml. +// +// Main-thread only. Approach after K-Sugar's active_apps.json (094cb35). + +#include +#include +#include +#include +#include + +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& apps() const { return _apps; } + +private: + std::map _apps; +}; diff --git a/fcitx5-engine/src/xtype.cpp b/fcitx5-engine/src/xtype.cpp index 3447540..79d1e2a 100644 --- a/fcitx5-engine/src/xtype.cpp +++ b/fcitx5-engine/src/xtype.cpp @@ -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) @@ -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 &, diff --git a/fcitx5-engine/src/xtype.h b/fcitx5-engine/src/xtype.h index 8046036..3b1fd7e 100644 --- a/fcitx5-engine/src/xtype.h +++ b/fcitx5-engine/src/xtype.h @@ -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 { @@ -75,6 +76,8 @@ class XTypeEngine : public fcitx::InputMethodEngineV2 { std::unique_ptr _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 _profile; // main-thread only diff --git a/fcitx5-engine/tests/CMakeLists.txt b/fcitx5-engine/tests/CMakeLists.txt index 4d9d53f..ea531e5 100644 --- a/fcitx5-engine/tests/CMakeLists.txt +++ b/fcitx5-engine/tests/CMakeLists.txt @@ -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 diff --git a/fcitx5-engine/tests/test_seen_apps.cpp b/fcitx5-engine/tests/test_seen_apps.cpp new file mode 100644 index 0000000..b4b1e93 --- /dev/null +++ b/fcitx5-engine/tests/test_seen_apps.cpp @@ -0,0 +1,76 @@ +#include + +#include +#include +#include + +#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(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()); +} diff --git a/settings/qt6-app/qml/pages/PageBlockList.qml b/settings/qt6-app/qml/pages/PageBlockList.qml index 53af1ee..20a09d6 100644 --- a/settings/qt6-app/qml/pages/PageBlockList.qml +++ b/settings/qt6-app/qml/pages/PageBlockList.qml @@ -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 } } diff --git a/settings/qt6-app/qml/pages/PagePerApp.qml b/settings/qt6-app/qml/pages/PagePerApp.qml index dfdaacb..41f0b8e 100644 --- a/settings/qt6-app/qml/pages/PagePerApp.qml +++ b/settings/qt6-app/qml/pages/PagePerApp.qml @@ -34,23 +34,63 @@ Item { XSection { title: "Per-app settings"; num: "01"; width: parent.width } + // Apps you've typed in (most recent first) plus apps already + // configured. Keys are Fcitx5 program names, as in [apps.""]. Repeater { - model: AppsKnown.knownApps() + id: appRepeater + model: AppsKnown.appList(Config.apps, AppsKnown.seenApps) delegate: XAppRow { required property var modelData appLabel: modelData.label - appSub: modelData.canonical - iconCls: modelData.iconCls - selected: root.selectedId === modelData.id + appSub: modelData.name + iconName: modelData.iconName + selected: root.selectedId === modelData.name width: parent ? parent.width : 0 - onClicked: root.selectedId = modelData.id + onClicked: root.selectedId = modelData.name XToggle { on: { - const entry = Config.apps[modelData.canonical] + const entry = Config.apps[modelData.name] return entry ? (entry.enabled !== undefined ? entry.enabled : true) : true } - onToggled: (v) => Config.setApp(modelData.canonical, "enabled", v) + onToggled: (v) => Config.setApp(modelData.name, "enabled", v) + } + } + } + + Text { + visible: appRepeater.count === 0 + width: parent.width + text: "No apps yet. Apps appear here after you type in them with XType on, or add one below." + wrapMode: Text.WordWrap + font.family: Theme.sansFamily; font.pixelSize: 13 + color: Theme.ink45 + renderType: Text.NativeRendering + } + + // Add an app by its program name (as shown under each app above, + // or in XType's log), e.g. one not typed in yet. + Row { + width: parent.width + spacing: 8 + topPadding: 6 + + XInput { + id: addField + width: parent.width - addButton.width - 8 + placeholderText: "Add app by program name, e.g. org.kde.kate" + onAccepted: addButton.add() + } + XButton { + id: addButton + label: "Add" + onClicked: add() + function add() { + const name = addField.text.trim() + if (name === "") return + if (!Config.apps[name]) Config.setApp(name, "enabled", true) + root.selectedId = name + addField.text = "" } } } @@ -81,7 +121,7 @@ Item { // Eyebrow Text { text: root.selectedId !== "" - ? "Configuring · " + AppsKnown.labelForCanonical(AppsKnown.canonicalForId(root.selectedId)) + ? "Configuring · " + AppsKnown.labelFor(root.selectedId) : "" font.family: Theme.monoFamily; font.pixelSize: 11 font.capitalization: Font.AllUppercase; font.letterSpacing: 1.2 @@ -97,13 +137,12 @@ Item { XToggle { on: { if (root.selectedId === "") return true - const c = AppsKnown.canonicalForId(root.selectedId) - const entry = Config.apps[c] + const entry = Config.apps[root.selectedId] return entry ? (entry.enabled !== undefined ? entry.enabled : true) : true } onToggled: (v) => { if (root.selectedId !== "") - Config.setApp(AppsKnown.canonicalForId(root.selectedId), "enabled", v) + Config.setApp(root.selectedId, "enabled", v) } } } @@ -117,13 +156,13 @@ Item { model: ["Default", "Code-aware", "Email tone", "Casual", "Off"] currentIndex: { if (root.selectedId === "") return 0 - const entry = Config.apps[AppsKnown.canonicalForId(root.selectedId)] + const entry = Config.apps[root.selectedId] const m = entry ? entry.mode || "Default" : "Default" return Math.max(0, ["Default","Code-aware","Email tone","Casual","Off"].indexOf(m)) } onActivated: (i) => { if (root.selectedId === "") return - Config.setApp(AppsKnown.canonicalForId(root.selectedId), "mode", model[i]) + Config.setApp(root.selectedId, "mode", model[i]) } implicitWidth: 160; implicitHeight: 32 font.family: Theme.sansFamily; font.pixelSize: 12 @@ -152,16 +191,32 @@ Item { min: 4; max: 48; step: 1 value: { if (root.selectedId === "") return Config.numPredict - const entry = Config.apps[AppsKnown.canonicalForId(root.selectedId)] + const entry = Config.apps[root.selectedId] return entry && entry.num_predict ? entry.num_predict : Config.numPredict } width: 160 onCommitted: (v) => { if (root.selectedId !== "") - Config.setApp(AppsKnown.canonicalForId(root.selectedId), "num_predict", v) + Config.setApp(root.selectedId, "num_predict", v) } } } + + // Drops this app's [apps.""] section. An app added by + // hand and never typed in then leaves the list. + XButton { + visible: root.selectedId !== "" && Config.apps[root.selectedId] !== undefined + label: "Reset to defaults" + variant: "ghost" + onClicked: { + const id = root.selectedId + const m = Object.assign({}, Config.apps) + delete m[id] + Config.apps = m + if (!AppsKnown.seenApps.some(a => a.name === id)) + root.selectedId = "" + } + } } } diff --git a/settings/qt6-app/qml/primitives/XAppIcon.qml b/settings/qt6-app/qml/primitives/XAppIcon.qml index 28fdfb9..521e250 100644 --- a/settings/qt6-app/qml/primitives/XAppIcon.qml +++ b/settings/qt6-app/qml/primitives/XAppIcon.qml @@ -4,9 +4,15 @@ import XType.Settings 1.0 Rectangle { id: root property string cls: "" + // Theme icon name or path from the app's .desktop file; shown when it resolves. + property string iconName: "" + // Letter shown on the badge when there is no cls and no icon. + property string fallbackLetter: "" width: 32; height: 32; radius: 7 - border.width: 1; border.color: cls === "" ? Theme.ink12 : "transparent" + readonly property bool _hasIcon: themeIcon.status === Image.Ready + border.width: 1; border.color: cls === "" && !_hasIcon ? Theme.ink12 : "transparent" + color: "transparent" readonly property color _g0: { switch (cls) { @@ -31,15 +37,30 @@ Rectangle { } } - gradient: Gradient { + gradient: _hasIcon ? null : badgeGradient + + Gradient { + id: badgeGradient orientation: Gradient.Horizontal GradientStop { position: 0.0; color: root._g0 } GradientStop { position: 1.0; color: root._g1 } } + Image { + id: themeIcon + anchors.fill: parent + source: root.iconName !== "" ? "image://appicon/" + root.iconName : "" + sourceSize: Qt.size(64, 64) + fillMode: Image.PreserveAspectFit + smooth: true + visible: root._hasIcon + } + Text { anchors.centerIn: parent - text: root.cls !== "" ? root.cls.slice(0, 1).toUpperCase() : "?" + visible: !root._hasIcon + text: root.cls !== "" ? root.cls.slice(0, 1).toUpperCase() + : root.fallbackLetter !== "" ? root.fallbackLetter.slice(0, 1).toUpperCase() : "?" font.family: Theme.sansFamily; font.pixelSize: 14; font.weight: Font.DemiBold color: root.cls !== "" ? "white" : Theme.ink65 renderType: Text.NativeRendering diff --git a/settings/qt6-app/qml/primitives/XAppRow.qml b/settings/qt6-app/qml/primitives/XAppRow.qml index 776b414..d2a11f1 100644 --- a/settings/qt6-app/qml/primitives/XAppRow.qml +++ b/settings/qt6-app/qml/primitives/XAppRow.qml @@ -6,6 +6,7 @@ Item { property string appLabel: "" property string appSub: "" property string iconCls: "" + property string iconName: "" property bool selected: false property bool comingSoon: false default property alias contentData: controlSlot.data @@ -31,7 +32,12 @@ Item { anchors { left: parent.left; leftMargin: 14; verticalCenter: parent.verticalCenter } spacing: 12 - XAppIcon { cls: root.iconCls; anchors.verticalCenter: parent.verticalCenter } + XAppIcon { + cls: root.iconCls + iconName: root.iconName + fallbackLetter: root.appLabel + anchors.verticalCenter: parent.verticalCenter + } Column { anchors.verticalCenter: parent.verticalCenter diff --git a/settings/qt6-app/qml/primitives/XInput.qml b/settings/qt6-app/qml/primitives/XInput.qml index e1d4d80..1c52f99 100644 --- a/settings/qt6-app/qml/primitives/XInput.qml +++ b/settings/qt6-app/qml/primitives/XInput.qml @@ -9,6 +9,7 @@ Item { property alias maximumLength: tf.maximumLength property bool comingSoon: false signal editingFinished() + signal accepted() implicitWidth: 240 implicitHeight: 38 @@ -27,6 +28,7 @@ Item { Connections { target: tf function onEditingFinished() { root.editingFinished() } + function onAccepted() { root.accepted() } } TextField { diff --git a/settings/qt6-app/src/apps_known.cpp b/settings/qt6-app/src/apps_known.cpp index 89a3550..9607a5d 100644 --- a/settings/qt6-app/src/apps_known.cpp +++ b/settings/qt6-app/src/apps_known.cpp @@ -1,80 +1,201 @@ #include "apps_known.h" #include -#include -#include +#include +#include +#include +#include +#include +#include +#include +#include + +#include namespace { -struct AppEntry { - QString id; +struct BlockerEntry { QString label; - QString canonical; + QString canonical; // blocklist key QString iconCls; - QString defaultMode; }; -// §4 #11: display labels never reach TOML; canonical program names are the keys -static const AppEntry kApps[] = { - {"kate", "Kate", "kate", "kate", "Default"}, - {"tb", "Thunderbird", "org.mozilla.thunderbird", "tb", "Default"}, - {"kons", "Konsole", "org.kde.konsole", "kons", "Default"}, - {"firefox", "Firefox", "firefox", "fox", "Default"}, - {"discord", "Discord", "discord", "disc", "Default"}, +// Curated blocklist candidates: password managers + terminals. +const BlockerEntry kBlockers[] = { + {"KeePassXC", "keepassxc", "kde"}, + {"1Password", "1password", "kde"}, + {"Bitwarden", "bitwarden", "kde"}, + {"Discord", "discord", "disc"}, + {"Konsole", "org.kde.konsole", "kons"}, }; -// Curated blocklist candidates: password managers + terminals -// canonical IDs used as Config.blocklistApps keys -static const AppEntry kBlockers[] = { - {"keepassxc", "KeePassXC", "keepassxc", "kde", "Off"}, - {"1password", "1Password", "1password", "kde", "Off"}, - {"bitwarden", "Bitwarden", "bitwarden", "kde", "Off"}, - {"discord", "Discord", "discord", "disc", "Off"}, - {"kons", "Konsole", "org.kde.konsole", "kons", "Off"}, -}; +constexpr int kPollMs = 3000; } // namespace -AppsKnown::AppsKnown(QObject *parent) : QObject(parent) {} +AppsKnown::AppsKnown(const QString &seenAppsPath, QObject *parent) + : QObject(parent), + _path(seenAppsPath.isEmpty() + ? QDir::homePath() + "/.local/share/xtype/active_apps.json" + : seenAppsPath) { + poll(); + _timer.setInterval(kPollMs); + connect(&_timer, &QTimer::timeout, this, &AppsKnown::poll); + _timer.start(); +} + +void AppsKnown::poll() { + const QFileInfo fi(_path); + const QDateTime mtime = fi.exists() ? fi.lastModified() : QDateTime(); + if (mtime == _mtime) return; + _mtime = mtime; + + QVariantList seen; + QFile f(_path); + if (f.open(QIODevice::ReadOnly)) + seen = parseSeenApps(f.readAll()); + if (seen != _seen) { + _seen = seen; + emit seenAppsChanged(); + } +} + +QVariantList AppsKnown::parseSeenApps(const QByteArray &json) { + QVariantList out; + const auto apps = QJsonDocument::fromJson(json).object().value("apps").toArray(); + for (const auto &v : apps) { + const auto o = v.toObject(); + const QString name = o.value("name").toString(); + if (name.isEmpty()) continue; + out.append(QVariantMap{{"name", name}, + {"last_seen", o.value("last_seen").toInteger()}}); + } + std::stable_sort(out.begin(), out.end(), [](const QVariant &a, const QVariant &b) { + return a.toMap().value("last_seen").toLongLong() > b.toMap().value("last_seen").toLongLong(); + }); + return out; +} + +AppsKnown::DesktopInfo AppsKnown::parseDesktopEntry(const QString &text) { + DesktopInfo info; + bool inEntry = false; + const auto lines = text.split('\n'); + for (QString line : lines) { + line = line.trimmed(); + if (line.startsWith('[')) { + inEntry = (line == "[Desktop Entry]"); + continue; + } + if (!inEntry) continue; + const int eq = line.indexOf('='); + if (eq <= 0) continue; + const QString key = line.left(eq).trimmed(); // "Name[pt_BR]" is a different key + const QString val = line.mid(eq + 1).trimmed(); + if (key == "Name" && info.name.isEmpty()) info.name = val; + else if (key == "Icon" && info.icon.isEmpty()) info.icon = val; + else if (key == "StartupWMClass" && info.wmClass.isEmpty()) info.wmClass = val; + } + return info; +} + +QString AppsKnown::findDesktopFile(const QString &program, const QStringList &dirs) { + if (program.isEmpty()) return {}; + const QString wanted = program + ".desktop"; + // 1. .desktop, case-insensitive (app ids like com.t3tools.T3Code). + for (const QString &dir : dirs) { + QDirIterator it(dir, {"*.desktop"}, QDir::Files); + while (it.hasNext()) { + it.next(); + if (it.fileName().compare(wanted, Qt::CaseInsensitive) == 0) + return it.filePath(); + } + } + // 2. A .desktop whose StartupWMClass is the program name. + for (const QString &dir : dirs) { + QDirIterator it(dir, {"*.desktop"}, QDir::Files); + while (it.hasNext()) { + QFile f(it.next()); + if (!f.open(QIODevice::ReadOnly)) continue; + const auto info = parseDesktopEntry(QString::fromUtf8(f.readAll())); + if (info.wmClass.compare(program, Qt::CaseInsensitive) == 0) + return it.filePath(); + } + } + return {}; +} + +QString AppsKnown::fallbackLabel(const QString &program) { + // Reverse-DNS ids read best as their last part. + const int dot = program.lastIndexOf('.'); + return (dot >= 0 && dot + 1 < program.size()) ? program.mid(dot + 1) : program; +} + +AppsKnown::DesktopInfo AppsKnown::desktopInfo(const QString &program) const { + auto it = _desktopCache.constFind(program); + if (it != _desktopCache.constEnd()) return *it; + DesktopInfo info; + const QString path = findDesktopFile( + program, QStandardPaths::standardLocations(QStandardPaths::ApplicationsLocation)); + if (!path.isEmpty()) { + QFile f(path); + if (f.open(QIODevice::ReadOnly)) + info = parseDesktopEntry(QString::fromUtf8(f.readAll())); + } + _desktopCache.insert(program, info); + return info; +} -QVariantList AppsKnown::knownApps() const { +QString AppsKnown::labelFor(const QString &name) const { + const auto info = desktopInfo(name); + return info.name.isEmpty() ? fallbackLabel(name) : info.name; +} + +QVariantList AppsKnown::appList(const QVariantMap &configured, const QVariantList &seen) const { QVariantList out; - for (const AppEntry &e : kApps) { + QSet listed; + for (const auto &v : seen) { + const auto m = v.toMap(); + const QString name = m.value("name").toString(); + if (name.isEmpty() || listed.contains(name)) continue; + listed.insert(name); + const auto info = desktopInfo(name); out.append(QVariantMap{ - {"id", e.id}, - {"label", e.label}, - {"canonical", e.canonical}, - {"iconCls", e.iconCls}, - {"mode", e.defaultMode}, + {"name", name}, + {"label", info.name.isEmpty() ? fallbackLabel(name) : info.name}, + {"iconName", info.icon}, + {"lastSeen", m.value("last_seen").toLongLong()}, + {"configured", configured.contains(name)}, + }); + } + // Configured but never seen (added by hand, or seen before a reset). + QVariantList unseen; + for (auto it = configured.constBegin(); it != configured.constEnd(); ++it) { + if (listed.contains(it.key())) continue; + const auto info = desktopInfo(it.key()); + unseen.append(QVariantMap{ + {"name", it.key()}, + {"label", info.name.isEmpty() ? fallbackLabel(it.key()) : info.name}, + {"iconName", info.icon}, + {"lastSeen", 0LL}, + {"configured", true}, }); } + std::sort(unseen.begin(), unseen.end(), [](const QVariant &a, const QVariant &b) { + return a.toMap().value("label").toString().compare( + b.toMap().value("label").toString(), Qt::CaseInsensitive) < 0; + }); + out.append(unseen); return out; } QVariantList AppsKnown::curatedBlockerCandidates() const { QVariantList out; - for (const AppEntry &e : kBlockers) { + for (const BlockerEntry &e : kBlockers) { out.append(QVariantMap{ - {"id", e.canonical}, // canonical used as blocklist key - {"label", e.label}, - {"iconCls", e.iconCls}, + {"id", e.canonical}, // canonical used as blocklist key + {"label", e.label}, + {"iconCls", e.iconCls}, }); } return out; } - -QString AppsKnown::canonicalForId(const QString &id) const { - for (const AppEntry &e : kApps) - if (e.id == id) return e.canonical; - for (const AppEntry &e : kBlockers) - if (e.id == id) return e.canonical; - return id; // fallback: treat id as canonical -} - -QString AppsKnown::labelForCanonical(const QString &canonical) const { - for (const AppEntry &e : kApps) - if (e.canonical == canonical) return e.label; - for (const AppEntry &e : kBlockers) - if (e.canonical == canonical) return e.label; - return canonical; -} diff --git a/settings/qt6-app/src/apps_known.h b/settings/qt6-app/src/apps_known.h index 1c9bb70..9f670dc 100644 --- a/settings/qt6-app/src/apps_known.h +++ b/settings/qt6-app/src/apps_known.h @@ -1,24 +1,67 @@ #pragma once +#include +#include +#include #include +#include +#include +#include #include #include +// Apps for the Per-app and Block-list pages. Nothing is hard-coded: the list +// is the apps configured in [apps.*] plus the apps the engine has seen the +// user type in (~/.local/share/xtype/active_apps.json, written by the +// engine's SeenApps). Names and icons come from the apps' .desktop files. class AppsKnown : public QObject { Q_OBJECT + Q_PROPERTY(QVariantList seenApps READ seenApps NOTIFY seenAppsChanged) public: - explicit AppsKnown(QObject *parent = nullptr); + // seenAppsPath empty → ~/.local/share/xtype/active_apps.json. + explicit AppsKnown(const QString &seenAppsPath = {}, QObject *parent = nullptr); - // Returns list of { id, label, canonical, iconCls, defaultMode } - Q_INVOKABLE QVariantList knownApps() const; + // [{ name, last_seen }] from the engine, most recent first. Re-read every + // few seconds while the settings app is open. + QVariantList seenApps() const { return _seen; } - // Returns list of curated blocklist candidates (password managers + terminals) + // Configured apps plus seen apps, most recently used first, then by + // label. Each: { name, label, iconName, lastSeen, configured }. + // Takes both inputs so QML bindings re-run when either changes. + Q_INVOKABLE QVariantList appList(const QVariantMap &configured, + const QVariantList &seen) const; + + // Display name for a program name: its .desktop Name, or a tidied + // program name ("com.t3tools.T3Code" → "T3Code"). + Q_INVOKABLE QString labelFor(const QString &name) const; + + // Ids are program names now, so this returns `id` unchanged. Kept for + // pages keyed by id that still map it to the [apps] key. + Q_INVOKABLE QString canonicalForId(const QString &id) const { return id; } + + // Curated blocklist candidates: password managers + terminals. Q_INVOKABLE QVariantList curatedBlockerCandidates() const; - // Maps short id → canonical program name for TOML keys - Q_INVOKABLE QString canonicalForId(const QString &id) const; + // ── Pure helpers (exposed for tests) ── + struct DesktopInfo { QString name; QString icon; QString wmClass; }; + static QVariantList parseSeenApps(const QByteArray &json); + static DesktopInfo parseDesktopEntry(const QString &text); + // The .desktop file for a program name in `dirs`: .desktop + // (case-insensitive), else one whose StartupWMClass is the name. + static QString findDesktopFile(const QString &program, const QStringList &dirs); + static QString fallbackLabel(const QString &program); + +signals: + void seenAppsChanged(); + +private: + void poll(); + DesktopInfo desktopInfo(const QString &program) const; // cached - // Maps canonical program name → display label - Q_INVOKABLE QString labelForCanonical(const QString &canonical) const; + QString _path; + QDateTime _mtime; + QVariantList _seen; + QTimer _timer; + mutable QHash _desktopCache; }; diff --git a/settings/qt6-app/src/main.cpp b/settings/qt6-app/src/main.cpp index 2b969af..342a850 100644 --- a/settings/qt6-app/src/main.cpp +++ b/settings/qt6-app/src/main.cpp @@ -6,6 +6,7 @@ #include #include #include +#include #include #ifdef HAVE_KF6_WINDOW_SYSTEM #include @@ -45,6 +46,22 @@ class GrainProvider : public QQuickImageProvider { } }; +// image://appicon/: a theme icon name or an +// absolute path. Unknown icons give an empty pixmap, so XAppIcon falls back +// to its letter badge. +class AppIconProvider : public QQuickImageProvider { +public: + AppIconProvider() : QQuickImageProvider(QQuickImageProvider::Pixmap) {} + + QPixmap requestPixmap(const QString &id, QSize *size, const QSize &requested) override { + const QIcon icon = id.startsWith('/') ? QIcon(id) : QIcon::fromTheme(id); + const QSize want = requested.isValid() ? requested : QSize(64, 64); + QPixmap pm = icon.isNull() ? QPixmap() : icon.pixmap(want); + if (size) *size = pm.size(); + return pm; + } +}; + int main(int argc, char** argv) { QGuiApplication app(argc, argv); QGuiApplication::setApplicationName("xtype-settings"); @@ -82,6 +99,7 @@ int main(int argc, char** argv) { QQmlApplicationEngine engine; engine.addImageProvider("grain", new GrainProvider); // must precede loadFromModule + engine.addImageProvider("appicon", new AppIconProvider); engine.loadFromModule("XType.Settings", "App"); if (engine.rootObjects().isEmpty()) return -1; diff --git a/settings/qt6-app/tests/CMakeLists.txt b/settings/qt6-app/tests/CMakeLists.txt index 04d1f26..0692645 100644 --- a/settings/qt6-app/tests/CMakeLists.txt +++ b/settings/qt6-app/tests/CMakeLists.txt @@ -19,6 +19,11 @@ target_link_libraries(xtype-settings-tests PRIVATE Catch2::Catch2WithMain ) +target_sources(xtype-settings-tests PRIVATE + test_apps_known.cpp + ${CMAKE_SOURCE_DIR}/src/apps_known.cpp +) + include(CTest) include(Catch) catch_discover_tests(xtype-settings-tests) diff --git a/settings/qt6-app/tests/test_apps_known.cpp b/settings/qt6-app/tests/test_apps_known.cpp new file mode 100644 index 0000000..dad6c86 --- /dev/null +++ b/settings/qt6-app/tests/test_apps_known.cpp @@ -0,0 +1,96 @@ +#include + +#include +#include +#include +#include + +#include "apps_known.h" + +static void writeFile(const QString &path, const QByteArray &content) { + QFile f(path); + REQUIRE(f.open(QIODevice::WriteOnly)); + f.write(content); +} + +TEST_CASE("parseSeenApps reads names, most recent first", "[apps_known]") { + const auto list = AppsKnown::parseSeenApps( + R"({"apps":[{"name":"omawrite","last_seen":100}, + {"name":"com.t3tools.T3Code","last_seen":300}, + {"name":"","last_seen":999}, + {"last_seen":5}]})"); + REQUIRE(list.size() == 2); + CHECK(list[0].toMap()["name"].toString() == "com.t3tools.T3Code"); + CHECK(list[1].toMap()["name"].toString() == "omawrite"); + CHECK(list[1].toMap()["last_seen"].toLongLong() == 100); +} + +TEST_CASE("parseSeenApps tolerates garbage", "[apps_known]") { + CHECK(AppsKnown::parseSeenApps("not json").isEmpty()); + CHECK(AppsKnown::parseSeenApps("").isEmpty()); +} + +TEST_CASE("parseDesktopEntry takes unlocalised Name, Icon, StartupWMClass", "[apps_known]") { + const auto info = AppsKnown::parseDesktopEntry( + "[Desktop Entry]\n" + "Name[pt_BR]=Escritor\n" + "Name=Omawrite\n" + "Icon=omawrite\n" + "StartupWMClass=omawrite-bin\n" + "[Desktop Action new]\n" + "Name=New document\n"); + CHECK(info.name == "Omawrite"); + CHECK(info.icon == "omawrite"); + CHECK(info.wmClass == "omawrite-bin"); +} + +TEST_CASE("findDesktopFile matches the file name, then StartupWMClass", "[apps_known]") { + QTemporaryDir dir; REQUIRE(dir.isValid()); + writeFile(dir.filePath("com.t3tools.T3Code.desktop"), "[Desktop Entry]\nName=T3 Code\n"); + writeFile(dir.filePath("teams.desktop"), + "[Desktop Entry]\nName=Teams\nStartupWMClass=teams-for-linux\n"); + const QStringList dirs{dir.path()}; + + CHECK(AppsKnown::findDesktopFile("com.t3tools.T3Code", dirs).endsWith("com.t3tools.T3Code.desktop")); + CHECK(AppsKnown::findDesktopFile("com.T3TOOLS.t3code", dirs).endsWith("com.t3tools.T3Code.desktop")); + CHECK(AppsKnown::findDesktopFile("teams-for-linux", dirs).endsWith("teams.desktop")); + CHECK(AppsKnown::findDesktopFile("unknown", dirs).isEmpty()); +} + +TEST_CASE("fallbackLabel uses the last part of reverse-DNS ids", "[apps_known]") { + CHECK(AppsKnown::fallbackLabel("com.t3tools.T3Code") == "T3Code"); + CHECK(AppsKnown::fallbackLabel("teams-for-linux") == "teams-for-linux"); + CHECK(AppsKnown::fallbackLabel("trailing.") == "trailing."); +} + +TEST_CASE("appList merges seen and configured apps", "[apps_known]") { + QStandardPaths::setTestModeEnabled(true); // no real .desktop files + QTemporaryDir tmp; REQUIRE(tmp.isValid()); + AppsKnown apps(tmp.filePath("active_apps.json")); + + const QVariantList seen = AppsKnown::parseSeenApps( + R"({"apps":[{"name":"omawrite","last_seen":300},{"name":"kate","last_seen":100}]})"); + QVariantMap configured; + configured["kate"] = QVariantMap{{"enabled", false}}; + configured["zed.Editor"] = QVariantMap{{"enabled", true}}; + configured["alpha.Thing"] = QVariantMap{{"enabled", true}}; + + const auto list = apps.appList(configured, seen); + REQUIRE(list.size() == 4); + // Seen apps first, by recency; then configured-only apps by label. + CHECK(list[0].toMap()["name"].toString() == "omawrite"); + CHECK(list[0].toMap()["configured"].toBool() == false); + CHECK(list[1].toMap()["name"].toString() == "kate"); + CHECK(list[1].toMap()["configured"].toBool() == true); + CHECK(list[2].toMap()["label"].toString() == "Editor"); + CHECK(list[3].toMap()["label"].toString() == "Thing"); +} + +TEST_CASE("seenApps reads the engine's file", "[apps_known]") { + QTemporaryDir tmp; REQUIRE(tmp.isValid()); + const QString path = tmp.filePath("active_apps.json"); + writeFile(path, R"({"apps":[{"name":"omawrite","last_seen":1}]})"); + AppsKnown apps(path); + REQUIRE(apps.seenApps().size() == 1); + CHECK(apps.seenApps()[0].toMap()["name"].toString() == "omawrite"); +}