Files
bananarchy/src/games/gambatte_phone.cpp
T

2537 lines
84 KiB
C++
Raw Normal View History

// SPDX-License-Identifier: GPL-2.0-only
// Bananarchy Gambatte Game Boy / Game Boy Color Emulator for 240x320 T9 Keypad Phones
#include <X11/Xatom.h>
#include <X11/Xlib.h>
#include <X11/Xutil.h>
#include <X11/keysym.h>
#include <X11/XF86keysym.h>
#ifndef _EVDEVK
#define _EVDEVK(_v) (0x10081000 + (_v))
#endif
#include <algorithm>
#include <alsa/asoundlib.h>
#include <atomic>
#include <cctype>
#include <csignal>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <dirent.h>
#include <fcntl.h>
#include <fstream>
#include <poll.h>
#include <sstream>
#include <string>
#include <sys/stat.h>
#include <sys/timerfd.h>
#include <sys/wait.h>
#include <thread>
#include <unistd.h>
#include <vector>
#include "gambatte.h"
namespace {
std::string trimStr(const std::string& s) {
size_t b = 0;
while (b < s.size() && std::isspace(static_cast<unsigned char>(s[b]))) ++b;
size_t e = s.size();
while (e > b && std::isspace(static_cast<unsigned char>(s[e - 1]))) --e;
if (e >= b + 2 &&
((s[b] == '"' && s[e - 1] == '"') || (s[b] == '\'' && s[e - 1] == '\''))) {
return s.substr(b + 1, e - b - 2);
}
return s.substr(b, e - b);
}
int hexNibble(char c) {
if (c >= '0' && c <= '9') return c - '0';
if (c >= 'a' && c <= 'f') return 10 + (c - 'a');
if (c >= 'A' && c <= 'F') return 10 + (c - 'A');
return -1;
}
bool parseHexRgb(const std::string& raw, unsigned long* outRgb) {
std::string s = trimStr(raw);
if (s.rfind("0x", 0) == 0 || s.rfind("0X", 0) == 0) {
s = "#" + s.substr(2);
}
if (s.size() == 7 && s[0] == '#') {
unsigned long v = 0;
for (int i = 1; i < 7; ++i) {
int n = hexNibble(s[i]);
if (n < 0) return false;
v = (v << 4) | static_cast<unsigned long>(n);
}
*outRgb = v;
return true;
}
return false;
}
struct ThemeSpec {
unsigned long bgMain = 0x222222;
unsigned long bgHeader = 0x1c1c1c;
unsigned long bgFooter = 0x181818;
unsigned long selBg = 0x005577;
unsigned long border = 0x444444;
unsigned long fgMain = 0xdddddd;
unsigned long fgMuted = 0x999999;
unsigned long accent = 0xf4d03f;
unsigned long success = 0x2ecc71;
unsigned long info = 0x5dade2;
unsigned long danger = 0xe74c3c;
};
ThemeSpec loadThemeSpec(Display* dpy, int screen) {
ThemeSpec t;
auto applyContent = [&](const std::string& content) {
std::istringstream ss(content);
std::string line;
while (std::getline(ss, line)) {
std::string tr = trimStr(line);
if (tr.empty() || tr[0] == '!' || tr[0] == '#') continue;
size_t colon = tr.find(':');
if (colon == std::string::npos) continue;
std::string k = trimStr(tr.substr(0, colon));
std::string v = trimStr(tr.substr(colon + 1));
unsigned long rgb = 0;
if (!parseHexRgb(v, &rgb)) continue;
if (k == "theme.bgMain" || k == "*background") t.bgMain = rgb;
else if (k == "theme.bgHeader" || k == "dmenu.background") t.bgHeader = rgb;
else if (k == "theme.bgFooter") t.bgFooter = rgb;
else if (k == "theme.selBg" || k == "dmenu.selbackground") t.selBg = rgb;
else if (k == "theme.border" || k == "dwm.normbordercolor") t.border = rgb;
else if (k == "theme.fgMain" || k == "*foreground") t.fgMain = rgb;
else if (k == "theme.fgMuted") t.fgMuted = rgb;
else if (k == "theme.accent" || k == "*accentColor") t.accent = rgb;
else if (k == "theme.success") t.success = rgb;
else if (k == "theme.info") t.info = rgb;
else if (k == "theme.danger") t.danger = rgb;
}
};
if (dpy) {
Atom actualType = None;
int actualFormat = 0;
unsigned long nitems = 0, bytesAfter = 0;
unsigned char* prop = nullptr;
if (XGetWindowProperty(dpy, RootWindow(dpy, screen), XA_RESOURCE_MANAGER,
0L, 65536L, False, XA_STRING, &actualType,
&actualFormat, &nitems, &bytesAfter,
&prop) == Success && prop) {
if (actualType == XA_STRING && actualFormat == 8 && nitems > 0) {
applyContent(std::string(reinterpret_cast<char*>(prop), nitems));
}
XFree(prop);
}
}
const char* h = std::getenv("HOME");
std::string xres = std::string((h && h[0]) ? h : "/home/user") + "/.Xresources";
std::ifstream in(xres);
if (in.is_open()) {
std::ostringstream ss;
ss << in.rdbuf();
applyContent(ss.str());
}
return t;
}
constexpr int kWinX = 0;
constexpr int kWinY = 24;
constexpr int kWinW = 240;
constexpr int kWinH = 296;
constexpr int kGbW = 160;
constexpr int kGbH = 144;
volatile sig_atomic_t gRunning = 1;
volatile sig_atomic_t gReloadTheme = 0;
void onSignal(int sig) {
if (sig == SIGUSR1) {
gReloadTheme = 1;
} else {
gRunning = 0;
}
}
int64_t nowMs() {
struct timespec ts {};
clock_gettime(CLOCK_MONOTONIC, &ts);
return static_cast<int64_t>(ts.tv_sec) * 1000 + ts.tv_nsec / 1000000;
}
void ensureDir(const std::string& path) {
std::string cur;
for (size_t i = 0; i < path.size(); ++i) {
cur.push_back(path[i]);
if (path[i] == '/' && cur.size() > 1) {
::mkdir(cur.c_str(), 0755);
}
}
::mkdir(path.c_str(), 0755);
}
std::string getHomeDir() {
const char* h = std::getenv("HOME");
return (h && h[0]) ? h : "/home/user";
}
std::string getConfigPath() {
const char* xdg = std::getenv("XDG_CONFIG_HOME");
std::string base = (xdg && xdg[0]) ? xdg : (getHomeDir() + "/.config");
return base + "/sxmo/gambatte.cfg";
}
std::string getSaveDir() {
const char* xdg = std::getenv("XDG_DATA_HOME");
std::string base = (xdg && xdg[0]) ? xdg : (getHomeDir() + "/.local/share");
return base + "/sxmo/gambatte/saves";
}
std::string getStateDir() {
const char* xdg = std::getenv("XDG_DATA_HOME");
std::string base = (xdg && xdg[0]) ? xdg : (getHomeDir() + "/.local/share");
return base + "/sxmo/gambatte/states";
}
std::string stripExtAndDir(const std::string& fullPath) {
size_t sl = fullPath.rfind('/');
std::string name = (sl == std::string::npos) ? fullPath : fullPath.substr(sl + 1);
size_t dot = name.rfind('.');
if (dot != std::string::npos && dot > 0) {
name = name.substr(0, dot);
}
return name;
}
std::string getExtLower(const std::string& name) {
size_t dot = name.rfind('.');
if (dot == std::string::npos || dot + 1 >= name.size()) {
return "";
}
std::string ext = name.substr(dot + 1);
for (char& c : ext) {
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
return ext;
}
bool isGbRomExt(const std::string& name) {
std::string ext = getExtLower(name);
return ext == "gb" || ext == "gbc";
}
int querySoftkeysDown(Display* d) {
char km[32];
if (!XQueryKeymap(d, km)) {
return 0;
}
int mask = 0;
if (km[135 / 8] & (1 << (135 % 8))) mask |= 1;
if (km[166 / 8] & (1 << (166 % 8))) mask |= 2;
return mask;
}
void writeSoftkeySuppress(int64_t untilMs) {
int fd = ::open("/tmp/sxmo_softkey_suppress",
O_WRONLY | O_CREAT | O_TRUNC | O_CLOEXEC, 0644);
if (fd >= 0) {
char buf[32];
int len = std::snprintf(buf, sizeof(buf), "%lld\n",
static_cast<long long>(untilMs));
(void)::write(fd, buf, len);
::close(fd);
}
}
void toggleXDrawer() {
int fd = ::open("/tmp/dwm_plugin_xdrawer.fifo",
O_WRONLY | O_NONBLOCK | O_CLOEXEC);
if (fd >= 0) {
(void)::write(fd, "TOGGLE\n", 7);
::close(fd);
return;
}
pid_t pid = ::fork();
if (pid == 0) {
if (::fork() == 0) {
::setsid();
execlp("xdrawer", "xdrawer", static_cast<char*>(nullptr));
_exit(0);
}
_exit(0);
} else if (pid > 0) {
int st = 0;
(void)::waitpid(pid, &st, 0);
}
}
bool isPidAliveFile(const std::string& path) {
int fd = ::open(path.c_str(), O_RDONLY | O_CLOEXEC);
if (fd < 0) return false;
char buf[64];
ssize_t n = ::read(fd, buf, sizeof(buf) - 1);
::close(fd);
if (n <= 0) return false;
buf[n] = '\0';
int pid = std::atoi(buf);
return (pid > 0 && ::kill(pid, 0) == 0);
}
bool isExternalOverlayActive() {
if (::access("/tmp/bananarchy_screen_locked", F_OK) == 0 ||
::access("/tmp/dwm_plugin_dmenu.active", F_OK) == 0 ||
::access("/tmp/sxmo_call_ringing", F_OK) == 0 ||
::access("/tmp/sxmo_active_call", F_OK) == 0) {
return true;
}
static const char* kOverlayPids[] = {
"xlocker.pid",
"xdrawer.pid",
"xcallscreen.pid",
"xdialer.pid",
"xcalllog.pid",
"xcontacts.pid",
"xsms.pid",
"xfiles.pid",
"xcamera.pid",
"xthemes.pid",
"xmodem.pid",
"xnetworks.pid",
"xringtones.pid",
"xwallpapers.pid",
"xmusic.pid",
"xsip.pid",
"xemail.pid",
"xirc.pid",
"xtox.pid",
"xsmallweb.pid",
"xwebarchy.pid",
"xgps.pid",
"xpasscode.pid",
"xengmenu.pid",
};
char uidDir[64];
std::snprintf(uidDir, sizeof(uidDir), "/run/user/%u",
static_cast<unsigned>(::getuid()));
const char* envRdir = std::getenv("XDG_RUNTIME_DIR");
for (const char* pf : kOverlayPids) {
if (envRdir && envRdir[0] &&
isPidAliveFile(std::string(envRdir) + "/" + pf)) {
return true;
}
if (isPidAliveFile(std::string(uidDir) + "/" + pf)) {
return true;
}
if (isPidAliveFile(std::string("/tmp/") + pf)) {
return true;
}
}
return false;
}
// 5x7 crisp bitmap font
void glyphRows(char ch, uint8_t out[7]) {
std::memset(out, 0, 7);
unsigned char uc = static_cast<unsigned char>(ch);
if (uc >= 'a' && uc <= 'z') {
uc = static_cast<unsigned char>(uc - 'a' + 'A');
}
switch (uc) {
case '0': { uint8_t r[7] = {0x0E,0x11,0x13,0x15,0x19,0x11,0x0E}; std::memcpy(out,r,7); break; }
case '1': { uint8_t r[7] = {0x04,0x0C,0x04,0x04,0x04,0x04,0x0E}; std::memcpy(out,r,7); break; }
case '2': { uint8_t r[7] = {0x0E,0x11,0x01,0x02,0x04,0x08,0x1F}; std::memcpy(out,r,7); break; }
case '3': { uint8_t r[7] = {0x1F,0x02,0x04,0x02,0x01,0x11,0x0E}; std::memcpy(out,r,7); break; }
case '4': { uint8_t r[7] = {0x02,0x06,0x0A,0x12,0x1F,0x02,0x02}; std::memcpy(out,r,7); break; }
case '5': { uint8_t r[7] = {0x1F,0x10,0x1E,0x01,0x01,0x11,0x0E}; std::memcpy(out,r,7); break; }
case '6': { uint8_t r[7] = {0x06,0x08,0x10,0x1E,0x11,0x11,0x0E}; std::memcpy(out,r,7); break; }
case '7': { uint8_t r[7] = {0x1F,0x01,0x02,0x04,0x08,0x08,0x08}; std::memcpy(out,r,7); break; }
case '8': { uint8_t r[7] = {0x0E,0x11,0x11,0x0E,0x11,0x11,0x0E}; std::memcpy(out,r,7); break; }
case '9': { uint8_t r[7] = {0x0E,0x11,0x11,0x0F,0x01,0x02,0x0C}; std::memcpy(out,r,7); break; }
case 'A': { uint8_t r[7] = {0x0E,0x11,0x11,0x1F,0x11,0x11,0x11}; std::memcpy(out,r,7); break; }
case 'B': { uint8_t r[7] = {0x1E,0x11,0x11,0x1E,0x11,0x11,0x1E}; std::memcpy(out,r,7); break; }
case 'C': { uint8_t r[7] = {0x0E,0x11,0x10,0x10,0x10,0x11,0x0E}; std::memcpy(out,r,7); break; }
case 'D': { uint8_t r[7] = {0x1C,0x12,0x11,0x11,0x11,0x12,0x1C}; std::memcpy(out,r,7); break; }
case 'E': { uint8_t r[7] = {0x1F,0x10,0x10,0x1E,0x10,0x10,0x1F}; std::memcpy(out,r,7); break; }
case 'F': { uint8_t r[7] = {0x1F,0x10,0x10,0x1E,0x10,0x10,0x10}; std::memcpy(out,r,7); break; }
case 'G': { uint8_t r[7] = {0x0E,0x11,0x10,0x17,0x11,0x11,0x0F}; std::memcpy(out,r,7); break; }
case 'H': { uint8_t r[7] = {0x11,0x11,0x11,0x1F,0x11,0x11,0x11}; std::memcpy(out,r,7); break; }
case 'I': { uint8_t r[7] = {0x0E,0x04,0x04,0x04,0x04,0x04,0x0E}; std::memcpy(out,r,7); break; }
case 'J': { uint8_t r[7] = {0x07,0x02,0x02,0x02,0x02,0x12,0x0C}; std::memcpy(out,r,7); break; }
case 'K': { uint8_t r[7] = {0x11,0x12,0x14,0x18,0x14,0x12,0x11}; std::memcpy(out,r,7); break; }
case 'L': { uint8_t r[7] = {0x10,0x10,0x10,0x10,0x10,0x10,0x1F}; std::memcpy(out,r,7); break; }
case 'M': { uint8_t r[7] = {0x11,0x1B,0x15,0x15,0x11,0x11,0x11}; std::memcpy(out,r,7); break; }
case 'N': { uint8_t r[7] = {0x11,0x11,0x19,0x15,0x13,0x11,0x11}; std::memcpy(out,r,7); break; }
case 'O': { uint8_t r[7] = {0x0E,0x11,0x11,0x11,0x11,0x11,0x0E}; std::memcpy(out,r,7); break; }
case 'P': { uint8_t r[7] = {0x1E,0x11,0x11,0x1E,0x10,0x10,0x10}; std::memcpy(out,r,7); break; }
case 'Q': { uint8_t r[7] = {0x0E,0x11,0x11,0x11,0x15,0x12,0x0D}; std::memcpy(out,r,7); break; }
case 'R': { uint8_t r[7] = {0x1E,0x11,0x11,0x1E,0x14,0x12,0x11}; std::memcpy(out,r,7); break; }
case 'S': { uint8_t r[7] = {0x0F,0x10,0x10,0x0E,0x01,0x01,0x1E}; std::memcpy(out,r,7); break; }
case 'T': { uint8_t r[7] = {0x1F,0x04,0x04,0x04,0x04,0x04,0x04}; std::memcpy(out,r,7); break; }
case 'U': { uint8_t r[7] = {0x11,0x11,0x11,0x11,0x11,0x11,0x0E}; std::memcpy(out,r,7); break; }
case 'V': { uint8_t r[7] = {0x11,0x11,0x11,0x11,0x11,0x0A,0x04}; std::memcpy(out,r,7); break; }
case 'W': { uint8_t r[7] = {0x11,0x11,0x11,0x15,0x15,0x1B,0x11}; std::memcpy(out,r,7); break; }
case 'X': { uint8_t r[7] = {0x11,0x11,0x0A,0x04,0x0A,0x11,0x11}; std::memcpy(out,r,7); break; }
case 'Y': { uint8_t r[7] = {0x11,0x11,0x0A,0x04,0x04,0x04,0x04}; std::memcpy(out,r,7); break; }
case 'Z': { uint8_t r[7] = {0x1F,0x01,0x02,0x04,0x08,0x10,0x1F}; std::memcpy(out,r,7); break; }
case ':': { uint8_t r[7] = {0x00,0x0C,0x0C,0x00,0x0C,0x0C,0x00}; std::memcpy(out,r,7); break; }
case '-': { uint8_t r[7] = {0x00,0x00,0x00,0x1F,0x00,0x00,0x00}; std::memcpy(out,r,7); break; }
case '+': { uint8_t r[7] = {0x00,0x04,0x04,0x1F,0x04,0x04,0x00}; std::memcpy(out,r,7); break; }
case '/': { uint8_t r[7] = {0x01,0x02,0x02,0x04,0x08,0x08,0x10}; std::memcpy(out,r,7); break; }
case '.': { uint8_t r[7] = {0x00,0x00,0x00,0x00,0x00,0x0C,0x0C}; std::memcpy(out,r,7); break; }
case ',': { uint8_t r[7] = {0x00,0x00,0x00,0x00,0x06,0x04,0x08}; std::memcpy(out,r,7); break; }
case '!': { uint8_t r[7] = {0x04,0x04,0x04,0x04,0x04,0x00,0x04}; std::memcpy(out,r,7); break; }
case '?': { uint8_t r[7] = {0x0E,0x11,0x01,0x02,0x04,0x00,0x04}; std::memcpy(out,r,7); break; }
case '*': { uint8_t r[7] = {0x00,0x15,0x0E,0x1F,0x0E,0x15,0x00}; std::memcpy(out,r,7); break; }
case '#': { uint8_t r[7] = {0x0A,0x1F,0x0A,0x0A,0x1F,0x0A,0x00}; std::memcpy(out,r,7); break; }
case '(':
case '[': { uint8_t r[7] = {0x06,0x08,0x08,0x08,0x08,0x08,0x06}; std::memcpy(out,r,7); break; }
case ')':
case ']': { uint8_t r[7] = {0x0C,0x02,0x02,0x02,0x02,0x02,0x0C}; std::memcpy(out,r,7); break; }
case '<': { uint8_t r[7] = {0x02,0x04,0x08,0x10,0x08,0x04,0x02}; std::memcpy(out,r,7); break; }
case '>': { uint8_t r[7] = {0x08,0x04,0x02,0x01,0x02,0x04,0x08}; std::memcpy(out,r,7); break; }
case '_': { uint8_t r[7] = {0x00,0x00,0x00,0x00,0x00,0x00,0x1F}; std::memcpy(out,r,7); break; }
default: break;
}
}
void drawText(Display* dpy, Pixmap pix, GC gc, int x, int y,
const char* text, int scale, unsigned long color,
int maxChars = 999) {
XRectangle rects[512];
int nrects = 0;
int cx = x;
int count = 0;
for (const char* p = text; *p && count < maxChars; ++p, ++count) {
uint8_t rows[7];
glyphRows(*p, rows);
for (int r = 0; r < 7; ++r) {
uint8_t bits = rows[r];
if (!bits) continue;
int c = 0;
while (c < 5) {
if (bits & (1 << (4 - c))) {
int start = c;
while (c < 5 && (bits & (1 << (4 - c)))) ++c;
if (nrects < static_cast<int>(sizeof(rects) / sizeof(rects[0]))) {
rects[nrects].x = static_cast<short>(cx + start * scale);
rects[nrects].y = static_cast<short>(y + r * scale);
rects[nrects].width =
static_cast<unsigned short>((c - start) * scale);
rects[nrects].height = static_cast<unsigned short>(scale);
++nrects;
}
} else {
++c;
}
}
}
cx += 6 * scale;
}
if (nrects > 0) {
XSetForeground(dpy, gc, color);
XFillRectangles(dpy, pix, gc, rects, nrects);
}
}
int textPixelWidth(const char* text, int scale) {
int len = static_cast<int>(std::strlen(text));
if (len <= 0) return 0;
return len * 6 * scale - scale;
}
void drawCenteredText(Display* dpy, Pixmap pix, GC gc, int y,
const char* text, int scale, unsigned long color) {
int w = textPixelWidth(text, scale);
int x = (kWinW - w) / 2;
drawText(dpy, pix, gc, x, y, text, scale, color);
}
// Configurable Key Action IDs
enum KeyAction {
ACT_B = 0,
ACT_TURBO_B,
ACT_A,
ACT_TURBO_A,
ACT_UP,
ACT_DOWN,
ACT_LEFT,
ACT_RIGHT,
ACT_START,
ACT_SELECT,
ACT_PALETTE,
ACT_FAST_FWD,
ACT_COUNT
};
const char* kActionNames[ACT_COUNT] = {
"B Button",
"Turbo B",
"A Button",
"Turbo A",
"D-Pad Up",
"D-Pad Down",
"D-Pad Left",
"D-Pad Right",
"Start",
"Select",
"Palette (*)",
"Fast Fwd"
};
const char* kActionCfgKeys[ACT_COUNT] = {
"key_b",
"key_turbo_b",
"key_a",
"key_turbo_a",
"key_up",
"key_down",
"key_left",
"key_right",
"key_start",
"key_select",
"key_palette",
"key_fast_fwd"
};
// Canonical token for any X11 key event on the T9 keypad
std::string keyEventToToken(KeySym sym, unsigned int keycode) {
if (keycode == 63 || keycode == 530 || sym == XK_asterisk ||
sym == XK_KP_Multiply || static_cast<uint32_t>(sym) == 0x1008ffaa) {
return "*";
}
if (keycode == 106 || keycode == 531 || sym == XK_numbersign ||
sym == XK_KP_Divide || static_cast<uint32_t>(sym) == 0x1008ffab) {
return "#";
}
if (sym >= XK_0 && sym <= XK_9) {
return std::string(1, static_cast<char>('0' + (sym - XK_0)));
}
if (sym >= XK_KP_0 && sym <= XK_KP_9) {
return std::string(1, static_cast<char>('0' + (sym - XK_KP_0)));
}
if (keycode >= 10 && keycode <= 18) {
return std::string(1, static_cast<char>('1' + (keycode - 10)));
}
if (keycode == 19) {
return "0";
}
switch (sym) {
case XK_Up:
case XK_KP_Up:
return "Up";
case XK_Down:
case XK_KP_Down:
return "Down";
case XK_Left:
case XK_KP_Left:
return "Left";
case XK_Right:
case XK_KP_Right:
return "Right";
case XK_Return:
case XK_KP_Enter:
return "OK";
case XF86XK_Phone:
case XF86XK_PickupPhone:
return "Call";
default:
break;
}
if (keycode == 177) {
return "Call";
}
const char* ks = XKeysymToString(sym);
if (ks && ks[0]) {
return ks;
}
return "";
}
struct EmulatorConfig {
std::string bindings[ACT_COUNT];
int paletteIdx = 0;
int scaleMode = 0; // 0 = Fit 240x216, 1 = 1:1 160x144, 2 = Stretch 240x244, 3 = Full 240x296
bool audioEnabled = true;
int stateSlot = 0;
std::string lastDir;
void resetControlsToDefault() {
// Requested defaults:
// B is 8, Turbo B is 5, A is 9, Turbo A is 6,
// D-pad for directions, 2 for start, 3 for select, * for palette selection
bindings[ACT_B] = "8";
bindings[ACT_TURBO_B] = "5";
bindings[ACT_A] = "9";
bindings[ACT_TURBO_A] = "6";
bindings[ACT_UP] = "Up";
bindings[ACT_DOWN] = "Down";
bindings[ACT_LEFT] = "Left";
bindings[ACT_RIGHT] = "Right";
bindings[ACT_START] = "2";
bindings[ACT_SELECT] = "3";
bindings[ACT_PALETTE] = "*";
bindings[ACT_FAST_FWD] = "0";
}
EmulatorConfig() {
resetControlsToDefault();
lastDir = getHomeDir();
}
void load() {
std::ifstream in(getConfigPath());
if (!in.is_open()) {
return;
}
std::string line;
while (std::getline(in, line)) {
if (line.empty() || line[0] == '#') continue;
size_t eq = line.find('=');
if (eq == std::string::npos) continue;
std::string k = line.substr(0, eq);
std::string v = line.substr(eq + 1);
if (k == "palette") {
paletteIdx = std::clamp(std::atoi(v.c_str()), 0, 9);
} else if (k == "scale_mode") {
scaleMode = std::clamp(std::atoi(v.c_str()), 0, 3);
} else if (k == "audio") {
audioEnabled = (std::atoi(v.c_str()) != 0);
} else if (k == "state_slot") {
stateSlot = std::clamp(std::atoi(v.c_str()), 0, 9);
} else if (k == "last_dir" && !v.empty()) {
lastDir = v;
} else {
for (int i = 0; i < ACT_COUNT; ++i) {
if (k == kActionCfgKeys[i] && !v.empty()) {
bindings[i] = v;
}
}
}
}
}
void save() const {
std::string path = getConfigPath();
size_t sl = path.rfind('/');
if (sl != std::string::npos) {
ensureDir(path.substr(0, sl));
}
std::ofstream out(path, std::ios::trunc);
if (!out.is_open()) return;
out << "palette=" << paletteIdx << "\n";
out << "scale_mode=" << scaleMode << "\n";
out << "audio=" << (audioEnabled ? 1 : 0) << "\n";
out << "state_slot=" << stateSlot << "\n";
out << "last_dir=" << lastDir << "\n";
for (int i = 0; i < ACT_COUNT; ++i) {
out << kActionCfgKeys[i] << "=" << bindings[i] << "\n";
}
}
};
struct ColorPalette {
const char* name;
uint32_t bg[4];
uint32_t sp1[4];
uint32_t sp2[4];
};
constexpr int kNumPalettes = 10;
const ColorPalette kPalettes[kNumPalettes] = {
{
"DMG Classic",
{0x9BBC0F, 0x8BAC0F, 0x306230, 0x0F380F},
{0x9BBC0F, 0x8BAC0F, 0x306230, 0x0F380F},
{0x9BBC0F, 0x8BAC0F, 0x306230, 0x0F380F},
},
{
"Bananarchy Gold",
{0xFFF3B0, 0xF5C518, 0x9E6B00, 0x1A1812},
{0xFFFFFF, 0xFF9F1C, 0xC84B31, 0x1A1812},
{0xFFF3B0, 0x5BC0BE, 0x1C7293, 0x1A1812},
},
{
"GB Pocket Gray",
{0xE0E0D8, 0xA0A098, 0x585850, 0x181814},
{0xE0E0D8, 0xA0A098, 0x585850, 0x181814},
{0xE0E0D8, 0xA0A098, 0x585850, 0x181814},
},
{
"GB Light Teal",
{0xC8FAF0, 0x5CD6C8, 0x1E8278, 0x062E2A},
{0xC8FAF0, 0x5CD6C8, 0x1E8278, 0x062E2A},
{0xC8FAF0, 0x5CD6C8, 0x1E8278, 0x062E2A},
},
{
"GBC Blue/Red",
{0xFFFFFF, 0x7BFF31, 0x0063C5, 0x000000},
{0xFFFFFF, 0xFF8484, 0x943A3A, 0x000000},
{0xFFFFFF, 0xFFB542, 0x845200, 0x000000},
},
{
"Super Game Boy",
{0xF7E7C6, 0xD68E49, 0xA63725, 0x331E50},
{0xF7E7C6, 0xE86A33, 0x8B1E3F, 0x1B0E24},
{0xF7E7C6, 0x68B0AB, 0x2E5266, 0x1B0E24},
},
{
"Amber CRT",
{0xFFD866, 0xF29E02, 0x994E00, 0x1F0D00},
{0xFFD866, 0xF29E02, 0x994E00, 0x1F0D00},
{0xFFD866, 0xF29E02, 0x994E00, 0x1F0D00},
},
{
"Mintberry",
{0xE8F8E8, 0x70D6B8, 0x4A6FA5, 0x1D1E2C},
{0xFFE6F2, 0xFF70A6, 0xA32658, 0x1D1E2C},
{0xE8F8E8, 0xFFD166, 0x8A5A00, 0x1D1E2C},
},
{
"Virtual Boy",
{0xFF3838, 0xB80000, 0x600000, 0x0A0000},
{0xFF6060, 0xD00000, 0x700000, 0x0A0000},
{0xFF3838, 0xB80000, 0x600000, 0x0A0000},
},
{
"Inverted Dark",
{0x14181D, 0x465466, 0x98A8B8, 0xF0F6FC},
{0x14181D, 0x52796F, 0x84A98C, 0xCAD2C5},
{0x14181D, 0x7F5539, 0xD4A373, 0xFAEDCD},
},
};
class PhoneInputGetter : public gambatte::InputGetter {
public:
unsigned state = 0;
unsigned operator()() override {
return state;
}
};
// Direct ALSA PCM audio engine (48000 Hz stereo S16_LE via libasound)
// with Gambatte's 64-tap Convoluted Cosine + DC-blocking High-Pass resampler,
// low-latency hardware ringbuffer (< 25 ms), and live speaker_vol scaling.
class PcmAudioOut {
public:
void start() {
refreshVolume(true);
if (threadRunning_.load(std::memory_order_relaxed)) return;
stop();
resetFilterState();
const char* xdgRun = std::getenv("XDG_RUNTIME_DIR");
if (!xdgRun || !xdgRun[0]) {
char runBuf[64];
std::snprintf(runBuf, sizeof(runBuf), "/run/user/%u",
static_cast<unsigned>(::getuid()));
::setenv("XDG_RUNTIME_DIR", runBuf, 0);
}
std::memset(ring_, 0, sizeof(ring_));
readPos_.store(0, std::memory_order_relaxed);
// Seed 512 frames (2 periods = 10.67 ms) of silence so the feeder thread
// always stays >= 1 period ahead of DMA period boundaries.
writePos_.store(512, std::memory_order_release);
threadRunning_.store(true, std::memory_order_release);
worker_ = std::thread(&PcmAudioOut::audioThreadMain, this);
}
void stop() {
if (threadRunning_.exchange(false, std::memory_order_acq_rel)) {
if (worker_.joinable()) {
worker_.join();
}
} else if (worker_.joinable()) {
worker_.join();
}
}
bool isOpen() const {
return threadRunning_.load(std::memory_order_relaxed);
}
int speakerVolPct() const {
return speakerPct_;
}
bool isSystemMuted() const {
return sysMuted_;
}
void refreshVolumeIfNeeded(int64_t tNow) {
if (tNow - lastVolCheckMs_ < 500) return;
lastVolCheckMs_ = tNow;
const char* xdg = std::getenv("XDG_CONFIG_HOME");
std::string path =
((xdg && xdg[0]) ? (std::string(xdg) + "/sxmo")
: (getHomeDir() + "/.config/sxmo")) +
"/speaker_vol";
struct stat st {};
if (::stat(path.c_str(), &st) == 0 &&
st.st_mtim.tv_sec != lastVolMtime_) {
lastVolMtime_ = st.st_mtim.tv_sec;
refreshVolume(false);
}
}
void refreshVolume(bool syncHw) {
lastVolCheckMs_ = nowMs();
const char* xdg = std::getenv("XDG_CONFIG_HOME");
std::string cfgDir =
(xdg && xdg[0]) ? (std::string(xdg) + "/sxmo")
: (getHomeDir() + "/.config/sxmo");
int pct = -1;
{
std::string volPath = cfgDir + "/speaker_vol";
struct stat st {};
if (::stat(volPath.c_str(), &st) == 0) {
lastVolMtime_ = st.st_mtim.tv_sec;
}
std::ifstream ifs(volPath);
if (ifs) {
ifs >> pct;
}
}
bool spkSwitch = true;
long rx3Cur = 84;
snd_ctl_t* ctl = nullptr;
if (snd_ctl_open(&ctl, "hw:0", 0) == 0 && ctl) {
spkSwitch = readCtlBool(ctl, "SPK DAC Switch", true);
rx3Cur = readCtlInt(ctl, "RX3 Digital Volume", 84);
if (pct < 0 || pct > 100) {
if (rx3Cur <= 0) {
pct = 0;
} else if (rx3Cur >= 84) {
pct = 100;
} else {
pct = std::clamp(
static_cast<int>(((rx3Cur - 60) * 100) / 32), 5, 100);
}
}
pct = std::clamp((pct / 5) * 5, 0, 100);
// Map 1..100% to RX3 Digital Volume 56..84 (84 = 0.0 dB unity gain on
// WCD9302) so the hardware codec never applies +8 dB digital overdrive.
long targetRx3 =
(pct <= 0) ? 0 : (56 + ((pct * 28 + 50) / 100));
if (spkSwitch && ((syncHw && rx3Cur != targetRx3) || rx3Cur > 84)) {
writeCtlInt(ctl, "RX3 Digital Volume", targetRx3);
}
snd_ctl_close(ctl);
} else {
if (pct < 0 || pct > 100) pct = 75;
pct = std::clamp((pct / 5) * 5, 0, 100);
}
speakerPct_ = pct;
sysMuted_ = !spkSwitch || (pct <= 0);
if (sysMuted_) {
volScale_ = 0;
} else {
volScale_ = std::max(1, (pct * 20 + 50) / 100);
}
}
void adjustSpeakerVol(int deltaPct) {
refreshVolume(false);
int nextPct = std::clamp(((speakerPct_ + deltaPct) / 5) * 5, 0, 100);
const char* xdg = std::getenv("XDG_CONFIG_HOME");
std::string cfgDir =
(xdg && xdg[0]) ? (std::string(xdg) + "/sxmo")
: (getHomeDir() + "/.config/sxmo");
ensureDir(cfgDir);
{
std::ofstream ofs(cfgDir + "/speaker_vol", std::ios::trunc);
if (ofs) ofs << nextPct << "\n";
}
char cmd[128];
std::snprintf(cmd, sizeof(cmd),
"sxmo_audio.sh vol set %d >/dev/null 2>&1 &", nextPct);
(void)std::system(cmd);
refreshVolume(false);
}
void resetFilterState() {
accumSamples_ = 0;
currentL_ = 0;
currentR_ = 0;
nextL_ = 0;
nextR_ = 0;
prevSmplL_ = 0;
prevSmplR_ = 0;
highpassL_ = 0;
highpassR_ = 0;
prevOutL_ = 0;
prevOutR_ = 0;
lpf1L_ = 0;
lpf1R_ = 0;
lpf2L_ = 0;
lpf2R_ = 0;
resamplePos_ = 0;
}
// Convolve 2097152 Hz Gambatte stereo samples to 65536 Hz (64-tap cosine + highpass),
// then linearly interpolate 65536 Hz -> 48000 Hz and push to lock-free ringbuffer.
void writeGbSamples(const gambatte::uint_least32_t* src, unsigned count) {
if (!threadRunning_.load(std::memory_order_relaxed) || count == 0) return;
static const int16_t kCcKernel[32] = {
0x0800, 0x07fb, 0x07eb, 0x07d3, 0x07b3, 0x0787, 0x0753, 0x0717,
0x06d3, 0x068b, 0x063b, 0x05e2, 0x0586, 0x052a, 0x04c6, 0x0466,
0x0402, 0x0399, 0x0339, 0x02d5, 0x0279, 0x021d, 0x01c4, 0x0174,
0x012c, 0x00e8, 0x00ac, 0x0078, 0x004c, 0x002c, 0x0014, 0x0004
};
static const int16_t kCcKernelR[32] = {
0x0000, 0x0004, 0x0014, 0x002c, 0x004c, 0x0078, 0x00ac, 0x00e8,
0x012c, 0x0174, 0x01c4, 0x021d, 0x0279, 0x02d5, 0x0339, 0x0399,
0x0402, 0x0466, 0x04c6, 0x052a, 0x0586, 0x05e2, 0x063b, 0x068b,
0x06d3, 0x0717, 0x0753, 0x0787, 0x07b3, 0x07d3, 0x07eb, 0x07fb
};
int16_t outBuf[1024 * 2];
size_t outFrames = 0;
const int32_t vscale = volScale_.load(std::memory_order_relaxed);
auto flushOutBuf = [&]() {
if (outFrames == 0) return;
uint32_t rp = readPos_.load(std::memory_order_acquire);
uint32_t wp = writePos_.load(std::memory_order_relaxed);
uint32_t queued = wp - rp;
// Cap software ringbuffer backlog at 1536 frames (6 periods) so normal
// 1x sub-slices never drop a single sample, while fast-forward or clock
// drift is cleanly bounded.
size_t startIdx = 0;
if (queued + outFrames > 1536) {
size_t maxPush = (queued < 1536) ? static_cast<size_t>(1536 - queued) : 0;
if (maxPush == 0) {
outFrames = 0;
return;
}
if (outFrames > maxPush) {
startIdx = outFrames - maxPush;
}
}
for (size_t i = startIdx; i < outFrames; ++i) {
uint32_t dst = wp & kRingMask;
ring_[dst * 2] = outBuf[i * 2];
ring_[dst * 2 + 1] = outBuf[i * 2 + 1];
++wp;
}
writePos_.store(wp, std::memory_order_release);
outFrames = 0;
};
for (unsigned i = 0; i < count; ++i) {
uint32_t s = src[i];
int32_t inL = static_cast<int16_t>(s & 0xFFFFu);
int32_t inR = static_cast<int16_t>((s >> 16) & 0xFFFFu);
currentL_ += inL * kCcKernel[accumSamples_];
currentR_ += inR * kCcKernel[accumSamples_];
nextL_ += inL * kCcKernelR[accumSamples_];
nextR_ += inR * kCcKernelR[accumSamples_];
if (++accumSamples_ == 32) {
accumSamples_ = 0;
// Keep intermediate high-pass state in 32-bit signed integers so
// square-wave edges (+-61440 delta) never wrap around 16-bit int16_t!
int32_t sampleL = currentL_ >> 16;
int32_t tmpL = highpassL_ + ((sampleL - prevSmplL_) << 8);
highpassL_ = tmpL - (tmpL >> 7);
prevSmplL_ = sampleL;
int32_t outL = (highpassL_ + 128) >> 8;
int32_t sampleR = currentR_ >> 16;
int32_t tmpR = highpassR_ + ((sampleR - prevSmplR_) << 8);
highpassR_ = tmpR - (tmpR >> 7);
prevSmplR_ = sampleR;
int32_t outR = (highpassR_ + 128) >> 8;
currentL_ = nextL_;
currentR_ = nextR_;
nextL_ = 0;
nextR_ = 0;
// 48000 / 65536 = 375 / 512 in lowest terms (avoids 32-bit overflow).
while (resamplePos_ < 375) {
int32_t interpL =
prevOutL_ + ((outL - prevOutL_) * resamplePos_) / 375;
int32_t interpR =
prevOutR_ + ((outR - prevOutR_) * resamplePos_) / 375;
// 2-stage 1-pole low-pass filter (alpha = 3/8, fc ~ 2.3 kHz -3dB)
// modeling the Game Boy's analog output stage to roll off harsh
// 3.5-16 kHz square-wave harmonics on the phone micro-speaker.
lpf1L_ += ((interpL - lpf1L_) * 3) >> 3;
lpf2L_ += ((lpf1L_ - lpf2L_) * 3) >> 3;
lpf1R_ += ((interpR - lpf1R_) * 3) >> 3;
lpf2R_ += ((lpf1R_ - lpf2R_) * 3) >> 3;
int32_t scaledL = (lpf2L_ * vscale) >> 8;
int32_t scaledR = (lpf2R_ * vscale) >> 8;
outBuf[outFrames * 2] =
static_cast<int16_t>(std::clamp<int32_t>(scaledL, -32768, 32767));
outBuf[outFrames * 2 + 1] =
static_cast<int16_t>(std::clamp<int32_t>(scaledR, -32768, 32767));
++outFrames;
if (outFrames == 256) {
flushOutBuf();
}
resamplePos_ += 512;
}
resamplePos_ -= 375;
prevOutL_ = outL;
prevOutR_ = outR;
}
}
flushOutBuf();
}
~PcmAudioOut() {
stop();
}
private:
void audioThreadMain() {
snd_pcm_t* h = nullptr;
const char* devs[] = {"hw:0,0", "default", "plughw:0,0"};
for (const char* dev : devs) {
if (snd_pcm_open(&h, dev, SND_PCM_STREAM_PLAYBACK, 0) >= 0) {
if (configureLowLatency(h)) {
break;
}
snd_pcm_close(h);
h = nullptr;
}
}
if (!h) {
for (const char* dev : devs) {
if (snd_pcm_open(&h, dev, SND_PCM_STREAM_PLAYBACK, 0) >= 0) {
if (snd_pcm_set_params(h, SND_PCM_FORMAT_S16_LE,
SND_PCM_ACCESS_RW_INTERLEAVED, 2, 48000, 1,
25000) >= 0) {
break;
}
snd_pcm_close(h);
h = nullptr;
}
}
}
if (!h) {
threadRunning_.store(false, std::memory_order_release);
return;
}
snd_pcm_prepare(h);
int16_t chunk[256 * 2];
int16_t lastL = 0;
int16_t lastR = 0;
while (threadRunning_.load(std::memory_order_acquire)) {
uint32_t rp = readPos_.load(std::memory_order_relaxed);
uint32_t wp = writePos_.load(std::memory_order_acquire);
uint32_t avail = wp - rp;
if (avail >= 256) {
for (uint32_t i = 0; i < 256; ++i) {
uint32_t src = (rp + i) & kRingMask;
lastL = ring_[src * 2];
lastR = ring_[src * 2 + 1];
chunk[i * 2] = lastL;
chunk[i * 2 + 1] = lastR;
}
readPos_.store(rp + 256, std::memory_order_release);
} else {
snd_pcm_state_t st = snd_pcm_state(h);
snd_pcm_sframes_t pcmAvail = snd_pcm_avail_update(h);
if (st == SND_PCM_STATE_XRUN || pcmAvail < 0) {
snd_pcm_prepare(h);
st = snd_pcm_state(h);
pcmAvail = snd_pcm_avail_update(h);
}
snd_pcm_sframes_t hwQueued =
(pcmAvail >= 0 && pcmAvail <= 1024) ? (1024 - pcmAvail) : 0;
if (st != SND_PCM_STATE_RUNNING || hwQueued >= 512) {
// ALSA still has >= 512 frames (>= 2 periods = 10.67 ms) in DMA;
// wait briefly for the emulator to push the next 4.18 ms slice.
::usleep(500);
continue;
}
// Hardware DMA is down to its final 256-frame period and ringbuffer has
// < 256 frames: keep the partial frames in ring_ so they accumulate to
// >= 256 on the next slice, and write one 256-frame smooth decay period
// to keep appl_ptr period-aligned and prevent an XRUN.
for (uint32_t i = 0; i < 256; ++i) {
lastL -= lastL >> 4;
lastR -= lastR >> 4;
chunk[i * 2] = lastL;
chunk[i * 2 + 1] = lastR;
}
}
snd_pcm_sframes_t written = 0;
while (written < 256 && threadRunning_.load(std::memory_order_relaxed)) {
snd_pcm_sframes_t w =
snd_pcm_writei(h, chunk + written * 2, 256 - written);
if (w > 0) {
written += w;
} else if (w == -EAGAIN) {
snd_pcm_wait(h, 4);
} else if (w < 0) {
if (snd_pcm_recover(h, static_cast<int>(w), 1) < 0) {
snd_pcm_prepare(h);
}
break;
}
}
}
snd_pcm_drop(h);
snd_pcm_close(h);
}
static bool configureLowLatency(snd_pcm_t* h) {
snd_pcm_hw_params_t* hw = nullptr;
snd_pcm_hw_params_alloca(&hw);
if (snd_pcm_hw_params_any(h, hw) < 0) return false;
if (snd_pcm_hw_params_set_access(h, hw, SND_PCM_ACCESS_RW_INTERLEAVED) < 0) {
return false;
}
if (snd_pcm_hw_params_set_format(h, hw, SND_PCM_FORMAT_S16_LE) < 0) {
return false;
}
if (snd_pcm_hw_params_set_channels(h, hw, 2) < 0) return false;
unsigned int rate = 48000;
if (snd_pcm_hw_params_set_rate_near(h, hw, &rate, nullptr) < 0 ||
rate != 48000) {
return false;
}
snd_pcm_uframes_t periodSize = 256;
snd_pcm_hw_params_set_period_size_near(h, hw, &periodSize, nullptr);
snd_pcm_uframes_t bufferSize = 1024; // 4 periods of 256 frames (21.3 ms)
snd_pcm_hw_params_set_buffer_size_near(h, hw, &bufferSize);
if (snd_pcm_hw_params(h, hw) < 0) return false;
snd_pcm_sw_params_t* sw = nullptr;
snd_pcm_sw_params_alloca(&sw);
if (snd_pcm_sw_params_current(h, sw) == 0) {
snd_pcm_sw_params_set_start_threshold(h, sw, 512);
snd_pcm_sw_params_set_avail_min(h, sw, 256);
snd_pcm_sw_params(h, sw);
}
return true;
}
static long readCtlInt(snd_ctl_t* ctl, const char* name, long 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);
}
static void writeCtlInt(snd_ctl_t* ctl, const char* name, long v) {
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);
(void)snd_ctl_elem_write(ctl, val);
}
static bool readCtlBool(snd_ctl_t* ctl, const char* name, bool 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;
}
static void writeCtlBool(snd_ctl_t* ctl, const char* name, bool v) {
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);
(void)snd_ctl_elem_write(ctl, val);
}
static constexpr uint32_t kRingFrames = 4096;
static constexpr uint32_t kRingMask = kRingFrames - 1;
int16_t ring_[kRingFrames * 2] = {0};
std::atomic<uint32_t> writePos_{0};
std::atomic<uint32_t> readPos_{0};
std::atomic<bool> threadRunning_{false};
std::thread worker_;
int speakerPct_ = 75;
bool sysMuted_ = false;
std::atomic<int32_t> volScale_{21};
int64_t lastVolCheckMs_ = 0;
time_t lastVolMtime_ = 0;
unsigned accumSamples_ = 0;
int32_t currentL_ = 0;
int32_t currentR_ = 0;
int32_t nextL_ = 0;
int32_t nextR_ = 0;
int32_t prevSmplL_ = 0;
int32_t prevSmplR_ = 0;
int32_t highpassL_ = 0;
int32_t highpassR_ = 0;
int32_t prevOutL_ = 0;
int32_t prevOutR_ = 0;
int32_t lpf1L_ = 0;
int32_t lpf1R_ = 0;
int32_t lpf2L_ = 0;
int32_t lpf2R_ = 0;
int32_t resamplePos_ = 0;
};
// Blend two 0x00RRGGBB pixels 50/50 in a single bitwise operation
inline uint32_t blend50(uint32_t a, uint32_t b) {
return ((a & 0xFEFEFEu) >> 1) + ((b & 0xFEFEFEu) >> 1) + (a & b & 0x010101u);
}
// Fast 1.5x (160x144 -> 240x216) area-interpolated scaler
void scale160x144To240x216(const gambatte::video_pixel_t* src, int srcPitch,
uint32_t* dst, int dstStride) {
uint32_t row0[240];
uint32_t row1[240];
auto scaleRowHoriz = [](const gambatte::video_pixel_t* srow, uint32_t* drow) {
int dx = 0;
for (int sx = 0; sx < 160; sx += 2) {
uint32_t p0 = static_cast<uint32_t>(srow[sx]);
uint32_t p1 = static_cast<uint32_t>(srow[sx + 1]);
drow[dx] = p0;
drow[dx + 1] = blend50(p0, p1);
drow[dx + 2] = p1;
dx += 3;
}
};
int dy = 0;
for (int sy = 0; sy < 144; sy += 2) {
scaleRowHoriz(src + sy * srcPitch, row0);
scaleRowHoriz(src + (sy + 1) * srcPitch, row1);
uint32_t* d0 = dst + dy * dstStride;
uint32_t* d1 = dst + (dy + 1) * dstStride;
uint32_t* d2 = dst + (dy + 2) * dstStride;
std::memcpy(d0, row0, 240 * sizeof(uint32_t));
for (int x = 0; x < 240; ++x) {
d1[x] = blend50(row0[x], row1[x]);
}
std::memcpy(d2, row1, 240 * sizeof(uint32_t));
dy += 3;
}
}
void scale160x144ToArbitrary(const gambatte::video_pixel_t* src, int srcPitch,
uint32_t* dst, int dstStride, int outW, int outH) {
uint32_t row0[240];
for (int y = 0; y < outH; ++y) {
int sy = (y * kGbH) / outH;
const gambatte::video_pixel_t* srow = src + sy * srcPitch;
int dx = 0;
for (int sx = 0; sx < 160; sx += 2) {
uint32_t p0 = static_cast<uint32_t>(srow[sx]);
uint32_t p1 = static_cast<uint32_t>(srow[sx + 1]);
row0[dx] = p0;
row0[dx + 1] = blend50(p0, p1);
row0[dx + 2] = p1;
dx += 3;
}
std::memcpy(dst + y * dstStride, row0, outW * sizeof(uint32_t));
}
}
struct RomEntry {
std::string name;
std::string fullPath;
bool isDir = false;
bool isParent = false;
};
} // namespace
void cartridge_set_rumble(unsigned active) {
static unsigned lastActive = 0;
if (active == lastActive) return;
lastActive = active;
int fd = ::open("/sys/class/leds/vibrator/brightness",
O_WRONLY | O_NONBLOCK | O_CLOEXEC);
if (fd >= 0) {
(void)::write(fd, active ? "180\n" : "0\n", active ? 4 : 2);
::close(fd);
}
}
int main(int argc, char** argv) {
struct sigaction sa {};
sa.sa_handler = onSignal;
sigemptyset(&sa.sa_mask);
sigaction(SIGTERM, &sa, nullptr);
sigaction(SIGINT, &sa, nullptr);
sigaction(SIGUSR1, &sa, nullptr);
signal(SIGPIPE, SIG_IGN);
Display* dpy = XOpenDisplay(nullptr);
if (!dpy) {
std::fprintf(stderr, "gambatte: cannot open X11 display\n");
return 1;
}
int screen = DefaultScreen(dpy);
Window root = RootWindow(dpy, screen);
Visual* visual = DefaultVisual(dpy, screen);
int depth = DefaultDepth(dpy, screen);
ThemeSpec tspec = loadThemeSpec(dpy, screen);
XSetWindowAttributes swa {};
swa.override_redirect = True;
swa.background_pixel = tspec.bgMain;
swa.border_pixel = tspec.border;
swa.event_mask = ExposureMask | KeyPressMask | KeyReleaseMask |
StructureNotifyMask | FocusChangeMask | VisibilityChangeMask;
Window win = XCreateWindow(
dpy, root, kWinX, kWinY, kWinW, kWinH, 0, depth, InputOutput, visual,
CWOverrideRedirect | CWBackPixel | CWBorderPixel | CWEventMask, &swa);
XClassHint ch {};
char resName[] = "gambatte";
char resClass[] = "Gambatte";
ch.res_name = resName;
ch.res_class = resClass;
XSetClassHint(dpy, win, &ch);
XStoreName(dpy, win, "Game Boy (Gambatte)");
Atom wmDelete = XInternAtom(dpy, "WM_DELETE_WINDOW", False);
XSetWMProtocols(dpy, win, &wmDelete, 1);
Pixmap pix = XCreatePixmap(dpy, win, kWinW, kWinH, depth);
GC gc = XCreateGC(dpy, pix, 0, nullptr);
XSetGraphicsExposures(dpy, gc, False);
// Offscreen XImage for scaled Game Boy video (up to 240x296)
std::vector<uint32_t> scaledPixels(kWinW * kWinH, 0);
XImage* ximg = XCreateImage(
dpy, visual, depth, ZPixmap, 0,
reinterpret_cast<char*>(scaledPixels.data()), kWinW, kWinH, 32,
kWinW * sizeof(uint32_t));
bool keyboardGrabbed = false;
XMapRaised(dpy, win);
XSetInputFocus(dpy, win, RevertToPointerRoot, CurrentTime);
for (int i = 0; i < 30; ++i) {
if (XGrabKeyboard(dpy, win, True, GrabModeAsync, GrabModeAsync,
CurrentTime) == GrabSuccess) {
keyboardGrabbed = true;
break;
}
::usleep(5000);
}
XFlush(dpy);
EmulatorConfig cfg;
cfg.load();
gambatte::GB gb;
PhoneInputGetter inputGetter;
gb.setInputGetter(&inputGetter);
PcmAudioOut audioOut;
audioOut.refreshVolume(true);
std::vector<gambatte::video_pixel_t> gbFrame(kGbW * kGbH, 0);
std::vector<gambatte::video_pixel_t> postFrame(kGbW * kGbH, 0);
std::vector<gambatte::uint_least32_t> soundBuf(35112 + 4096, 0);
std::string currentRomPath;
std::string currentRomBase;
std::string currentRomTitle;
bool romLoaded = false;
std::string toastText;
int64_t toastUntilMs = 0;
auto showToast = [&](const std::string& msg, int durationMs = 1500) {
toastText = msg;
toastUntilMs = nowMs() + durationMs;
};
auto applyDmgPalette = [&]() {
const ColorPalette& pal = kPalettes[cfg.paletteIdx % kNumPalettes];
for (unsigned c = 0; c < 4; ++c) {
gb.setDmgPaletteColor(0, c, pal.bg[c]);
gb.setDmgPaletteColor(1, c, pal.sp1[c]);
gb.setDmgPaletteColor(2, c, pal.sp2[c]);
}
};
auto saveBatterySram = [&]() {
if (!romLoaded || currentRomBase.empty()) return;
unsigned sz = gb.savedata_size();
void* ptr = gb.savedata_ptr();
if (sz > 0 && ptr) {
ensureDir(getSaveDir());
std::string savPath = getSaveDir() + "/" + currentRomBase + ".sav";
std::ofstream out(savPath, std::ios::binary | std::ios::trunc);
if (out.is_open()) {
out.write(static_cast<const char*>(ptr), sz);
}
}
unsigned rsz = gb.rtcdata_size();
void* rptr = gb.rtcdata_ptr();
if (rsz > 0 && rptr) {
ensureDir(getSaveDir());
std::string rtcPath = getSaveDir() + "/" + currentRomBase + ".rtc";
std::ofstream out(rtcPath, std::ios::binary | std::ios::trunc);
if (out.is_open()) {
out.write(static_cast<const char*>(rptr), rsz);
}
}
};
auto loadBatterySram = [&]() {
if (!romLoaded || currentRomBase.empty()) return;
unsigned sz = gb.savedata_size();
void* ptr = gb.savedata_ptr();
if (sz > 0 && ptr) {
std::string savPath = getSaveDir() + "/" + currentRomBase + ".sav";
std::ifstream in(savPath, std::ios::binary);
if (in.is_open()) {
in.read(static_cast<char*>(ptr), sz);
}
}
unsigned rsz = gb.rtcdata_size();
void* rptr = gb.rtcdata_ptr();
if (rsz > 0 && rptr) {
std::string rtcPath = getSaveDir() + "/" + currentRomBase + ".rtc";
std::ifstream in(rtcPath, std::ios::binary);
if (in.is_open()) {
in.read(static_cast<char*>(rptr), rsz);
}
}
};
auto saveEmulatorState = [&](int slot) -> bool {
if (!romLoaded || currentRomBase.empty()) return false;
size_t stSize = gb.stateSize();
if (stSize == 0) return false;
std::vector<uint8_t> buf(stSize);
gb.saveState(buf.data());
ensureDir(getStateDir());
std::string stPath =
getStateDir() + "/" + currentRomBase + ".st" + std::to_string(slot);
std::ofstream out(stPath, std::ios::binary | std::ios::trunc);
if (!out.is_open()) return false;
out.write(reinterpret_cast<const char*>(buf.data()),
static_cast<std::streamsize>(buf.size()));
return out.good();
};
auto loadEmulatorState = [&](int slot) -> bool {
if (!romLoaded || currentRomBase.empty()) return false;
std::string stPath =
getStateDir() + "/" + currentRomBase + ".st" + std::to_string(slot);
std::ifstream in(stPath, std::ios::binary | std::ios::ate);
if (!in.is_open()) return false;
std::streamsize sz = in.tellg();
if (sz <= 0) return false;
in.seekg(0, std::ios::beg);
std::vector<uint8_t> buf(static_cast<size_t>(sz));
if (!in.read(reinterpret_cast<char*>(buf.data()), sz)) return false;
return gb.loadState(buf.data(), buf.size());
};
auto loadRomFile = [&](const std::string& path) -> bool {
std::ifstream in(path, std::ios::binary | std::ios::ate);
if (!in.is_open()) {
showToast("Failed to open ROM");
return false;
}
std::streamsize sz = in.tellg();
if (sz <= 0 || sz > 16 * 1024 * 1024) {
showToast("Invalid ROM size");
return false;
}
in.seekg(0, std::ios::beg);
std::vector<uint8_t> romBytes(static_cast<size_t>(sz));
if (!in.read(reinterpret_cast<char*>(romBytes.data()), sz)) {
showToast("Failed to read ROM");
return false;
}
if (romLoaded) {
saveBatterySram();
}
if (gb.load(romBytes.data(), static_cast<unsigned>(romBytes.size()), 0) != 0) {
showToast("Unsupported ROM format");
return false;
}
currentRomPath = path;
currentRomBase = stripExtAndDir(path);
currentRomTitle = currentRomBase;
if (currentRomTitle.size() > 18) {
currentRomTitle = currentRomTitle.substr(0, 18);
}
size_t sl = path.rfind('/');
if (sl != std::string::npos && sl > 0) {
cfg.lastDir = path.substr(0, sl);
cfg.save();
}
romLoaded = true;
applyDmgPalette();
loadBatterySram();
return true;
};
enum class UiState {
Playing = 0,
PauseMenu = 1,
ControlsMenu = 2,
WaitingForKey = 3,
RomBrowser = 4,
};
UiState uiState = UiState::RomBrowser;
int pauseMenuSel = 0;
int controlsSel = 0;
int romBrowserSel = 0;
std::string browseDir = cfg.lastDir;
std::vector<RomEntry> browserEntries;
auto populateRomBrowser = [&](const std::string& dirPath) {
browserEntries.clear();
browseDir = dirPath;
// 1. Quick-scan common ROM directories at top if browsing home dir
auto scanQuickDir = [&](const std::string& dpath, const std::string& tag) {
DIR* d = ::opendir(dpath.c_str());
if (!d) return;
std::vector<RomEntry> found;
struct dirent* ent;
while ((ent = ::readdir(d)) != nullptr) {
std::string nm = ent->d_name;
if (nm.empty() || nm[0] == '.') continue;
if (isGbRomExt(nm)) {
bool dup = false;
for (const auto& existing : browserEntries) {
size_t sl = existing.fullPath.rfind('/');
std::string base = (sl == std::string::npos)
? existing.fullPath
: existing.fullPath.substr(sl + 1);
if (base == nm) {
dup = true;
break;
}
}
if (dup) continue;
RomEntry re;
re.name = tag.empty() ? nm : (tag + "/" + nm);
re.fullPath = dpath + "/" + nm;
re.isDir = false;
found.push_back(re);
}
}
::closedir(d);
std::sort(found.begin(), found.end(),
[](const RomEntry& a, const RomEntry& b) {
return a.name < b.name;
});
browserEntries.insert(browserEntries.end(), found.begin(), found.end());
};
if (dirPath != "/") {
size_t sl = dirPath.rfind('/');
std::string parent = (sl == 0 || sl == std::string::npos)
? "/"
: dirPath.substr(0, sl);
RomEntry up;
up.name = ".. (Parent Folder)";
up.fullPath = parent;
up.isDir = true;
up.isParent = true;
browserEntries.push_back(up);
}
if (dirPath == getHomeDir()) {
scanQuickDir("/usr/share/games/gb", "BuiltIn");
scanQuickDir(getHomeDir() + "/Games", "Games");
scanQuickDir(getHomeDir() + "/ROMs", "ROMs");
scanQuickDir(getHomeDir() + "/Downloads", "Downloads");
}
DIR* d = ::opendir(dirPath.c_str());
if (d) {
std::vector<RomEntry> dirs;
std::vector<RomEntry> roms;
struct dirent* ent;
while ((ent = ::readdir(d)) != nullptr) {
std::string nm = ent->d_name;
if (nm.empty() || nm[0] == '.') continue;
std::string full =
(dirPath == "/") ? ("/" + nm) : (dirPath + "/" + nm);
struct stat st {};
if (::stat(full.c_str(), &st) != 0) continue;
if (S_ISDIR(st.st_mode)) {
RomEntry re;
re.name = "[" + nm + "]";
re.fullPath = full;
re.isDir = true;
dirs.push_back(re);
} else if (isGbRomExt(nm)) {
RomEntry re;
re.name = nm;
re.fullPath = full;
re.isDir = false;
roms.push_back(re);
}
}
::closedir(d);
std::sort(dirs.begin(), dirs.end(),
[](const RomEntry& a, const RomEntry& b) {
return a.name < b.name;
});
std::sort(roms.begin(), roms.end(),
[](const RomEntry& a, const RomEntry& b) {
return a.name < b.name;
});
browserEntries.insert(browserEntries.end(), roms.begin(), roms.end());
browserEntries.insert(browserEntries.end(), dirs.begin(), dirs.end());
}
romBrowserSel = 0;
};
if (argc >= 2 && argv[1] && argv[1][0] != '-') {
if (loadRomFile(argv[1])) {
uiState = UiState::Playing;
} else {
populateRomBrowser(cfg.lastDir);
uiState = UiState::RomBrowser;
}
} else {
populateRomBrowser(cfg.lastDir);
uiState = UiState::RomBrowser;
}
// Active key hold states for each action
bool actionDown[ACT_COUNT] = {false};
uint64_t frameCount = 0;
int64_t lastSramFlushMs = nowMs();
int softkeyPending = 0;
int64_t softkeyDeadlineMs = 0;
int lastSoftkeyMask = 0;
int64_t lastSoftkeyMs = 0;
auto cyclePalette = [&](int delta) {
cfg.paletteIdx = (cfg.paletteIdx + kNumPalettes + delta) % kNumPalettes;
applyDmgPalette();
cfg.save();
std::string pMsg = std::string("Palette: ") + kPalettes[cfg.paletteIdx].name;
showToast(pMsg, 1400);
};
bool toastWasVisible = false;
auto renderScreen = [&](bool fullRedraw = true) {
bool toastActive = (!toastText.empty() && nowMs() < toastUntilMs);
if (!toastActive && toastWasVisible) {
fullRedraw = true;
}
toastWasVisible = toastActive;
if (!fullRedraw && uiState == UiState::Playing && !toastActive) {
const gambatte::video_pixel_t* srcFb = gbFrame.data();
if (gb.isCgb() && cfg.paletteIdx > 0) {
const ColorPalette& pal = kPalettes[cfg.paletteIdx % kNumPalettes];
for (int i = 0; i < kGbW * kGbH; ++i) {
uint32_t px = static_cast<uint32_t>(gbFrame[i]);
unsigned r = (px >> 16) & 0xFFu;
unsigned g = (px >> 8) & 0xFFu;
unsigned b = px & 0xFFu;
unsigned luma = (r * 77u + g * 150u + b * 29u) >> 8;
unsigned shade = 3u - (luma >> 6);
postFrame[i] = pal.bg[shade & 3u];
}
srcFb = postFrame.data();
}
if (cfg.scaleMode == 3) {
scale160x144ToArbitrary(srcFb, kGbW, scaledPixels.data(), kWinW,
kWinW, kWinH);
XPutImage(dpy, win, gc, ximg, 0, 0, 0, 0, kWinW, kWinH);
} else if (cfg.scaleMode == 0) {
scale160x144To240x216(srcFb, kGbW, scaledPixels.data(), kWinW);
XPutImage(dpy, win, gc, ximg, 0, 0, 0, 39, 240, 216);
} else if (cfg.scaleMode == 1) {
for (int y = 0; y < kGbH; ++y) {
for (int x = 0; x < kGbW; ++x) {
scaledPixels[y * kWinW + x] =
static_cast<uint32_t>(srcFb[y * kGbW + x]);
}
}
XPutImage(dpy, win, gc, ximg, 0, 0, 40, 75, kGbW, kGbH);
} else {
scale160x144ToArbitrary(srcFb, kGbW, scaledPixels.data(), kWinW,
240, 246);
XPutImage(dpy, win, gc, ximg, 0, 0, 0, 24, 240, 246);
}
XFlush(dpy);
return;
}
unsigned long colBg = tspec.bgMain;
unsigned long colHeader = tspec.bgHeader;
unsigned long colFooter = tspec.bgFooter;
unsigned long colSel = tspec.selBg;
unsigned long colBorder = tspec.border;
unsigned long colWhite = tspec.fgMain;
unsigned long colMuted = tspec.fgMuted;
unsigned long colYellow = tspec.accent;
unsigned long colGreen = tspec.success;
unsigned long colBlue = tspec.info;
unsigned long colRed = tspec.danger;
XSetForeground(dpy, gc, colBg);
XFillRectangle(dpy, pix, gc, 0, 0, kWinW, kWinH);
if (uiState == UiState::Playing) {
// Optional palette tint for CGB games when paletteIdx > 0 so '*' always works!
const gambatte::video_pixel_t* srcFb = gbFrame.data();
if (gb.isCgb() && cfg.paletteIdx > 0) {
const ColorPalette& pal = kPalettes[cfg.paletteIdx % kNumPalettes];
for (int i = 0; i < kGbW * kGbH; ++i) {
uint32_t px = static_cast<uint32_t>(gbFrame[i]);
unsigned r = (px >> 16) & 0xFFu;
unsigned g = (px >> 8) & 0xFFu;
unsigned b = px & 0xFFu;
unsigned luma = (r * 77u + g * 150u + b * 29u) >> 8;
unsigned shade = 3u - (luma >> 6);
postFrame[i] = pal.bg[shade & 3u];
}
srcFb = postFrame.data();
}
if (cfg.scaleMode == 3) {
// Full 240x296 edge-to-edge
scale160x144ToArbitrary(srcFb, kGbW, scaledPixels.data(), kWinW,
kWinW, kWinH);
XPutImage(dpy, pix, gc, ximg, 0, 0, 0, 0, kWinW, kWinH);
} else {
// Top HUD bar (24px)
XSetForeground(dpy, gc, colHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinW, 24);
XSetForeground(dpy, gc, colBorder);
XDrawLine(dpy, pix, gc, 0, 23, kWinW, 23);
drawText(dpy, pix, gc, 6, 8,
gb.isCgb() ? "GBC" : "GB", 1,
gb.isCgb() ? colGreen : colYellow);
drawText(dpy, pix, gc, 32, 8, currentRomTitle.c_str(), 1, colWhite, 22);
char slotTag[16];
std::snprintf(slotTag, sizeof(slotTag), "S:%d", cfg.stateSlot);
drawText(dpy, pix, gc, kWinW - 24, 8, slotTag, 1, colBlue);
if (cfg.scaleMode == 0) {
// 1.5x Fit (240x216) centered between Y=24 and Y=270
scale160x144To240x216(srcFb, kGbW, scaledPixels.data(), kWinW);
XPutImage(dpy, pix, gc, ximg, 0, 0, 0, 39, 240, 216);
} else if (cfg.scaleMode == 1) {
// 1:1 Pixel Perfect (160x144) centered at (40, 75)
XSetForeground(dpy, gc, colBorder);
XDrawRectangle(dpy, pix, gc, 38, 73, kGbW + 3, kGbH + 3);
for (int y = 0; y < kGbH; ++y) {
for (int x = 0; x < kGbW; ++x) {
scaledPixels[y * kWinW + x] =
static_cast<uint32_t>(srcFb[y * kGbW + x]);
}
}
XPutImage(dpy, pix, gc, ximg, 0, 0, 40, 75, kGbW, kGbH);
} else {
// Stretch (240x246) filling Y=24..270
scale160x144ToArbitrary(srcFb, kGbW, scaledPixels.data(), kWinW,
240, 246);
XPutImage(dpy, pix, gc, ximg, 0, 0, 0, 24, 240, 246);
}
// Bottom Softkey Bar (26px)
int sbY = kWinH - 26;
XSetForeground(dpy, gc, colFooter);
XFillRectangle(dpy, pix, gc, 0, sbY, kWinW, 26);
XSetForeground(dpy, gc, colBorder);
XDrawLine(dpy, pix, gc, 0, sbY, kWinW, sbY);
drawText(dpy, pix, gc, 6, sbY + 9, "Menu", 1, colBlue);
std::string hint =
"B:" + cfg.bindings[ACT_B] + " A:" + cfg.bindings[ACT_A] +
" *:" + kPalettes[cfg.paletteIdx].name;
drawText(dpy, pix, gc, 42, sbY + 9, hint.c_str(), 1, colMuted, 24);
drawText(dpy, pix, gc, kWinW - 30, sbY + 9, "Pause", 1, colWhite);
}
} else if (uiState == UiState::PauseMenu) {
XSetForeground(dpy, gc, colHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinW, 30);
XSetForeground(dpy, gc, colBorder);
XDrawLine(dpy, pix, gc, 0, 29, kWinW, 29);
drawCenteredText(dpy, pix, gc, 8, "GAMBATTE MENU", 2, colYellow);
const char* scaleLabels[4] = {
"Fit 240x216",
"1:1 160x144",
"Fill 240x246",
"Full 240x296"
};
std::string audioLabel = "Audio: OFF";
if (cfg.audioEnabled) {
if (audioOut.isSystemMuted()) {
audioLabel = "Audio: < MUTED (0%) >";
} else {
audioLabel = "Audio: < ON (" +
std::to_string(audioOut.speakerVolPct()) + "%) >";
}
}
std::string items[10] = {
"Resume Game",
"Save State [Slot " + std::to_string(cfg.stateSlot) + "]",
"Load State [Slot " + std::to_string(cfg.stateSlot) + "]",
"State Slot: < " + std::to_string(cfg.stateSlot) + " >",
std::string("Palette: < ") + kPalettes[cfg.paletteIdx].name + " >",
std::string("Screen: < ") + scaleLabels[cfg.scaleMode] + " >",
audioLabel,
"Keypad Controls...",
"Load Another ROM...",
"Reset / Quit Emulator"
};
constexpr int kVis = 8;
int scroll = 0;
if (pauseMenuSel >= kVis) scroll = pauseMenuSel - kVis + 1;
for (int i = 0; i < kVis; ++i) {
int idx = scroll + i;
if (idx >= 10) break;
int ry = 34 + i * 29;
bool isSel = (idx == pauseMenuSel);
if (isSel) {
XSetForeground(dpy, gc, colSel);
XFillRectangle(dpy, pix, gc, 4, ry, kWinW - 8, 27);
XSetForeground(dpy, gc, colYellow);
XFillRectangle(dpy, pix, gc, 4, ry, 3, 27);
}
drawText(dpy, pix, gc, 12, ry + 10, items[idx].c_str(), 1,
isSel ? colYellow : colWhite, 36);
}
int sbY = kWinH - 26;
XSetForeground(dpy, gc, colFooter);
XFillRectangle(dpy, pix, gc, 0, sbY, kWinW, 26);
drawText(dpy, pix, gc, 6, sbY + 9, "Select", 1, colBlue);
drawCenteredText(dpy, pix, gc, sbY + 9, "OK", 1, colGreen);
drawText(dpy, pix, gc, kWinW - 42, sbY + 9, "Resume", 1, colWhite);
} else if (uiState == UiState::ControlsMenu ||
uiState == UiState::WaitingForKey) {
XSetForeground(dpy, gc, colHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinW, 30);
XSetForeground(dpy, gc, colBorder);
XDrawLine(dpy, pix, gc, 0, 29, kWinW, 29);
drawCenteredText(dpy, pix, gc, 8, "KEYPAD CONTROLS", 2, colYellow);
int totalRows = ACT_COUNT + 1; // +1 for "Reset to Defaults"
constexpr int kVis = 8;
int scroll = 0;
if (controlsSel >= kVis) scroll = controlsSel - kVis + 1;
for (int i = 0; i < kVis; ++i) {
int idx = scroll + i;
if (idx >= totalRows) break;
int ry = 34 + i * 29;
bool isSel = (idx == controlsSel);
if (isSel) {
XSetForeground(dpy, gc, colSel);
XFillRectangle(dpy, pix, gc, 4, ry, kWinW - 8, 27);
XSetForeground(dpy, gc, colYellow);
XFillRectangle(dpy, pix, gc, 4, ry, 3, 27);
}
if (idx < ACT_COUNT) {
drawText(dpy, pix, gc, 12, ry + 10, kActionNames[idx], 1,
isSel ? colWhite : colMuted, 20);
std::string val = "[" + cfg.bindings[idx] + "]";
if (isSel && uiState == UiState::WaitingForKey) {
val = "[PRESS KEY...]";
}
int vw = textPixelWidth(val.c_str(), 1);
drawText(dpy, pix, gc, kWinW - vw - 12, ry + 10, val.c_str(), 1,
isSel ? colYellow : colGreen);
} else {
drawText(dpy, pix, gc, 12, ry + 10,
"Reset Controls to Default", 1,
isSel ? colRed : colYellow);
}
}
int sbY = kWinH - 26;
XSetForeground(dpy, gc, colFooter);
XFillRectangle(dpy, pix, gc, 0, sbY, kWinW, 26);
drawText(dpy, pix, gc, 6, sbY + 9, "Remap", 1, colBlue);
drawCenteredText(dpy, pix, gc, sbY + 9, "CHANGE", 1, colGreen);
drawText(dpy, pix, gc, kWinW - 30, sbY + 9, "Back", 1, colWhite);
} else if (uiState == UiState::RomBrowser) {
XSetForeground(dpy, gc, colHeader);
XFillRectangle(dpy, pix, gc, 0, 0, kWinW, 30);
XSetForeground(dpy, gc, colBorder);
XDrawLine(dpy, pix, gc, 0, 29, kWinW, 29);
drawCenteredText(dpy, pix, gc, 8, "SELECT GB/GBC ROM", 2, colYellow);
if (browserEntries.empty()) {
drawCenteredText(dpy, pix, gc, 120, "NO .GB / .GBC FILES", 1, colMuted);
} else {
constexpr int kVis = 8;
int total = static_cast<int>(browserEntries.size());
int scroll = 0;
if (romBrowserSel >= kVis) scroll = romBrowserSel - kVis + 1;
for (int i = 0; i < kVis; ++i) {
int idx = scroll + i;
if (idx >= total) break;
int ry = 34 + i * 29;
bool isSel = (idx == romBrowserSel);
if (isSel) {
XSetForeground(dpy, gc, colSel);
XFillRectangle(dpy, pix, gc, 4, ry, kWinW - 8, 27);
XSetForeground(dpy, gc, colYellow);
XFillRectangle(dpy, pix, gc, 4, ry, 3, 27);
}
const auto& re = browserEntries[idx];
unsigned long c = re.isDir ? colBlue : (isSel ? colYellow : colWhite);
drawText(dpy, pix, gc, 12, ry + 10, re.name.c_str(), 1, c, 36);
}
}
int sbY = kWinH - 26;
XSetForeground(dpy, gc, colFooter);
XFillRectangle(dpy, pix, gc, 0, sbY, kWinW, 26);
drawText(dpy, pix, gc, 6, sbY + 9, "Controls", 1, colBlue);
drawCenteredText(dpy, pix, gc, sbY + 9, "OPEN", 1, colGreen);
drawText(dpy, pix, gc, kWinW - 30, sbY + 9,
romLoaded ? "Back" : "Quit", 1, colWhite);
}
// Toast notification overlay
if (!toastText.empty() && nowMs() < toastUntilMs) {
int tw = std::min(kWinW - 16, textPixelWidth(toastText.c_str(), 1) + 16);
int tx = (kWinW - tw) / 2;
int ty = kWinH - 52;
XSetForeground(dpy, gc, colSel);
XFillRectangle(dpy, pix, gc, tx, ty, tw, 20);
XSetForeground(dpy, gc, colYellow);
XDrawRectangle(dpy, pix, gc, tx, ty, tw - 1, 19);
drawCenteredText(dpy, pix, gc, ty + 6, toastText.c_str(), 1, colYellow);
}
XCopyArea(dpy, pix, win, gc, 0, 0, kWinW, kWinH, 0, 0);
XFlush(dpy);
};
int64_t overlayCooldownUntilMs = 0;
int64_t softkeyIgnoreUntilMs = 0;
auto unfocusWindow = [&](bool forXDrawerToggle) {
std::memset(actionDown, 0, sizeof(actionDown));
inputGetter.state = 0;
audioOut.stop();
if (uiState == UiState::Playing && romLoaded) {
saveBatterySram();
pauseMenuSel = 0;
uiState = UiState::PauseMenu;
renderScreen();
}
if (keyboardGrabbed) {
XUngrabKeyboard(dpy, CurrentTime);
keyboardGrabbed = false;
}
XSetInputFocus(dpy, PointerRoot, RevertToPointerRoot, CurrentTime);
XLowerWindow(dpy, win);
XSync(dpy, False);
if (forXDrawerToggle) {
int64_t tNow = nowMs();
writeSoftkeySuppress(tNow + 500);
overlayCooldownUntilMs = tNow + 500;
toggleXDrawer();
}
};
auto refocusWindow = [&]() {
audioOut.refreshVolume(true);
XMapRaised(dpy, win);
XSetInputFocus(dpy, win, RevertToPointerRoot, CurrentTime);
for (int i = 0; i < 30; ++i) {
if (XGrabKeyboard(dpy, win, True, GrabModeAsync, GrabModeAsync,
CurrentTime) == GrabSuccess) {
keyboardGrabbed = true;
break;
}
::usleep(4000);
}
XFlush(dpy);
softkeyPending = 0;
softkeyDeadlineMs = 0;
lastSoftkeyMask = 0;
lastSoftkeyMs = 0;
softkeyIgnoreUntilMs = nowMs() + 350;
renderScreen();
};
auto handlePauseMenuExec = [&]() {
switch (pauseMenuSel) {
case 0: // Resume
uiState = UiState::Playing;
break;
case 1: // Save State
if (saveEmulatorState(cfg.stateSlot)) {
showToast("Saved Slot " + std::to_string(cfg.stateSlot));
} else {
showToast("Save State failed");
}
uiState = UiState::Playing;
break;
case 2: // Load State
if (loadEmulatorState(cfg.stateSlot)) {
showToast("Loaded Slot " + std::to_string(cfg.stateSlot));
} else {
showToast("Empty Slot " + std::to_string(cfg.stateSlot));
}
uiState = UiState::Playing;
break;
case 3: // Cycle State Slot
cfg.stateSlot = (cfg.stateSlot + 1) % 10;
cfg.save();
break;
case 4: // Cycle Palette
cyclePalette(1);
break;
case 5: // Cycle Screen Scale
cfg.scaleMode = (cfg.scaleMode + 1) % 4;
cfg.save();
break;
case 6: // Toggle Audio
cfg.audioEnabled = !cfg.audioEnabled;
if (cfg.audioEnabled) {
audioOut.refreshVolume(true);
} else {
audioOut.stop();
}
cfg.save();
break;
case 7: // Keypad Controls
controlsSel = 0;
uiState = UiState::ControlsMenu;
break;
case 8: // Load Another ROM
populateRomBrowser(cfg.lastDir);
uiState = UiState::RomBrowser;
break;
case 9: // Quit Emulator
saveBatterySram();
gRunning = 0;
break;
}
};
// Sub-frame pacing timerfd: 4 slices per GB frame (~238.91 Hz = 4,185,676 ns,
// 8,778 GB samples = ~201 48-kHz samples per slice) so the ALSA ringbuffer
// is fed every 4.18 ms (faster than the 5.33 ms hardware period).
int tfd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK | TFD_CLOEXEC);
struct itimerspec its {};
its.it_interval.tv_sec = 0;
its.it_interval.tv_nsec = 4185676L;
its.it_value = its.it_interval;
if (tfd >= 0) {
timerfd_settime(tfd, 0, &its, nullptr);
}
uint32_t subSliceCount = 0;
uint32_t samplesSinceRender = 0;
renderScreen();
int xfd = ConnectionNumber(dpy);
int64_t lastExtCheckMs = 0;
while (gRunning) {
int64_t tLoop = nowMs();
// Yield focus if xdrawer or another system overlay opened externally,
// and reclaim focus automatically when it closes.
if (!keyboardGrabbed || (tLoop - lastExtCheckMs >= 100)) {
lastExtCheckMs = tLoop;
bool extActive = isExternalOverlayActive();
if (extActive && keyboardGrabbed) {
unfocusWindow(false);
} else if (!extActive && !keyboardGrabbed &&
tLoop >= overlayCooldownUntilMs) {
refocusWindow();
}
}
if (gReloadTheme) {
gReloadTheme = 0;
tspec = loadThemeSpec(dpy, screen);
if (keyboardGrabbed) renderScreen();
}
while (XPending(dpy) > 0) {
XEvent ev;
XNextEvent(dpy, &ev);
if (ev.type == ClientMessage) {
if (static_cast<Atom>(ev.xclient.data.l[0]) == wmDelete) {
gRunning = 0;
}
} else if (ev.type == Expose && ev.xexpose.count == 0) {
if (keyboardGrabbed && !isExternalOverlayActive()) {
renderScreen();
}
} else if (ev.type == VisibilityNotify &&
ev.xvisibility.state != VisibilityUnobscured) {
if (isExternalOverlayActive() || nowMs() < overlayCooldownUntilMs) {
if (keyboardGrabbed) unfocusWindow(false);
}
} else if (ev.type == FocusOut) {
std::memset(actionDown, 0, sizeof(actionDown));
inputGetter.state = 0;
if (isExternalOverlayActive() && keyboardGrabbed) {
unfocusWindow(false);
}
} else if (ev.type == KeyPress || ev.type == KeyRelease) {
if (!keyboardGrabbed) continue;
bool isPress = (ev.type == KeyPress);
// Filter out X11 key auto-repeat on KeyRelease so held buttons stay smooth
if (!isPress && XEventsQueued(dpy, QueuedAfterReading)) {
XEvent nev;
XPeekEvent(dpy, &nev);
if (nev.type == KeyPress && nev.xkey.time == ev.xkey.time &&
nev.xkey.keycode == ev.xkey.keycode) {
XNextEvent(dpy, &nev);
continue;
}
}
unsigned int kc = ev.xkey.keycode;
KeySym sym = XLookupKeysym(&ev.xkey, 0);
if (isPress && (sym == XF86XK_PowerOff || kc == 124)) {
unfocusWindow(false);
int64_t tNow = nowMs();
writeSoftkeySuppress(tNow + 500);
overlayCooldownUntilMs = tNow + 500;
int ffd = ::open("/tmp/dwm_plugin_dmenu.fifo",
O_WRONLY | O_NONBLOCK | O_CLOEXEC);
if (ffd >= 0) {
(void)::write(ffd, "OPEN power\n", 11);
::close(ffd);
}
continue;
}
if (isPress && (sym == XF86XK_AudioLowerVolume ||
sym == XF86XK_AudioRaiseVolume)) {
audioOut.adjustSpeakerVol(
(sym == XF86XK_AudioRaiseVolume) ? +5 : -5);
showToast("Volume: " + std::to_string(audioOut.speakerVolPct()) +
"%");
renderScreen();
continue;
}
bool isLeftSoft =
(kc == 135 || sym == XK_Menu || sym == XF86XK_KbdLcdMenu1 ||
sym == _EVDEVK(0x246) || sym == XK_F1);
bool isRightSoft =
(kc == 166 || sym == XF86XK_Back || sym == XF86XK_KbdLcdMenu2 ||
sym == _EVDEVK(0x247) || sym == XK_F2);
if (isLeftSoft || isRightSoft) {
if (!isPress) continue;
int64_t tSk = nowMs();
if (tSk < softkeyIgnoreUntilMs) continue;
int which = isLeftSoft ? 1 : 2;
int comb = softkeyPending | which | querySoftkeysDown(dpy);
if (lastSoftkeyMask != 0 && (tSk - lastSoftkeyMs) <= 320) {
comb |= lastSoftkeyMask;
}
if (comb == 3) {
softkeyPending = 0;
softkeyDeadlineMs = 0;
lastSoftkeyMask = 0;
lastSoftkeyMs = 0;
unfocusWindow(true);
continue;
}
softkeyPending = which;
lastSoftkeyMask = which;
lastSoftkeyMs = tSk;
softkeyDeadlineMs = tSk + 45;
continue;
}
std::string tok = keyEventToToken(sym, kc);
if (uiState == UiState::WaitingForKey) {
if (isPress) {
if (sym == XK_Escape || sym == XK_BackSpace) {
uiState = UiState::ControlsMenu;
} else if (!tok.empty() && tok != "OK" && controlsSel >= 0 &&
controlsSel < ACT_COUNT) {
std::string oldKey = cfg.bindings[controlsSel];
for (int i = 0; i < ACT_COUNT; ++i) {
if (i != controlsSel && cfg.bindings[i] == tok) {
cfg.bindings[i] = oldKey;
}
}
cfg.bindings[controlsSel] = tok;
cfg.save();
showToast(std::string(kActionNames[controlsSel]) + " -> " + tok);
uiState = UiState::ControlsMenu;
}
renderScreen();
}
continue;
}
if (uiState == UiState::Playing) {
if (isPress && (sym == XK_Escape || sym == XK_BackSpace || tok == "#")) {
saveBatterySram();
audioOut.stop();
pauseMenuSel = 0;
uiState = UiState::PauseMenu;
renderScreen();
continue;
}
// Check Palette key on press
if (isPress && tok == cfg.bindings[ACT_PALETTE]) {
cyclePalette(1);
renderScreen(true);
continue;
}
// Quick scale toggle ('1' if not bound to an action)
bool usedByAction = false;
for (int i = 0; i < ACT_COUNT; ++i) {
if (tok == cfg.bindings[i]) {
actionDown[i] = isPress;
usedByAction = true;
}
}
if (isPress && !usedByAction) {
if (tok == "1") {
cfg.scaleMode = (cfg.scaleMode + 1) % 4;
cfg.save();
showToast("Screen Mode Changed");
renderScreen(true);
} else if (tok == "4") {
if (saveEmulatorState(cfg.stateSlot)) {
showToast("Saved Slot " + std::to_string(cfg.stateSlot));
renderScreen(true);
}
} else if (tok == "7") {
if (loadEmulatorState(cfg.stateSlot)) {
showToast("Loaded Slot " + std::to_string(cfg.stateSlot));
renderScreen(true);
}
}
}
} else if (isPress && uiState == UiState::PauseMenu) {
if (sym == XK_Escape || sym == XK_BackSpace) {
uiState = UiState::Playing;
} else if (sym == XK_Up || sym == XK_KP_Up) {
pauseMenuSel = (pauseMenuSel + 9) % 10;
} else if (sym == XK_Down || sym == XK_KP_Down) {
pauseMenuSel = (pauseMenuSel + 1) % 10;
} else if (sym == XK_Left || sym == XK_KP_Left) {
if (pauseMenuSel == 3) {
cfg.stateSlot = (cfg.stateSlot + 9) % 10;
cfg.save();
} else if (pauseMenuSel == 4) {
cyclePalette(-1);
} else if (pauseMenuSel == 5) {
cfg.scaleMode = (cfg.scaleMode + 3) % 4;
cfg.save();
} else if (pauseMenuSel == 6) {
cfg.audioEnabled = true;
cfg.save();
audioOut.adjustSpeakerVol(-5);
}
} else if (sym == XK_Right || sym == XK_KP_Right) {
if (pauseMenuSel == 3) {
cfg.stateSlot = (cfg.stateSlot + 1) % 10;
cfg.save();
} else if (pauseMenuSel == 4) {
cyclePalette(1);
} else if (pauseMenuSel == 5) {
cfg.scaleMode = (cfg.scaleMode + 1) % 4;
cfg.save();
} else if (pauseMenuSel == 6) {
cfg.audioEnabled = true;
cfg.save();
audioOut.adjustSpeakerVol(+5);
}
} else if (sym == XK_Return || sym == XK_KP_Enter) {
handlePauseMenuExec();
} else if (tok == cfg.bindings[ACT_PALETTE]) {
cyclePalette(1);
}
renderScreen();
} else if (isPress && uiState == UiState::ControlsMenu) {
int totalRows = ACT_COUNT + 1;
if (sym == XK_Escape || sym == XK_BackSpace || sym == XK_Left) {
uiState = romLoaded ? UiState::PauseMenu : UiState::RomBrowser;
} else if (sym == XK_Up || sym == XK_KP_Up) {
controlsSel = (controlsSel + totalRows - 1) % totalRows;
} else if (sym == XK_Down || sym == XK_KP_Down) {
controlsSel = (controlsSel + 1) % totalRows;
} else if (sym == XK_Return || sym == XK_KP_Enter) {
if (controlsSel < ACT_COUNT) {
uiState = UiState::WaitingForKey;
} else {
cfg.resetControlsToDefault();
cfg.save();
showToast("Reset Controls to Default");
}
}
renderScreen();
} else if (isPress && uiState == UiState::RomBrowser) {
if (sym == XK_Escape || sym == XK_BackSpace) {
if (romLoaded) {
uiState = UiState::PauseMenu;
renderScreen();
} else {
gRunning = 0;
}
} else if (sym == XK_Up || sym == XK_KP_Up) {
if (!browserEntries.empty()) {
int n = static_cast<int>(browserEntries.size());
romBrowserSel = (romBrowserSel + n - 1) % n;
renderScreen();
}
} else if (sym == XK_Down || sym == XK_KP_Down) {
if (!browserEntries.empty()) {
int n = static_cast<int>(browserEntries.size());
romBrowserSel = (romBrowserSel + 1) % n;
renderScreen();
}
} else if (sym == XK_Return || sym == XK_KP_Enter) {
if (!browserEntries.empty() && romBrowserSel >= 0 &&
romBrowserSel < static_cast<int>(browserEntries.size())) {
RomEntry chosen = browserEntries[romBrowserSel];
if (chosen.isDir) {
populateRomBrowser(chosen.fullPath);
} else if (loadRomFile(chosen.fullPath)) {
uiState = UiState::Playing;
}
renderScreen();
}
}
}
}
}
if (keyboardGrabbed && softkeyPending != 0 && nowMs() >= softkeyDeadlineMs) {
int comb = softkeyPending | querySoftkeysDown(dpy);
softkeyPending = 0;
softkeyDeadlineMs = 0;
if (comb == 3) {
unfocusWindow(true);
} else if (comb == 1) { // Left Softkey
if (uiState == UiState::Playing) {
saveBatterySram();
audioOut.stop();
pauseMenuSel = 0;
uiState = UiState::PauseMenu;
} else if (uiState == UiState::PauseMenu) {
handlePauseMenuExec();
} else if (uiState == UiState::ControlsMenu) {
if (controlsSel < ACT_COUNT) {
uiState = UiState::WaitingForKey;
} else {
cfg.resetControlsToDefault();
cfg.save();
showToast("Reset Controls to Default");
}
} else if (uiState == UiState::RomBrowser) {
controlsSel = 0;
uiState = UiState::ControlsMenu;
}
renderScreen();
} else if (comb == 2) { // Right Softkey
if (uiState == UiState::Playing) {
saveBatterySram();
audioOut.stop();
pauseMenuSel = 0;
uiState = UiState::PauseMenu;
renderScreen();
} else if (uiState == UiState::PauseMenu) {
uiState = UiState::Playing;
renderScreen();
} else if (uiState == UiState::WaitingForKey) {
uiState = UiState::ControlsMenu;
renderScreen();
} else if (uiState == UiState::ControlsMenu) {
uiState = romLoaded ? UiState::PauseMenu : UiState::RomBrowser;
renderScreen();
} else if (uiState == UiState::RomBrowser) {
if (romLoaded) {
uiState = UiState::PauseMenu;
renderScreen();
} else {
gRunning = 0;
}
}
}
}
if (keyboardGrabbed && uiState == UiState::Playing && romLoaded) {
bool justStartedAudio = false;
if (cfg.audioEnabled) {
if (!audioOut.isOpen()) {
audioOut.start();
if (tfd >= 0) {
uint64_t drainExp = 0;
(void)::read(tfd, &drainExp, sizeof(drainExp));
timerfd_settime(tfd, 0, &its, nullptr);
}
justStartedAudio = true;
} else {
audioOut.refreshVolumeIfNeeded(nowMs());
}
} else if (audioOut.isOpen()) {
audioOut.stop();
}
uint64_t exp = 0;
if (justStartedAudio) {
exp = 4; // 1 full video frame (4 * 8778 = 35112 GB samples)
} else {
struct pollfd pfds[2] = {
{xfd, POLLIN, 0},
{tfd, POLLIN, 0}
};
int pr = ::poll(pfds, (tfd >= 0) ? 2 : 1, 6);
exp = (tfd < 0) ? 1 : 0;
if (pr > 0 && tfd >= 0 && (pfds[1].revents & POLLIN)) {
(void)::read(tfd, &exp, sizeof(exp));
}
}
if (exp > 0) {
int catchup = static_cast<int>(std::min<uint64_t>(exp, 12));
int slicesToRun = actionDown[ACT_FAST_FWD] ? (catchup * 2) : catchup;
for (int s = 0; s < slicesToRun; ++s) {
++subSliceCount;
bool turboPulse = (((subSliceCount >> 2) & 2u) == 0);
unsigned pad = 0;
if (actionDown[ACT_A] || (actionDown[ACT_TURBO_A] && turboPulse)) {
pad |= gambatte::InputGetter::A;
}
if (actionDown[ACT_B] || (actionDown[ACT_TURBO_B] && turboPulse)) {
pad |= gambatte::InputGetter::B;
}
if (actionDown[ACT_START]) pad |= gambatte::InputGetter::START;
if (actionDown[ACT_SELECT]) pad |= gambatte::InputGetter::SELECT;
if (actionDown[ACT_UP]) pad |= gambatte::InputGetter::UP;
if (actionDown[ACT_DOWN]) pad |= gambatte::InputGetter::DOWN;
if (actionDown[ACT_LEFT]) pad |= gambatte::InputGetter::LEFT;
if (actionDown[ACT_RIGHT]) pad |= gambatte::InputGetter::RIGHT;
inputGetter.state = pad;
bool writeAudio =
cfg.audioEnabled && (!actionDown[ACT_FAST_FWD] || (s & 1) == 0);
// 35112 / 4 = 8778 GB samples per 4.185 ms slice.
// Loop until all 8778 samples of the slice are produced even if
// gb.runFor returns early at a VBlank boundary.
unsigned remaining = 8778;
while (remaining > 0) {
unsigned chunk = remaining;
long blit = gb.runFor(gbFrame.data(), kGbW, soundBuf.data(),
soundBuf.size(), chunk);
if (writeAudio && chunk > 0) {
audioOut.writeGbSamples(soundBuf.data(), chunk);
}
samplesSinceRender += chunk;
if (blit >= 0) {
++frameCount;
samplesSinceRender = 0;
if ((frameCount & 1u) == 0) {
renderScreen(false);
}
} else if (samplesSinceRender >= 70224) {
++frameCount;
samplesSinceRender = 0;
renderScreen(false);
}
if (chunk == 0 || chunk >= remaining) {
break;
}
remaining -= chunk;
}
}
if (nowMs() - lastSramFlushMs >= 5000) {
saveBatterySram();
lastSramFlushMs = nowMs();
}
}
} else {
if (audioOut.isOpen()) {
audioOut.stop();
}
struct pollfd pfd {xfd, POLLIN, 0};
::poll(&pfd, 1, 40);
}
}
saveBatterySram();
audioOut.stop();
writeSoftkeySuppress(nowMs() + 350);
if (tfd >= 0) ::close(tfd);
ximg->data = nullptr;
XDestroyImage(ximg);
XUngrabKeyboard(dpy, CurrentTime);
XFreeGC(dpy, gc);
XFreePixmap(dpy, pix);
XDestroyWindow(dpy, win);
XCloseDisplay(dpy);
return 0;
}