// SPDX-License-Identifier: GPL-2.0-only // CallScreen DWM Plugin - Unified X11 Incoming & In-Call UI for Bananarchy (240x320) #include #include #include #include #include #include #ifndef _EVDEVK #define _EVDEVK(_v) (0x10081000 + (_v)) #endif #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include #include "../sxmo-dwm/dwm_plugin.h" #include "phone_data.h" namespace { using namespace bananarchy; volatile sig_atomic_t gRunning = 1; void handleSignal(int) { gRunning = 0; } class AlsaCallControl { public: AlsaCallControl() { if (snd_ctl_open(&ctl_, "hw:0", 0) < 0) { ctl_ = nullptr; } } ~AlsaCallControl() { if (ctl_) { snd_ctl_close(ctl_); } } long getInteger(const char* name, long fallback = 0) const { if (!ctl_) { return fallback; } snd_ctl_elem_id_t* id = nullptr; snd_ctl_elem_value_t* val = nullptr; snd_ctl_elem_id_alloca(&id); snd_ctl_elem_value_alloca(&val); snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_MIXER); snd_ctl_elem_id_set_name(id, name); snd_ctl_elem_value_set_id(val, id); if (snd_ctl_elem_read(ctl_, val) < 0) { return fallback; } return snd_ctl_elem_value_get_integer(val, 0); } bool setInteger(const char* name, long v) { if (!ctl_) { return false; } snd_ctl_elem_id_t* id = nullptr; snd_ctl_elem_value_t* val = nullptr; snd_ctl_elem_id_alloca(&id); snd_ctl_elem_value_alloca(&val); snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_MIXER); snd_ctl_elem_id_set_name(id, name); snd_ctl_elem_value_set_id(val, id); snd_ctl_elem_value_set_integer(val, 0, v); return snd_ctl_elem_write(ctl_, val) >= 0; } bool getBoolean(const char* name, bool fallback = true) const { if (!ctl_) { return fallback; } snd_ctl_elem_id_t* id = nullptr; snd_ctl_elem_value_t* val = nullptr; snd_ctl_elem_id_alloca(&id); snd_ctl_elem_value_alloca(&val); snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_MIXER); snd_ctl_elem_id_set_name(id, name); snd_ctl_elem_value_set_id(val, id); if (snd_ctl_elem_read(ctl_, val) < 0) { return fallback; } return snd_ctl_elem_value_get_boolean(val, 0) != 0; } bool setBoolean(const char* name, bool v) { if (!ctl_) { return false; } snd_ctl_elem_id_t* id = nullptr; snd_ctl_elem_value_t* val = nullptr; snd_ctl_elem_id_alloca(&id); snd_ctl_elem_value_alloca(&val); snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_MIXER); snd_ctl_elem_id_set_name(id, name); snd_ctl_elem_value_set_id(val, id); snd_ctl_elem_value_set_boolean(val, 0, v ? 1 : 0); return snd_ctl_elem_write(ctl_, val) >= 0; } unsigned int getEnum(const char* name, unsigned int fallback = 0) const { if (!ctl_) { return fallback; } snd_ctl_elem_id_t* id = nullptr; snd_ctl_elem_value_t* val = nullptr; snd_ctl_elem_id_alloca(&id); snd_ctl_elem_value_alloca(&val); snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_MIXER); snd_ctl_elem_id_set_name(id, name); snd_ctl_elem_value_set_id(val, id); if (snd_ctl_elem_read(ctl_, val) < 0) { return fallback; } return snd_ctl_elem_value_get_enumerated(val, 0); } bool setEnum(const char* name, unsigned int v) { if (!ctl_) { return false; } snd_ctl_elem_id_t* id = nullptr; snd_ctl_elem_value_t* val = nullptr; snd_ctl_elem_id_alloca(&id); snd_ctl_elem_value_alloca(&val); snd_ctl_elem_id_set_interface(id, SND_CTL_ELEM_IFACE_MIXER); snd_ctl_elem_id_set_name(id, name); snd_ctl_elem_value_set_id(val, id); snd_ctl_elem_value_set_enumerated(val, 0, v); return snd_ctl_elem_write(ctl_, val) >= 0; } private: snd_ctl_t* ctl_ = nullptr; }; enum class CallState { Idle = 0, Incoming = 1, Outgoing = 2, Active = 3, Ended = 4, SelectSim = 5, }; std::string formatTimerSec(int totalSec) { if (totalSec < 0) { totalSec = 0; } char buf[32]; if (totalSec >= 3600) { std::snprintf(buf, sizeof(buf), "%d:%02d:%02d", totalSec / 3600, (totalSec % 3600) / 60, totalSec % 60); } else { std::snprintf(buf, sizeof(buf), "%02d:%02d", totalSec / 60, totalSec % 60); } return buf; } std::string sanitizeForFilename(const std::string& raw) { std::string out; for (unsigned char c : raw) { if (std::isalnum(c) || c == '+' || c == '-' || c == '_') { out.push_back(static_cast(c)); } else if (c == ' ') { out.push_back('_'); } } if (out.empty()) { return "voice"; } if (out.size() > 10 && out[0] == '+') { out = out.substr(out.size() - 10); } else if (out.size() > 10) { out = out.substr(0, 10); } return out; } std::string getRecordingsDir() { const char* home = std::getenv("HOME"); std::string dir = std::string(home && home[0] ? home : "/home/user") + "/Recordings"; ::mkdir(dir.c_str(), 0755); return dir; } void finalizeWavHeader(const std::string& path) { if (path.empty()) return; int fd = ::open(path.c_str(), O_RDWR); if (fd < 0) return; struct stat st {}; if (::fstat(fd, &st) != 0 || st.st_size <= 44) { ::close(fd); return; } uint8_t hdr[64] = {0}; ssize_t n = ::pread(fd, hdr, sizeof(hdr), 0); if (n < 44 || std::memcmp(hdr, "RIFF", 4) != 0 || std::memcmp(hdr + 8, "WAVE", 4) != 0) { ::close(fd); return; } uint32_t riffLen = static_cast(st.st_size - 8); uint32_t curRiff = static_cast(hdr[4]) | (static_cast(hdr[5]) << 8) | (static_cast(hdr[6]) << 16) | (static_cast(hdr[7]) << 24); if (curRiff == 0 || curRiff != riffLen) { uint8_t b[4] = { static_cast(riffLen & 0xff), static_cast((riffLen >> 8) & 0xff), static_cast((riffLen >> 16) & 0xff), static_cast((riffLen >> 24) & 0xff), }; (void)::pwrite(fd, b, 4, 4); } ssize_t dataOff = -1; uint32_t dataBytes = 0; uint16_t audioFmt = static_cast(hdr[20]) | (static_cast(hdr[21]) << 8); uint16_t bitsPerSample = static_cast(hdr[34]) | (static_cast(hdr[35]) << 8); for (ssize_t off = 12; off + 8 <= n;) { uint32_t chunkLen = static_cast(hdr[off + 4]) | (static_cast(hdr[off + 5]) << 8) | (static_cast(hdr[off + 6]) << 16) | (static_cast(hdr[off + 7]) << 24); if (std::memcmp(hdr + off, "data", 4) == 0) { uint32_t expectedData = static_cast(st.st_size - (off + 8)); dataOff = off + 8; dataBytes = expectedData; if (chunkLen == 0 || chunkLen != expectedData) { uint8_t b[4] = { static_cast(expectedData & 0xff), static_cast((expectedData >> 8) & 0xff), static_cast((expectedData >> 16) & 0xff), static_cast((expectedData >> 24) & 0xff), }; (void)::pwrite(fd, b, 4, off + 4); } break; } if (chunkLen == 0) break; off += 8 + static_cast((chunkLen + 1) & ~1u); } // Peak-normalize quiet 16-bit signed PCM recordings so playback is clearly audible if (audioFmt == 1 && bitsPerSample == 16 && dataOff >= 44 && dataBytes >= 2 && dataBytes <= 32 * 1024 * 1024) { size_t numSamples = dataBytes / 2; std::vector pcm(numSamples); ssize_t rd = ::pread(fd, pcm.data(), numSamples * sizeof(int16_t), dataOff); if (rd == static_cast(numSamples * sizeof(int16_t))) { int maxAbs = 0; size_t skip = std::min(numSamples / 4, 400); for (size_t i = skip; i < numSamples; ++i) { int v = std::abs(static_cast(pcm[i])); if (v > maxAbs) { maxAbs = v; } } if (maxAbs >= 32 && maxAbs < 18000) { double gain = std::min(24.0, 24000.0 / static_cast(maxAbs)); if (gain > 1.15) { for (size_t i = 0; i < numSamples; ++i) { int scaled = static_cast(std::lround(pcm[i] * gain)); pcm[i] = static_cast(std::clamp(scaled, -32767, 32767)); } (void)::pwrite(fd, pcm.data(), numSamples * sizeof(int16_t), dataOff); } } } } ::fsync(fd); ::close(fd); } void wakeDisplayHardware(Display* dpy) { int saved = readIntFile("/tmp/sxmo_saved_brightness", -1); if (saved <= 1) { saved = readIntFile("/sys/class/backlight/backlight/max_brightness", 14); if (saved <= 1) { saved = 14; } } writeIntFile("/sys/class/backlight/backlight/bl_power", 0); writeIntFile("/sys/class/backlight/backlight/brightness", saved); writeIntFile("/sys/class/leds/white:kbd_backlight/brightness", 255); if (dpy) { XForceScreenSaver(dpy, ScreenSaverReset); } } int callscreen_run_main(int argc, char** argv) { gRunning = 1; bool isPreload = false; std::string initCmd; for (int i = 1; i < argc; ++i) { if (!argv[i] || !argv[i][0]) { continue; } if (std::strcmp(argv[i], "--preload") == 0) { isPreload = true; } else { if (!initCmd.empty()) { initCmd.push_back(' '); } initCmd += argv[i]; } } auto buildFifoCmdFromArgs = [&]() -> std::string { if (isPreload) { return "NOP"; } if (argc >= 2 && argv[1]) { std::string v = toLowerStr(argv[1]); std::string a1 = (argc >= 3 && argv[2]) ? argv[2] : "-"; std::string a2 = (argc >= 4 && argv[3]) ? argv[3] : ""; if (v == "incoming") { return "INCOMING " + a1 + (a2.empty() ? "" : (" " + a2)); } else if (v == "outgoing") { return "OUTGOING " + a1 + (a2.empty() ? "" : (" " + a2)); } else if (v == "active") { return "ACTIVE " + a1 + (a2.empty() ? "" : (" " + a2)); } else if (v == "accept" || v == "pickup") { return "ACCEPT"; } else if (v == "hangup" || v == "reject") { return "HANGUP"; } else if (v == "mute" || v == "mute_ring" || v == "ignore") { return "MUTE_RING"; } else if (v == "ended" || v == "end") { return a1 != "-" ? ("ENDED " + a1) : "ENDED"; } else if (v == "close") { return "CLOSE"; } else if (v == "record" || v == "toggle_rec") { return "TOGGLE_REC"; } else if (v == "mic" || v == "toggle_mic") { return "TOGGLE_MIC"; } } return initCmd.empty() ? "OPEN" : ("OPEN " + initCmd); }; std::string forwardedCmd = buildFifoCmdFromArgs(); if (sendPluginCommand("callscreen", forwardedCmd)) { return 0; } std::string daemonPidPath = getPluginDaemonPidPath("callscreen"); std::string activePidPath = getRuntimeFile("xcallscreen.pid"); writeIntFile(daemonPidPath, static_cast(::getpid())); int fifoFd = setupPluginDaemonFifo("callscreen"); struct sigaction sa {}; sa.sa_handler = handleSignal; sigemptyset(&sa.sa_mask); sigaction(SIGTERM, &sa, nullptr); sigaction(SIGINT, &sa, nullptr); struct sigaction saChld {}; saChld.sa_handler = SIG_DFL; sigemptyset(&saChld.sa_mask); saChld.sa_flags = SA_NOCLDSTOP; sigaction(SIGCHLD, &saChld, nullptr); NeoWindow neo; if (!neo.create("xcallscreen", "XCallScreen", "Call Screen")) { if (fifoFd >= 0) ::close(fifoFd); ::unlink(daemonPidPath.c_str()); return 1; } Display* dpy = neo.dpy; int screen = neo.screen; Visual* visual = neo.visual; Colormap cmap = neo.cmap; Window win = neo.win; Pixmap pix = neo.pix; GC gc = neo.gc; PangoLayout* layoutNum = neo.layoutNum; PangoLayout* layoutMain = neo.layoutMain; PangoLayout* layoutSmall = neo.layoutSmall; PangoLayout* layoutIcon = neo.layoutIcon; PluginTheme& theme = neo.theme; XftColor& colWhite = theme.colWhite; XftColor& colLight = theme.colLight; XftColor& colMuted = theme.colMuted; XftColor& colYellow = theme.colYellow; XftColor& colGreen = theme.colGreen; XftColor& colRed = theme.colRed; XftColor& colBlue = theme.colBlue; ContactBook book; FileStamp contactsStamp; bool contactsLoadedOnce = false; auto reloadContactsIfNeeded = [&]() { if (contactsStamp.checkAndUpdate(getContactsFilePath()) || !contactsLoadedOnce) { contactsLoadedOnce = true; book.load(); } }; reloadContactsIfNeeded(); AlsaCallControl alsa; unsigned int savedMicMux = 1; CallState callState = CallState::Idle; std::string callId; std::string callNumber; std::string contactName; int activeSimSlot = 0; std::string sipZrtpSas; DualSimInfo simInfo = queryDualSimInfo(); std::string endReason = "CALL ENDED"; std::string statusNotice; int64_t statusNoticeUntilMs = 0; std::string dtmfSent; bool dtmfMode = false; bool ringMuted = false; bool micMuted = false; bool speakerOn = false; int callVolumePct = 85; int selectedRow = 0; int64_t callStartMs = 0; int64_t endedAtMs = 0; int lastFinalDurationSec = 0; int64_t lastModemPollMs = 0; pid_t recordPid = -1; int64_t recordStartMs = 0; std::string recordFilePath; std::string recordFileName; int lastRecordedSec = 0; int recordedClipCount = 0; bool visible = false; int64_t openStartMs = 0; int64_t startupIgnoreUntilMs = 0; bool initialSoftkeysReleased = true; int softkeyPending = 0; int64_t softkeyDeadlineMs = 0; auto pctToHwVol = [](int pct, bool spk, bool hp = false) -> long { int c = std::clamp(pct, 5, 100); if (hp) return 52 + (c * 32 + 50) / 100; return spk ? (56 + (c * 32 + 50) / 100) : (60 + (c * 32 + 50) / 100); }; auto refreshHardwareAudioState = [&]() { unsigned int dec1 = alsa.getEnum("DEC1 MUX", 1); if (dec1 > 0) { savedMicMux = dec1; writeIntFile("/tmp/xdrawer_mic_mux", static_cast(savedMicMux)); micMuted = false; } else { savedMicMux = static_cast(std::max(1, readIntFile("/tmp/xdrawer_mic_mux", 1))); micMuted = true; } int savedVol = readIntFile("/tmp/sxmo_call_vol", -1); if (savedVol >= 5 && savedVol <= 100) { callVolumePct = savedVol; } }; auto setMicMuted = [&](bool mute) { micMuted = mute; alsa.setEnum("DEC1 MUX", mute ? 0 : (savedMicMux > 0 ? savedMicMux : 1)); alsa.setInteger("ADC1 Volume", mute ? 0 : 8); alsa.setInteger("ADC3 Volume", mute ? 0 : 8); alsa.setInteger("TX1 Digital Volume", mute ? 0 : 88); alsa.setBoolean("VoiceMMode1 Capture Mixer TERT_MI2S_TX", !mute); runAsyncCmd(mute ? "wpctl set-mute @DEFAULT_AUDIO_SOURCE@ 1 >/dev/null 2>&1" : "wpctl set-mute @DEFAULT_AUDIO_SOURCE@ 0 >/dev/null 2>&1"); statusNotice = mute ? "Microphone muted" : "Microphone unmuted"; statusNoticeUntilMs = nowMs() + 2000; }; auto isVoipCallId = [&](const std::string& cid) -> bool { return cid.rfind("sip:", 0) == 0 || cid.rfind("tox:", 0) == 0; }; auto setSpeakerRoute = [&](bool toSpeaker) { speakerOn = toSpeaker; bool jackPlugged = (readIntFile("/tmp/sxmo_jack_plugged", 0) == 1); long hwVol = pctToHwVol(callVolumePct, toSpeaker, !toSpeaker && jackPlugged); bool voip = isVoipCallId(callId); if (!voip) { alsa.setBoolean("PRI_MI2S_RX Voice Mixer VoiceMMode1", true); alsa.setBoolean("VoiceMMode1 Capture Mixer TERT_MI2S_TX", !micMuted); } alsa.setEnum("CIC1 MUX", 0); if (!micMuted) { alsa.setEnum("DEC1 MUX", savedMicMux > 0 ? savedMicMux : 1); alsa.setInteger("ADC1 Volume", 8); alsa.setInteger("TX1 Digital Volume", 88); } if (toSpeaker) { alsa.setEnum("EAR_S", 0); alsa.setEnum("HPHL", 0); alsa.setEnum("HPHR", 0); alsa.setEnum("RX1 MIX1 INP1", 0); alsa.setEnum("RX2 MIX1 INP1", 0); alsa.setBoolean("SPK DAC Switch", true); alsa.setEnum("RX3 MIX1 INP1", 3); alsa.setInteger("RX3 Digital Volume", hwVol); runAsyncCmd("sxmo_audio.sh device set Speaker >/dev/null 2>&1"); statusNotice = "Audio routed to Speaker"; } else if (jackPlugged) { alsa.setBoolean("SPK DAC Switch", false); alsa.setEnum("RX3 MIX1 INP1", 0); alsa.setInteger("RX3 Digital Volume", 0); alsa.setEnum("EAR_S", 0); alsa.setEnum("RX1 MIX1 INP1", 3); alsa.setEnum("RX2 MIX1 INP1", 4); alsa.setEnum("RDAC2 MUX", 1); alsa.setEnum("HPHL", 1); alsa.setEnum("HPHR", 1); alsa.setBoolean("RX1 Mute Switch", false); alsa.setInteger("RX1 Digital Volume", hwVol); alsa.setInteger("RX2 Digital Volume", hwVol); runAsyncCmd("sxmo_audio.sh device set Headphones >/dev/null 2>&1"); statusNotice = "Audio routed to Headphones"; } else { alsa.setBoolean("SPK DAC Switch", false); alsa.setEnum("RX3 MIX1 INP1", 0); alsa.setInteger("RX3 Digital Volume", 0); alsa.setEnum("HPHL", 0); alsa.setEnum("HPHR", 0); alsa.setEnum("RX2 MIX1 INP1", 0); alsa.setEnum("RX1 MIX1 INP1", 3); alsa.setEnum("RDAC2 MUX", 0); alsa.setEnum("EAR_S", 1); alsa.setBoolean("RX1 Mute Switch", false); alsa.setInteger("RX1 Digital Volume", hwVol); runAsyncCmd("sxmo_audio.sh device set Earpiece >/dev/null 2>&1"); statusNotice = "Audio routed to Earpiece"; } statusNoticeUntilMs = nowMs() + 2000; }; auto adjustVolume = [&](int deltaPct) { callVolumePct = std::clamp(callVolumePct + deltaPct, 5, 100); writeIntFile("/tmp/sxmo_call_vol", callVolumePct); bool jackPlugged = (readIntFile("/tmp/sxmo_jack_plugged", 0) == 1); if (speakerOn) { alsa.setInteger("RX3 Digital Volume", pctToHwVol(callVolumePct, true, false)); } else if (jackPlugged) { long hw = pctToHwVol(callVolumePct, false, true); alsa.setInteger("RX1 Digital Volume", hw); alsa.setInteger("RX2 Digital Volume", hw); } else { alsa.setInteger("RX1 Digital Volume", pctToHwVol(callVolumePct, false, false)); } char cmd[128]; std::snprintf(cmd, sizeof(cmd), "sxmo_audio.sh vol set %d >/dev/null 2>&1", callVolumePct); runAsyncCmd(cmd); }; auto finishRecordingFile = [&]() { alsa.setBoolean("MultiMedia2 Mixer TERT_MI2S_TX", false); finalizeWavHeader(recordFilePath); struct stat st {}; if (!recordFilePath.empty() && ::stat(recordFilePath.c_str(), &st) == 0 && st.st_size > 44) { int durFromBytes = static_cast((st.st_size - 44 + 8000) / 16000); int durFromWall = static_cast((nowMs() - recordStartMs + 500) / 1000); lastRecordedSec = std::max(1, std::max(durFromBytes, durFromWall)); ++recordedClipCount; statusNotice = "SAVED (" + formatTimerSec(lastRecordedSec) + ") " + recordFileName; statusNoticeUntilMs = nowMs() + 8000; } else if (!recordFileName.empty()) { statusNotice = "Recording failed"; statusNoticeUntilMs = nowMs() + 4000; } }; auto checkRecordingAlive = [&]() -> bool { if (recordPid <= 0) { return false; } int status = 0; pid_t r = ::waitpid(recordPid, &status, WNOHANG); if (r == recordPid || (r < 0 && ::kill(recordPid, 0) != 0)) { recordPid = -1; finishRecordingFile(); return false; } return true; }; auto stopRecording = [&]() { if (recordPid <= 0) { return; } ::kill(recordPid, SIGINT); for (int i = 0; i < 150; ++i) { int status = 0; if (::waitpid(recordPid, &status, WNOHANG) == recordPid) { recordPid = -1; break; } usleep(10000); } if (recordPid > 0) { ::kill(recordPid, SIGTERM); for (int i = 0; i < 20; ++i) { if (::waitpid(recordPid, nullptr, WNOHANG) == recordPid) { break; } usleep(10000); } recordPid = -1; } finishRecordingFile(); }; auto startRecording = [&]() -> bool { if (checkRecordingAlive()) { return true; } std::string dir = getRecordingsDir(); time_t nowSec = ::time(nullptr); struct tm tmNow {}; localtime_r(&nowSec, &tmNow); char tsBuf[32]; std::strftime(tsBuf, sizeof(tsBuf), "%H%M%S", &tmNow); std::string tag = sanitizeForFilename( !contactName.empty() ? contactName : (!callNumber.empty() ? callNumber : "voice")); recordFileName = std::string("rec_") + tsBuf + "_" + tag + ".wav"; recordFilePath = dir + "/" + recordFileName; // Enable MultiMedia2 capture mixer at 8 kHz mono to match active VoiceMMode1 AFE port alsa.setEnum("CIC1 MUX", 0); if (!micMuted) { alsa.setEnum("DEC1 MUX", savedMicMux > 0 ? savedMicMux : 1); alsa.setInteger("ADC1 Volume", 8); alsa.setInteger("TX1 Digital Volume", 88); } alsa.setBoolean("MultiMedia2 Mixer TERT_MI2S_TX", true); pid_t pid = ::fork(); if (pid < 0) { return false; } if (pid == 0) { ::setsid(); int nullfd = ::open("/dev/null", O_RDWR); if (nullfd >= 0) { ::dup2(nullfd, STDIN_FILENO); ::dup2(nullfd, STDOUT_FILENO); ::dup2(nullfd, STDERR_FILENO); if (nullfd > 2) { ::close(nullfd); } } execlp("arecord", "arecord", "-q", "-D", "hw:0,1", "-f", "S16_LE", "-r", "8000", "-c", "1", recordFilePath.c_str(), static_cast(nullptr)); execlp("arecord", "arecord", "-q", "-f", "S16_LE", "-r", "8000", "-c", "1", recordFilePath.c_str(), static_cast(nullptr)); _exit(1); } recordPid = pid; recordStartMs = nowMs(); statusNotice = "REC -> " + recordFileName; statusNoticeUntilMs = nowMs() + 3000; return true; }; auto toggleRecording = [&]() { if (checkRecordingAlive()) { stopRecording(); } else { startRecording(); } }; auto updateCallerDetails = [&](const std::string& rawId, const std::string& rawNum) { reloadContactsIfNeeded(); if (!rawId.empty() && rawId != "-") { callId = trimStr(rawId); } else if (callId.empty()) { callId = "-"; } if (!rawNum.empty() && rawNum != "-") { callNumber = trimStr(rawNum); } if (!callNumber.empty()) { contactName = book.resolveName(callNumber); } else { contactName.clear(); } }; auto writeActiveStateFiles = [&]() { if (callState == CallState::Incoming) { writeIntFile("/tmp/sxmo_call_ringing", 1); writeIntFile("/tmp/sxmo_active_call", 1); } else if (callState == CallState::Outgoing || callState == CallState::Active) { ::unlink("/tmp/sxmo_call_ringing"); writeIntFile("/tmp/sxmo_active_call", 2); } else { ::unlink("/tmp/sxmo_call_ringing"); ::unlink("/tmp/sxmo_active_call"); } }; auto drawPango = [&](PangoLayout* layout, XftColor* color, int x, int y, int h, const std::string& text, int maxW = -1) { neo.drawPango(layout, color, x, y, h, text, maxW); }; auto pangoWidth = [&](PangoLayout* layout, const std::string& text) -> int { return neo.pangoWidth(layout, text); }; constexpr int kHeaderH = 116; constexpr int kSoftbarH = 26; constexpr int kBodyY = kHeaderH; constexpr int kBodyH = kWinHeight - kHeaderH - kSoftbarH; // 154px auto render = [&]() { int64_t now = nowMs(); bool isRec = checkRecordingAlive(); XSetForeground(dpy, gc, theme.spec.bgMain); XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, kWinHeight); // 1. Top Caller Card (0..kHeaderH) XSetForeground(dpy, gc, theme.spec.bgHeader); XFillRectangle(dpy, pix, gc, 0, 0, kWinWidth, kHeaderH); // Top Status Strip (0..26) const char* stateIcon = kIconPhone; std::string stateBadge = "READY"; XftColor* stateCol = &colBlue; unsigned long stateAccentPx = theme.spec.accent; std::string simTag; if (activeSimSlot == 3 || callId.rfind("sip:", 0) == 0) { simTag = sipZrtpSas.empty() ? " [SIP]" : (" [ZRTP:" + sipZrtpSas + "]"); } else if (activeSimSlot == 4 || callId.rfind("tox:", 0) == 0) { simTag = " [TOX]"; } else if (activeSimSlot == 1 || activeSimSlot == 2) { simTag = " [SIM " + std::to_string(activeSimSlot) + "]"; } if (callState == CallState::SelectSim) { stateIcon = kIconOutCall; stateBadge = "SELECT SIM CARD"; stateCol = &colYellow; stateAccentPx = theme.spec.accent; } else if (callState == CallState::Incoming) { stateIcon = ringMuted ? kIconSoundOff : kIconInCall; stateBadge = (ringMuted ? "RING SILENCED" : "INCOMING") + simTag; stateCol = ringMuted ? &colYellow : &colGreen; stateAccentPx = theme.spec.accent; } else if (callState == CallState::Outgoing) { stateIcon = kIconOutCall; stateBadge = "DIALING" + simTag + "..."; stateCol = &colYellow; stateAccentPx = theme.spec.accent; } else if (callState == CallState::Active) { stateIcon = kIconPhone; stateBadge = "IN CALL" + simTag; stateCol = &colGreen; stateAccentPx = theme.spec.accent; } else if (callState == CallState::Ended) { stateIcon = kIconMissedCall; stateBadge = endReason; stateCol = &colRed; stateAccentPx = theme.spec.border; } drawPango(layoutIcon, stateCol, 8, 3, 22, stateIcon); drawPango(layoutSmall, stateCol, 28, 3, 22, stateBadge, 148); int elapsedSec = 0; if (callState == CallState::Ended) { elapsedSec = lastFinalDurationSec; } else if (callStartMs > 0 && callState != CallState::Idle && callState != CallState::SelectSim) { elapsedSec = static_cast((now - callStartMs) / 1000); } if ((callState != CallState::Idle && callState != CallState::SelectSim) || elapsedSec > 0) { std::string timerStr = formatTimerSec(elapsedSec); int tw = pangoWidth(layoutMain, timerStr); drawPango(layoutMain, (callState == CallState::Active) ? &colWhite : stateCol, kWinWidth - tw - 8, 2, 24, timerStr); } // Caller Avatar Box + Name + Number (28..88) XSetForeground(dpy, gc, theme.spec.bgAltOdd); XFillRectangle(dpy, pix, gc, 8, 32, 42, 42); XSetForeground(dpy, gc, stateAccentPx); XDrawRectangle(dpy, pix, gc, 8, 32, 41, 41); const char* avatarIcon = contactName.empty() ? kIconPhone : kIconUser; int aw = pangoWidth(layoutIcon, avatarIcon); drawPango(layoutIcon, stateCol, 8 + (42 - aw) / 2, 32, 42, avatarIcon); std::string primaryTitle; std::string secondarySub; if (!contactName.empty()) { primaryTitle = contactName; secondarySub = callNumber.empty() ? "Saved Contact" : callNumber; } else if (!callNumber.empty()) { primaryTitle = callNumber; secondarySub = (callState == CallState::Idle) ? "Ready" : "Unknown Caller"; } else { primaryTitle = "Voice Call"; secondarySub = (callState == CallState::Idle) ? "No active call" : "Private Number"; } drawPango(layoutNum, &colWhite, 58, 30, 26, primaryTitle, 174); drawPango(layoutMain, &colYellow, 58, 56, 22, secondarySub, 174); // Sub-header Banner (88..114) XSetForeground(dpy, gc, theme.spec.bgAltEven); XFillRectangle(dpy, pix, gc, 0, 88, kWinWidth, 26); if (isRec) { int recSec = static_cast((now - recordStartMs) / 1000); std::string recStr = "REC " + formatTimerSec(recSec); drawPango(layoutIcon, &colRed, 8, 88, 26, kIconRecord); drawPango(layoutSmall, &colRed, 26, 88, 26, recStr); int fnW = pangoWidth(layoutSmall, recordFileName); drawPango(layoutSmall, &colLight, std::max(96, kWinWidth - fnW - 8), 88, 26, recordFileName, 136); } else if (now < statusNoticeUntilMs && !statusNotice.empty()) { drawPango(layoutSmall, &colGreen, 8, 88, 26, statusNotice, 224); } else if (dtmfMode) { std::string dtmfLabel = "DTMF (0-9/*/#): " + (dtmfSent.empty() ? "_" : dtmfSent); drawPango(layoutSmall, &colYellow, 8, 88, 26, dtmfLabel, 224); } else if (callState == CallState::SelectSim) { drawPango(layoutSmall, &colYellow, 8, 88, 26, "[1/2] Choose SIM [OK/Call] Dial", 224); } else if (callState == CallState::Incoming) { drawPango(layoutSmall, &colLight, 8, 88, 26, "[Call] Answer [*] Mute [End] Reject", 224); } else if (callState == CallState::Ended) { if (recordedClipCount > 0 && !recordFileName.empty()) { std::string savedStr = "SAVED (" + formatTimerSec(lastRecordedSec) + ") " + recordFileName; drawPango(layoutSmall, &colGreen, 8, 88, 26, savedStr, 224); } else { drawPango(layoutSmall, &colMuted, 8, 88, 26, "Call finished", 224); } } else if (recordedClipCount > 0 && !recordFileName.empty()) { std::string savedStr = "SAVED (" + formatTimerSec(lastRecordedSec) + ") " + recordFileName; drawPango(layoutSmall, &colGreen, 8, 88, 26, savedStr, 224); } else { drawPango(layoutSmall, &colMuted, 8, 88, 26, "[1] Mic [2] Rec [3] Route [0] DTMF", 224); } XSetForeground(dpy, gc, stateAccentPx); XFillRectangle(dpy, pix, gc, 0, kHeaderH - 2, kWinWidth, 2); // 2. Body Area (kBodyY..kBodyY+kBodyH) if (callState == CallState::SelectSim) { constexpr int kSimRows = 2; for (int i = 0; i < kSimRows; ++i) { int slotNum = i + 1; int ry = kBodyY + (i * kBodyH) / kSimRows; int nextRy = kBodyY + ((i + 1) * kBodyH) / kSimRows; int rowH = nextRy - ry; bool isSel = (selectedRow == i); bool isPref = (simInfo.preferredSlot == slotNum); XSetForeground(dpy, gc, isSel ? theme.spec.selBg : ((i % 2 == 0) ? theme.spec.bgAltEven : theme.spec.bgAltOdd)); XFillRectangle(dpy, pix, gc, 0, ry, kWinWidth, rowH); if (isSel) { XSetForeground(dpy, gc, theme.spec.accent); XFillRectangle(dpy, pix, gc, 0, ry, 4, rowH); } std::string op = (slotNum == 1) ? simInfo.slot1Operator : simInfo.slot2Operator; std::string rat = (slotNum == 1) ? simInfo.slot1Rat : simInfo.slot2Rat; std::string msisdn = (slotNum == 1) ? simInfo.slot1Number : simInfo.slot2Number; std::string title = "[" + std::to_string(slotNum) + "] SIM " + std::to_string(slotNum); if (!op.empty()) { title += " - " + op; } if (!rat.empty()) { title += " (" + rat + ")"; } std::string subLine = msisdn.empty() ? (isPref ? "Primary / Default SIM" : "Standby SIM") : msisdn; std::string badge = isPref ? "DEFAULT" : "STANDBY"; int bw = pangoWidth(layoutSmall, badge); drawPango(layoutIcon, isSel ? &colGreen : &colBlue, 10, ry, rowH, kIconPhone); drawPango(layoutMain, isSel ? &colWhite : &colLight, 34, ry + 12, 24, title, std::max(80, kWinWidth - bw - 48)); drawPango(layoutSmall, isSel ? &colYellow : &colMuted, 34, ry + 38, 20, subLine, std::max(80, kWinWidth - 44)); drawPango(layoutSmall, isPref ? &colGreen : &colMuted, kWinWidth - bw - 8, ry + 12, 24, badge); } } else if (callState == CallState::Incoming) { struct IncomingAction { const char* icon; const char* title; const char* hint; const char* badge; XftColor* color; }; IncomingAction actions[3] = { {kIconPhone, "Answer Call", "Green Call or OK key", "ACCEPT", &colGreen}, {kIconSoundOff, ringMuted ? "Ringtone Muted" : "Silence Ring", "Press * or 0 key", ringMuted ? "MUTED" : "SILENCE", &colYellow}, {kIconMissedCall, "Reject Call", "Red End or Right Soft", "REJECT", &colRed}, }; constexpr int kIncRows = 3; for (int i = 0; i < kIncRows; ++i) { int ry = kBodyY + (i * kBodyH) / kIncRows; int nextRy = kBodyY + ((i + 1) * kBodyH) / kIncRows; int rowH = nextRy - ry; bool isSel = (selectedRow == i); XSetForeground(dpy, gc, isSel ? theme.spec.selBg : ((i % 2 == 0) ? theme.spec.bgAltEven : theme.spec.bgAltOdd)); XFillRectangle(dpy, pix, gc, 0, ry, kWinWidth, rowH); if (isSel) { XSetForeground(dpy, gc, theme.spec.accent); XFillRectangle(dpy, pix, gc, 0, ry, 4, rowH); } int bw = pangoWidth(layoutSmall, actions[i].badge); int textMaxW = std::max(80, kWinWidth - bw - 48); drawPango(layoutIcon, actions[i].color, 10, ry, rowH, actions[i].icon); drawPango(layoutMain, isSel ? &colWhite : &colLight, 34, ry + 4, 22, actions[i].title, textMaxW); drawPango(layoutSmall, isSel ? &colYellow : &colMuted, 34, ry + 25, 18, actions[i].hint, textMaxW); drawPango(layoutSmall, actions[i].color, kWinWidth - bw - 8, ry, rowH, actions[i].badge); } } else { constexpr int kCtrlRows = 4; for (int i = 0; i < kCtrlRows; ++i) { int ry = kBodyY + (i * kBodyH) / kCtrlRows; int nextRy = kBodyY + ((i + 1) * kBodyH) / kCtrlRows; int rowH = nextRy - ry; bool isSel = (selectedRow == i); XSetForeground(dpy, gc, isSel ? theme.spec.selBg : ((i % 2 == 0) ? theme.spec.bgAltEven : theme.spec.bgAltOdd)); XFillRectangle(dpy, pix, gc, 0, ry, kWinWidth, rowH); if (isSel) { XSetForeground(dpy, gc, theme.spec.accent); XFillRectangle(dpy, pix, gc, 0, ry, 4, rowH); } if (i == 0) { const char* ic = micMuted ? kIconMicOff : kIconMicOn; XftColor* icCol = micMuted ? &colRed : &colGreen; std::string valStr = micMuted ? "MUTED" : "ON"; int vw = pangoWidth(layoutMain, valStr); drawPango(layoutIcon, icCol, 10, ry, rowH, ic); drawPango(layoutMain, isSel ? &colWhite : &colLight, 34, ry, rowH, "[1] Microphone", std::max(80, kWinWidth - vw - 48)); drawPango(layoutMain, icCol, kWinWidth - vw - 8, ry, rowH, valStr); } else if (i == 1) { XftColor* icCol = isRec ? &colRed : (recordedClipCount > 0 ? &colGreen : &colMuted); std::string valStr; if (isRec) { valStr = "REC " + formatTimerSec(static_cast((now - recordStartMs) / 1000)); } else if (recordedClipCount > 0) { valStr = "SAVED " + formatTimerSec(lastRecordedSec); } else { valStr = "OFF"; } int vw = pangoWidth(layoutMain, valStr); drawPango(layoutIcon, icCol, 10, ry, rowH, kIconRecord); drawPango(layoutMain, isSel ? &colWhite : &colLight, 34, ry, rowH, "[2] Record", std::max(72, kWinWidth - vw - 44)); drawPango(layoutMain, icCol, kWinWidth - vw - 8, ry, rowH, valStr); } else if (i == 2) { const char* ic = speakerOn ? kIconSpeaker : kIconEarpiece; XftColor* icCol = speakerOn ? &colYellow : &colBlue; std::string valStr = speakerOn ? "SPEAKER" : "EARPIECE"; int vw = pangoWidth(layoutMain, valStr); drawPango(layoutIcon, icCol, 10, ry, rowH, ic); drawPango(layoutMain, isSel ? &colWhite : &colLight, 34, ry, rowH, "[3] Audio Out", std::max(80, kWinWidth - vw - 48)); drawPango(layoutMain, icCol, kWinWidth - vw - 8, ry, rowH, valStr); } else if (i == 3) { drawPango(layoutIcon, &colLight, 10, ry, rowH, kIconSpeaker); drawPango(layoutMain, isSel ? &colWhite : &colLight, 34, ry, rowH, "Volume", 70); int barX = 104; int barW = 82; int barH = 10; int barY = ry + (rowH - barH) / 2; XSetForeground(dpy, gc, theme.spec.bgMain); XFillRectangle(dpy, pix, gc, barX, barY, barW, barH); XSetForeground(dpy, gc, theme.spec.border); XDrawRectangle(dpy, pix, gc, barX, barY, barW - 1, barH - 1); int fillW = ((barW - 2) * std::clamp(callVolumePct, 0, 100)) / 100; if (fillW > 0) { XSetForeground(dpy, gc, isSel ? theme.spec.accent : theme.spec.selBg); XFillRectangle(dpy, pix, gc, barX + 1, barY + 1, fillW, barH - 2); } char pctBuf[16]; std::snprintf(pctBuf, sizeof(pctBuf), "%d%%", callVolumePct); int pw = pangoWidth(layoutSmall, pctBuf); drawPango(layoutSmall, isSel ? &colYellow : &colLight, kWinWidth - pw - 8, ry, rowH, pctBuf); } } } // 3. Softkey Footer Bar int sbY = kWinHeight - kSoftbarH; XSetForeground(dpy, gc, theme.spec.bgFooter); XFillRectangle(dpy, pix, gc, 0, sbY, kWinWidth, kSoftbarH); XSetForeground(dpy, gc, theme.spec.border); XFillRectangle(dpy, pix, gc, 0, sbY, kWinWidth, 1); std::string leftLabel; std::string centerLabel; std::string rightLabel; XftColor* leftCol = &colLight; XftColor* centerCol = &colGreen; XftColor* rightCol = &colRed; if (callState == CallState::SelectSim) { leftLabel = "Dial"; centerLabel = (selectedRow == 1) ? "CALL SIM 2" : "CALL SIM 1"; rightLabel = "Cancel"; leftCol = &colGreen; centerCol = &colGreen; rightCol = &colRed; } else if (callState == CallState::Incoming) { leftLabel = "Accept"; centerLabel = "ANSWER"; rightLabel = "Reject"; leftCol = &colGreen; centerCol = &colGreen; rightCol = &colRed; } else if (callState == CallState::Outgoing || callState == CallState::Active) { leftLabel = dtmfMode ? "Controls" : "DTMF"; centerLabel = dtmfMode ? "TONE" : "TOGGLE"; rightLabel = "Hangup"; leftCol = dtmfMode ? &colYellow : &colLight; centerCol = &colYellow; rightCol = &colRed; } else if (callState == CallState::Ended) { leftLabel = "Call Log"; centerLabel = "CLOSE"; rightLabel = "Close"; leftCol = &colLight; centerCol = &colLight; rightCol = &colLight; } else { leftLabel = "Dialer"; centerLabel = "TOGGLE"; rightLabel = "Close"; leftCol = &colLight; centerCol = &colGreen; rightCol = &colLight; } drawPango(layoutMain, leftCol, 6, sbY + 1, kSoftbarH - 1, leftLabel); int cw = pangoWidth(layoutMain, centerLabel); drawPango(layoutMain, centerCol, (kWinWidth - cw) / 2, sbY + 1, kSoftbarH - 1, centerLabel); int rw = pangoWidth(layoutMain, rightLabel); drawPango(layoutMain, rightCol, kWinWidth - rw - 6, sbY + 1, kSoftbarH - 1, rightLabel); if (visible) { XCopyArea(dpy, pix, win, gc, 0, 0, kWinWidth, kWinHeight, 0, 0); XFlush(dpy); } }; // Pre-warm glyph cache into offscreen Pixmap at startup render(); drawPango(layoutIcon, &colGreen, 0, 0, 20, std::string(kIconPhone) + kIconInCall + kIconOutCall + kIconMissedCall + kIconMicOn + kIconMicOff + kIconSpeaker + kIconEarpiece + kIconRecord + kIconSoundOff + kIconUser); render(); XSync(dpy, False); auto showWindow = [&]() { writeIntFile(activePidPath, static_cast(::getpid())); closeOtherPlugins("callscreen"); wakeDisplayHardware(dpy); theme.checkAndReload(dpy, screen, visual, cmap, layoutMain, layoutSmall, layoutIcon, layoutNum, win); reloadContactsIfNeeded(); refreshHardwareAudioState(); if (!visible) { openStartMs = nowMs(); startupIgnoreUntilMs = openStartMs + 70; initialSoftkeysReleased = (querySoftkeysDown(dpy) == 0); softkeyPending = 0; softkeyDeadlineMs = 0; visible = true; XMapRaised(dpy, win); render(); grabPluginKeyboard(dpy, win); XFlush(dpy); } else { XMapRaised(dpy, win); grabPluginKeyboard(dpy, win); render(); } }; auto hideWindow = [&](bool drainSoftkeys) { if (!visible) { return; } int xfd = ConnectionNumber(dpy); if (drainSoftkeys) { int64_t drainDeadline = nowMs() + 180; while (nowMs() < drainDeadline && querySoftkeysDown(dpy) != 0) { while (XPending(dpy)) { XEvent ev; XNextEvent(dpy, &ev); } struct pollfd pfd {}; pfd.fd = xfd; pfd.events = POLLIN; ::poll(&pfd, 1, 10); } writeSoftkeySuppress(nowMs() + 300); } XUngrabKeyboard(dpy, CurrentTime); XUnmapWindow(dpy, win); XFlush(dpy); ::unlink(activePidPath.c_str()); visible = false; softkeyPending = 0; softkeyDeadlineMs = 0; }; auto resolveActiveModemCallId = [&]() -> std::string { if (!callId.empty() && callId != "-" && callId != "sim" && callId != "test") { return callId; } std::string callsDir = getRuntimeFile("sxmo_calls"); DIR* d = ::opendir(callsDir.c_str()); if (d) { struct dirent* ent; while ((ent = ::readdir(d)) != nullptr) { std::string name = ent->d_name; size_t dot = name.find('.'); if (dot != std::string::npos && dot > 0) { std::string candidate = name.substr(0, dot); bool validId = (candidate.rfind("sub1_", 0) == 0 || candidate.rfind("sub0_", 0) == 0); if (!validId) { validId = !candidate.empty(); for (char c : candidate) { if (!std::isdigit(static_cast(c))) { validId = false; break; } } } if (validId) { ::closedir(d); callId = candidate; return callId; } } } ::closedir(d); } return callId; }; auto stopRingingJobs = [&]() { ::unlink("/tmp/sxmo_call_ringing"); runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1; " "pkill -TERM -f 'pw-play.*ring' >/dev/null 2>&1; " "pkill -TERM -f 'mpv.*ring' >/dev/null 2>&1; " "pkill -TERM -x sxmo_vibrate >/dev/null 2>&1"); }; auto acceptIncomingCall = [&]() { if (callState != CallState::Incoming) { return; } std::string cid = resolveActiveModemCallId(); callState = CallState::Active; callStartMs = nowMs(); ringMuted = false; dtmfMode = false; dtmfSent.clear(); selectedRow = 0; writeActiveStateFiles(); stopRingingJobs(); setSpeakerRoute(false); render(); if (cid.rfind("sip:", 0) == 0) { sendPluginCommand("sip", "CALL_ACCEPT " + cid); } else if (cid.rfind("tox:", 0) == 0) { sendPluginCommand("tox", "CALL_ACCEPT " + cid); } else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { runAsyncArgv("sxmo_modemcall.sh", "pickup", cid.c_str()); } }; auto silenceRing = [&]() { if (callState != CallState::Incoming || ringMuted) { return; } ringMuted = true; stopRingingJobs(); std::string cid = resolveActiveModemCallId(); if (cid.rfind("sip:", 0) == 0) { sendPluginCommand("sip", "CALL_MUTE_RING " + cid); } else if (cid.rfind("tox:", 0) == 0) { sendPluginCommand("tox", "CALL_MUTE_RING " + cid); } else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { runAsyncArgv("sxmo_modemcall.sh", "mute", cid.c_str()); } statusNotice = "Ringtone silenced"; statusNoticeUntilMs = nowMs() + 2500; render(); }; auto transitionToEnded = [&](const std::string& reason) { stopRecording(); if (micMuted) { setMicMuted(false); } if (callStartMs > 0 && (callState == CallState::Active || callState == CallState::Outgoing)) { lastFinalDurationSec = static_cast((nowMs() - callStartMs) / 1000); } else { lastFinalDurationSec = 0; } endReason = reason.empty() ? "CALL ENDED" : reason; callState = CallState::Ended; endedAtMs = nowMs(); dtmfMode = false; ringMuted = false; writeActiveStateFiles(); stopRingingJobs(); alsa.setBoolean("PRI_MI2S_RX Voice Mixer VoiceMMode1", false); alsa.setBoolean("VoiceMMode1 Capture Mixer TERT_MI2S_TX", false); alsa.setEnum("EAR_S", 0); alsa.setEnum("RX3 MIX1 INP1", 3); alsa.setBoolean("SPK DAC Switch", true); runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " "pkill -TERM -f sxmo_hook_ring.sh >/dev/null 2>&1; " "pkill -TERM -f 'pw-play.*ring' >/dev/null 2>&1; " "pkill -TERM -f 'mpv.*ring' >/dev/null 2>&1; " "pkill -TERM -x sxmo_vibrate >/dev/null 2>&1; " "sxmo_modemaudio.sh disable_call_audio_mode >/dev/null 2>&1"); render(); }; auto hangupCall = [&]() { std::string cid = resolveActiveModemCallId(); bool wasIncoming = (callState == CallState::Incoming); stopRingingJobs(); if (cid.rfind("sip:", 0) == 0) { sendPluginCommand("sip", "CALL_HANGUP " + cid); } else if (cid.rfind("tox:", 0) == 0) { sendPluginCommand("tox", "CALL_HANGUP " + cid); } else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { runAsyncArgv("sxmo_modemcall.sh", "hangup", cid.c_str()); } else { runAsyncCmd("mmcli -m any --voice-hangup-all >/dev/null 2>&1"); } transitionToEnded(wasIncoming ? "CALL REJECTED" : "CALL ENDED"); }; auto sendDtmfTone = [&](char ch) { dtmfSent.push_back(ch); if (dtmfSent.size() > 16) { dtmfSent.erase(0, dtmfSent.size() - 16); } std::string cid = resolveActiveModemCallId(); if (cid.rfind("sip:", 0) == 0) { sendPluginCommand("sip", std::string("CALL_DTMF ") + ch); } else if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test" && cid.rfind("tox:", 0) != 0) { if (cid.rfind("sub", 0) == 0) { char cmd[160]; std::snprintf(cmd, sizeof(cmd), "doas -n /usr/libexec/msm-modem-uim-selection call-dtmf '%c' >/dev/null 2>&1", ch); runAsyncCmd(cmd); } else { char cmd[160]; std::snprintf(cmd, sizeof(cmd), "mmcli -m any -o '%s' --send-dtmf='%c' >/dev/null 2>&1", cid.c_str(), ch); runAsyncCmd(cmd); } } render(); }; auto queryQmiVoiceCalls = [&](std::string& outId, std::string& outDir, std::string& outState, std::string& outNum, bool& outSawTerminated) -> bool { constexpr int kAfQipcrtr = 42; constexpr uint32_t kQrtrPortCtrl = 0xfffffffeu; constexpr uint32_t kQrtrTypeNewServer = 4; constexpr uint32_t kQrtrTypeNewLookup = 10; constexpr uint32_t kQmiServiceVoice = 9; struct SockAddrQrtr { unsigned short sq_family; uint32_t sq_node; uint32_t sq_port; }; struct QrtrCtrlPkt { uint32_t cmd; uint32_t service; uint32_t instance; uint32_t node; uint32_t port; } __attribute__((packed)); int lfd = ::socket(kAfQipcrtr, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (lfd < 0) { return false; } SockAddrQrtr localSq {}; socklen_t sl = sizeof(localSq); if (::getsockname(lfd, reinterpret_cast(&localSq), &sl) < 0) { ::close(lfd); return false; } SockAddrQrtr ctrlSq { kAfQipcrtr, localSq.sq_node, kQrtrPortCtrl }; QrtrCtrlPkt lookup { kQrtrTypeNewLookup, kQmiServiceVoice, 0, 0, 0 }; if (::sendto(lfd, &lookup, sizeof(lookup), 0, reinterpret_cast(&ctrlSq), sizeof(ctrlSq)) < 0) { ::close(lfd); return false; } uint32_t vNode = 0, vPort = 0; bool foundSrv = false; for (int i = 0; i < 8; ++i) { struct pollfd pfd { lfd, POLLIN, 0 }; if (::poll(&pfd, 1, 40) <= 0) break; QrtrCtrlPkt pkt {}; ssize_t n = ::recv(lfd, &pkt, sizeof(pkt), 0); if (n >= static_cast(sizeof(pkt)) && pkt.cmd == kQrtrTypeNewServer) { if (pkt.service == kQmiServiceVoice && pkt.port != 0) { vNode = pkt.node; vPort = pkt.port; foundSrv = true; break; } if (pkt.service == 0 && pkt.node == 0 && pkt.port == 0) break; } } ::close(lfd); if (!foundSrv) { return false; } SockAddrQrtr vSq { kAfQipcrtr, vNode, vPort }; for (int sub : {1, 0}) { int sfd = ::socket(kAfQipcrtr, SOCK_DGRAM | SOCK_CLOEXEC, 0); if (sfd < 0) continue; uint8_t bindReq[11] = { 0x00, 0x01, 0x00, 0x44, 0x00, 0x04, 0x00, 0x01, 0x01, 0x00, static_cast(sub) }; ::sendto(sfd, bindReq, sizeof(bindReq), 0, reinterpret_cast(&vSq), sizeof(vSq)); struct pollfd pfd { sfd, POLLIN, 0 }; if (::poll(&pfd, 1, 40) > 0) { uint8_t tmp[256]; ::recv(sfd, tmp, sizeof(tmp), 0); } uint8_t infoReq[7] = { 0x00, 0x02, 0x00, 0x2F, 0x00, 0x00, 0x00 }; ::sendto(sfd, infoReq, sizeof(infoReq), 0, reinterpret_cast(&vSq), sizeof(vSq)); if (::poll(&pfd, 1, 50) > 0) { uint8_t buf[1024]; ssize_t rlen = ::recv(sfd, buf, sizeof(buf), 0); if (rlen >= 7 && buf[0] == 0x02 && buf[3] == 0x2F) { const uint8_t* rawCi = nullptr; uint16_t lenCi = 0; const uint8_t* rawNum = nullptr; uint16_t lenNum = 0; size_t pos = 7; while (pos + 3 <= static_cast(rlen)) { uint8_t tt = buf[pos]; uint16_t tl = static_cast(buf[pos + 1]) | (static_cast(buf[pos + 2]) << 8); pos += 3; if (pos + tl > static_cast(rlen)) break; if (tt == 0x10) { rawCi = buf + pos; lenCi = tl; } else if (tt == 0x11) { rawNum = buf + pos; lenNum = tl; } pos += tl; } if (rawCi && lenCi >= 1) { uint8_t cnt = rawCi[0]; size_t off = 1; for (uint8_t i = 0; i < cnt && off + 7 <= lenCi; ++i, off += 7) { uint8_t cid = rawCi[off]; uint8_t cstate = rawCi[off + 1]; uint8_t cdir = rawCi[off + 3]; if (cstate == 8 || cstate == 9) { outSawTerminated = true; continue; } std::string st; if (cstate == 3) st = "active"; else if (cstate == 2 || cstate == 7) st = "ringing-in"; else if (cstate == 5) st = "ringing-out"; else if (cstate == 1 || cstate == 4 || cstate == 10) st = "dialing"; else if (cstate == 6) st = "held"; if (!st.empty() && outId.empty()) { outId = (sub == 1) ? ("sub1_" + std::to_string(cid)) : std::to_string(cid); outState = st; outDir = (cdir == 2) ? "incoming" : "outgoing"; if (rawNum && lenNum >= 1) { uint8_t ncnt = rawNum[0]; size_t noff = 1; for (uint8_t ni = 0; ni < ncnt && noff + 3 <= lenNum; ++ni) { uint8_t ncid = rawNum[noff]; uint8_t nlen = rawNum[noff + 2]; noff += 3; if (noff + nlen > lenNum) break; if (ncid == cid && nlen > 0) { outNum.assign(reinterpret_cast(rawNum + noff), nlen); outNum = trimStr(outNum); } noff += nlen; } } } } } } } ::close(sfd); } return true; }; auto syncModemCalls = [&]() { if (callId == "sim" || callId == "test" || isVoipCallId(callId)) { return; } std::string foundId; std::string foundDir; std::string foundState; std::string foundNum; bool sawTerminated = false; FILE* fp = ::popen("mmcli -m any --voice-list-calls -a 2>/dev/null", "r"); if (fp) { char line[512]; while (std::fgets(line, sizeof(line), fp)) { std::string s(line); if (s.find("No calls") != std::string::npos) { continue; } if (s.find("terminated") != std::string::npos) { sawTerminated = true; continue; } size_t callPos = s.find("/Call/"); if (callPos == std::string::npos) { continue; } size_t idStart = callPos + 6; size_t idEnd = idStart; while (idEnd < s.size() && std::isdigit(static_cast(s[idEnd]))) { ++idEnd; } if (idEnd == idStart) { continue; } foundId = s.substr(idStart, idEnd - idStart); if (s.find("incoming") != std::string::npos) { foundDir = "incoming"; } else if (s.find("outgoing") != std::string::npos) { foundDir = "outgoing"; } size_t lp = s.find('('); size_t rp = s.find(')', lp == std::string::npos ? 0 : lp); if (lp != std::string::npos && rp != std::string::npos && rp > lp + 1) { foundState = s.substr(lp + 1, rp - lp - 1); } break; } ::pclose(fp); } if (sawTerminated) { runAsyncCmd("sxmo_modem.sh checkforfinishedcalls >/dev/null 2>&1"); } if (foundId.empty()) { queryQmiVoiceCalls(foundId, foundDir, foundState, foundNum, sawTerminated); } if (!foundId.empty()) { if (callId.empty() || callId == "-") { callId = foundId; } if (callNumber.empty()) { if (!foundNum.empty()) { updateCallerDetails(foundId, foundNum); } else { char numCmd[160]; std::snprintf(numCmd, sizeof(numCmd), "sxmo_modemcall.sh vid_to_number '%s' 2>/dev/null", foundId.c_str()); FILE* nfp = ::popen(numCmd, "r"); if (nfp) { char nbuf[128]; if (std::fgets(nbuf, sizeof(nbuf), nfp)) { updateCallerDetails(foundId, trimStr(nbuf)); } ::pclose(nfp); } } } if (foundState == "active" && callState != CallState::Active) { if (callState != CallState::Outgoing) { speakerOn = false; } callState = CallState::Active; callStartMs = nowMs(); ringMuted = false; writeActiveStateFiles(); stopRingingJobs(); setSpeakerRoute(speakerOn); render(); } else if (foundState == "ringing-in" && callState == CallState::Idle) { callState = CallState::Incoming; callStartMs = nowMs(); selectedRow = 0; writeActiveStateFiles(); render(); } else if ((foundState == "dialing" || foundState == "ringing-out") && callState == CallState::Idle) { callState = CallState::Outgoing; callStartMs = nowMs(); selectedRow = 0; writeActiveStateFiles(); render(); } } else if (callState == CallState::Active || callState == CallState::Incoming || sawTerminated || (callState == CallState::Outgoing && ((!callId.empty() && callId != "-") || nowMs() - callStartMs > 3500))) { std::string callsDir = getRuntimeFile("sxmo_calls"); DIR* d = ::opendir(callsDir.c_str()); if (d) { struct dirent* ent; while ((ent = ::readdir(d)) != nullptr) { if (ent->d_name[0] != '.' && ent->d_name[0] != '\0') { std::string fn(ent->d_name); if (fn.rfind("sub", 0) == 0 || fn.find(".ringing-in") != std::string::npos || fn.find(".dialing") != std::string::npos || fn.find(".ringing-out") != std::string::npos || fn.find(".active") != std::string::npos) { std::string fpPath = callsDir + "/" + fn; ::unlink(fpPath.c_str()); } } } ::closedir(d); } transitionToEnded("CALL ENDED"); } }; auto handleFifoCommand = [&](const std::string& rawLine) { std::string line = trimStr(rawLine); if (line.empty() || line == "NOP") { return; } if (line == "CLOSE") { hideWindow(false); return; } if (line == "RELOAD_THEME") { theme.load(dpy, screen, visual, cmap, layoutMain, layoutSmall, layoutIcon, layoutNum, win); render(); return; } if (line == "ACCEPT") { if (callState == CallState::Incoming) { acceptIncomingCall(); showWindow(); } return; } if (line == "HANGUP" || line.rfind("HANGUP ", 0) == 0) { if (callState == CallState::Incoming || callState == CallState::Outgoing || callState == CallState::Active) { hangupCall(); } else { hideWindow(false); } return; } if (line == "MUTE_RING") { silenceRing(); return; } if (line == "TOGGLE_MIC") { setMicMuted(!micMuted); render(); return; } if (line == "TOGGLE_REC") { toggleRecording(); render(); return; } if (line.rfind("NOTICE ", 0) == 0) { statusNotice = trimStr(line.substr(7)); statusNoticeUntilMs = nowMs() + 12000; render(); return; } if (line == "ENDED" || line.rfind("ENDED ", 0) == 0) { std::string reason = (line.size() > 6) ? trimStr(line.substr(6)) : "CALL ENDED"; sipZrtpSas.clear(); if (callState != CallState::Idle) { transitionToEnded(reason); } else { hideWindow(false); } return; } // Parse PROMPT_SIM / INCOMING / OUTGOING / ACTIVE / OPEN std::istringstream iss(line); std::string verb, arg1, arg2, arg3; iss >> verb >> arg1 >> arg2 >> arg3; if (verb == "PROMPT_SIM") { simInfo = queryDualSimInfo(true); callId = "-"; callNumber.clear(); contactName.clear(); updateCallerDetails("-", arg1); callState = CallState::SelectSim; selectedRow = (simInfo.preferredSlot == 2) ? 1 : 0; activeSimSlot = 0; writeActiveStateFiles(); showWindow(); return; } if (verb == "OPEN" && !arg1.empty()) { std::string low = toLowerStr(arg1); if (low == "incoming" || low == "outgoing" || low == "active") { verb = (low == "incoming") ? "INCOMING" : ((low == "outgoing") ? "OUTGOING" : "ACTIVE"); arg1 = arg2.empty() ? "-" : arg2; arg2 = arg3; arg3.clear(); iss >> arg3; } } auto parseSimTag = [&](const std::string& cidStr, const std::string& tagStr) { if (tagStr == "SIP" || tagStr.rfind("SIP:", 0) == 0 || cidStr.rfind("sip:", 0) == 0) { activeSimSlot = 3; if (tagStr.rfind("SIP:", 0) == 0 && tagStr.size() > 4) { sipZrtpSas = tagStr.substr(4); } else if (tagStr == "SIP") { sipZrtpSas.clear(); } return; } sipZrtpSas.clear(); if (tagStr == "TOX" || cidStr.rfind("tox:", 0) == 0) { activeSimSlot = 4; return; } simInfo = queryDualSimInfo(); if (tagStr == "SIM1") { activeSimSlot = 1; } else if (tagStr == "SIM2") { activeSimSlot = 2; } else if (cidStr.rfind("sub1_", 0) == 0) { activeSimSlot = (simInfo.secondaryGwSlot > 0) ? simInfo.secondaryGwSlot : 1; } else if (simInfo.dualSimActive) { activeSimSlot = (simInfo.primaryGwSlot > 0) ? simInfo.primaryGwSlot : simInfo.preferredSlot; } else { activeSimSlot = 0; } }; if (verb == "INCOMING") { callId.clear(); callNumber.clear(); contactName.clear(); recordFileName.clear(); recordFilePath.clear(); lastRecordedSec = 0; recordedClipCount = 0; updateCallerDetails(arg1, arg2); parseSimTag(arg1, arg3); callState = CallState::Incoming; callStartMs = nowMs(); ringMuted = false; speakerOn = false; dtmfMode = false; dtmfSent.clear(); selectedRow = 0; writeActiveStateFiles(); showWindow(); } else if (verb == "OUTGOING") { callId.clear(); callNumber.clear(); contactName.clear(); recordFileName.clear(); recordFilePath.clear(); lastRecordedSec = 0; recordedClipCount = 0; updateCallerDetails(arg1, arg2); parseSimTag(arg1, arg3); callState = CallState::Outgoing; callStartMs = nowMs(); ringMuted = false; speakerOn = false; dtmfMode = false; dtmfSent.clear(); selectedRow = 0; setSpeakerRoute(false); statusNotice.clear(); statusNoticeUntilMs = 0; writeActiveStateFiles(); showWindow(); } else if (verb == "ACTIVE") { bool wasActive = (callState == CallState::Active); bool wasOutgoing = (callState == CallState::Outgoing); updateCallerDetails(arg1, arg2); if (!arg3.empty() || activeSimSlot == 0) { parseSimTag(arg1, arg3); } callState = CallState::Active; if (!wasActive) { callStartMs = nowMs(); if (!wasOutgoing) { speakerOn = false; } } ringMuted = false; selectedRow = 0; setSpeakerRoute(speakerOn); statusNotice.clear(); statusNoticeUntilMs = 0; writeActiveStateFiles(); showWindow(); } else if (verb == "OPEN") { if (!arg1.empty()) { updateCallerDetails("-", arg1); } if (callState == CallState::Idle || callState == CallState::Ended) { syncModemCalls(); } showWindow(); } }; if (!isPreload) { handleFifoCommand(forwardedCmd); } auto startDialOnSim = [&](int chosenSim) { std::string num = normalizePhone(callNumber); if (num.empty()) { return; } std::string simStr = (chosenSim == 2) ? "2" : "1"; handleFifoCommand("OUTGOING - " + num + " SIM" + simStr); runAsyncArgv("sxmo_modemdial.sh", "--sim", simStr.c_str(), num.c_str()); }; int xfd = ConnectionNumber(dpy); while (gRunning) { for (const std::string& cmd : readFifoLines(fifoFd)) { handleFifoCommand(cmd); } int64_t now = nowMs(); // Auto-close Ended screen after 1300 ms if (callState == CallState::Ended && endedAtMs > 0 && now - endedAtMs >= 1300) { callState = CallState::Idle; callId.clear(); callNumber.clear(); contactName.clear(); endedAtMs = 0; writeActiveStateFiles(); hideWindow(false); } // Periodically sync call state with ModemManager when a real call is in progress if ((callState == CallState::Incoming || callState == CallState::Outgoing || callState == CallState::Active) && now - lastModemPollMs >= 1500) { lastModemPollMs = now; syncModemCalls(); } if (visible && !initialSoftkeysReleased && querySoftkeysDown(dpy) == 0) { initialSoftkeysReleased = true; } while (XPending(dpy)) { XEvent ev; XNextEvent(dpy, &ev); if (!visible) { continue; } if (!initialSoftkeysReleased && querySoftkeysDown(dpy) == 0) { initialSoftkeysReleased = true; } if (ev.type == Expose) { if (ev.xexpose.count == 0) { render(); } } else if (ev.type == VisibilityNotify && ev.xvisibility.state != VisibilityUnobscured) { if (isAnotherPluginActive("callscreen")) { hideWindow(false); } else { XRaiseWindow(dpy, win); grabPluginKeyboard(dpy, win); render(); } } else if (ev.type == KeyRelease) { KeySym sym = XLookupKeysym(&ev.xkey, 0); if (sym == XK_Menu || sym == XF86XK_KbdLcdMenu1 || sym == XF86XK_Back || sym == XF86XK_KbdLcdMenu2 || ev.xkey.keycode == 135 || ev.xkey.keycode == 166) { if (querySoftkeysDown(dpy) == 0) { initialSoftkeysReleased = true; } } } else if (ev.type == KeyPress) { KeySym sym = XLookupKeysym(&ev.xkey, 0); unsigned int kc = ev.xkey.keycode; bool isLeftSoft = (sym == XK_Menu || sym == XF86XK_KbdLcdMenu1 || kc == 135); bool isRightSoft = (sym == XF86XK_Back || sym == XF86XK_KbdLcdMenu2 || kc == 166); if (isLeftSoft || isRightSoft) { if (!initialSoftkeysReleased || nowMs() < startupIgnoreUntilMs) { continue; } int which = (isLeftSoft ? 1 : 0) | (isRightSoft ? 2 : 0); softkeyPending |= which | querySoftkeysDown(dpy); if (softkeyPending == 3) { writeSoftkeySuppress(nowMs() + 500); hideWindow(false); if (!sendPluginCommand("xdrawer", "TOGGLE")) { runAsyncArgv("xdrawer"); } break; } if (softkeyDeadlineMs == 0) { softkeyDeadlineMs = nowMs() + 40; } continue; } // Physical Red End / Power button or Escape / BackSpace in SelectSim if (sym == XK_Escape || sym == XF86XK_PowerOff || kc == 124 || (callState == CallState::SelectSim && sym == XK_BackSpace)) { writeSoftkeySuppress(nowMs() + 350); if (callState == CallState::Incoming || callState == CallState::Outgoing || callState == CallState::Active) { hangupCall(); } else { callState = CallState::Idle; writeActiveStateFiles(); hideWindow(true); } continue; } // Physical Green Call button if (sym == XF86XK_Phone || sym == XF86XK_PickupPhone || kc == 177) { if (nowMs() < startupIgnoreUntilMs) { continue; } if (callState == CallState::SelectSim) { int chosenSim = (selectedRow == 1) ? 2 : 1; startDialOnSim(chosenSim); } else if (callState == CallState::Incoming) { acceptIncomingCall(); } else if (callState == CallState::Ended) { callState = CallState::Idle; writeActiveStateFiles(); hideWindow(true); } else if (callState == CallState::Idle) { writeSoftkeySuppress(nowMs() + 250); hideWindow(false); if (!sendPluginCommand("dialer", "OPEN")) { runAsyncArgv("xdialer"); } } continue; } // Keypad digits 0-9 / * / # char dialCh = mapDialKey(sym, kc, ev.xkey.state); if (dialCh != '\0') { if (callState == CallState::SelectSim) { if (dialCh == '1') { selectedRow = 0; startDialOnSim(1); } else if (dialCh == '2') { selectedRow = 1; startDialOnSim(2); } continue; } if (callState == CallState::Incoming) { if (dialCh == '*' || dialCh == '0') { silenceRing(); } else if (dialCh == '1') { acceptIncomingCall(); } else if (dialCh == '#') { hangupCall(); } continue; } if (callState == CallState::Ended) { callState = CallState::Idle; writeActiveStateFiles(); hideWindow(true); continue; } if (dtmfMode) { sendDtmfTone(dialCh); continue; } if (dialCh == '1' || dialCh == '*') { setMicMuted(!micMuted); selectedRow = 0; render(); } else if (dialCh == '2' || dialCh == '#') { toggleRecording(); selectedRow = 1; render(); } else if (dialCh == '3') { setSpeakerRoute(!speakerOn); selectedRow = 2; render(); } else if (dialCh == '0') { dtmfMode = !dtmfMode; render(); } else { sendDtmfTone(dialCh); } continue; } switch (sym) { case XK_Up: case XK_KP_Up: { int maxRows = (callState == CallState::SelectSim) ? 2 : ((callState == CallState::Incoming) ? 3 : 4); selectedRow = (selectedRow + maxRows - 1) % maxRows; render(); break; } case XK_Down: case XK_KP_Down: { int maxRows = (callState == CallState::SelectSim) ? 2 : ((callState == CallState::Incoming) ? 3 : 4); selectedRow = (selectedRow + 1) % maxRows; render(); break; } case XK_Left: case XK_KP_Left: case XF86XK_AudioLowerVolume: if (callState != CallState::Incoming && callState != CallState::SelectSim) { adjustVolume(-5); selectedRow = 3; render(); } break; case XK_Right: case XK_KP_Right: case XF86XK_AudioRaiseVolume: if (callState != CallState::Incoming && callState != CallState::SelectSim) { adjustVolume(+5); selectedRow = 3; render(); } break; case XK_Return: case XK_KP_Enter: if (nowMs() < startupIgnoreUntilMs) { break; } if (callState == CallState::SelectSim) { int chosenSim = (selectedRow == 1) ? 2 : 1; startDialOnSim(chosenSim); } else if (callState == CallState::Incoming) { if (selectedRow == 0) { acceptIncomingCall(); } else if (selectedRow == 1) { silenceRing(); } else { hangupCall(); } } else if (callState == CallState::Ended) { callState = CallState::Idle; writeActiveStateFiles(); hideWindow(true); } else { if (selectedRow == 0) { setMicMuted(!micMuted); } else if (selectedRow == 1) { toggleRecording(); } else if (selectedRow == 2) { setSpeakerRoute(!speakerOn); } else if (selectedRow == 3) { adjustVolume(callVolumePct >= 95 ? -50 : +10); } render(); } break; default: break; } } } if (visible && softkeyPending != 0 && nowMs() >= softkeyDeadlineMs) { int comb = softkeyPending | querySoftkeysDown(dpy); softkeyPending = 0; softkeyDeadlineMs = 0; if (comb == 3) { writeSoftkeySuppress(nowMs() + 500); hideWindow(false); if (!sendPluginCommand("xdrawer", "TOGGLE")) { runAsyncArgv("xdrawer"); } } else if (comb == 1) { if (callState == CallState::SelectSim) { int chosenSim = (selectedRow == 1) ? 2 : 1; startDialOnSim(chosenSim); } else if (callState == CallState::Incoming) { acceptIncomingCall(); } else if (callState == CallState::Outgoing || callState == CallState::Active) { dtmfMode = !dtmfMode; render(); } else if (callState == CallState::Ended) { callState = CallState::Idle; writeActiveStateFiles(); hideWindow(false); if (!sendPluginCommand("calllog", "OPEN")) { runAsyncArgv("xcalllog"); } } else { hideWindow(false); if (!sendPluginCommand("dialer", "OPEN")) { runAsyncArgv("xdialer"); } } } else if (comb == 2) { if (callState == CallState::Incoming || callState == CallState::Outgoing || callState == CallState::Active) { hangupCall(); } else { callState = CallState::Idle; writeActiveStateFiles(); writeSoftkeySuppress(nowMs() + 350); hideWindow(true); } } } if (visible && (callState != CallState::Idle || checkRecordingAlive())) { render(); } int timeoutMs = -1; if (visible || callState != CallState::Idle || checkRecordingAlive()) { timeoutMs = 250; if (softkeyDeadlineMs > 0) { timeoutMs = static_cast(std::max(5, softkeyDeadlineMs - nowMs())); } } struct pollfd pfds[2] {}; pfds[0].fd = xfd; pfds[0].events = POLLIN; pfds[1].fd = fifoFd; pfds[1].events = POLLIN; ::poll(pfds, (fifoFd >= 0) ? 2 : 1, timeoutMs); } stopRecording(); if (micMuted) { setMicMuted(false); } ::unlink("/tmp/sxmo_call_ringing"); ::unlink("/tmp/sxmo_active_call"); hideWindow(false); if (fifoFd >= 0) { ::close(fifoFd); } ::unlink(getPluginFifoPath("callscreen").c_str()); ::unlink(daemonPidPath.c_str()); return 0; } int callscreen_plugin_init(const DwmHostApi* host) { if (host && host->spawn_plugin) { host->spawn_plugin("callscreen", "--preload"); } return 0; } int callscreen_on_global_key(const DwmHostApi* host, KeySym keysym, unsigned int keycode, unsigned int state, int is_press) { (void)host; if (!is_press || state != 0) { return 0; } if (!isCallActiveOrRingingFast()) { return 0; } // Green Call button: Accept ringing call or reopen active Call Screen if (keysym == XF86XK_Phone || keysym == XF86XK_PickupPhone || keycode == 177) { if (isCallRingingFast()) { if (!sendPluginCommand("callscreen", "ACCEPT")) { runAsyncArgv("xcallscreen", "accept"); } } else { if (!sendPluginCommand("callscreen", "OPEN")) { runAsyncArgv("xcallscreen"); } } return 1; } // Red End button: Reject ringing call or hang up active call if (keysym == XF86XK_PowerOff || keycode == 124) { if (!sendPluginCommand("callscreen", "HANGUP")) { runAsyncArgv("xcallscreen", "hangup"); } return 1; } return 0; } int callscreen_on_idle_key(const DwmHostApi* host, KeySym keysym, unsigned int keycode, unsigned int state) { if (!host || state != 0) { return 0; } if (!isCallActiveOrRingingFast()) { return 0; } if (keysym == XF86XK_Phone || keysym == XF86XK_PickupPhone || keycode == 177) { if (isCallRingingFast()) { sendPluginCommand("callscreen", "ACCEPT"); } else { sendPluginCommand("callscreen", "OPEN"); } return 1; } if (keysym == XF86XK_PowerOff || keycode == 124) { sendPluginCommand("callscreen", "HANGUP"); return 1; } return 0; } } // namespace extern "C" __attribute__((visibility("default"))) const DwmPlugin dwm_plugin_entry = { DWM_PLUGIN_API_VERSION, "callscreen", "Incoming & active call screen with mic mute, speaker routing, and call recording", callscreen_plugin_init, nullptr, nullptr, callscreen_on_idle_key, callscreen_on_global_key, callscreen_run_main };