// 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, }; 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 "unknown"; } if (out.size() > 20) { out = out.substr(0, 20); } 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); } 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)); 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); } ::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); Display* dpy = XOpenDisplay(nullptr); if (!dpy) { if (fifoFd >= 0) ::close(fifoFd); ::unlink(daemonPidPath.c_str()); return 1; } int screen = DefaultScreen(dpy); Window root = RootWindow(dpy, screen); Visual* visual = DefaultVisual(dpy, screen); Colormap cmap = DefaultColormap(dpy, screen); XSetWindowAttributes swa{}; swa.override_redirect = True; swa.background_pixel = 0x222222; swa.border_pixel = 0x005577; swa.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask | ButtonPressMask | StructureNotifyMask | VisibilityChangeMask; Window win = XCreateWindow( dpy, root, kWinX, kWinY, kWinWidth, kWinHeight, 0, DefaultDepth(dpy, screen), CopyFromParent, visual, CWOverrideRedirect | CWBackPixel | CWBorderPixel | CWEventMask, &swa); XClassHint ch{}; char resName[] = "xcallscreen"; char resClass[] = "XCallScreen"; ch.res_name = resName; ch.res_class = resClass; XSetClassHint(dpy, win, &ch); XStoreName(dpy, win, "Call Screen"); Pixmap pix = XCreatePixmap(dpy, win, kWinWidth, kWinHeight, DefaultDepth(dpy, screen)); GC gc = XCreateGC(dpy, pix, 0, nullptr); XftDraw* xftDraw = XftDrawCreate(dpy, pix, visual, cmap); PangoFontMap* fontMap = pango_xft_get_font_map(dpy, screen); PangoContext* pangoCtx = pango_font_map_create_context(fontMap); PangoLayout* layoutNum = pango_layout_new(pangoCtx); PangoLayout* layoutMain = pango_layout_new(pangoCtx); PangoLayout* layoutSmall = pango_layout_new(pangoCtx); PangoLayout* layoutIcon = pango_layout_new(pangoCtx); PluginTheme theme; theme.load(dpy, screen, visual, cmap, layoutMain, layoutSmall, layoutIcon, layoutNum, win); 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; 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 = 80; 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; bool visible = false; int64_t openStartMs = 0; int64_t startupIgnoreUntilMs = 0; bool initialSoftkeysReleased = true; int softkeyPending = 0; int64_t softkeyDeadlineMs = 0; 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; } bool spkSwitch = alsa.getBoolean("SPK DAC Switch", false); bool earSwitch = (alsa.getEnum("EAR_S", 1) != 0); speakerOn = (spkSwitch && !earSwitch); long rawVol = speakerOn ? alsa.getInteger("RX3 Digital Volume", 68) : alsa.getInteger("RX1 Digital Volume", 68); if (rawVol <= 0) { rawVol = alsa.getInteger("RX1 Digital Volume", 68); } callVolumePct = std::clamp(static_cast(std::lround((rawVol * 100.0) / 84.0)), 0, 100); callVolumePct = (callVolumePct / 5) * 5; if (callVolumePct == 0) { callVolumePct = 75; } }; auto setMicMuted = [&](bool mute) { micMuted = mute; alsa.setEnum("DEC1 MUX", mute ? 0 : (savedMicMux > 0 ? savedMicMux : 1)); alsa.setInteger("ADC1 Volume", mute ? 0 : 6); alsa.setInteger("ADC3 Volume", mute ? 0 : 6); 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 setSpeakerRoute = [&](bool toSpeaker) { speakerOn = toSpeaker; long hwVol = std::lround((callVolumePct * 84.0) / 100.0); if (toSpeaker) { alsa.setEnum("EAR_S", 0); alsa.setEnum("RX1 MIX1 INP1", 0); alsa.setBoolean("SPK DAC Switch", true); alsa.setEnum("RX3 MIX1 INP1", 3); alsa.setInteger("RX3 Digital Volume", hwVol); statusNotice = "Audio routed to Speaker"; } else { alsa.setBoolean("SPK DAC Switch", false); alsa.setEnum("RX3 MIX1 INP1", 0); alsa.setEnum("RX1 MIX1 INP1", 3); alsa.setEnum("RDAC2 MUX", 0); alsa.setEnum("EAR_S", 1); alsa.setInteger("RX1 Digital Volume", hwVol); statusNotice = "Audio routed to Earpiece"; } statusNoticeUntilMs = nowMs() + 2000; }; auto adjustVolume = [&](int deltaPct) { callVolumePct = std::clamp(callVolumePct + deltaPct, 5, 100); long hwVol = std::lround((callVolumePct * 84.0) / 100.0); alsa.setInteger("RX1 Digital Volume", hwVol); if (speakerOn) { alsa.setInteger("RX3 Digital Volume", hwVol); } char cmd[128]; std::snprintf(cmd, sizeof(cmd), "wpctl set-volume @DEFAULT_AUDIO_SINK@ %d%% >/dev/null 2>&1", callVolumePct); runAsyncCmd(cmd); }; 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; finalizeWavHeader(recordFilePath); 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; } finalizeWavHeader(recordFilePath); if (!recordFileName.empty()) { statusNotice = "Saved: " + recordFileName; statusNoticeUntilMs = nowMs() + 3500; } }; 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), "%Y%m%d_%H%M%S", &tmNow); std::string tag = sanitizeForFilename( !contactName.empty() ? contactName : (!callNumber.empty() ? callNumber : "voice")); recordFileName = "call_" + tag + "_" + tsBuf + ".wav"; recordFilePath = dir + "/" + recordFileName; // Ensure MultiMedia2 capture mixer and primary mic path are active for PipeWire recording alsa.setEnum("CIC1 MUX", 0); if (!micMuted) { alsa.setEnum("DEC1 MUX", savedMicMux > 0 ? savedMicMux : 1); alsa.setInteger("ADC1 Volume", 6); } alsa.setBoolean("MultiMedia2 Mixer TERT_MI2S_TX", true); pid_t pid = ::fork(); if (pid < 0) { return false; } if (pid == 0) { ::setsid(); std::string runtimeDir = "/run/user/" + std::to_string(::getuid()); const char* xdg = std::getenv("XDG_RUNTIME_DIR"); struct stat stRuntime {}; if (!xdg || !*xdg || ::stat(xdg, &stRuntime) != 0) { ::setenv("XDG_RUNTIME_DIR", runtimeDir.c_str(), 1); } 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("pw-record", "pw-record", "--format", "s16", "--rate", "16000", "--channels", "1", recordFilePath.c_str(), static_cast(nullptr)); execlp("parecord", "parecord", "--rate=16000", "--channels=1", "--file-format=wav", recordFilePath.c_str(), static_cast(nullptr)); execlp("arecord", "arecord", "-f", "S16_LE", "-r", "16000", "-c", "1", recordFilePath.c_str(), static_cast(nullptr)); _exit(1); } recordPid = pid; recordStartMs = nowMs(); statusNotice = "Recording to " + recordFileName; statusNoticeUntilMs = nowMs() + 2500; 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) { pango_layout_set_text(layout, text.c_str(), static_cast(text.size())); if (maxW > 0) { pango_layout_set_width(layout, maxW * PANGO_SCALE); pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_END); } else { pango_layout_set_width(layout, -1); pango_layout_set_ellipsize(layout, PANGO_ELLIPSIZE_NONE); } PangoRectangle ink{}, logical{}; pango_layout_get_pixel_extents(layout, &ink, &logical); int ty = y + (h - logical.height) / 2; pango_xft_render_layout(xftDraw, color, layout, x * PANGO_SCALE, ty * PANGO_SCALE); }; auto pangoWidth = [&](PangoLayout* layout, const std::string& text) -> int { pango_layout_set_width(layout, -1); pango_layout_set_text(layout, text.c_str(), static_cast(text.size())); PangoRectangle ink{}, logical{}; pango_layout_get_pixel_extents(layout, &ink, &logical); return logical.width; }; 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; if (callState == CallState::Incoming) { stateIcon = ringMuted ? kIconSoundOff : kIconInCall; stateBadge = ringMuted ? "RING SILENCED" : "INCOMING CALL"; stateCol = ringMuted ? &colYellow : &colGreen; stateAccentPx = theme.spec.accent; } else if (callState == CallState::Outgoing) { stateIcon = kIconOutCall; stateBadge = "DIALING..."; stateCol = &colYellow; stateAccentPx = theme.spec.accent; } else if (callState == CallState::Active) { stateIcon = kIconPhone; stateBadge = "IN CALL"; 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, 138); int elapsedSec = 0; if (callState == CallState::Ended) { elapsedSec = lastFinalDurationSec; } else if (callStartMs > 0 && callState != CallState::Idle) { elapsedSec = static_cast((now - callStartMs) / 1000); } if (callState != CallState::Idle || 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::Incoming) { drawPango(layoutSmall, &colLight, 8, 88, 26, "[Call] Answer [*] Mute [End] Reject", 224); } else if (callState == CallState::Ended) { drawPango(layoutSmall, &colMuted, 8, 88, 26, recordFileName.empty() ? "Call finished" : ("Saved: " + recordFileName), 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::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 : &colMuted; std::string valStr = isRec ? ("REC " + formatTimerSec(static_cast((now - recordStartMs) / 1000))) : "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(80, kWinWidth - vw - 44)); drawPango(layoutMain, isRec ? &colRed : &colMuted, 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::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 allDigits = true; for (char c : candidate) { if (!std::isdigit(static_cast(c))) { allDigits = false; break; } } if (allDigits) { ::closedir(d); callId = candidate; return callId; } } } ::closedir(d); } return callId; }; 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(); setSpeakerRoute(false); render(); if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { runAsyncArgv("sxmo_modemcall.sh", "pickup", cid.c_str()); } else { runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1"); } }; auto silenceRing = [&]() { if (callState != CallState::Incoming || ringMuted) { return; } ringMuted = true; std::string cid = resolveActiveModemCallId(); if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { runAsyncArgv("sxmo_modemcall.sh", "mute", cid.c_str()); } else { runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1"); } statusNotice = "Ringtone silenced"; statusNoticeUntilMs = nowMs() + 2500; render(); }; auto transitionToEnded = [&](const std::string& reason) { stopRecording(); if (micMuted) { setMicMuted(false); } 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_modemaudio.sh disable_call_audio_mode >/dev/null 2>&1"); 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(); render(); }; auto hangupCall = [&]() { std::string cid = resolveActiveModemCallId(); bool wasIncoming = (callState == CallState::Incoming); if (!cid.empty() && cid != "-" && cid != "sim" && cid != "test") { runAsyncArgv("sxmo_modemcall.sh", "hangup", cid.c_str()); } else { runAsyncCmd("sxmo_jobs.sh stop ringing >/dev/null 2>&1; " "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.empty() && cid != "-" && cid != "sim" && cid != "test") { 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 syncModemCalls = [&]() { if (callId == "sim" || callId == "test") { return; } FILE* fp = ::popen("mmcli -m any --voice-list-calls -a 2>/dev/null", "r"); if (!fp) { return; } char line[512]; std::string foundId; std::string foundDir; std::string foundState; while (std::fgets(line, sizeof(line), fp)) { std::string s(line); if (s.find("terminated") != std::string::npos || s.find("No calls") != std::string::npos) { 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 (!foundId.empty()) { if (callId.empty() || callId == "-") { callId = foundId; } if (callNumber.empty()) { 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) { callState = CallState::Active; callStartMs = nowMs(); ringMuted = false; writeActiveStateFiles(); 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 || (callState == CallState::Outgoing && nowMs() - callStartMs > 6000)) { if (!isCallActiveOrRingingFast() || ::access("/tmp/sxmo_active_call", F_OK) == 0) { // Verify sxmo_calls dir is empty before auto-ending std::string callsDir = getRuntimeFile("sxmo_calls"); bool anyFile = false; 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') { anyFile = true; break; } } ::closedir(d); } if (!anyFile) { 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") { 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 == "ENDED" || line.rfind("ENDED ", 0) == 0) { std::string reason = (line.size() > 6) ? trimStr(line.substr(6)) : "CALL ENDED"; if (callState != CallState::Idle) { transitionToEnded(reason); } else { hideWindow(false); } return; } // Parse INCOMING / OUTGOING / ACTIVE / OPEN std::istringstream iss(line); std::string verb, arg1, arg2; iss >> verb >> arg1 >> arg2; 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.clear(); iss >> arg2; } } if (verb == "INCOMING") { callId.clear(); callNumber.clear(); contactName.clear(); updateCallerDetails(arg1, arg2); callState = CallState::Incoming; callStartMs = nowMs(); ringMuted = false; dtmfMode = false; dtmfSent.clear(); selectedRow = 0; writeActiveStateFiles(); showWindow(); } else if (verb == "OUTGOING") { callId.clear(); callNumber.clear(); contactName.clear(); updateCallerDetails(arg1, arg2); callState = CallState::Outgoing; callStartMs = nowMs(); ringMuted = false; dtmfMode = false; dtmfSent.clear(); selectedRow = 0; writeActiveStateFiles(); showWindow(); } else if (verb == "ACTIVE") { bool wasActive = (callState == CallState::Active); updateCallerDetails(arg1, arg2); callState = CallState::Active; if (!wasActive) { callStartMs = nowMs(); } ringMuted = false; selectedRow = 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); } 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 if (sym == XK_Escape || sym == XF86XK_PowerOff || kc == 124) { 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::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::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::Incoming) ? 3 : 4; selectedRow = (selectedRow + maxRows - 1) % maxRows; render(); break; } case XK_Down: case XK_KP_Down: { int maxRows = (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) { adjustVolume(-5); selectedRow = 3; render(); } break; case XK_Right: case XK_KP_Right: case XF86XK_AudioRaiseVolume: if (callState != CallState::Incoming) { adjustVolume(+5); selectedRow = 3; render(); } break; case XK_Return: case XK_KP_Enter: if (nowMs() < startupIgnoreUntilMs) { break; } 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::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()); g_object_unref(layoutIcon); g_object_unref(layoutSmall); g_object_unref(layoutMain); g_object_unref(layoutNum); g_object_unref(pangoCtx); XftDrawDestroy(xftDraw); XFreeGC(dpy, gc); XFreePixmap(dpy, pix); XDestroyWindow(dpy, win); XCloseDisplay(dpy); 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 };