#import "ActivityHistory.h" #import #import #import #include #include #include #include #include "../common/logger.h" // Mprintf(Start 失败要留痕) // 与 Windows 端 client/ActivityHistory.h、Linux 端 linux/LinuxActivityHistory.h 一致 #ifndef ACTIVITY_MIN_DWELL_SEC #define ACTIVITY_MIN_DWELL_SEC 5 // 一闪而过阈值(秒):驻留低于此值不记录 #endif #ifndef ACTIVITY_HISTORY_MAX #define ACTIVITY_HISTORY_MAX 500 // 内存保留的最大记录条数 #endif namespace { struct ProbeResult { uint64_t id = 0; // 窗口号(CGWindowNumber),0 表示空闲/无窗口 std::string title; }; std::string CFStrToUtf8(CFStringRef s) { if (!s) return std::string(); char buf[1024] = {}; if (!CFStringGetCString(s, buf, sizeof(buf), kCFStringEncodingUTF8)) return std::string(); return std::string(buf); } // 按字节截断可能切在多字节字符中间,而服务端要按 UTF-8 转 GBK(对话框)或 // 塞进 JSON(MCP),半截字符会变成乱码/非法 JSON。返回可以安全截断的位置。 // 与 linux/LinuxActivityHistory.h 的 Utf8Boundary 同实现。 size_t Utf8Boundary(const std::string& s) { const size_t n = s.size(); size_t i = n; while (i > 0 && n - i < 3 && ((unsigned char)s[i - 1] & 0xC0) == 0x80) --i; if (i == 0) return n; const unsigned char c = (unsigned char)s[i - 1]; size_t need = 1; if ((c & 0x80) == 0) need = 1; else if ((c & 0xE0) == 0xC0) need = 2; else if ((c & 0xF0) == 0xE0) need = 3; else if ((c & 0xF8) == 0xF0) need = 4; return (n - (i - 1) >= need) ? n : i - 1; } // 控制字符换成空格(换行会破坏「每行一条」),可选截断 std::string CleanLine(const std::string& s, size_t maxLen = 512) { std::string out; out.reserve(std::min(s.size(), maxLen)); bool cut = false; for (char c : s) { unsigned char uc = (unsigned char)c; out += (uc < 0x20 || uc == 0x7f) ? ' ' : c; if (out.size() >= maxLen) { cut = true; break; } } if (cut) out.resize(Utf8Boundary(out)); return out; } std::string FormatTimeStamp(std::time_t t) { std::tm tm{}; localtime_r(&t, &tm); char buf[64]; snprintf(buf, sizeof(buf), "%04d-%02d-%02d %02d:%02d:%02d", tm.tm_year + 1900, tm.tm_mon + 1, tm.tm_mday, tm.tm_hour, tm.tm_min, tm.tm_sec); return buf; } // 时长格式化:Ns / Nm / NmNs / NhNm(与 Windows/Linux 端一致) std::string FormatDuration(int sec) { if (sec < 0) sec = 0; if (sec < 60) return std::to_string(sec) + "s"; if (sec < 3600) { int m = sec / 60, s = sec % 60; return s ? std::to_string(m) + "m" + std::to_string(s) + "s" : std::to_string(m) + "m"; } int h = sec / 3600, m = (sec % 3600) / 60; return std::to_string(h) + "h" + std::to_string(m) + "m"; } std::string FormatWindowRecord(const std::string& startTime, const std::string& title, int dwellSec) { return "[" + startTime + "] [" + CleanLine(title) + "] " + FormatDuration(dwellSec); } // 前台窗口探测。CGWindowListCopyWindowInfo 按「从前往后」返回屏幕上的窗口, // 第一个 layer==0 的普通窗口就是当前最前面的那个;窗口标题(kCGWindowName) // 只有录到屏权限时才可见,没有权限时退化为只报应用名。 ProbeResult ProbeFrontWindow() { ProbeResult r; CFArrayRef list = CGWindowListCopyWindowInfo( kCGWindowListOptionOnScreenOnly | kCGWindowListExcludeDesktopElements, kCGNullWindowID); if (list == nullptr) return r; const CFIndex count = CFArrayGetCount(list); for (CFIndex i = 0; i < count; ++i) { CFDictionaryRef window = (CFDictionaryRef)CFArrayGetValueAtIndex(list, i); // 菜单栏/停靠栏/悬浮层都不是「用户在用的窗口」 int layer = 0; CFNumberRef layerRef = (CFNumberRef)CFDictionaryGetValue(window, kCGWindowLayer); if (layerRef) CFNumberGetValue(layerRef, kCFNumberIntType, &layer); if (layer != 0) continue; // 跳过本进程自己的窗口(客户端没有界面,但保险) int ownerPid = 0; CFNumberRef pidRef = (CFNumberRef)CFDictionaryGetValue(window, kCGWindowOwnerPID); if (pidRef) CFNumberGetValue(pidRef, kCFNumberIntType, &ownerPid); if (ownerPid == (int)getpid()) continue; std::string owner = CFStrToUtf8((CFStringRef)CFDictionaryGetValue(window, kCGWindowOwnerName)); if (owner.empty()) continue; // 无主的系统杂项窗口 std::string name = CFStrToUtf8((CFStringRef)CFDictionaryGetValue(window, kCGWindowName)); uint64_t number = 0; CFNumberRef numRef = (CFNumberRef)CFDictionaryGetValue(window, kCGWindowNumber); if (numRef) CFNumberGetValue(numRef, kCFNumberSInt64Type, &number); r.id = number ? number : 1; r.title = name.empty() ? owner : owner + " - " + name; break; } CFRelease(list); return r; } } // namespace MacActivityHistory& MacActivityHistory::Instance() { static MacActivityHistory inst; return inst; } std::string MacActivityHistory::EmptyText() { return "[来源] 桌面窗口活动:暂无记录(没有停留超过 5 秒的活动窗口)\n"; } void MacActivityHistory::Start() { bool expected = false; if (!m_started.compare_exchange_strong(expected, true)) return; m_running = true; try { m_thread = std::thread(&MacActivityHistory::Loop, this); } catch (const std::exception& e) { // 采样是附加功能:线程起不来就降级成「没有历史活动」,别让异常穿过 main // (main.mm 里是裸调用,逃出去就是 std::terminate)。复位后允许再次 Start。 m_running = false; m_started.store(false); Mprintf("*** ActivityHistory: failed to start sampler: %s ***\n", e.what()); } } void MacActivityHistory::Stop() { m_running = false; if (m_thread.joinable()) m_thread.join(); m_started.store(false); } std::string MacActivityHistory::Dump() const { std::lock_guard lock(m_mutex); std::string out; if (!m_curTitle.empty() && m_curDwellSec >= ACTIVITY_MIN_DWELL_SEC) out += FormatWindowRecord(m_curStartTime, m_curTitle, m_curDwellSec) + "\n"; for (const auto& rec : m_records) out += rec + "\n"; return out; } void MacActivityHistory::Loop() { uint64_t lastId = 0; std::string lastTitle, startTime; int dwellSec = 0; while (m_running) { ProbeResult p = ProbeFrontWindow(); { std::lock_guard lock(m_mutex); if (p.id == 0 || p.title.empty()) { // 空闲/锁屏/无窗口:结账上一个窗口 if (lastId != 0 && dwellSec >= ACTIVITY_MIN_DWELL_SEC) m_records.push_front(FormatWindowRecord(startTime, lastTitle, dwellSec)); lastId = 0; lastTitle.clear(); dwellSec = 0; } else if (p.id == lastId) { // 同一窗口:标题变了也连续累计(浏览器标签切换标题常变) ++dwellSec; lastTitle = p.title; } else { if (lastId != 0 && dwellSec >= ACTIVITY_MIN_DWELL_SEC) m_records.push_front(FormatWindowRecord(startTime, lastTitle, dwellSec)); lastId = p.id; lastTitle = p.title; startTime = FormatTimeStamp(std::time(nullptr)); dwellSec = 1; } while (m_records.size() > ACTIVITY_HISTORY_MAX) m_records.pop_back(); m_curTitle = lastTitle; m_curStartTime = startTime; m_curDwellSec = dwellSec; } std::this_thread::sleep_for(std::chrono::seconds(1)); } }