Add Bluetooth audio/HID/discoverability/alias support, fix SD card hotplug & caller ID matching, and expand ReMEdy J2ME JSRs + 64MB GC

This commit is contained in:
Luxferre committed 2026-11-01 16:18:04 +02:00
1 parent 456d3fbc42
commit 471916424e
51 files changed
+2961 -305

No files matched your search

+7 -6
View File
@@ -44,12 +44,13 @@ struct BtSendTarget {
std::vector<BtSendTarget> queryBtSendTargets(bool scanFirst = false) {
std::string rfk = runCaptureCmd("/usr/sbin/rfkill list bluetooth 2>/dev/null");
if (rfk.find("Soft blocked: yes") != std::string::npos ||
if (::access("/run/bluetoothd.pid", F_OK) != 0 ||
rfk.find("Soft blocked: yes") != std::string::npos ||
rfk.find("Hard blocked: yes") != std::string::npos) {
runCaptureCmd("SXMO_OS=alpine doas -n sxmo_bluetoothtoggle.sh on >/dev/null 2>&1");
}
if (scanFirst) {
runCaptureCmd("bluetoothctl --timeout 4 scan on >/dev/null 2>&1");
runCaptureCmd("timeout 5 bluetoothctl --timeout 4 scan on >/dev/null 2>&1");
}
std::unordered_set<std::string> pairedMacs;
std::unordered_set<std::string> connectedMacs;
@@ -62,14 +63,14 @@ std::vector<BtSendTarget> queryBtSendTargets(bool scanFirst = false) {
}
}
};
parseSet(runCaptureCmd("bluetoothctl devices Paired 2>/dev/null || "
"bluetoothctl paired-devices 2>/dev/null"),
parseSet(runCaptureCmd("timeout 2 bluetoothctl devices Paired 2>/dev/null || "
"timeout 2 bluetoothctl paired-devices 2>/dev/null"),
pairedMacs);
parseSet(runCaptureCmd("bluetoothctl devices Connected 2>/dev/null"),
parseSet(runCaptureCmd("timeout 2 bluetoothctl devices Connected 2>/dev/null"),
connectedMacs);
std::vector<BtSendTarget> out;
std::string allRaw = runCaptureCmd("bluetoothctl devices 2>/dev/null");
std::string allRaw = runCaptureCmd("timeout 2 bluetoothctl devices 2>/dev/null");
std::istringstream ss(allRaw);
std::string line;
while (std::getline(ss, line)) {
+532 -85
View File
@@ -38,6 +38,20 @@ enum class NetModal {
WifiPassword = 2,
ApnEditor = 3,
BtActions = 4,
BtNameEditor = 5,
};
constexpr const char* kIconHeadphones = "\xef\x80\xa5"; // U+F025 headphones
constexpr const char* kIconKeyboard = "\xef\x84\x9c"; // U+F11C keyboard
constexpr const char* kIconMouse = "\xef\x89\x85"; // U+F245 mouse pointer
enum class BtDevKind {
Generic = 0,
Audio = 1,
Gamepad = 2,
Keyboard = 3,
Mouse = 4,
Phone = 5,
};
enum class TextMode {
@@ -109,8 +123,76 @@ struct BtDeviceEntry {
std::string name;
bool paired = false;
bool connected = false;
BtDevKind kind = BtDevKind::Generic;
std::string profileLabel;
int batteryPct = -1;
};
struct BtControllerState {
std::string name = "Bananarchy";
bool discoverable = true;
int activeCount = 0;
std::string activeSummary;
};
std::string getSystemHostname() {
char buf[128] = {};
if (::gethostname(buf, sizeof(buf) - 1) == 0 && buf[0] != '\0') {
std::string h = trimStr(buf);
if (!h.empty()) return h;
}
std::ifstream in("/etc/hostname");
std::string line;
if (in.is_open() && std::getline(in, line)) {
line = trimStr(line);
if (!line.empty()) return line;
}
return "Bananarchy";
}
std::string readSavedBtName() {
std::string path = getHomeDirPath() + "/.config/sxmo/bt_name";
std::ifstream in(path);
std::string line;
if (in.is_open() && std::getline(in, line)) {
line = trimStr(line);
if (!line.empty()) return line;
}
return getSystemHostname();
}
void writeSavedBtName(const std::string& name) {
std::string dir = getHomeDirPath() + "/.config/sxmo";
::mkdir(dir.c_str(), 0755);
std::ofstream out(dir + "/bt_name", std::ios::trunc);
if (out.is_open()) {
out << name << "\n";
}
}
bool readSavedBtDiscoverable() {
std::string path = getHomeDirPath() + "/.config/sxmo/bt_discoverable";
std::ifstream in(path);
std::string line;
if (in.is_open() && std::getline(in, line)) {
std::string v = toLowerStr(trimStr(line));
if (v == "0" || v == "off" || v == "no" || v == "false") {
return false;
}
if (!v.empty()) return true;
}
return true;
}
void writeSavedBtDiscoverable(bool disc) {
std::string dir = getHomeDirPath() + "/.config/sxmo";
::mkdir(dir.c_str(), 0755);
std::ofstream out(dir + "/bt_discoverable", std::ios::trunc);
if (out.is_open()) {
out << (disc ? "1\n" : "0\n");
}
}
struct BtRxStatus {
std::string state = "IDLE";
std::string fileName;
@@ -162,6 +244,9 @@ bool isWifiEnabledFast() {
}
bool isBtEnabledFast() {
if (::access("/run/bluetoothd.pid", F_OK) != 0) {
return false;
}
std::string out = runCaptureCmd("/usr/sbin/rfkill list bluetooth 2>/dev/null");
if (out.find("Soft blocked: yes") != std::string::npos ||
out.find("Hard blocked: yes") != std::string::npos) {
@@ -324,6 +409,17 @@ CellularNetInfo queryCellularInfo() {
return info;
}
const char* iconForBtDevice(const BtDeviceEntry& d) {
switch (d.kind) {
case BtDevKind::Audio: return kIconHeadphones;
case BtDevKind::Gamepad: return kIconGamepad;
case BtDevKind::Keyboard: return kIconKeyboard;
case BtDevKind::Mouse: return kIconMouse;
case BtDevKind::Phone: return kIconPhone;
default: return kIconBluetooth;
}
}
std::vector<BtDeviceEntry> queryBtDevices() {
std::vector<BtDeviceEntry> out;
std::unordered_set<std::string> pairedMacs;
@@ -334,22 +430,27 @@ std::vector<BtDeviceEntry> queryBtDevices() {
std::istringstream ss(raw);
std::string line;
while (std::getline(ss, line)) {
// Format: "Device XX:XX:XX:XX:XX:XX Name..."
if (line.rfind("Device ", 0) == 0 && line.size() >= 24) {
dst.insert(line.substr(7, 17));
}
}
};
parseMacSet(runCaptureCmd("bluetoothctl devices Paired 2>/dev/null || "
"bluetoothctl paired-devices 2>/dev/null"),
parseMacSet(runCaptureCmd("timeout 2 bluetoothctl devices Paired 2>/dev/null || "
"timeout 2 bluetoothctl paired-devices 2>/dev/null"),
pairedMacs);
parseMacSet(runCaptureCmd("bluetoothctl devices Connected 2>/dev/null"),
parseMacSet(runCaptureCmd("timeout 2 bluetoothctl devices Connected 2>/dev/null"),
connectedMacs);
std::string allRaw = runCaptureCmd("bluetoothctl devices 2>/dev/null");
std::string paRaw = runCaptureCmd(
"pactl list sinks short 2>/dev/null; pactl list sources short 2>/dev/null");
std::string allRaw = runCaptureCmd("timeout 2 bluetoothctl devices 2>/dev/null");
std::istringstream ss(allRaw);
std::string line;
std::string infoCmd;
int infoCount = 0;
while (std::getline(ss, line)) {
if (line.rfind("Device ", 0) != 0 || line.size() < 24) continue;
BtDeviceEntry d;
@@ -358,6 +459,115 @@ std::vector<BtDeviceEntry> queryBtDevices() {
d.paired = (pairedMacs.count(d.mac) > 0);
d.connected = (connectedMacs.count(d.mac) > 0);
out.push_back(d);
if ((d.connected || d.paired) && infoCount < 12) {
infoCmd += "printf '===BTDEV %s===\\n' " + shellQuote(d.mac) +
"; timeout 1 bluetoothctl info " + shellQuote(d.mac) +
" 2>/dev/null; ";
++infoCount;
}
}
std::unordered_map<std::string, std::string> infoByMac;
if (!infoCmd.empty()) {
std::string batchInfo = runCaptureCmd(infoCmd);
std::istringstream iss(batchInfo);
std::string iline;
std::string curMac;
while (std::getline(iss, iline)) {
if (iline.rfind("===BTDEV ", 0) == 0 && iline.size() >= 26) {
curMac = iline.substr(9, 17);
} else if (!curMac.empty()) {
infoByMac[curMac] += iline + "\n";
}
}
}
for (auto& d : out) {
std::string macU = d.mac;
for (char& c : macU) {
if (c == ':') c = '_';
}
bool hasPaSink = (paRaw.find("bluez_output." + macU) != std::string::npos);
bool hasPaSrc = (paRaw.find("bluez_input." + macU) != std::string::npos);
std::string info = infoByMac[d.mac];
std::string infoLow = toLowerStr(info);
std::string nameLow = toLowerStr(d.name);
bool hasA2dp = (infoLow.find("0000110b-") != std::string::npos ||
infoLow.find("0000110a-") != std::string::npos ||
infoLow.find("audio sink") != std::string::npos ||
infoLow.find("audio source") != std::string::npos);
bool hasHfp = (infoLow.find("00001108-") != std::string::npos ||
infoLow.find("00001112-") != std::string::npos ||
infoLow.find("0000111e-") != std::string::npos ||
infoLow.find("0000111f-") != std::string::npos ||
infoLow.find("handsfree") != std::string::npos ||
infoLow.find("headset") != std::string::npos);
bool hasHid = (infoLow.find("00001124-") != std::string::npos ||
infoLow.find("00001812-") != std::string::npos ||
infoLow.find("human interface device") != std::string::npos);
if (infoLow.find("icon: input-gaming") != std::string::npos ||
infoLow.find("icon: input-joystick") != std::string::npos ||
nameLow.find("gamepad") != std::string::npos ||
nameLow.find("controller") != std::string::npos ||
nameLow.find("joy-con") != std::string::npos ||
nameLow.find("dualshock") != std::string::npos ||
nameLow.find("dualsense") != std::string::npos ||
nameLow.find("8bitdo") != std::string::npos ||
nameLow.find("xbox") != std::string::npos) {
d.kind = BtDevKind::Gamepad;
d.profileLabel = "HID Gamepad";
} else if (infoLow.find("icon: input-keyboard") != std::string::npos ||
nameLow.find("keyboard") != std::string::npos ||
nameLow.find("keychron") != std::string::npos) {
d.kind = BtDevKind::Keyboard;
d.profileLabel = "HID Keyboard";
} else if (infoLow.find("icon: input-mouse") != std::string::npos ||
infoLow.find("icon: input-tablet") != std::string::npos ||
nameLow.find("mouse") != std::string::npos ||
nameLow.find("trackpad") != std::string::npos) {
d.kind = BtDevKind::Mouse;
d.profileLabel = "HID Mouse";
} else if (hasPaSink || hasPaSrc || hasA2dp || hasHfp ||
infoLow.find("icon: audio-") != std::string::npos) {
d.kind = BtDevKind::Audio;
if (d.connected) {
if (hasPaSrc) {
d.profileLabel = "HSP/HFP";
} else if (hasPaSink) {
d.profileLabel = "A2DP";
} else if (hasA2dp && hasHfp) {
d.profileLabel = "A2DP+HFP";
} else if (hasHfp) {
d.profileLabel = "HSP/HFP";
} else {
d.profileLabel = "A2DP";
}
} else {
if (hasA2dp && hasHfp) d.profileLabel = "Audio A2DP/HFP";
else if (hasHfp) d.profileLabel = "Audio HSP/HFP";
else d.profileLabel = "Audio A2DP";
}
} else if (hasHid) {
d.kind = BtDevKind::Keyboard;
d.profileLabel = "HID Input";
} else if (infoLow.find("icon: phone") != std::string::npos ||
infoLow.find("icon: computer") != std::string::npos) {
d.kind = BtDevKind::Phone;
d.profileLabel = "OBEX/PAN";
}
size_t batPos = info.find("Battery Percentage:");
if (batPos != std::string::npos) {
size_t lp = info.find('(', batPos);
size_t rp = info.find(')', batPos);
if (lp != std::string::npos && rp != std::string::npos && rp > lp + 1) {
d.batteryPct = std::clamp(
std::atoi(info.substr(lp + 1, rp - lp - 1).c_str()), 0, 100);
}
}
}
std::sort(out.begin(), out.end(),
@@ -369,6 +579,48 @@ std::vector<BtDeviceEntry> queryBtDevices() {
return out;
}
BtControllerState queryBtController(bool btOn,
const std::vector<BtDeviceEntry>& devs) {
BtControllerState st;
st.name = readSavedBtName();
st.discoverable = readSavedBtDiscoverable();
if (btOn) {
std::string showOut = runCaptureCmd("timeout 2 bluetoothctl show 2>/dev/null");
std::istringstream ss(showOut);
std::string line;
while (std::getline(ss, line)) {
std::string t = trimStr(line);
if (t.rfind("Discoverable:", 0) == 0) {
std::string v = toLowerStr(trimStr(t.substr(13)));
if (v == "yes") st.discoverable = true;
else if (v == "no") st.discoverable = false;
} else if (t.rfind("Alias:", 0) == 0) {
std::string al = trimStr(t.substr(6));
if (!al.empty() && al.rfind("BlueZ", 0) != 0 &&
::access((getHomeDirPath() + "/.config/sxmo/bt_name").c_str(), F_OK) != 0) {
st.name = al;
}
}
}
}
for (const auto& d : devs) {
if (!d.connected) continue;
++st.activeCount;
std::string item = d.name;
if (!d.profileLabel.empty()) {
item += " (" + d.profileLabel + ")";
}
if (st.activeSummary.empty()) {
st.activeSummary = item;
} else {
st.activeSummary += ", " + item;
}
}
return st;
}
int runNetworksApp(int argc, char** argv) {
gRunning = 1;
std::setlocale(LC_ALL, "");
@@ -448,8 +700,10 @@ int runNetworksApp(int argc, char** argv) {
bool btOn = false;
std::vector<BtDeviceEntry> btList;
BtControllerState btCtrl;
BtRxStatus btRx;
int btRowSel = 0; // 0 = BT Power Toggle, 1 = Scan Devices, 2 = File Reception Widget, 3..N = BT devices
std::string btNameEdit;
int btRowSel = 0; // 0=Power, 1=Discoverable, 2=Device Name, 3=Scan, 4=OBEX Rx, 5..N=Devices
int actionSel = 0;
@@ -503,16 +757,19 @@ int runNetworksApp(int argc, char** argv) {
} else if (activeTab == NetTab::Bluetooth) {
btOn = isBtEnabledFast();
if (btOn) {
runAsyncCmd("/usr/bin/bananarchy-bt-obex start >/dev/null 2>&1");
if (::access("/tmp/bananarchy_bt_obex.pid", F_OK) != 0) {
runAsyncCmd("/usr/bin/bananarchy-bt-obex start >/dev/null 2>&1");
}
btRx = readBtRxStatus();
if (forceScan) {
runCaptureCmd("bluetoothctl --timeout 5 scan on >/dev/null 2>&1");
runCaptureCmd("timeout 6 bluetoothctl --timeout 5 scan on >/dev/null 2>&1");
}
btList = queryBtDevices();
} else {
btList.clear();
}
int maxRow = btOn ? (2 + static_cast<int>(btList.size())) : 1;
btCtrl = queryBtController(btOn, btList);
int maxRow = btOn ? (4 + static_cast<int>(btList.size())) : 2;
if (btRowSel > maxRow) btRowSel = maxRow;
}
};
@@ -729,96 +986,146 @@ int runNetworksApp(int argc, char** argv) {
}
drawSoftkeyBar("Refresh", "Select", "Close");
} else if (activeTab == NetTab::Bluetooth) {
// Row 0: BT Power Toggle (height 26)
// Row 0: BT Power Toggle + Active Connection Badge (height 22)
bool sel0 = (btRowSel == 0);
XSetForeground(dpy, gc, sel0 ? pt.spec.selBg : pt.spec.bgAltEven);
XFillRectangle(dpy, pix, gc, 4, contentY, kWinWidth - 8, 26);
drawPango(layoutIcon, btOn ? &colBlue : &colMuted, 10, contentY, 26, kIconBluetooth);
drawPango(layoutMain, sel0 ? &colWhite : &colLight,
30, contentY, 26, std::string("Bluetooth: ") + (btOn ? "ON" : "OFF"));
XFillRectangle(dpy, pix, gc, 4, contentY, kWinWidth - 8, 22);
drawPango(layoutIcon, btOn ? &colBlue : &colMuted, 10, contentY, 22, kIconBluetooth);
std::string btPowerLbl = std::string("Bluetooth: ") + (btOn ? "ON" : "OFF");
if (btOn) {
btPowerLbl += (btCtrl.activeCount > 0)
? (" (" + std::to_string(btCtrl.activeCount) + " Active)")
: " (Idle)";
}
drawPango(layoutSmall, sel0 ? &colWhite : (btCtrl.activeCount > 0 ? &colGreen : &colLight),
28, contentY, 22, btPowerLbl, kWinWidth - 58);
drawPango(layoutIcon, btOn ? &colGreen : &colMuted,
kWinWidth - 28, contentY, 26, btOn ? kIconToggleOn : kIconToggleOff);
kWinWidth - 26, contentY, 22, btOn ? kIconToggleOn : kIconToggleOff);
// Row 1: Scan for Devices (height 24)
// Row 1: Discoverability Toggle (height 22)
bool sel1 = (btRowSel == 1);
int r1Y = contentY + 23;
XSetForeground(dpy, gc, sel1 ? pt.spec.selBg : pt.spec.bgAltOdd);
XFillRectangle(dpy, pix, gc, 4, contentY + 28, kWinWidth - 8, 24);
drawPango(layoutIcon, &colYellow, 10, contentY + 28, 24, kIconSearch);
XFillRectangle(dpy, pix, gc, 4, r1Y, kWinWidth - 8, 22);
drawPango(layoutIcon, btCtrl.discoverable ? &colGreen : &colMuted,
10, r1Y, 22, kIconEye);
drawPango(layoutSmall, sel1 ? &colWhite : &colLight,
30, contentY + 28, 24, "Scan for Bluetooth Devices");
28, r1Y, 22,
std::string("Discoverable: ") +
(btCtrl.discoverable ? "ON (Visible)" : "OFF (Hidden)"),
kWinWidth - 58);
drawPango(layoutIcon, btCtrl.discoverable ? &colGreen : &colMuted,
kWinWidth - 26, r1Y, 22,
btCtrl.discoverable ? kIconToggleOn : kIconToggleOff);
// Row 2: Bluetooth Device Name (height 22)
bool sel2 = (btRowSel == 2);
int r2Y = contentY + 46;
XSetForeground(dpy, gc, sel2 ? pt.spec.selBg : pt.spec.bgAltEven);
XFillRectangle(dpy, pix, gc, 4, r2Y, kWinWidth - 8, 22);
drawPango(layoutIcon, &colYellow, 10, r2Y, 22, kIconEdit);
drawPango(layoutSmall, sel2 ? &colWhite : &colLight,
28, r2Y, 22, "Name: " + btCtrl.name, kWinWidth - 66);
drawPango(layoutSmall, sel2 ? &colYellow : &colMuted,
kWinWidth - 38, r2Y, 22, "[Edit]");
if (!btOn) {
drawPango(layoutMain, &colMuted, 18, contentY + 96, 24,
drawPango(layoutMain, &colMuted, 18, contentY + 102, 24,
"Bluetooth is turned off.");
drawPango(layoutSmall, &colMuted, 18, contentY + 128, 20,
"Visibility & Name apply on start.");
} else {
// Row 2: Bluetooth File Reception Widget (height 36)
bool sel2 = (btRowSel == 2);
int rxY = contentY + 54;
XSetForeground(dpy, gc, sel2 ? pt.spec.selBg : pt.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 4, rxY, kWinWidth - 8, 36);
// Row 3: Scan for Devices + Active Summary (height 22)
bool sel3 = (btRowSel == 3);
int r3Y = contentY + 69;
XSetForeground(dpy, gc, sel3 ? pt.spec.selBg : pt.spec.bgAltOdd);
XFillRectangle(dpy, pix, gc, 4, r3Y, kWinWidth - 8, 22);
drawPango(layoutIcon, &colYellow, 10, r3Y, 22, kIconSearch);
std::string scanLbl = (btCtrl.activeCount > 0)
? ("Scan [Active: " + btCtrl.activeSummary + "]")
: "Scan for Bluetooth Devices";
drawPango(layoutSmall, sel3 ? &colWhite : (btCtrl.activeCount > 0 ? &colGreen : &colLight),
28, r3Y, 22, scanLbl, kWinWidth - 34);
// Row 4: Compact OBEX File Reception Bar (height 22)
bool sel4 = (btRowSel == 4);
int rxY = contentY + 92;
XSetForeground(dpy, gc, sel4 ? pt.spec.selBg : pt.spec.bgHeader);
XFillRectangle(dpy, pix, gc, 4, rxY, kWinWidth - 8, 22);
XSetForeground(dpy, gc, btRx.state == "RECEIVING" ? pt.spec.warning
: (btRx.state == "RECEIVED" ? pt.spec.success : pt.spec.accent));
XDrawRectangle(dpy, pix, gc, 4, rxY, kWinWidth - 9, 35);
: (btRx.state == "RECEIVED" ? pt.spec.success : pt.spec.border));
XDrawRectangle(dpy, pix, gc, 4, rxY, kWinWidth - 9, 21);
drawPango(layoutIcon,
btRx.state == "RECEIVED" ? &colGreen
: (btRx.state == "RECEIVING" ? &colYellow : &colBlue),
10, rxY + 1, 18,
10, rxY, 22,
btRx.state == "RECEIVED" ? kIconCheck : kIconFolderOpen);
if (btRx.state == "RECEIVING") {
drawPango(layoutSmall, &colYellow, 30, rxY + 1, 18,
"Receiving: " + btRx.fileName + " (" + btRx.detail + ")",
kWinWidth - 38);
int barW = kWinWidth - 42;
XSetForeground(dpy, gc, pt.spec.bgInput);
XFillRectangle(dpy, pix, gc, 30, rxY + 22, barW, 8);
int fillW = (barW * std::clamp(btRx.pct, 0, 100)) / 100;
XSetForeground(dpy, gc, pt.spec.success);
XFillRectangle(dpy, pix, gc, 30, rxY + 22, fillW, 8);
drawPango(layoutSmall, &colYellow, 28, rxY, 22,
"Rx: " + btRx.fileName + " (" + btRx.detail + ")",
kWinWidth - 34);
} else if (btRx.state == "RECEIVED") {
drawPango(layoutSmall, &colGreen, 30, rxY + 1, 18,
"Received: " + btRx.fileName, kWinWidth - 38);
drawPango(layoutSmall, sel2 ? &colWhite : &colLight, 30, rxY + 18, 16,
btRx.detail + " [OK: Open in Files]", kWinWidth - 38);
drawPango(layoutSmall, sel4 ? &colWhite : &colGreen, 28, rxY, 22,
"Received: " + btRx.fileName + " [Open]",
kWinWidth - 34);
} else {
drawPango(layoutSmall, sel2 ? &colWhite : &colYellow, 30, rxY + 1, 18,
"File Receive: Ready (OBEX Push)", kWinWidth - 38);
drawPango(layoutSmall, sel2 ? &colLight : &colMuted, 30, rxY + 18, 16,
"Saves to ~/Downloads [OK: Open]", kWinWidth - 38);
drawPango(layoutSmall, sel4 ? &colWhite : &colMuted, 28, rxY, 22,
"OBEX Receive: ~/Downloads [Open]",
kWinWidth - 34);
}
int listY = contentY + 92;
int listH = contentH - 92;
int listY = contentY + 116;
int listH = contentH - 116;
if (btList.empty()) {
drawPango(layoutMain, &colMuted, 18, listY + 34, 24,
"No devices. Select Scan.");
drawPango(layoutSmall, &colMuted, 18, listY + 30, 22,
"No devices found. Press Scan.");
} else {
const int rowH = 36;
const int maxVis = std::max(1, listH / rowH);
int devSel = std::max(0, btRowSel - 3);
const int rowH = 38;
const int maxVis = std::max(1, listH / rowH); // 3 rows
int devSel = std::max(0, btRowSel - 5);
int startIdx = std::clamp(devSel - maxVis / 2, 0,
std::max(0, static_cast<int>(btList.size()) - maxVis));
for (int i = 0; i < maxVis && (startIdx + i) < static_cast<int>(btList.size()); ++i) {
int idx = startIdx + i;
const auto& d = btList[idx];
int ry = listY + i * rowH;
bool isSel = (btRowSel == (idx + 3));
bool isSel = (btRowSel == (idx + 5));
XSetForeground(dpy, gc, isSel ? pt.spec.selBg
: ((i % 2 == 0) ? pt.spec.bgAltEven : pt.spec.bgAltOdd));
XFillRectangle(dpy, pix, gc, 4, ry, kWinWidth - 8, rowH - 2);
if (d.connected) {
XSetForeground(dpy, gc, pt.spec.success);
XDrawRectangle(dpy, pix, gc, 4, ry, kWinWidth - 9, rowH - 3);
}
drawPango(layoutIcon, d.connected ? &colGreen : (d.paired ? &colBlue : &colMuted),
10, ry + 1, 18, kIconBluetooth);
10, ry + 1, 18, iconForBtDevice(d));
int nameMaxW = (d.batteryPct >= 0) ? (kWinWidth - 76) : (kWinWidth - 38);
drawPango(layoutMain, isSel ? &colWhite : &colLight,
30, ry + 1, 18, d.name, kWinWidth - 42);
28, ry + 1, 18, d.name, nameMaxW);
if (d.batteryPct >= 0) {
std::string batStr = std::to_string(d.batteryPct) + "%";
drawPango(layoutSmall, &colGreen, kWinWidth - 40, ry + 2, 16, batStr);
}
std::string st = d.connected ? "[Connected] "
: (d.paired ? "[Paired] " : "[Available] ");
std::string st;
if (d.connected) {
st = "[ACTIVE: " +
(d.profileLabel.empty() ? std::string("Connected") : d.profileLabel) +
"] ";
} else if (d.paired) {
st = "[Paired" +
(d.profileLabel.empty() ? std::string("") : (": " + d.profileLabel)) +
"] ";
} else {
st = "[Available] ";
}
st += d.mac;
drawPango(layoutSmall, d.connected ? &colGreen : (isSel ? &colLight : &colMuted),
30, ry + 18, 16, st, kWinWidth - 42);
28, ry + 19, 16, st, kWinWidth - 36);
}
}
}
@@ -938,26 +1245,69 @@ int runNetworksApp(int argc, char** argv) {
drawSoftkeyBar("Save", "Select", "Cancel");
} else if (modal == NetModal::BtActions) {
XSetForeground(dpy, gc, pt.spec.bgOverlay);
XFillRectangle(dpy, pix, gc, 12, 48, kWinWidth - 24, 174);
XFillRectangle(dpy, pix, gc, 10, 40, kWinWidth - 20, 194);
XSetForeground(dpy, gc, pt.spec.accent);
XDrawRectangle(dpy, pix, gc, 12, 48, kWinWidth - 25, 173);
XDrawRectangle(dpy, pix, gc, 10, 40, kWinWidth - 21, 193);
drawPango(layoutMain, &colYellow, 20, 52, 24, targetBt.name, kWinWidth - 40);
const char* acts[4] = {
drawPango(layoutMain, &colYellow, 18, 44, 22, targetBt.name, kWinWidth - 36);
const char* acts[5] = {
"Connect Device",
"Disconnect Device",
"Pair & Trust Device",
"Switch Audio (A2DP / HSP-HFP)",
"Forget / Remove Device",
};
for (int i = 0; i < 4; ++i) {
int ry = 82 + i * 32;
for (int i = 0; i < 5; ++i) {
int ry = 70 + i * 31;
bool isSel = (actionSel == i);
XSetForeground(dpy, gc, isSel ? pt.spec.selBg : pt.spec.bgButton);
XFillRectangle(dpy, pix, gc, 18, ry, kWinWidth - 36, 28);
XFillRectangle(dpy, pix, gc, 16, ry, kWinWidth - 32, 27);
drawPango(layoutSmall, isSel ? &colWhite : &colLight,
24, ry, 28, acts[i], kWinWidth - 48);
22, ry, 27, acts[i], kWinWidth - 44);
}
drawSoftkeyBar("Select", "OK", "Back");
} else if (modal == NetModal::BtNameEditor) {
XSetForeground(dpy, gc, pt.spec.bgOverlay);
XFillRectangle(dpy, pix, gc, 10, 42, kWinWidth - 20, 198);
XSetForeground(dpy, gc, pt.spec.accent);
XDrawRectangle(dpy, pix, gc, 10, 42, kWinWidth - 21, 197);
drawPango(layoutMain, &colYellow, 18, 48, 22,
"Bluetooth Name", kWinWidth - 80);
drawPango(layoutSmall, &colBlue, kWinWidth - 58, 48, 22,
std::string("[") + textModeLabel() + "]");
drawPango(layoutSmall, &colLight, 18, 74, 20,
"Visible name on other devices:");
XSetForeground(dpy, gc, pt.spec.bgInputFocus);
XFillRectangle(dpy, pix, gc, 18, 98, kWinWidth - 36, 34);
XSetForeground(dpy, gc, pt.spec.accent);
XDrawRectangle(dpy, pix, gc, 18, 98, kWinWidth - 37, 33);
std::string dispFit =
tailFitPangoText(layoutMain, btNameEdit + "_", kWinWidth - 48);
drawPango(layoutMain, &colWhite, 24, 98, 34, dispFit, kWinWidth - 48);
if (lastTapDigit >= 0 && lastTapDigit <= 9 &&
(nowMs() - lastTapMs) <= 850) {
const char* seq = (textMode == TextMode::Sym)
? kSymTapMap[lastTapDigit]
: kMultiTapMap[lastTapDigit];
std::string cand = formatMultiTapBar(
std::to_string(lastTapDigit) + ":", seq, lastTapCycle,
textMode == TextMode::Upper, 6, 19);
drawPango(layoutSmall, &colYellow, 18, 142, 18, cand, kWinWidth - 36);
} else {
drawPango(layoutSmall, &colMuted, 18, 142, 18,
"# Input mode", kWinWidth - 36);
}
drawPango(layoutSmall, &colMuted, 18, 162, 18,
"[BackSpace] Delete character");
drawPango(layoutSmall, &colMuted, 18, 182, 18,
"Independent from system hostname");
drawSoftkeyBar("Save", "Save", "Cancel");
}
if (!statusBanner.empty() && nowMs() < statusBannerUntilMs) {
@@ -1113,35 +1463,96 @@ int runNetworksApp(int argc, char** argv) {
}
};
auto saveBtDeviceName = [&]() {
std::string clean = trimStr(btNameEdit);
if (clean.empty()) {
clean = getSystemHostname();
}
modal = NetModal::None;
writeSavedBtName(clean);
btCtrl.name = clean;
if (btOn) {
runCaptureCmd("timeout 2 bluetoothctl system-alias " + shellQuote(clean) +
" >/dev/null 2>&1");
}
refreshCurrentTab(false);
setBanner("Bluetooth name: " + clean);
};
auto toggleBtDiscoverable = [&]() {
bool nextDisc = !btCtrl.discoverable;
writeSavedBtDiscoverable(nextDisc);
btCtrl.discoverable = nextDisc;
if (btOn) {
runCaptureCmd("timeout 2 bluetoothctl discoverable-timeout 0 >/dev/null 2>&1; "
"timeout 2 bluetoothctl discoverable " +
std::string(nextDisc ? "on" : "off") + " >/dev/null 2>&1");
}
refreshCurrentTab(false);
setBanner(nextDisc ? "Bluetooth: Visible to nearby devices"
: "Bluetooth: Hidden from discovery");
};
auto executeBtAction = [&](int act) {
modal = NetModal::None;
int rc = 0;
if (act == 0) {
setBanner("Connecting " + targetBt.name + "...");
render();
runCaptureCmd("bluetoothctl connect " + shellQuote(targetBt.mac) +
runCaptureCmd("timeout 8 bluetoothctl connect " + shellQuote(targetBt.mac) +
" >/dev/null 2>&1", &rc);
refreshCurrentTab(false);
if (rc == 0 && targetBt.kind == BtDevKind::Audio) {
runAsyncCmd("sxmo_audio.sh device set Bluetooth >/dev/null 2>&1");
}
setBanner(rc == 0 ? ("Connected: " + targetBt.name) : "Connect failed");
} else if (act == 1) {
setBanner("Disconnecting " + targetBt.name + "...");
render();
runCaptureCmd("bluetoothctl disconnect " + shellQuote(targetBt.mac) +
runCaptureCmd("timeout 4 bluetoothctl disconnect " + shellQuote(targetBt.mac) +
" >/dev/null 2>&1", &rc);
refreshCurrentTab(false);
setBanner("Disconnected " + targetBt.name);
} else if (act == 2) {
setBanner("Pairing " + targetBt.name + "...");
render();
runCaptureCmd("bluetoothctl --timeout 8 pair " + shellQuote(targetBt.mac) +
" >/dev/null 2>&1; bluetoothctl trust " +
runCaptureCmd("timeout 10 bluetoothctl --timeout 8 pair " +
shellQuote(targetBt.mac) +
" >/dev/null 2>&1; timeout 2 bluetoothctl trust " +
shellQuote(targetBt.mac) + " >/dev/null 2>&1; "
"bluetoothctl connect " + shellQuote(targetBt.mac) +
"timeout 6 bluetoothctl connect " + shellQuote(targetBt.mac) +
" >/dev/null 2>&1", &rc);
refreshCurrentTab(false);
setBanner("Paired & trusted " + targetBt.name);
} else if (act == 3) {
runCaptureCmd("bluetoothctl remove " + shellQuote(targetBt.mac) +
std::string macU = targetBt.mac;
for (char& c : macU) {
if (c == ':') c = '_';
}
std::string card = "bluez_card." + macU;
bool wantHfp = (targetBt.profileLabel.find("HSP") == std::string::npos &&
targetBt.profileLabel.find("HFP") == std::string::npos);
setBanner(std::string("Switching to ") + (wantHfp ? "HSP/HFP..." : "A2DP..."));
render();
if (wantHfp) {
runCaptureCmd("pactl set-card-profile " + shellQuote(card) +
" headset-head-unit >/dev/null 2>&1 || "
"pactl set-card-profile " + shellQuote(card) +
" headset-head-unit-msbc >/dev/null 2>&1 || "
"pactl set-card-profile " + shellQuote(card) +
" headset-head-unit-cvsd >/dev/null 2>&1", &rc);
runAsyncCmd("sxmo_audio.sh device set Bluetooth >/dev/null 2>&1; "
"sxmo_audio.sh device setinput Bluetooth >/dev/null 2>&1");
} else {
runCaptureCmd("pactl set-card-profile " + shellQuote(card) +
" a2dp-sink >/dev/null 2>&1", &rc);
runAsyncCmd("sxmo_audio.sh device set Bluetooth >/dev/null 2>&1");
}
refreshCurrentTab(false);
setBanner(rc == 0 ? (std::string("Audio profile: ") + (wantHfp ? "HSP/HFP" : "A2DP"))
: "Profile switch unsupported by device");
} else if (act == 4) {
runCaptureCmd("timeout 3 bluetoothctl remove " + shellQuote(targetBt.mac) +
" >/dev/null 2>&1", &rc);
refreshCurrentTab(false);
setBanner("Removed " + targetBt.name);
@@ -1169,6 +1580,10 @@ int runNetworksApp(int argc, char** argv) {
executeBtAction(actionSel);
return;
}
if (modal == NetModal::BtNameEditor) {
saveBtDeviceName();
return;
}
if (activeTab == NetTab::Wifi) {
if (wifiRowSel == 0) {
@@ -1255,12 +1670,19 @@ int runNetworksApp(int argc, char** argv) {
runCaptureCmd("SXMO_OS=alpine doas -n sxmo_bluetoothtoggle.sh " +
std::string(btOn ? "off" : "on") + " >/dev/null 2>&1");
refreshCurrentTab(false);
setBanner(btOn ? "Bluetooth enabled" : "Bluetooth disabled");
} else if (btRowSel == 1) {
toggleBtDiscoverable();
} else if (btRowSel == 2) {
btNameEdit = btCtrl.name;
lastTapDigit = -1;
modal = NetModal::BtNameEditor;
} else if (btRowSel == 3 && btOn) {
setBanner("Scanning Bluetooth devices (5s)...");
render();
refreshCurrentTab(true);
setBanner("Found " + std::to_string(btList.size()) + " device(s)");
} else if (btRowSel == 2 && btOn) {
} else if (btRowSel == 4 && btOn) {
std::string target = (!btRx.savedPath.empty())
? btRx.savedPath
: (getHomeDirPath() + "/Downloads");
@@ -1269,9 +1691,9 @@ int runNetworksApp(int argc, char** argv) {
if (!sendPluginCommand("files", "OPEN " + target)) {
runAsyncArgv("xfiles", target.c_str());
}
} else if (btRowSel - 3 >= 0 &&
btRowSel - 3 < static_cast<int>(btList.size())) {
targetBt = btList[btRowSel - 3];
} else if (btOn && btRowSel - 5 >= 0 &&
btRowSel - 5 < static_cast<int>(btList.size())) {
targetBt = btList[btRowSel - 5];
actionSel = 0;
modal = NetModal::BtActions;
}
@@ -1283,6 +1705,10 @@ int runNetworksApp(int argc, char** argv) {
saveAndConnectApn();
return;
}
if (modal == NetModal::BtNameEditor) {
saveBtDeviceName();
return;
}
if (modal != NetModal::None) {
handleEnterKey();
return;
@@ -1296,10 +1722,17 @@ int runNetworksApp(int argc, char** argv) {
refreshCurrentTab(false);
setBanner("Refreshed cellular state");
} else if (activeTab == NetTab::Bluetooth) {
setBanner("Scanning Bluetooth (5s)...");
render();
refreshCurrentTab(true);
setBanner("Found " + std::to_string(btList.size()) + " device(s)");
if (!btOn) {
setBanner("Turning Bluetooth ON...");
render();
runCaptureCmd("SXMO_OS=alpine doas -n sxmo_bluetoothtoggle.sh on >/dev/null 2>&1");
refreshCurrentTab(false);
} else {
setBanner("Scanning Bluetooth (5s)...");
render();
refreshCurrentTab(true);
setBanner("Found " + std::to_string(btList.size()) + " device(s)");
}
}
};
@@ -1422,12 +1855,25 @@ int runNetworksApp(int argc, char** argv) {
continue;
}
if (modal == NetModal::BtNameEditor) {
if (sym == XK_Return || sym == XK_KP_Enter) {
saveBtDeviceName();
render();
continue;
}
if (handleMultiTapKey(btNameEdit, sym, kc, ev.xkey.state)) {
render();
}
continue;
}
if (modal == NetModal::WifiActions || modal == NetModal::BtActions) {
int actCount = (modal == NetModal::BtActions) ? 5 : 4;
if (sym == XK_Up || sym == XK_KP_Up) {
actionSel = (actionSel + 3) % 4;
actionSel = (actionSel + actCount - 1) % actCount;
render();
} else if (sym == XK_Down || sym == XK_KP_Down) {
actionSel = (actionSel + 1) % 4;
actionSel = (actionSel + 1) % actCount;
render();
} else if (sym == XK_Return || sym == XK_KP_Enter) {
handleEnterKey();
@@ -1470,7 +1916,7 @@ int runNetworksApp(int argc, char** argv) {
} else if (activeTab == NetTab::Cellular) {
cellRowSel = (cellRowSel + 3) % 4;
} else if (activeTab == NetTab::Bluetooth) {
int total = btOn ? (3 + static_cast<int>(btList.size())) : 2;
int total = btOn ? (5 + static_cast<int>(btList.size())) : 3;
btRowSel = (btRowSel + total - 1) % total;
}
render();
@@ -1481,7 +1927,7 @@ int runNetworksApp(int argc, char** argv) {
} else if (activeTab == NetTab::Cellular) {
cellRowSel = (cellRowSel + 1) % 4;
} else if (activeTab == NetTab::Bluetooth) {
int total = btOn ? (3 + static_cast<int>(btList.size())) : 2;
int total = btOn ? (5 + static_cast<int>(btList.size())) : 3;
btRowSel = (btRowSel + 1) % total;
}
render();
@@ -1525,7 +1971,8 @@ int runNetworksApp(int argc, char** argv) {
}
}
if (lastTapDigit != -1 &&
(modal == NetModal::WifiPassword || modal == NetModal::ApnEditor)) {
(modal == NetModal::WifiPassword || modal == NetModal::ApnEditor ||
modal == NetModal::BtNameEditor)) {
int64_t tRem = (lastTapMs + 851) - now;
if (tRem <= 0) {
lastTapDigit = -1;
+24 -3
View File
@@ -1007,8 +1007,24 @@ class PcmAudioOut {
private:
void audioThreadMain() {
snd_pcm_t* h = nullptr;
const char* devs[] = {"hw:0,0", "default", "plughw:0,0"};
for (const char* dev : devs) {
bool preferDefault = (::access("/run/bluetoothd.pid", F_OK) == 0);
if (!preferDefault) {
FILE* af = std::fopen("/tmp/sxmo_audio_out_device", "r");
if (af) {
char abuf[64] = {};
if (std::fgets(abuf, sizeof(abuf), af)) {
if (std::strstr(abuf, "Bluetooth") || std::strstr(abuf, "bluetooth")) {
preferDefault = true;
}
}
std::fclose(af);
}
}
const char* devsHwFirst[] = {"hw:0,0", "default", "plughw:0,0"};
const char* devsDefFirst[] = {"default", "hw:0,0", "plughw:0,0"};
const char** devs = preferDefault ? devsDefFirst : devsHwFirst;
for (int di = 0; di < 3; ++di) {
const char* dev = devs[di];
if (snd_pcm_open(&h, dev, SND_PCM_STREAM_PLAYBACK, 0) >= 0) {
if (configureLowLatency(h)) {
break;
@@ -1018,7 +1034,8 @@ class PcmAudioOut {
}
}
if (!h) {
for (const char* dev : devs) {
for (int di = 0; di < 3; ++di) {
const char* dev = devs[di];
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,
@@ -2253,6 +2270,10 @@ int main(int argc, char** argv) {
usedByAction = true;
}
}
if (!usedByAction && tok == "OK") {
actionDown[ACT_A] = isPress;
usedByAction = true;
}
if (isPress && !usedByAction) {
if (tok == "1") {
cfg.scaleMode = (cfg.scaleMode + 1) % 4;
+769 -17
View File
@@ -333,6 +333,7 @@ class AlsaSoundEngine {
int playerId = -1;
bool active = false;
bool loop = false;
size_t rawSize = 0;
float gain = 0.8f;
std::vector<MidiEvent> events;
size_t eventIdx = 0;
@@ -777,10 +778,20 @@ class AlsaSoundEngine {
auto it = playerGains_.find(playerId);
if (it != playerGains_.end()) g = it->second;
if (midiSeq_.active && midiSeq_.playerId == playerId &&
midiSeq_.rawSize == mid.size() && midiSeq_.currentFrame > 0 &&
midiSeq_.currentFrame < midiSeq_.totalFrames) {
midiSeq_.loop = loop;
midiSeq_.gain = g;
lastActiveMs_ = nowMs();
return;
}
midiSeq_ = MidiSequence{};
midiSeq_.playerId = playerId;
midiSeq_.active = true;
midiSeq_.loop = loop;
midiSeq_.rawSize = mid.size();
midiSeq_.gain = g;
midiSeq_.events = std::move(frameEvents);
midiSeq_.totalFrames =
@@ -1132,12 +1143,32 @@ class AlsaSoundEngine {
snd_pcm_close(pcm);
pcm = nullptr;
}
if (!enabled || sysMuted) {
std::lock_guard<std::mutex> lk(mu_);
voices_.clear();
for (auto it = pcmStreams_.begin(); it != pcmStreams_.end();) {
if (!it->loop) {
it = pcmStreams_.erase(it);
} else {
++it;
}
}
if (midiSeq_.active && !midiSeq_.loop) {
midiSeq_.active = false;
midiVoices_.clear();
}
}
::usleep(10000);
continue;
}
if (!pcm) {
for (const char* dev : {"hw:0,0", "default", "plughw:0,0"}) {
bool preferDefault = (::access("/run/bluetoothd.pid", F_OK) == 0);
const char* devsHwFirst[] = {"hw:0,0", "default", "plughw:0,0"};
const char* devsDefFirst[] = {"default", "hw:0,0", "plughw:0,0"};
const char** devs = preferDefault ? devsDefFirst : devsHwFirst;
for (int di = 0; di < 3; ++di) {
const char* dev = devs[di];
if (snd_pcm_open(&pcm, dev, SND_PCM_STREAM_PLAYBACK, 0) == 0) {
if (!configureLowLatency(pcm, kSampleRate, kPeriod, kBuffer)) {
snd_pcm_set_params(pcm, SND_PCM_FORMAT_S16_LE,
@@ -1577,13 +1608,29 @@ class CldcNetMediaRuntime {
});
// java/lang/System & Runtime
uint32_t sysOutRef = vm.allocObject("java/io/PrintStream");
uint32_t sysErrRef = vm.allocObject("java/io/PrintStream");
vm.setStaticFieldVal("java/lang/System", "out", "Ljava/io/PrintStream;",
JVal::MakeRef(sysOutRef));
vm.setStaticFieldVal("java/lang/System", "err", "Ljava/io/PrintStream;",
JVal::MakeRef(sysErrRef));
uint32_t boolTrueRef = vm.allocObject("java/lang/Boolean");
vm.getObj(boolTrueRef)->setField("value", JVal::MakeInt(1));
uint32_t boolFalseRef = vm.allocObject("java/lang/Boolean");
vm.getObj(boolFalseRef)->setField("value", JVal::MakeInt(0));
vm.setStaticFieldVal("java/lang/Boolean", "TRUE", "Ljava/lang/Boolean;",
JVal::MakeRef(boolTrueRef));
vm.setStaticFieldVal("java/lang/Boolean", "FALSE", "Ljava/lang/Boolean;",
JVal::MakeRef(boolFalseRef));
vm.registerNative("java/lang/System", "currentTimeMillis", "()J",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeLong(wallTimeMs());
return true;
});
vm.registerNative("java/lang/System", "gc", "()V",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal*) {
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal*) {
v.collectGarbage();
return true;
});
vm.registerNative("java/lang/System", "exit", "(I)V",
@@ -1653,6 +1700,7 @@ class CldcNetMediaRuntime {
else if (key == "microedition.locale") val = "en-US";
else if (key == "microedition.m3g.version") val = "1.1";
else if (key == "microedition.io.file.FileConnection.version") val = "1.0";
else if (key == "bluetooth.api.version") val = "1.1";
else if (key == "file.separator") val = "/";
else if (key == "fileconn.dir.photos") val = "file:///home/user/Pictures/";
else if (key == "fileconn.dir.music") val = "file:///home/user/Music/";
@@ -1674,17 +1722,18 @@ class CldcNetMediaRuntime {
return true;
});
vm.registerNative("java/lang/Runtime", "freeMemory", "()J",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeLong(16 * 1024 * 1024LL);
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeLong(v.freeHeapBytes());
return true;
});
vm.registerNative("java/lang/Runtime", "totalMemory", "()J",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeLong(32 * 1024 * 1024LL);
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeLong(v.totalHeapBytes());
return true;
});
vm.registerNative("java/lang/Runtime", "gc", "()V",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal*) {
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal*) {
v.collectGarbage();
return true;
});
@@ -2380,6 +2429,182 @@ class CldcNetMediaRuntime {
*r = JVal::MakeRef(v.allocString(std::to_string(val)));
return true;
});
vm.registerNative("java/lang/Integer", "toBinaryString",
"(I)Ljava/lang/String;",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
uint32_t u = static_cast<uint32_t>(a[0].i);
if (u == 0) {
*r = JVal::MakeRef(v.allocString("0"));
return true;
}
std::string s;
while (u > 0) {
s.insert(s.begin(), (u & 1) ? '1' : '0');
u >>= 1;
}
*r = JVal::MakeRef(v.allocString(s));
return true;
});
vm.registerNative("java/lang/Integer", "toOctalString",
"(I)Ljava/lang/String;",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
char buf[32];
std::snprintf(buf, sizeof(buf), "%o",
static_cast<uint32_t>(a[0].i));
*r = JVal::MakeRef(v.allocString(buf));
return true;
});
vm.registerNative("java/lang/Character", "isDigit", "(C)Z",
[](Jvm&, JThread&, const std::vector<JVal>& a, JVal* r) {
*r = JVal::MakeInt((a[0].i >= '0' && a[0].i <= '9') ? 1 : 0);
return true;
});
vm.registerNative("java/lang/Character", "isLowerCase", "(C)Z",
[](Jvm&, JThread&, const std::vector<JVal>& a, JVal* r) {
*r = JVal::MakeInt((a[0].i >= 'a' && a[0].i <= 'z') ? 1 : 0);
return true;
});
vm.registerNative("java/lang/Character", "isUpperCase", "(C)Z",
[](Jvm&, JThread&, const std::vector<JVal>& a, JVal* r) {
*r = JVal::MakeInt((a[0].i >= 'A' && a[0].i <= 'Z') ? 1 : 0);
return true;
});
vm.registerNative("java/lang/Character", "toLowerCase", "(C)C",
[](Jvm&, JThread&, const std::vector<JVal>& a, JVal* r) {
int c = a[0].i;
if (c >= 'A' && c <= 'Z') c += ('a' - 'A');
*r = JVal::MakeInt(c);
return true;
});
vm.registerNative("java/lang/Character", "toUpperCase", "(C)C",
[](Jvm&, JThread&, const std::vector<JVal>& a, JVal* r) {
int c = a[0].i;
if (c >= 'a' && c <= 'z') c -= ('a' - 'A');
*r = JVal::MakeInt(c);
return true;
});
vm.registerNative("java/lang/Character", "digit", "(CI)I",
[](Jvm&, JThread&, const std::vector<JVal>& a, JVal* r) {
int c = a[0].i;
int radix = a[1].i;
int d = -1;
if (c >= '0' && c <= '9') d = c - '0';
else if (c >= 'a' && c <= 'z') d = 10 + (c - 'a');
else if (c >= 'A' && c <= 'Z') d = 10 + (c - 'A');
if (d >= radix) d = -1;
*r = JVal::MakeInt(d);
return true;
});
vm.registerNative("java/lang/Float", "<init>", "*",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal*) {
JObject* self = v.getObj(a[0].ref);
if (!self || a.size() < 2) return true;
float fv = (a[1].type == JType::Double)
? static_cast<float>(a[1].d)
: a[1].f;
self->setField("value", JVal::MakeFloat(fv));
return true;
});
vm.registerNative("java/lang/Float", "floatValue", "()F",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
const JObject* self = v.getObj(a[0].ref);
*r = JVal::MakeFloat(self ? self->getField("value", 'F').f : 0.0f);
return true;
});
vm.registerNative("java/lang/Float", "parseFloat", "(Ljava/lang/String;)F",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
*r = JVal::MakeFloat(
std::strtof(v.getStringUtf8(a[0].ref).c_str(), nullptr));
return true;
});
vm.registerNative("java/lang/Float", "valueOf", "(Ljava/lang/String;)Ljava/lang/Float;",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
float fv = std::strtof(v.getStringUtf8(a[0].ref).c_str(), nullptr);
uint32_t ref = v.allocObject("java/lang/Float");
v.getObj(ref)->setField("value", JVal::MakeFloat(fv));
*r = JVal::MakeRef(ref);
return true;
});
vm.registerNative("java/lang/Float", "toString", "*",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
float fv = (a[0].type == JType::Ref)
? (v.getObj(a[0].ref)
? v.getObj(a[0].ref)->getField("value", 'F').f
: 0.0f)
: a[0].f;
char buf[64];
std::snprintf(buf, sizeof(buf), "%g", fv);
*r = JVal::MakeRef(v.allocString(buf));
return true;
});
vm.registerNative("java/lang/Float", "floatToIntBits", "(F)I",
[](Jvm&, JThread&, const std::vector<JVal>& a, JVal* r) {
int32_t bits = 0;
std::memcpy(&bits, &a[0].f, sizeof(int32_t));
*r = JVal::MakeInt(bits);
return true;
});
vm.registerNative("java/lang/Float", "intBitsToFloat", "(I)F",
[](Jvm&, JThread&, const std::vector<JVal>& a, JVal* r) {
float fv = 0.0f;
std::memcpy(&fv, &a[0].i, sizeof(float));
*r = JVal::MakeFloat(fv);
return true;
});
vm.registerNative("java/lang/Double", "<init>", "(D)V",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal*) {
JObject* self = v.getObj(a[0].ref);
if (self && a.size() >= 2) {
self->setField("value", JVal::MakeDouble(a[1].d));
}
return true;
});
vm.registerNative("java/lang/Double", "doubleValue", "()D",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
const JObject* self = v.getObj(a[0].ref);
*r = JVal::MakeDouble(self ? self->getField("value", 'D').d : 0.0);
return true;
});
vm.registerNative("java/lang/Double", "parseDouble", "(Ljava/lang/String;)D",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
*r = JVal::MakeDouble(
std::strtod(v.getStringUtf8(a[0].ref).c_str(), nullptr));
return true;
});
vm.registerNative("java/lang/Double", "valueOf", "(Ljava/lang/String;)Ljava/lang/Double;",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
double dv = std::strtod(v.getStringUtf8(a[0].ref).c_str(), nullptr);
uint32_t ref = v.allocObject("java/lang/Double");
v.getObj(ref)->setField("value", JVal::MakeDouble(dv));
*r = JVal::MakeRef(ref);
return true;
});
vm.registerNative("java/lang/Double", "toString", "*",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
double dv = (a[0].type == JType::Ref)
? (v.getObj(a[0].ref)
? v.getObj(a[0].ref)->getField("value", 'D').d
: 0.0)
: a[0].d;
char buf[64];
std::snprintf(buf, sizeof(buf), "%g", dv);
*r = JVal::MakeRef(v.allocString(buf));
return true;
});
vm.registerNative("java/lang/Double", "doubleToLongBits", "(D)J",
[](Jvm&, JThread&, const std::vector<JVal>& a, JVal* r) {
int64_t bits = 0;
std::memcpy(&bits, &a[0].d, sizeof(int64_t));
*r = JVal::MakeLong(bits);
return true;
});
vm.registerNative("java/lang/Double", "longBitsToDouble", "(J)D",
[](Jvm&, JThread&, const std::vector<JVal>& a, JVal* r) {
double dv = 0.0;
std::memcpy(&dv, &a[0].l, sizeof(double));
*r = JVal::MakeDouble(dv);
return true;
});
// java/lang/Math
vm.registerNative("java/lang/Math", "abs", "(I)I",
@@ -2982,7 +3207,10 @@ class CldcNetMediaRuntime {
vm.registerNative("java/util/Hashtable", "clear", "()V",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal*) {
JObject* self = v.getObj(a[0].ref);
if (self) self->fields.clear();
if (self) {
self->fields.clear();
self->refArr.clear();
}
return true;
});
vm.registerNative("java/util/Hashtable", "size", "()I",
@@ -2993,6 +3221,45 @@ class CldcNetMediaRuntime {
: 0);
return true;
});
vm.registerNative("java/util/Hashtable", "isEmpty", "()Z",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
JObject* self = v.getObj(a[0].ref);
*r = JVal::MakeInt(
(!self || self->fields.empty()) ? 1 : 0);
return true;
});
vm.registerNative("java/util/Hashtable", "keys",
"()Ljava/util/Enumeration;",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
JObject* self = v.getObj(a[0].ref);
uint32_t en = v.allocObject("java/util/Enumeration");
JObject* eo = v.getObj(en);
if (self && eo) {
eo->nativeTag = 0;
for (const auto& kv : self->fields) {
eo->refArr.push_back(v.allocString(kv.first));
}
}
*r = JVal::MakeRef(en);
return true;
});
vm.registerNative("java/util/Hashtable", "elements",
"()Ljava/util/Enumeration;",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
JObject* self = v.getObj(a[0].ref);
uint32_t en = v.allocObject("java/util/Enumeration");
JObject* eo = v.getObj(en);
if (self && eo) {
eo->nativeTag = 0;
for (const auto& kv : self->fields) {
if (kv.second.type == JType::Ref) {
eo->refArr.push_back(kv.second.ref);
}
}
}
*r = JVal::MakeRef(en);
return true;
});
// java/util/Timer & TimerTask
vm.registerNative("java/util/Timer", "<init>", "*",
@@ -3436,6 +3703,199 @@ class CldcNetMediaRuntime {
return true;
});
}
// Reader & InputStreamReader (UTF-8 / ISO-8859-1 character stream decoder)
auto readOneUtf8Char = [](NativeInputStream* nis) -> int {
if (!nis) return -1;
int b = nis->readByte();
if (b < 0) return -1;
if ((b & 0x80) == 0) return b;
if ((b & 0xE0) == 0xC0) {
int b2 = nis->readByte();
if (b2 < 0) return b;
return ((b & 0x1F) << 6) | (b2 & 0x3F);
}
if ((b & 0xF0) == 0xE0) {
int b2 = nis->readByte();
int b3 = nis->readByte();
if (b2 < 0 || b3 < 0) return b;
return ((b & 0x0F) << 12) | ((b2 & 0x3F) << 6) | (b3 & 0x3F);
}
return b;
};
for (const char* rdrCls : {"java/io/Reader", "java/io/InputStreamReader"}) {
vm.registerNative(
rdrCls, "<init>", "*",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal*) {
JObject* self = v.getObj(a[0].ref);
if (self && a.size() >= 2 && a[1].type == JType::Ref) {
JObject* src = v.getObj(a[1].ref);
if (src && src->nativeData) {
self->nativeData = src->nativeData;
}
self->setField("in", a[1]);
}
return true;
});
vm.registerNative(
rdrCls, "read", "()I",
[readOneUtf8Char](Jvm& v, JThread&, const std::vector<JVal>& a,
JVal* r) {
auto nis = getOrCreateInputStream(v, a[0].ref);
*r = JVal::MakeInt(readOneUtf8Char(nis.get()));
return true;
});
vm.registerNative(
rdrCls, "read", "([C)I",
[readOneUtf8Char](Jvm& v, JThread&, const std::vector<JVal>& a,
JVal* r) {
auto nis = getOrCreateInputStream(v, a[0].ref);
JObject* arr = v.getObj(a[1].ref);
if (!nis || !arr || arr->arrayKind != ArrayKind::Char) {
*r = JVal::MakeInt(-1);
return true;
}
int len = static_cast<int>(arr->charArr.size());
if (len == 0) {
*r = JVal::MakeInt(0);
return true;
}
int count = 0;
for (int i = 0; i < len; ++i) {
int c = readOneUtf8Char(nis.get());
if (c < 0) break;
arr->charArr[i] = static_cast<uint16_t>(c);
++count;
}
*r = JVal::MakeInt(count == 0 ? -1 : count);
return true;
});
vm.registerNative(
rdrCls, "read", "([CII)I",
[readOneUtf8Char](Jvm& v, JThread&, const std::vector<JVal>& a,
JVal* r) {
auto nis = getOrCreateInputStream(v, a[0].ref);
JObject* arr = v.getObj(a[1].ref);
int off = a[2].i;
int len = a[3].i;
if (!nis || !arr || arr->arrayKind != ArrayKind::Char || off < 0 ||
len < 0 || off + len > static_cast<int>(arr->charArr.size())) {
*r = JVal::MakeInt(-1);
return true;
}
if (len == 0) {
*r = JVal::MakeInt(0);
return true;
}
int count = 0;
for (int i = 0; i < len; ++i) {
int c = readOneUtf8Char(nis.get());
if (c < 0) break;
arr->charArr[off + i] = static_cast<uint16_t>(c);
++count;
}
*r = JVal::MakeInt(count == 0 ? -1 : count);
return true;
});
vm.registerNative(
rdrCls, "skip", "(J)J",
[readOneUtf8Char](Jvm& v, JThread&, const std::vector<JVal>& a,
JVal* r) {
auto nis = getOrCreateInputStream(v, a[0].ref);
int64_t want = std::max<int64_t>(0, a[1].l);
int64_t skipped = 0;
while (skipped < want && readOneUtf8Char(nis.get()) >= 0) {
++skipped;
}
*r = JVal::MakeLong(skipped);
return true;
});
vm.registerNative(
rdrCls, "ready", "()Z",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
auto nis = getOrCreateInputStream(v, a[0].ref);
*r = JVal::MakeInt((nis && nis->available() > 0) ? 1 : 0);
return true;
});
vm.registerNative(
rdrCls, "markSupported", "()Z",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeInt(1);
return true;
});
vm.registerNative(
rdrCls, "mark", "(I)V",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal*) {
auto nis = getOrCreateInputStream(v, a[0].ref);
if (nis) nis->markPos = nis->pos;
return true;
});
vm.registerNative(
rdrCls, "reset", "()V",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal*) {
auto nis = getOrCreateInputStream(v, a[0].ref);
if (nis) nis->pos = nis->markPos;
return true;
});
vm.registerNative(
rdrCls, "close", "()V",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal*) { return true; });
}
// Writer & OutputStreamWriter
for (const char* wrCls : {"java/io/Writer", "java/io/OutputStreamWriter"}) {
vm.registerNative(
wrCls, "<init>", "*",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal*) {
JObject* self = v.getObj(a[0].ref);
if (self && a.size() >= 2 && a[1].type == JType::Ref) {
JObject* sub = v.getObj(a[1].ref);
if (sub && sub->nativeData) self->nativeData = sub->nativeData;
}
return true;
});
vm.registerNative(
wrCls, "write", "(I)V",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal*) {
auto nos = getOrCreateOutputStream(v, a[0].ref);
if (nos) {
uint16_t ch = static_cast<uint16_t>(a[1].i);
std::string s = Jvm::u16ToUtf8(&ch, 1);
nos->writeBytes(reinterpret_cast<const uint8_t*>(s.data()),
static_cast<int>(s.size()));
}
return true;
});
vm.registerNative(
wrCls, "write", "*",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal*) {
auto nos = getOrCreateOutputStream(v, a[0].ref);
if (!nos || a.size() < 2 || a[1].type != JType::Ref) return true;
JObject* arg = v.getObj(a[1].ref);
if (!arg) return true;
std::string s;
if (arg->arrayKind == ArrayKind::Char) {
int off = (a.size() >= 4) ? a[2].i : 0;
int len = (a.size() >= 4) ? a[3].i
: static_cast<int>(arg->charArr.size());
off = std::clamp(off, 0, static_cast<int>(arg->charArr.size()));
len = std::clamp(len, 0,
static_cast<int>(arg->charArr.size()) - off);
s = Jvm::u16ToUtf8(arg->charArr.data() + off, len);
} else {
s = v.getStringUtf8(a[1].ref);
}
nos->writeBytes(reinterpret_cast<const uint8_t*>(s.data()),
static_cast<int>(s.size()));
return true;
});
vm.registerNative(
wrCls, "flush", "()V",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal*) { return true; });
vm.registerNative(
wrCls, "close", "()V",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal*) { return true; });
}
}
void registerRms(Jvm& vm) {
@@ -4161,6 +4621,7 @@ class CldcNetMediaRuntime {
"javax/microedition/media/Control",
"javax/microedition/media/control/VolumeControl",
"javax/microedition/media/control/ToneControl",
"javax/microedition/media/control/MIDIControl",
"com/nokia/mid/sound/Sound"}) {
vm.registerNative(
pCls, "<init>", "*",
@@ -4331,13 +4792,12 @@ class CldcNetMediaRuntime {
return true;
}
if (np->state == 400 && !np->data.empty()) {
bool isMidi = (np->data.size() >= 4 &&
std::memcmp(np->data.data(), "MThd", 4) == 0);
bool isLooping = (np->loopCount < 0 || np->loopCount > 1);
if (!isMidi && !isLooping) {
// One-shot WAV SFX play asynchronously in the 6-channel mixer;
// report PREFETCHED (300) so games that check getState() == 400
// before starting music or rapid SFX never drop sounds.
if (!isLooping) {
// One-shot WAV/MIDI SFX and jingles play asynchronously in the
// mixer; report PREFETCHED (300) so games that check
// getState() == 400 before loading a level or playing SFX
// never deadlock.
np->state = 300;
} else if (!sound.isPlayerActive(np->playerId)) {
np->state = 300; // Transition back to PREFETCHED when finished
@@ -4414,9 +4874,12 @@ class CldcNetMediaRuntime {
? v.getStringUtf8(a[1].ref)
: "VolumeControl";
std::string clsName =
(ctrlType.find("ToneControl") != std::string::npos)
? "javax/microedition/media/control/ToneControl"
: "javax/microedition/media/control/VolumeControl";
"javax/microedition/media/control/VolumeControl";
if (ctrlType.find("ToneControl") != std::string::npos) {
clsName = "javax/microedition/media/control/ToneControl";
} else if (ctrlType.find("MIDIControl") != std::string::npos) {
clsName = "javax/microedition/media/control/MIDIControl";
}
uint32_t cref = v.allocObject(clsName);
JObject* co = v.getObj(cref);
if (co && self) {
@@ -4519,7 +4982,296 @@ class CldcNetMediaRuntime {
}
return true;
});
vm.registerNative(
pCls, "shortMidiEvent", "(III)V",
[this, ensureNativePlayer](Jvm& v, JThread&,
const std::vector<JVal>& a, JVal*) {
if (a.size() >= 4) {
int status = a[1].i & 0xF0;
int data1 = a[2].i & 0x7F;
int data2 = a[3].i & 0x7F;
if (status == 0x90 && data2 > 0) {
NativePlayer* np = ensureNativePlayer(v.getObj(a[0].ref));
int vol = np ? (np->muted ? 0 : np->volumeLevel) : 80;
sound.playTone(data1, 90,
std::clamp((data2 * vol) / 127, 0, 100));
}
}
return true;
});
vm.registerNative(
pCls, "longMidiEvent", "([BII)I",
[](Jvm&, JThread&, const std::vector<JVal>& a, JVal* r) {
*r = JVal::MakeInt(a.size() >= 4 ? a[3].i : 0);
return true;
});
vm.registerNative(
pCls, "setChannelVolume", "(II)V",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal*) { return true; });
vm.registerNative(
pCls, "setProgram", "(III)V",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal*) { return true; });
}
// StreamConnectionNotifier & ServerSocketConnection
for (const char* scnCls :
{"javax/microedition/io/StreamConnectionNotifier",
"javax/microedition/io/ServerSocketConnection"}) {
vm.registerNative(
scnCls, "acceptAndOpen",
"()Ljavax/microedition/io/StreamConnection;",
[](Jvm& v, JThread& th, const std::vector<JVal>&, JVal*) {
v.throwException(th, "java/io/IOException",
"Connection closed");
return false;
});
vm.registerNative(
scnCls, "close", "()V",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal*) { return true; });
}
// JSR-82 Bluetooth API (javax.bluetooth.*)
vm.registerNative(
"javax/bluetooth/LocalDevice", "getLocalDevice",
"()Ljavax/bluetooth/LocalDevice;",
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeRef(v.allocObject("javax/bluetooth/LocalDevice"));
return true;
});
vm.registerNative(
"javax/bluetooth/LocalDevice", "getProperty",
"(Ljava/lang/String;)Ljava/lang/String;",
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeRef(v.allocString("1.1"));
return true;
});
vm.registerNative(
"javax/bluetooth/LocalDevice", "getDiscoveryAgent",
"()Ljavax/bluetooth/DiscoveryAgent;",
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeRef(v.allocObject("javax/bluetooth/DiscoveryAgent"));
return true;
});
vm.registerNative(
"javax/bluetooth/LocalDevice", "getFriendlyName",
"()Ljava/lang/String;",
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeRef(v.allocString("Nokia 8110 4G"));
return true;
});
vm.registerNative(
"javax/bluetooth/LocalDevice", "getBluetoothAddress",
"()Ljava/lang/String;",
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeRef(v.allocString("001122334455"));
return true;
});
vm.registerNative(
"javax/bluetooth/LocalDevice", "setDiscoverable", "(I)Z",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeInt(1);
return true;
});
vm.registerNative(
"javax/bluetooth/LocalDevice", "getDiscoverable", "()I",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeInt(0x9E8B33);
return true;
});
vm.registerNative(
"javax/bluetooth/LocalDevice", "getRecord",
"(Ljavax/microedition/io/Connection;)Ljavax/bluetooth/ServiceRecord;",
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeRef(v.allocObject("javax/bluetooth/ServiceRecord"));
return true;
});
vm.registerNative(
"javax/bluetooth/LocalDevice", "updateRecord",
"(Ljavax/bluetooth/ServiceRecord;)V",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal*) { return true; });
vm.registerNative(
"javax/bluetooth/DiscoveryAgent", "startInquiry",
"(ILjavax/bluetooth/DiscoveryListener;)Z",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
if (a.size() >= 3 && a[2].ref != 0) {
v.invokeMethodSync(a[2].ref, "inquiryCompleted", "(I)V",
{JVal::MakeInt(0)});
}
*r = JVal::MakeInt(1);
return true;
});
vm.registerNative(
"javax/bluetooth/DiscoveryAgent", "cancelInquiry",
"(Ljavax/bluetooth/DiscoveryListener;)Z",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeInt(1);
return true;
});
vm.registerNative(
"javax/bluetooth/DiscoveryAgent", "searchServices",
"([I[Ljavax/bluetooth/UUID;Ljavax/bluetooth/RemoteDevice;Ljavax/bluetooth/DiscoveryListener;)I",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
if (a.size() >= 5 && a[4].ref != 0) {
v.invokeMethodSync(a[4].ref, "serviceSearchCompleted", "(II)V",
{JVal::MakeInt(1), JVal::MakeInt(4)});
}
*r = JVal::MakeInt(1);
return true;
});
vm.registerNative(
"javax/bluetooth/DiscoveryAgent", "cancelServiceSearch", "(I)Z",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeInt(1);
return true;
});
vm.registerNative(
"javax/bluetooth/DiscoveryAgent", "retrieveDevices",
"(I)[Ljavax/bluetooth/RemoteDevice;",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::Null();
return true;
});
vm.registerNative(
"javax/bluetooth/RemoteDevice", "getFriendlyName",
"(Z)Ljava/lang/String;",
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeRef(v.allocString("BT Device"));
return true;
});
vm.registerNative(
"javax/bluetooth/RemoteDevice", "getBluetoothAddress",
"()Ljava/lang/String;",
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeRef(v.allocString("001122334455"));
return true;
});
vm.registerNative(
"javax/bluetooth/ServiceRecord", "getConnectionURL",
"(IZ)Ljava/lang/String;",
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeRef(v.allocString("btspp://001122334455:1"));
return true;
});
vm.registerNative(
"javax/bluetooth/ServiceRecord", "getHostDevice",
"()Ljavax/bluetooth/RemoteDevice;",
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeRef(v.allocObject("javax/bluetooth/RemoteDevice"));
return true;
});
vm.registerNative(
"javax/bluetooth/ServiceRecord", "getAttributeValue",
"(I)Ljavax/bluetooth/DataElement;",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::Null();
return true;
});
vm.registerNative(
"javax/bluetooth/ServiceRecord", "setAttributeValue",
"(ILjavax/bluetooth/DataElement;)Z",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeInt(1);
return true;
});
vm.registerNative(
"javax/bluetooth/ServiceRecord", "setDeviceServiceClasses", "(I)V",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal*) { return true; });
vm.registerNative(
"javax/bluetooth/DataElement", "<init>", "*",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal*) {
JObject* self = v.getObj(a[0].ref);
if (self && a.size() >= 3) self->setField("value", a[2]);
return true;
});
vm.registerNative(
"javax/bluetooth/DataElement", "addElement",
"(Ljavax/bluetooth/DataElement;)V",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal*) {
JObject* self = v.getObj(a[0].ref);
if (self && a.size() >= 2) self->refArr.push_back(a[1].ref);
return true;
});
vm.registerNative(
"javax/bluetooth/DataElement", "getValue", "()Ljava/lang/Object;",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal* r) {
JObject* self = v.getObj(a[0].ref);
if (self && !self->refArr.empty()) {
uint32_t en = v.allocObject("java/util/Enumeration");
JObject* eo = v.getObj(en);
eo->refArr = self->refArr;
eo->nativeTag = 0;
*r = JVal::MakeRef(en);
} else {
*r = self ? self->getField("value", 'L') : JVal::Null();
}
return true;
});
vm.registerNative(
"javax/bluetooth/UUID", "<init>", "*",
[](Jvm& v, JThread&, const std::vector<JVal>& a, JVal*) {
JObject* self = v.getObj(a[0].ref);
if (self && a.size() >= 2 && a[1].type == JType::Ref) {
self->strUtf8 = v.getStringUtf8(a[1].ref);
}
return true;
});
// JSR-75 FileSystemRegistry & FileConnection extras
vm.registerNative(
"javax/microedition/io/file/FileSystemRegistry", "listRoots",
"()Ljava/util/Enumeration;",
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
uint32_t en = v.allocObject("java/util/Enumeration");
JObject* eo = v.getObj(en);
if (eo) {
eo->nativeTag = 0;
eo->refArr.push_back(v.allocString("root1/"));
}
*r = JVal::MakeRef(en);
return true;
});
for (const char* fcMethod : {"exists", "isDirectory", "canRead", "canWrite"}) {
vm.registerNative(
"javax/microedition/io/file/FileConnection", fcMethod, "()Z",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeInt(0);
return true;
});
}
vm.registerNative(
"javax/microedition/io/file/FileConnection", "fileSize", "()J",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeLong(0);
return true;
});
vm.registerNative(
"javax/microedition/io/file/FileConnection", "list", "*",
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeRef(v.allocObject("java/util/Enumeration"));
return true;
});
for (const char* fcVoid : {"create", "mkdir", "delete", "truncate"}) {
vm.registerNative(
"javax/microedition/io/file/FileConnection", fcVoid, "*",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal*) { return true; });
}
// JSR-120 Wireless Messaging API (javax.wireless.messaging.*)
vm.registerNative(
"javax/wireless/messaging/MessageConnection", "newMessage", "*",
[](Jvm& v, JThread&, const std::vector<JVal>&, JVal* r) {
*r = JVal::MakeRef(
v.allocObject("javax/wireless/messaging/TextMessage"));
return true;
});
vm.registerNative(
"javax/wireless/messaging/MessageConnection", "send",
"(Ljavax/wireless/messaging/Message;)V",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal*) { return true; });
vm.registerNative(
"javax/wireless/messaging/TextMessage", "setPayloadText",
"(Ljava/lang/String;)V",
[](Jvm&, JThread&, const std::vector<JVal>&, JVal*) { return true; });
}
};
+229 -52
View File
@@ -442,6 +442,9 @@ class Jvm {
MidletSuiteInfo* suiteInfo = nullptr;
RmsManager* rms = nullptr;
bool exitRequested = false;
std::function<void(const JObject&, const std::function<void(uint32_t)>&)>
traceNativeRefs;
std::function<void(const std::function<void(uint32_t)>&)> traceExtraRoots;
Jvm() {
heap_.emplace_back(); // id 0 == null
@@ -454,21 +457,33 @@ class Jvm {
// Heap allocation helpers
JObject* getObj(uint32_t ref) {
if (ref == 0 || ref >= heap_.size()) return nullptr;
if (ref == 0 || ref >= heap_.size() || heap_[ref].id == 0) return nullptr;
return &heap_[ref];
}
const JObject* getObj(uint32_t ref) const {
if (ref == 0 || ref >= heap_.size()) return nullptr;
if (ref == 0 || ref >= heap_.size() || heap_[ref].id == 0) return nullptr;
return &heap_[ref];
}
uint32_t allocObject(const std::string& className) {
uint32_t allocHeapSlot(JObject&& obj) {
if (!freeSlots_.empty()) {
uint32_t id = freeSlots_.back();
freeSlots_.pop_back();
obj.id = id;
heap_[id] = std::move(obj);
return id;
}
uint32_t id = static_cast<uint32_t>(heap_.size());
JObject obj;
obj.id = id;
obj.className = className;
heap_.push_back(std::move(obj));
return id;
}
uint32_t allocObject(const std::string& className) {
JObject obj;
obj.className = className;
uint32_t id = allocHeapSlot(std::move(obj));
initInstanceDefaultFields(id, className);
return id;
}
@@ -486,14 +501,11 @@ class Jvm {
std::string readString(uint32_t ref) const { return getStringUtf8(ref); }
uint32_t allocString(const std::string& utf8) {
uint32_t id = static_cast<uint32_t>(heap_.size());
JObject obj;
obj.id = id;
obj.className = "java/lang/String";
obj.isString = true;
obj.strUtf8 = utf8;
heap_.push_back(std::move(obj));
return id;
return allocHeapSlot(std::move(obj));
}
uint32_t internString(const std::string& utf8) {
@@ -579,9 +591,7 @@ class Jvm {
uint32_t allocPrimitiveArray(uint8_t atype, int32_t count) {
if (count < 0) count = 0;
uint32_t id = static_cast<uint32_t>(heap_.size());
JObject obj;
obj.id = id;
switch (atype) {
case 4: // T_BOOLEAN
obj.className = "[Z";
@@ -629,15 +639,12 @@ class Jvm {
obj.intArr.assign(count, 0);
break;
}
heap_.push_back(std::move(obj));
return id;
return allocHeapSlot(std::move(obj));
}
uint32_t allocRefArray(const std::string& elemClass, int32_t count) {
if (count < 0) count = 0;
uint32_t id = static_cast<uint32_t>(heap_.size());
JObject obj;
obj.id = id;
if (!elemClass.empty() && elemClass[0] == '[') {
obj.className = "[" + elemClass;
} else {
@@ -645,8 +652,7 @@ class Jvm {
}
obj.arrayKind = ArrayKind::Ref;
obj.refArr.assign(count, 0);
heap_.push_back(std::move(obj));
return id;
return allocHeapSlot(std::move(obj));
}
uint32_t allocMultiArray(const std::string& desc, const int32_t* dims,
@@ -830,7 +836,7 @@ class Jvm {
bool invokeManagedSync(JThread& th, JClass* cls, const JMethodInfo* m,
const std::vector<JVal>& args,
int maxSteps = 500000) {
int maxSteps = 50000000) {
if (!cls || !m || !m->hasCode) return false;
size_t depth = th.frames.size();
pushBytecodeFrame(th, cls, m, args);
@@ -895,7 +901,7 @@ class Jvm {
JThread tempThread;
tempThread.id = 9999;
pushBytecodeFrame(tempThread, cls, &m, {});
runThreadUntilReturn(tempThread, 0, 2000000);
runThreadUntilReturn(tempThread, 0, 20000000);
break;
}
}
@@ -946,12 +952,12 @@ class Jvm {
}
// Synchronously invoke a method on an object (e.g. MIDlet.startApp, Canvas.paint,
//Canvas.keyPressed, CommandListener.commandAction, Runnable.run)
// Canvas.keyPressed, CommandListener.commandAction, Runnable.run)
bool invokeMethodSync(uint32_t objRef, const std::string& methodName,
const std::string& descriptor,
const std::vector<JVal>& extraArgs = {},
JVal* outRet = nullptr,
int maxSteps = 500000) {
int maxSteps = 50000000) {
JObject* obj = getObj(objRef);
if (!obj) return false;
std::vector<JVal> allArgs;
@@ -993,15 +999,32 @@ class Jvm {
// Execute up to `maxSteps` bytecode instructions on `th` until `th.frames.size() <= targetDepth`
bool runThreadUntilReturn(JThread& th, size_t targetDepth, int maxSteps,
JVal* outRet = nullptr) {
activeSyncThreads_.push_back(&th);
int steps = 0;
bool ok = true;
while (steps < maxSteps && th.frames.size() > targetDepth &&
!exitRequested) {
if (!stepOneInstruction(th, outRet, targetDepth)) {
return false;
ok = false;
break;
}
if (th.yieldSlice || th.state != ThreadState::Runnable) {
th.yieldSlice = false;
th.state = ThreadState::Runnable;
th.wakeTimeMs = 0;
th.waitingOnRef = 0;
stepThreads(5000);
}
++steps;
}
return th.pendingExceptionRef == 0;
if (!activeSyncThreads_.empty() && activeSyncThreads_.back() == &th) {
activeSyncThreads_.pop_back();
} else {
activeSyncThreads_.erase(
std::remove(activeSyncThreads_.begin(), activeSyncThreads_.end(), &th),
activeSyncThreads_.end());
}
return ok && th.pendingExceptionRef == 0;
}
// Execute a quantum slice of instructions on a scheduled thread
@@ -1059,8 +1082,171 @@ class Jvm {
return "";
}
static constexpr int64_t kTotalHeapBudgetBytes = 64LL * 1024 * 1024;
int64_t totalHeapBytes() const { return kTotalHeapBudgetBytes; }
int64_t usedHeapBytes() const {
int64_t used = 0;
for (size_t i = 1; i < heap_.size(); ++i) {
const JObject& o = heap_[i];
if (o.id == 0) continue;
used += 64;
used += static_cast<int64_t>(o.strUtf8.size());
used += static_cast<int64_t>(o.byteArr.size());
used += static_cast<int64_t>(o.charArr.size()) * 2;
used += static_cast<int64_t>(o.shortArr.size()) * 2;
used += static_cast<int64_t>(o.intArr.size()) * 4;
used += static_cast<int64_t>(o.longArr.size()) * 8;
used += static_cast<int64_t>(o.floatArr.size()) * 4;
used += static_cast<int64_t>(o.doubleArr.size()) * 8;
used += static_cast<int64_t>(o.refArr.size()) * 4;
used += static_cast<int64_t>(o.fields.size()) * 32;
}
return std::min<int64_t>(used, kTotalHeapBudgetBytes - 4 * 1024 * 1024);
}
int64_t freeHeapBytes() const {
return std::max<int64_t>(4 * 1024 * 1024,
kTotalHeapBudgetBytes - usedHeapBytes());
}
// Mark-and-sweep garbage collector over Jvm::heap_
size_t collectGarbage(const std::vector<uint32_t>& extraRoots = {}) {
if (heap_.size() <= 1) return 0;
std::vector<uint8_t> marked(heap_.size(), 0);
std::vector<uint32_t> worklist;
worklist.reserve(1024);
auto markRef = [&](uint32_t r) {
if (r > 0 && r < heap_.size() && !marked[r] && heap_[r].id != 0) {
marked[r] = 1;
worklist.push_back(r);
}
};
for (uint32_t r : extraRoots) markRef(r);
if (traceExtraRoots) traceExtraRoots(markRef);
for (const auto& kv : internPool_) markRef(kv.second);
for (const auto& ckv : classes_) {
const JClass* cls = ckv.second.get();
if (!cls) continue;
for (const auto& fkv : cls->staticFields) {
if (fkv.second.type == JType::Ref) markRef(fkv.second.ref);
}
for (const auto& ce : cls->cp) {
if (ce.cachedStringRef != 0) markRef(ce.cachedStringRef);
}
}
auto markThread = [&](const JThread& th) {
markRef(th.threadObjRef);
markRef(th.pendingExceptionRef);
markRef(th.waitingOnRef);
for (const auto& f : th.frames) {
for (const auto& lv : f.locals) {
if (lv.type == JType::Ref) markRef(lv.ref);
}
for (const auto& sv : f.stack) {
if (sv.type == JType::Ref) markRef(sv.ref);
}
}
};
for (const auto& th : threads_) {
if (th) markThread(*th);
}
for (const JThread* sth : activeSyncThreads_) {
if (sth) markThread(*sth);
}
while (!worklist.empty()) {
uint32_t cur = worklist.back();
worklist.pop_back();
const JObject& obj = heap_[cur];
for (uint32_t r : obj.refArr) markRef(r);
for (const auto& fkv : obj.fields) {
if (fkv.second.type == JType::Ref) markRef(fkv.second.ref);
}
if (traceNativeRefs && obj.nativeData) {
traceNativeRefs(obj, markRef);
}
}
freeSlots_.clear();
size_t swept = 0;
for (uint32_t i = static_cast<uint32_t>(heap_.size()) - 1; i >= 1; --i) {
if (!marked[i]) {
if (heap_[i].id != 0) {
heap_[i] = JObject{};
++swept;
}
freeSlots_.push_back(i);
}
}
// Reap finished background threads that have no remaining frames
threads_.erase(
std::remove_if(threads_.begin(), threads_.end(),
[](const std::unique_ptr<JThread>& t) {
return !t ||
(t->state == ThreadState::Finished &&
t->frames.empty());
}),
threads_.end());
return swept;
}
JVal* resolveStaticSlot(const std::string& className,
const std::string& fieldName,
const std::string& desc) {
std::string fkey = JObject::makeFieldKey(fieldName, desc);
JClass* cls = loadClass(className);
if (!cls) {
std::string name = className;
for (char& c : name) {
if (c == '.') c = '/';
}
if (!name.empty() && name[0] == 'L' && name.back() == ';') {
name = name.substr(1, name.size() - 2);
}
auto synth = std::make_unique<JClass>();
synth->name = name;
synth->superName = getSuperClassName(name);
synth->clinitStarted = true;
synth->clinitDone = true;
cls = synth.get();
classes_[name] = std::move(synth);
}
JVal* s = findStaticSlotIn(cls, fkey, fieldName, 0);
if (s) return s;
auto ins = cls->staticFields.emplace(
fkey, defaultValueForDesc(desc.empty() ? 'I' : desc[0]));
return &ins.first->second;
}
JVal getStaticFieldVal(const std::string& className,
const std::string& fieldName,
const std::string& desc) {
JVal* s = resolveStaticSlot(className, fieldName, desc);
if (s) return *s;
return defaultValueForDesc(desc.empty() ? 'I' : desc[0]);
}
void setStaticFieldVal(const std::string& className,
const std::string& fieldName,
const std::string& desc,
const JVal& val) {
JVal* s = resolveStaticSlot(className, fieldName, desc);
if (s) *s = val;
}
private:
std::deque<JObject> heap_;
std::vector<uint32_t> freeSlots_;
std::vector<JThread*> activeSyncThreads_;
std::unordered_map<std::string, uint32_t> internPool_;
std::unordered_map<std::string, std::unique_ptr<JClass>> classes_;
std::unordered_map<std::string, std::string> builtinSupers_;
@@ -1179,8 +1365,28 @@ class Jvm {
"java/lang/RuntimeException";
builtinSupers_["java/lang/ClassCastException"] =
"java/lang/RuntimeException";
builtinSupers_["java/lang/NumberFormatException"] =
"java/lang/IllegalArgumentException";
builtinSupers_["java/lang/IndexOutOfBoundsException"] =
"java/lang/RuntimeException";
builtinSupers_["java/lang/StringIndexOutOfBoundsException"] =
"java/lang/IndexOutOfBoundsException";
builtinSupers_["java/lang/NegativeArraySizeException"] =
"java/lang/RuntimeException";
builtinSupers_["java/lang/SecurityException"] =
"java/lang/RuntimeException";
builtinSupers_["java/lang/OutOfMemoryError"] = "java/lang/Throwable";
builtinSupers_["java/lang/Error"] = "java/lang/Throwable";
builtinSupers_["java/io/IOException"] = "java/lang/Exception";
builtinSupers_["java/io/EOFException"] = "java/io/IOException";
builtinSupers_["java/io/UnsupportedEncodingException"] =
"java/io/IOException";
builtinSupers_["javax/microedition/io/ConnectionNotFoundException"] =
"java/io/IOException";
builtinSupers_["javax/bluetooth/BluetoothStateException"] =
"java/io/IOException";
builtinSupers_["javax/microedition/media/MediaException"] =
"java/lang/Exception";
builtinSupers_["javax/microedition/rms/RecordStoreException"] =
"java/lang/Exception";
builtinSupers_["javax/microedition/rms/RecordStoreNotFoundException"] =
@@ -1277,35 +1483,6 @@ class Jvm {
return nullptr;
}
JVal* resolveStaticSlot(const std::string& className,
const std::string& fieldName,
const std::string& desc) {
std::string fkey = JObject::makeFieldKey(fieldName, desc);
JClass* cls = loadClass(className);
if (!cls) return nullptr;
JVal* s = findStaticSlotIn(cls, fkey, fieldName, 0);
if (s) return s;
auto ins = cls->staticFields.emplace(
fkey, defaultValueForDesc(desc.empty() ? 'I' : desc[0]));
return &ins.first->second;
}
JVal getStaticFieldVal(const std::string& className,
const std::string& fieldName,
const std::string& desc) {
JVal* s = resolveStaticSlot(className, fieldName, desc);
if (s) return *s;
return defaultValueForDesc(desc.empty() ? 'I' : desc[0]);
}
void setStaticFieldVal(const std::string& className,
const std::string& fieldName,
const std::string& desc,
const JVal& val) {
JVal* s = resolveStaticSlot(className, fieldName, desc);
if (s) *s = val;
}
// Big-endian readers for .class format
static uint16_t be16(const uint8_t* p) {
return (static_cast<uint16_t>(p[0]) << 8) | p[1];
+17
View File
@@ -80,6 +80,8 @@ struct NativeImageSurface {
int height = 320;
bool mutableImg = true;
bool isMutable = true;
int maxDrawnX = 0;
int maxDrawnY = 0;
std::vector<uint32_t> pixels; // 0xAARRGGBB
NativeImageSurface(int w = 240, int h = 320, uint32_t fill = 0xFFFFFFFFu)
@@ -96,21 +98,32 @@ struct NativeImageSurface {
void clear(uint32_t fill = 0xFF000000u) {
std::fill(pixels.begin(), pixels.end(), fill);
maxDrawnX = 0;
maxDrawnY = 0;
}
void resize(int w, int h, uint32_t fill = 0xFF000000u) {
width = std::max(1, w);
height = std::max(1, h);
maxDrawnX = 0;
maxDrawnY = 0;
pixels.assign(static_cast<size_t>(width) * height, fill);
}
static bool DecodeFromMemory(const uint8_t* data, size_t len,
NativeImageSurface* out);
inline uint32_t getPixel(int x, int y) const {
if (x < 0 || y < 0 || x >= width || y >= height) return 0;
return pixels[static_cast<size_t>(y) * width + x];
}
inline void blendPixel(int x, int y, uint32_t srcArgb) {
if (x < 0 || y < 0 || x >= width || y >= height) return;
uint32_t a = (srcArgb >> 24) & 0xFFu;
if (a == 0) return;
if (x > maxDrawnX) maxDrawnX = x;
if (y > maxDrawnY) maxDrawnY = y;
uint32_t& dst = pixels[static_cast<size_t>(y) * width + x];
if (a == 255) {
dst = srcArgb | 0xFF000000u;
@@ -318,6 +331,8 @@ struct NativeGraphicsState {
int x1 = std::min({target->width, clipX + clipW, x + w});
int y1 = std::min({target->height, clipY + clipH, y + h});
if (x0 >= x1 || y0 >= y1) return;
if (x1 - 1 > target->maxDrawnX) target->maxDrawnX = x1 - 1;
if (y1 - 1 > target->maxDrawnY) target->maxDrawnY = y1 - 1;
uint32_t a = (colorArgb >> 24) & 0xFFu;
for (int py = y0; py < y1; ++py) {
uint32_t* row = target->pixels.data() + static_cast<size_t>(py) * target->width;
@@ -541,6 +556,7 @@ struct LcduiScreenState {
std::string title;
std::string tickerText;
uint32_t listenerRef = 0;
uint32_t selectCommandRef = 0;
std::vector<LcduiCommandInfo> commands;
bool fullScreen = true;
int selectedIdx = 0;
@@ -548,6 +564,7 @@ struct LcduiScreenState {
// For List / ChoiceGroup:
int choiceType = 1; // 1=EXCLUSIVE, 2=MULTIPLE, 3=IMPLICIT
std::vector<std::string> listItems;
std::vector<uint32_t> listItemRefs;
std::vector<uint32_t> listImages;
std::vector<bool> listSelected;
// For Form:
+391 -12
View File
@@ -28,10 +28,14 @@ struct RuntimeAppContext {
uint32_t currentDisplayableRef = 0;
uint32_t midletRef = 0;
uint32_t sharedGraphicsRef = 0;
uint32_t graphics3dRef = 0;
uint32_t listSelectCommandRef = 0;
bool midletDestroyed = false;
bool midletPaused = false;
bool repaintPending = true;
bool inPaint = false;
bool paintedInStep = false;
bool commandMenuOpen = false;
int commandMenuSel = 0;
int latchedKeyStates = 0;
@@ -58,6 +62,7 @@ struct LcduiItemState {
int choiceType = 1;
int selectedIdx = 0;
std::vector<std::string> choices;
std::vector<uint32_t> choiceRefs;
std::vector<bool> choiceSel;
uint32_t imageRef = 0;
};
@@ -144,6 +149,93 @@ inline uint32_t createGraphicsForSurface(Jvm& vm, NativeImageSurface* surf) {
}
inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
// Register GC root and nativeData reference tracers
vm.traceExtraRoots = [ctx](const std::function<void(uint32_t)>& mark) {
if (!ctx) return;
mark(ctx->displayRef);
mark(ctx->currentDisplayableRef);
mark(ctx->midletRef);
mark(ctx->sharedGraphicsRef);
mark(ctx->graphics3dRef);
mark(ctx->listSelectCommandRef);
for (uint32_t r : ctx->serialRunnables) mark(r);
if (ctx->m3g) {
mark(ctx->m3g->boundGraphicsRef);
mark(ctx->m3g->boundTargetRef);
}
};
vm.traceNativeRefs = [&vm](const JObject& obj,
const std::function<void(uint32_t)>& mark) {
if (!obj.nativeData) return;
const std::string& cn = obj.className;
if (cn == "javax/microedition/lcdui/Form" ||
cn == "javax/microedition/lcdui/List" ||
cn == "javax/microedition/lcdui/TextBox" ||
cn == "javax/microedition/lcdui/Alert" ||
cn == "javax/microedition/lcdui/Canvas" ||
cn == "javax/microedition/lcdui/game/GameCanvas" ||
cn == "com/nokia/mid/ui/FullCanvas" ||
vm.isSubclassOf(cn, "javax/microedition/lcdui/Displayable")) {
auto* st = static_cast<LcduiScreenState*>(obj.nativeData.get());
mark(st->listenerRef);
mark(st->selectCommandRef);
mark(st->alertNextDisplayableRef);
for (const auto& c : st->commands) mark(c.cmdRef);
for (uint32_t r : st->listItemRefs) mark(r);
for (uint32_t r : st->listImages) mark(r);
for (uint32_t r : st->formItemRefs) mark(r);
} else if (cn == "javax/microedition/lcdui/StringItem" ||
cn == "javax/microedition/lcdui/ImageItem" ||
cn == "javax/microedition/lcdui/TextField" ||
cn == "javax/microedition/lcdui/ChoiceGroup" ||
cn == "javax/microedition/lcdui/Gauge" ||
vm.isSubclassOf(cn, "javax/microedition/lcdui/Item")) {
auto* is = static_cast<LcduiItemState*>(obj.nativeData.get());
mark(is->imageRef);
for (uint32_t r : is->choiceRefs) mark(r);
} else if (cn == "javax/microedition/lcdui/game/Sprite" ||
vm.isSubclassOf(cn, "javax/microedition/lcdui/game/Sprite")) {
auto* sp = static_cast<SpriteNativeState*>(obj.nativeData.get());
mark(sp->imageRef);
} else if (cn == "javax/microedition/lcdui/game/TiledLayer" ||
vm.isSubclassOf(cn, "javax/microedition/lcdui/game/TiledLayer")) {
auto* tl = static_cast<TiledLayerNativeState*>(obj.nativeData.get());
mark(tl->imageRef);
} else if (cn == "javax/microedition/m3g/VertexBuffer") {
auto* vb = static_cast<M3gVertexBufferData*>(obj.nativeData.get());
mark(vb->positionsRef);
mark(vb->normalsRef);
mark(vb->colorsRef);
mark(vb->texCoordsRef);
} else if (cn == "javax/microedition/m3g/Mesh" ||
cn == "javax/microedition/m3g/MorphingMesh" ||
cn == "javax/microedition/m3g/SkinnedMesh") {
auto* md = static_cast<M3gMeshData*>(obj.nativeData.get());
mark(md->vertexBufferRef);
for (uint32_t r : md->submeshRefs) mark(r);
for (uint32_t r : md->appearanceRefs) mark(r);
for (uint32_t r : md->childrenRefs) mark(r);
}
};
// Initialize List.SELECT_COMMAND and AlertType.* static constants
uint32_t selCmd = vm.allocObject("javax/microedition/lcdui/Command");
if (JObject* co = vm.getObj(selCmd)) {
co->setField("label", JValue::FromRef(vm.internString("")));
co->setField("type", JValue::FromInt(1)); // SCREEN
co->setField("priority", JValue::FromInt(0));
}
ctx->listSelectCommandRef = selCmd;
vm.setStaticFieldVal("javax/microedition/lcdui/List", "SELECT_COMMAND",
"Ljavax/microedition/lcdui/Command;",
JValue::FromRef(selCmd));
for (const char* atName :
{"INFO", "WARNING", "ERROR", "ALARM", "CONFIRMATION"}) {
uint32_t atRef = vm.allocObject("javax/microedition/lcdui/AlertType");
vm.setStaticFieldVal("javax/microedition/lcdui/AlertType", atName,
"Ljavax/microedition/lcdui/AlertType;",
JValue::FromRef(atRef));
}
// -------------------------------------------------------------------------
// javax.microedition.midlet.MIDlet
// -------------------------------------------------------------------------
@@ -363,11 +455,41 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
ctx->repaintPending = true;
return JValue::Null();
});
v.registerWildcardNative(cls, "serviceRepaints",
[ctx](Jvm&, JThread&, JValue*) -> JValue {
ctx->repaintPending = true;
return JValue::Null();
});
v.registerWildcardNative(
cls, "serviceRepaints",
[ctx](Jvm& vmRef, JThread&, JValue*) -> JValue {
uint32_t dispRef = ctx->currentDisplayableRef;
if (!ctx->inPaint && dispRef != 0 &&
isCanvasDisplayable(vmRef, dispRef)) {
JObject* dispObj = vmRef.getObj(dispRef);
if (dispObj) {
ctx->inPaint = true;
ctx->repaintPending = false;
JObject* gObj = vmRef.getObj(ctx->sharedGraphicsRef);
if (gObj && gObj->nativeData) {
auto* gs =
static_cast<NativeGraphicsState*>(gObj->nativeData.get());
gs->resetTarget(&ctx->canvasFb);
}
auto [rc, rm] = vmRef.resolveMethod(
dispObj->className, "paint",
"(Ljavax/microedition/lcdui/Graphics;)V", false);
if (rm && !rm->code.empty()) {
JThread paintTh;
vmRef.invokeManagedSync(
paintTh, rc, rm,
{JValue::FromRef(dispRef),
JValue::FromRef(ctx->sharedGraphicsRef)},
25000000);
}
ctx->inPaint = false;
ctx->paintedInStep = true;
return JValue::Null();
}
}
ctx->repaintPending = true;
return JValue::Null();
});
v.registerWildcardNative(cls, "setTitle",
[ctx](Jvm& vmRef, JThread&, JValue* a) -> JValue {
LcduiScreenState* st = ensureScreenState(vmRef, a[0].ref);
@@ -1129,6 +1251,11 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
}
return JValue::Null();
});
vm.registerWildcardNative(
"javax/microedition/lcdui/Graphics", "getDisplayColor",
[](Jvm&, JThread&, JValue* a) -> JValue {
return JValue::FromInt(a[1].i & 0x00FFFFFF);
});
// com.nokia.mid.ui.DirectUtils / DirectGraphics
vm.registerWildcardNative(
@@ -1154,6 +1281,193 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
auto surf = std::make_shared<NativeImageSurface>(w, h, true, col);
return JValue::FromRef(createImageObjectFromSurface(v, surf));
});
for (const char* dgCls :
{"com/nokia/mid/ui/DirectGraphics",
"javax/microedition/lcdui/Graphics"}) {
vm.registerWildcardNative(
dgCls, "setARGBColor",
[getGraphicsState](Jvm& v, JThread&, JValue* a) -> JValue {
if (auto* g = getGraphicsState(v, a[0].ref)) {
g->colorArgb = static_cast<uint32_t>(a[1].i);
}
return JValue::Null();
});
vm.registerWildcardNative(
dgCls, "getAlphaComponent",
[getGraphicsState](Jvm& v, JThread&, JValue* a) -> JValue {
auto* g = getGraphicsState(v, a[0].ref);
return JValue::FromInt(
g ? static_cast<int32_t>((g->colorArgb >> 24) & 0xFFu) : 255);
});
vm.registerWildcardNative(
dgCls, "getNativePixelFormat",
[](Jvm&, JThread&, JValue*) -> JValue {
return JValue::FromInt(8888); // TYPE_INT_8888_ARGB
});
vm.registerWildcardNative(
dgCls, "drawTriangle",
[getGraphicsState](Jvm& v, JThread&, JValue* a) -> JValue {
if (auto* g = getGraphicsState(v, a[0].ref)) {
if (a[7].i != 0) g->colorArgb = static_cast<uint32_t>(a[7].i);
g->drawLine(a[1].i, a[2].i, a[3].i, a[4].i);
g->drawLine(a[3].i, a[4].i, a[5].i, a[6].i);
g->drawLine(a[5].i, a[6].i, a[1].i, a[2].i);
}
return JValue::Null();
});
vm.registerWildcardNative(
dgCls, "fillTriangle",
[getGraphicsState, dgCls](Jvm& v, JThread&, JValue* a) -> JValue {
if (auto* g = getGraphicsState(v, a[0].ref)) {
if (a[7].i != 0 && dgCls[0] == 'c') {
g->colorArgb = static_cast<uint32_t>(a[7].i);
}
g->fillTriangle(a[1].i, a[2].i, a[3].i, a[4].i, a[5].i, a[6].i);
}
return JValue::Null();
});
vm.registerWildcardNative(
dgCls, "drawPolygon",
[getGraphicsState](Jvm& v, JThread&, JValue* a) -> JValue {
auto* g = getGraphicsState(v, a[0].ref);
JObject* xArr = v.getObj(a[1].ref);
JObject* yArr = v.getObj(a[3].ref);
if (!g || !xArr || !yArr) return JValue::Null();
int xOff = a[2].i, yOff = a[4].i, n = a[5].i;
g->colorArgb = static_cast<uint32_t>(a[6].i);
for (int i = 0; i < n; ++i) {
int j = (i + 1) % n;
if (xOff + i >= 0 && yOff + i >= 0 && xOff + j >= 0 &&
yOff + j >= 0 &&
static_cast<size_t>(xOff + i) < xArr->intArr.size() &&
static_cast<size_t>(yOff + i) < yArr->intArr.size() &&
static_cast<size_t>(xOff + j) < xArr->intArr.size() &&
static_cast<size_t>(yOff + j) < yArr->intArr.size()) {
g->drawLine(xArr->intArr[xOff + i], yArr->intArr[yOff + i],
xArr->intArr[xOff + j], yArr->intArr[yOff + j]);
}
}
return JValue::Null();
});
vm.registerWildcardNative(
dgCls, "fillPolygon",
[getGraphicsState](Jvm& v, JThread&, JValue* a) -> JValue {
auto* g = getGraphicsState(v, a[0].ref);
JObject* xArr = v.getObj(a[1].ref);
JObject* yArr = v.getObj(a[3].ref);
if (!g || !xArr || !yArr) return JValue::Null();
int xOff = a[2].i, yOff = a[4].i, n = a[5].i;
g->colorArgb = static_cast<uint32_t>(a[6].i);
for (int i = 1; i + 1 < n; ++i) {
if (xOff + i + 1 < static_cast<int>(xArr->intArr.size()) &&
yOff + i + 1 < static_cast<int>(yArr->intArr.size())) {
g->fillTriangle(xArr->intArr[xOff], yArr->intArr[yOff],
xArr->intArr[xOff + i], yArr->intArr[yOff + i],
xArr->intArr[xOff + i + 1],
yArr->intArr[yOff + i + 1]);
}
}
return JValue::Null();
});
vm.registerWildcardNative(
dgCls, "drawPixels",
[getGraphicsState](Jvm& v, JThread&, JValue* a) -> JValue {
auto* g = getGraphicsState(v, a[0].ref);
JObject* arr = v.getObj(a[1].ref);
if (!g || !arr) return JValue::Null();
bool trans = (a[2].i != 0);
int offset = a[3].i, scanlen = a[4].i, x = a[5].i, y = a[6].i;
int w = a[7].i, h = a[8].i, manip = a[9].i, fmt = a[10].i;
bool flipX = (manip & 8192) != 0;
bool flipY = (manip & 16384) != 0;
int rot = manip & 0x1FFF;
if (rot == 180) {
flipX = !flipX;
flipY = !flipY;
}
for (int row = 0; row < h; ++row) {
int sRow = flipY ? (h - 1 - row) : row;
for (int col = 0; col < w; ++col) {
int sCol = flipX ? (w - 1 - col) : col;
int idx = offset + sRow * scanlen + sCol;
if (idx < 0) continue;
uint32_t argb = 0;
if (arr->arrayKind == ArrayKind::Int &&
static_cast<size_t>(idx) < arr->intArr.size()) {
argb = static_cast<uint32_t>(arr->intArr[idx]);
if (!trans || fmt == 888) argb |= 0xFF000000u;
} else if (arr->arrayKind == ArrayKind::Short &&
static_cast<size_t>(idx) < arr->shortArr.size()) {
uint16_t spx = static_cast<uint16_t>(arr->shortArr[idx]);
if (fmt == 565) {
uint32_t r = ((spx >> 11) & 0x1Fu) * 255u / 31u;
uint32_t gr = ((spx >> 5) & 0x3Fu) * 255u / 63u;
uint32_t b = (spx & 0x1Fu) * 255u / 31u;
argb = 0xFF000000u | (r << 16) | (gr << 8) | b;
} else if (fmt == 1555) {
uint32_t al = (!trans || (spx & 0x8000u)) ? 255u : 0u;
uint32_t r = ((spx >> 10) & 0x1Fu) * 255u / 31u;
uint32_t gr = ((spx >> 5) & 0x1Fu) * 255u / 31u;
uint32_t b = (spx & 0x1Fu) * 255u / 31u;
argb = (al << 24) | (r << 16) | (gr << 8) | b;
} else {
// 4444 or 444
uint32_t al = (!trans || fmt == 444)
? 255u
: (((spx >> 12) & 0xFu) * 17u);
uint32_t r = ((spx >> 8) & 0xFu) * 17u;
uint32_t gr = ((spx >> 4) & 0xFu) * 17u;
uint32_t b = (spx & 0xFu) * 17u;
argb = (al << 24) | (r << 16) | (gr << 8) | b;
}
} else {
continue;
}
if ((argb >> 24) == 0) continue;
g->putClipped(x + g->transX + col, y + g->transY + row, argb);
}
}
return JValue::Null();
});
vm.registerWildcardNative(
dgCls, "getPixels",
[getGraphicsState](Jvm& v, JThread&, JValue* a) -> JValue {
auto* g = getGraphicsState(v, a[0].ref);
JObject* arr = v.getObj(a[1].ref);
if (!g || !g->target || !arr) return JValue::Null();
int offset = a[3].i, scanlen = a[4].i, x = a[5].i, y = a[6].i;
int w = a[7].i, h = a[8].i, fmt = a[9].i;
for (int row = 0; row < h; ++row) {
for (int col = 0; col < w; ++col) {
int idx = offset + row * scanlen + col;
if (idx < 0) continue;
uint32_t argb = g->target->getPixel(x + g->transX + col,
y + g->transY + row);
if (arr->arrayKind == ArrayKind::Int &&
static_cast<size_t>(idx) < arr->intArr.size()) {
arr->intArr[idx] = static_cast<int32_t>(argb);
} else if (arr->arrayKind == ArrayKind::Short &&
static_cast<size_t>(idx) < arr->shortArr.size()) {
uint32_t al = (argb >> 24) & 0xFFu;
uint32_t r = (argb >> 16) & 0xFFu;
uint32_t gr = (argb >> 8) & 0xFFu;
uint32_t b = argb & 0xFFu;
uint16_t spx = 0;
if (fmt == 565) {
spx = static_cast<uint16_t>(((r >> 3) << 11) |
((gr >> 2) << 5) | (b >> 3));
} else {
spx = static_cast<uint16_t>(((al >> 4) << 12) |
((r >> 4) << 8) |
((gr >> 4) << 4) | (b >> 4));
}
arr->shortArr[idx] = static_cast<int16_t>(spx);
}
}
}
return JValue::Null();
});
}
vm.registerWildcardNative("com/nokia/mid/ui/DeviceControl", "setLights",
[](Jvm&, JThread&, JValue*) -> JValue { return JValue::Null(); });
vm.registerWildcardNative("com/nokia/mid/ui/DeviceControl", "startVibra",
@@ -1243,15 +1557,19 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
// List
vm.registerWildcardNative(
"javax/microedition/lcdui/List", "<init>",
[](Jvm& v, JThread&, JValue* a) -> JValue {
[ctx](Jvm& v, JThread&, JValue* a) -> JValue {
LcduiScreenState* st = ensureScreenState(v, a[0].ref);
if (st) {
st->title = v.readString(a[1].ref);
st->choiceType = a[2].i;
if (st->choiceType == 3) {
st->selectCommandRef = ctx->listSelectCommandRef;
}
JObject* strArr = v.getObj(a[3].ref);
if (strArr) {
for (uint32_t sref : strArr->refArr) {
st->listItems.push_back(v.readString(sref));
st->listItemRefs.push_back(sref);
st->listImages.push_back(0);
st->listSelected.push_back(false);
}
@@ -1265,11 +1583,28 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
LcduiScreenState* st = ensureScreenState(v, a[0].ref);
if (!st) return JValue::FromInt(0);
st->listItems.push_back(v.readString(a[1].ref));
st->listItemRefs.push_back(a[1].ref);
st->listImages.push_back(a[2].ref);
st->listSelected.push_back(false);
ctx->repaintPending = true;
return JValue::FromInt(static_cast<int32_t>(st->listItems.size()) - 1);
});
vm.registerWildcardNative(
"javax/microedition/lcdui/List", "insert",
[ctx](Jvm& v, JThread&, JValue* a) -> JValue {
LcduiScreenState* st = ensureScreenState(v, a[0].ref);
if (st) {
int idx = std::clamp(
a[1].i, 0, static_cast<int>(st->listItems.size()));
st->listItems.insert(st->listItems.begin() + idx,
v.readString(a[2].ref));
st->listItemRefs.insert(st->listItemRefs.begin() + idx, a[2].ref);
st->listImages.insert(st->listImages.begin() + idx, a[3].ref);
st->listSelected.insert(st->listSelected.begin() + idx, false);
ctx->repaintPending = true;
}
return JValue::Null();
});
vm.registerWildcardNative(
"javax/microedition/lcdui/List", "set",
[ctx](Jvm& v, JThread&, JValue* a) -> JValue {
@@ -1277,6 +1612,7 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
if (st && a[1].i >= 0 &&
static_cast<size_t>(a[1].i) < st->listItems.size()) {
st->listItems[a[1].i] = v.readString(a[2].ref);
st->listItemRefs[a[1].i] = a[2].ref;
st->listImages[a[1].i] = a[3].ref;
ctx->repaintPending = true;
}
@@ -1289,6 +1625,7 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
if (st && a[1].i >= 0 &&
static_cast<size_t>(a[1].i) < st->listItems.size()) {
st->listItems.erase(st->listItems.begin() + a[1].i);
st->listItemRefs.erase(st->listItemRefs.begin() + a[1].i);
st->listImages.erase(st->listImages.begin() + a[1].i);
st->listSelected.erase(st->listSelected.begin() + a[1].i);
ctx->repaintPending = true;
@@ -1301,6 +1638,7 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
LcduiScreenState* st = ensureScreenState(v, a[0].ref);
if (st) {
st->listItems.clear();
st->listItemRefs.clear();
st->listImages.clear();
st->listSelected.clear();
st->selectedIdx = 0;
@@ -1319,6 +1657,11 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
LcduiScreenState* st = ensureScreenState(v, a[0].ref);
if (st && a[1].i >= 0 &&
static_cast<size_t>(a[1].i) < st->listItems.size()) {
if (static_cast<size_t>(a[1].i) <
st->listItemRefs.size() &&
st->listItemRefs[a[1].i] != 0) {
return JValue::FromRef(st->listItemRefs[a[1].i]);
}
return JValue::FromRef(
v.internString(st->listItems[a[1].i]));
}
@@ -1351,7 +1694,9 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
return JValue::FromInt(st->selectedIdx == a[1].i ? 1 : 0);
});
vm.registerWildcardNative("javax/microedition/lcdui/List", "setSelectCommand",
[](Jvm&, JThread&, JValue*) -> JValue {
[](Jvm& v, JThread&, JValue* a) -> JValue {
LcduiScreenState* st = ensureScreenState(v, a[0].ref);
if (st) st->selectCommandRef = a[1].ref;
return JValue::Null();
});
@@ -1531,6 +1876,7 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
if (arr) {
for (uint32_t sref : arr->refArr) {
is->choices.push_back(v.readString(sref));
is->choiceRefs.push_back(sref);
is->choiceSel.push_back(false);
}
}
@@ -1543,6 +1889,7 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
LcduiItemState* is = ensureItemState(v, a[0].ref);
if (!is) return JValue::FromInt(0);
is->choices.push_back(v.readString(a[1].ref));
is->choiceRefs.push_back(a[1].ref);
is->choiceSel.push_back(false);
ctx->repaintPending = true;
return JValue::FromInt(static_cast<int32_t>(is->choices.size()) - 1);
@@ -1571,10 +1918,32 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
LcduiItemState* is = ensureItemState(v, a[0].ref);
if (is && a[1].i >= 0 &&
static_cast<size_t>(a[1].i) < is->choices.size()) {
if (static_cast<size_t>(a[1].i) < is->choiceRefs.size() &&
is->choiceRefs[a[1].i] != 0) {
return JValue::FromRef(is->choiceRefs[a[1].i]);
}
return JValue::FromRef(v.internString(is->choices[a[1].i]));
}
return JValue::FromRef(v.internString(""));
});
vm.registerWildcardNative(
"javax/microedition/lcdui/ChoiceGroup", "isSelected",
[](Jvm& v, JThread&, JValue* a) -> JValue {
LcduiItemState* is = ensureItemState(v, a[0].ref);
if (!is) return JValue::FromInt(0);
if (is->choiceType == 2 && a[1].i >= 0 &&
static_cast<size_t>(a[1].i) < is->choiceSel.size()) {
return JValue::FromInt(is->choiceSel[a[1].i] ? 1 : 0);
}
return JValue::FromInt(is->selectedIdx == a[1].i ? 1 : 0);
});
vm.registerWildcardNative(
"javax/microedition/lcdui/ChoiceGroup", "size",
[](Jvm& v, JThread&, JValue* a) -> JValue {
LcduiItemState* is = ensureItemState(v, a[0].ref);
return JValue::FromInt(
is ? static_cast<int32_t>(is->choices.size()) : 0);
});
vm.registerWildcardNative(
"javax/microedition/lcdui/Gauge", "<init>",
@@ -1610,6 +1979,17 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
LcduiItemState* is = ensureItemState(v, a[0].ref);
return JValue::FromInt(is ? is->maxValue : 100);
});
vm.registerWildcardNative(
"javax/microedition/lcdui/Gauge", "setMaxValue",
[ctx](Jvm& v, JThread&, JValue* a) -> JValue {
LcduiItemState* is = ensureItemState(v, a[0].ref);
if (is) {
is->maxValue = std::max(1, a[1].i);
is->value = std::clamp(is->value, 0, is->maxValue);
ctx->repaintPending = true;
}
return JValue::Null();
});
// -------------------------------------------------------------------------
// javax.microedition.lcdui.game.Sprite / TiledLayer / LayerManager
@@ -1781,12 +2161,11 @@ inline void registerLcduiAndM3gNatives(Jvm& vm, RuntimeAppContext* ctx) {
// -------------------------------------------------------------------------
vm.registerWildcardNative(
"javax/microedition/m3g/Graphics3D", "getInstance",
[](Jvm& v, JThread&, JValue*) -> JValue {
static uint32_t g3dRef = 0;
if (g3dRef == 0) {
g3dRef = v.allocObject("javax/microedition/m3g/Graphics3D");
[ctx](Jvm& v, JThread&, JValue*) -> JValue {
if (ctx->graphics3dRef == 0) {
ctx->graphics3dRef = v.allocObject("javax/microedition/m3g/Graphics3D");
}
return JValue::FromRef(g3dRef);
return JValue::FromRef(ctx->graphics3dRef);
});
vm.registerWildcardNative(
"javax/microedition/m3g/Graphics3D", "bindTarget",
+113 -25
View File
@@ -8,6 +8,7 @@
#include <X11/XF86keysym.h>
#include <X11/keysym.h>
#include <malloc.h>
#include <poll.h>
#include <sys/stat.h>
#include <sys/timerfd.h>
@@ -65,6 +66,7 @@ static const char* const kActionNames[ACT_COUNT] = {
struct RemedyConfig {
bool hwAccel3D = true;
int scaleMode = 0; // 0=Auto, 1=Full Stretch, 2=1:1 (240x320)
int softbarMode = 0; // 0=Auto (non-fullscreen Canvas), 1=Always Overlay, 2=Hidden
int fpsLimit = 30; // 30 or 60 FPS
bool audioEnabled = true;
@@ -95,6 +97,7 @@ struct RemedyConfig {
std::string v = line.substr(eq + 1);
int iv = std::atoi(v.c_str());
if (k == "hwAccel3D") hwAccel3D = (iv != 0);
else if (k == "scaleMode") scaleMode = std::clamp(iv, 0, 2);
else if (k == "softbarMode") softbarMode = std::clamp(iv, 0, 2);
else if (k == "fpsLimit") fpsLimit = (iv == 60) ? 60 : 30;
else if (k == "audioEnabled") audioEnabled = (iv != 0);
@@ -115,6 +118,7 @@ struct RemedyConfig {
std::ofstream f(p, std::ios::trunc);
if (!f) return;
f << "hwAccel3D=" << (hwAccel3D ? 1 : 0) << "\n";
f << "scaleMode=" << scaleMode << "\n";
f << "softbarMode=" << softbarMode << "\n";
f << "fpsLimit=" << fpsLimit << "\n";
f << "audioEnabled=" << (audioEnabled ? 1 : 0) << "\n";
@@ -336,6 +340,7 @@ class RemedyEmulator {
}
void shutdown() {
unloadMidletSuite();
if (canvasXimg) {
canvasXimg->data = nullptr;
XDestroyImage(canvasXimg);
@@ -347,6 +352,29 @@ class RemedyEmulator {
neoWin.destroy();
}
void unloadMidletSuite() {
cldcRuntime.sound.stopAll();
activeCanvasKeys.clear();
if (vm && hasLoadedMidlet && appCtx.midletRef != 0) {
JObject* mo = vm->getObj(appCtx.midletRef);
if (mo) {
auto [dc, dm] =
vm->resolveMethod(mo->className, "destroyApp", "(Z)V", false);
if (dm && !dm->code.empty()) {
JThread dTh;
vm->invokeManagedSync(
dTh, dc, dm,
{JValue::FromRef(appCtx.midletRef), JValue::FromInt(1)},
1000000);
}
}
}
vm.reset();
appCtx = RuntimeAppContext{};
jar = ZipArchive{};
hasLoadedMidlet = false;
}
void grabKeyboard() {
if (!neoWin.dpy || neoWin.win == None) return;
if (isExternalOverlayActive()) {
@@ -490,8 +518,7 @@ class RemedyEmulator {
}
bool loadMidletSuite(const std::string& path) {
cldcRuntime.sound.stopAll();
activeCanvasKeys.clear();
unloadMidletSuite();
midletTickCount = 0;
std::string errMsg;
if (!loadSuiteFromJarOrJad(path, &jar, &suite, &errMsg)) {
@@ -538,7 +565,7 @@ class RemedyEmulator {
vm->resolveMethod(mainClass, "<init>", "()V", false);
if (initM && !initM->code.empty()) {
vm->invokeManagedSync(mainTh, initCls, initM,
{JValue::FromRef(midletRef)}, 5000000);
{JValue::FromRef(midletRef)}, 20000000);
}
mainTh.pendingExceptionRef = 0;
mainTh.frames.clear();
@@ -546,7 +573,7 @@ class RemedyEmulator {
vm->resolveMethod(mainClass, "startApp", "()V", false);
if (startM && !startM->code.empty()) {
vm->invokeManagedSync(mainTh, startCls, startM,
{JValue::FromRef(midletRef)}, 25000000);
{JValue::FromRef(midletRef)}, 50000000);
}
currentJarOrJadPath = path;
@@ -598,20 +625,27 @@ class RemedyEmulator {
// Use a wall-clock budget (~60% of the frame interval) instead of a fixed
// instruction count so CPU-heavy loaders (level/asset unpacking in games
// like Castlevania) run at full interpreter speed, while idle games that
// sleep in Thread.sleep() / wait() still return to poll() immediately.
// sleep in Thread.sleep() / wait() or finish a serviceRepaints() frame
// return to poll() immediately.
cldcRuntime.tickTimersAndSerialCallbacks(*vm);
{
int64_t frameMs = 1000 / std::max(1, cfg.fpsLimit);
int64_t budgetMs = std::max<int64_t>(6, (frameMs * 6) / 10);
int64_t deadline = Jvm::NowMs() + budgetMs;
int slices = 0;
appCtx.paintedInStep = false;
do {
vm->stepThreads(20000);
++slices;
} while (slices < 64 && !vm->exitRequested && !appCtx.midletDestroyed &&
vm->anyThreadReady() && Jvm::NowMs() < deadline);
!appCtx.paintedInStep && vm->anyThreadReady() &&
Jvm::NowMs() < deadline);
}
midletTickCount++;
if (midletTickCount % 120 == 0 ||
vm->usedHeapBytes() > 24 * 1024 * 1024) {
vm->collectGarbage();
}
if (!activeCanvasKeys.empty()) {
int64_t nowMs = Jvm::NowMs();
@@ -633,8 +667,7 @@ class RemedyEmulator {
}
if (appCtx.midletDestroyed || vm->exitRequested) {
cldcRuntime.sound.stopAll();
hasLoadedMidlet = false;
unloadMidletSuite();
mode = EmuUiMode::BROWSER;
renderBrowserMenu();
return;
@@ -671,7 +704,9 @@ class RemedyEmulator {
// Active Displayable is a full-screen 240x320 Canvas / GameCanvas
JObject* dispObj = vm->getObj(dispRef);
if (dispObj && appCtx.repaintPending) {
if (dispObj && appCtx.repaintPending && !appCtx.inPaint) {
appCtx.inPaint = true;
appCtx.repaintPending = false;
JObject* gObj = vm->getObj(appCtx.sharedGraphicsRef);
if (gObj && gObj->nativeData) {
auto* gs = static_cast<NativeGraphicsState*>(gObj->nativeData.get());
@@ -686,14 +721,54 @@ class RemedyEmulator {
paintTh, rc, rm,
{JValue::FromRef(dispRef),
JValue::FromRef(appCtx.sharedGraphicsRef)},
250000);
25000000);
}
appCtx.repaintPending = false;
appCtx.inPaint = false;
}
// Blit 240x320 ARGB8888 canvasFb to NeoWindow's offscreen Pixmap
std::memcpy(ximgPixels.data(), appCtx.canvasFb.pixels.data(),
240 * 320 * sizeof(uint32_t));
// Blit 240x320 ARGB8888 canvasFb to NeoWindow's offscreen Pixmap,
// automatically scaling sub-QVGA games (128x128, 128x160, 176x208, 176x220)
int maxX = appCtx.canvasFb.maxDrawnX;
int maxY = appCtx.canvasFb.maxDrawnY;
if (cfg.scaleMode != 2 && maxX > 0 && maxX < 192 && maxY > 0 && maxY < 236) {
int srcW = 240;
int srcH = 320;
if (maxX < 128 && maxY < 128) {
srcW = 128;
srcH = 128;
} else if (maxX < 128 && maxY < 160) {
srcW = 128;
srcH = 160;
} else if (maxX < 176 && maxY < 208) {
srcW = 176;
srcH = 208;
} else if (maxX < 176 && maxY < 220) {
srcW = 176;
srcH = 220;
} else {
srcW = maxX + 1;
srcH = maxY + 1;
}
int dstW = 240;
int dstH = (cfg.scaleMode == 1)
? 320
: std::min(320, (srcH * 240 + srcW / 2) / srcW);
int dstY0 = (320 - dstH) / 2;
std::fill(ximgPixels.begin(), ximgPixels.end(), 0xFF000000u);
const uint32_t* srcPx = appCtx.canvasFb.pixels.data();
for (int dy = 0; dy < dstH; ++dy) {
int sy = (dy * srcH) / dstH;
const uint32_t* sRow = srcPx + sy * 240;
uint32_t* dRow = ximgPixels.data() + (dstY0 + dy) * 240;
for (int dx = 0; dx < dstW; ++dx) {
int sx = (dx * srcW) / dstW;
dRow[dx] = sRow[sx];
}
}
} else {
std::memcpy(ximgPixels.data(), appCtx.canvasFb.pixels.data(),
240 * 320 * sizeof(uint32_t));
}
XPutImage(neoWin.dpy, neoWin.pix, neoWin.gc, canvasXimg, 0, 0, 0, 0, 240, 320);
// Optional softkey bar or command popup overlay via NeoUI
@@ -813,6 +888,8 @@ class RemedyEmulator {
items.push_back("Resume MIDlet");
items.push_back("MIDlet Commands...");
}
const char* scModes[] = {"< Auto >", "< Full Stretch >", "< 1:1 (240x320) >"};
items.push_back(std::string("Canvas Scale: ") + scModes[cfg.scaleMode]);
items.push_back(std::string("3D Engine: ") +
(m3g.useHardwareGl ? "< Adreno FD304 GL >" : "< Software 3D >"));
const char* sbModes[] = {"< Auto >", "< Overlay >", "< Full 240x320 >"};
@@ -1069,7 +1146,7 @@ class RemedyEmulator {
vm->invokeManagedSync(
keyTh, rc, rm,
{JValue::FromRef(dispRef), JValue::FromInt(midpKeyCode)},
100000);
5000000);
}
}
@@ -1153,21 +1230,28 @@ class RemedyEmulator {
static_cast<size_t>(st->selectedIdx) < st->listSelected.size()) {
st->listSelected[st->selectedIdx] = !st->listSelected[st->selectedIdx];
}
// Trigger IMPLICIT list command or first OK/SCREEN command
// Trigger IMPLICIT list selectCommand (List.SELECT_COMMAND by default)
// or first OK/SCREEN/ITEM command
uint32_t cmdToFire = 0;
for (const auto& c : st->commands) {
if (c.type == 1 || c.type == 4 || c.type == 8) {
cmdToFire = c.cmdRef;
break;
if (st->choiceType == 3) {
cmdToFire = st->selectCommandRef != 0
? st->selectCommandRef
: appCtx.listSelectCommandRef;
}
if (cmdToFire == 0) {
for (const auto& c : st->commands) {
if (c.type == 1 || c.type == 4 || c.type == 8) {
cmdToFire = c.cmdRef;
break;
}
}
}
if (cmdToFire == 0) {
cmdToFire = appCtx.listSelectCommandRef;
}
JThread cmdTh;
if (cmdToFire != 0) {
invokeCommandOnDisplayable(*vm, cmdTh, dispRef, cmdToFire);
} else if (st->listenerRef != 0) {
// List.SELECT_COMMAND (null or synthetic command)
uint32_t selCmd = vm->allocObject("javax/microedition/lcdui/Command");
invokeCommandOnDisplayable(*vm, cmdTh, dispRef, selCmd);
}
appCtx.repaintPending = true;
}
@@ -1500,7 +1584,11 @@ class RemedyEmulator {
appCtx.repaintPending = true;
return true;
}
if (choice.rfind("3D Engine:", 0) == 0) {
if (choice.rfind("Canvas Scale:", 0) == 0) {
int dir = (ks == XK_Left) ? 2 : 1;
cfg.scaleMode = (cfg.scaleMode + dir) % 3;
cfg.save();
} else if (choice.rfind("3D Engine:", 0) == 0) {
cfg.hwAccel3D = !cfg.hwAccel3D;
m3g.useHardwareGl = cfg.hwAccel3D && m3g.hwInitialized;
cfg.save();
+45 -1
View File
@@ -1459,7 +1459,7 @@ bool NeoWindow::create(const char* resName, const char* resClass,
swa.override_redirect = overrideRedirect ? True : False;
swa.background_pixel = 0x222222;
swa.border_pixel = 0x005577;
swa.event_mask = eventMask | VisibilityChangeMask | FocusChangeMask;
swa.event_mask = eventMask | VisibilityChangeMask | FocusChangeMask | ButtonPressMask;
win = XCreateWindow(
dpy, root, x, y, width, height, 0, DefaultDepth(dpy, screen),
@@ -2880,6 +2880,50 @@ int neoui_poll_event(int timeout_ms) {
}
continue;
}
if (ev.type == ButtonPress && ctx->visible) {
if (ev.xbutton.button == Button4) {
ctx->lastEventKey = NEO_KEY_UP;
ctx->lastEventKeysym = XK_Up;
ctx->lastEventType = NEO_EV_KEY_PRESS;
return NEO_EV_KEY_PRESS;
}
if (ev.xbutton.button == Button5) {
ctx->lastEventKey = NEO_KEY_DOWN;
ctx->lastEventKeysym = XK_Down;
ctx->lastEventType = NEO_EV_KEY_PRESS;
return NEO_EV_KEY_PRESS;
}
if (ev.xbutton.button == Button3) {
ctx->lastEventKey = NEO_KEY_SOFT_RIGHT;
ctx->lastEventKeysym = XK_F2;
ctx->lastEventType = NEO_EV_SOFTKEY_RIGHT;
return NEO_EV_SOFTKEY_RIGHT;
}
if (ev.xbutton.button == Button1) {
int winW = ctx->w ? ctx->w->width : NEO_WIN_W;
int winH = ctx->w ? ctx->w->height : NEO_WIN_H;
int sbH = NEO_SOFTBAR_H;
if (ev.xbutton.y >= winH - sbH) {
if (ev.xbutton.x < winW / 3) {
ctx->lastEventKey = NEO_KEY_SOFT_LEFT;
ctx->lastEventKeysym = XK_F1;
ctx->lastEventType = NEO_EV_SOFTKEY_LEFT;
return NEO_EV_SOFTKEY_LEFT;
}
if (ev.xbutton.x > (winW * 2) / 3) {
ctx->lastEventKey = NEO_KEY_SOFT_RIGHT;
ctx->lastEventKeysym = XK_F2;
ctx->lastEventType = NEO_EV_SOFTKEY_RIGHT;
return NEO_EV_SOFTKEY_RIGHT;
}
}
ctx->lastEventKey = NEO_KEY_OK;
ctx->lastEventKeysym = XK_Return;
ctx->lastEventType = NEO_EV_KEY_PRESS;
return NEO_EV_KEY_PRESS;
}
continue;
}
if (ev.type == KeyPress || ev.type == KeyRelease) {
if (bananarchy::isExternalOverlayOrLockActive(ctx->appName) ||
bananarchy::monotonicMs() < ctx->overlayGraceUntilMs) {
+8 -1
View File
@@ -2019,6 +2019,8 @@ readstdin(void)
static int
bt_is_unblocked_fast(void)
{
if (access("/run/bluetoothd.pid", F_OK) != 0)
return 0;
DIR *d = opendir("/sys/class/rfkill");
if (!d)
return 0;
@@ -2689,7 +2691,12 @@ open_builtin_menu(const char *menu_name, int keep_idx)
int is_ear = (strstr(out_dev, "Earpiece") != NULL || strstr(out_dev, "earpiece") != NULL);
int is_hp = (strstr(out_dev, "Headphone") != NULL || strstr(out_dev, "headphone") != NULL ||
strstr(out_dev, "Headset") != NULL || strstr(out_dev, "headset") != NULL);
int is_spk = (!is_ear && !is_hp);
int is_bt = (strstr(out_dev, "Bluetooth") != NULL || strstr(out_dev, "bluetooth") != NULL ||
strstr(out_dev, "bluez") != NULL);
int is_spk = (!is_ear && !is_hp && !is_bt);
snprintf(label, sizeof(label), "%s Route to Bluetooth %s", ICON_BTH, is_bt ? ICON_TON : ICON_TOF);
add_menu_item(label, "printf 'Bluetooth\\n' > /tmp/sxmo_audio_out_device; sxmo_audio.sh device set Bluetooth >/dev/null 2>&1", 1);
snprintf(label, sizeof(label), "%s Route to Speaker %s", ICON_MUS, is_spk ? ICON_TON : ICON_TOF);
add_menu_item(label, "printf 'Speaker\\n' > /tmp/sxmo_audio_out_device; sxmo_audio.sh device set Speaker >/dev/null 2>&1", 1);
+61 -1
View File
@@ -636,6 +636,9 @@ unswallow(Client *c)
setclientstate(c, NormalState);
}
static void dwm_cursor_set_visible(int show);
static void dwm_handle_softbar_click(int x);
void
buttonpress(XEvent *e)
{
@@ -645,6 +648,11 @@ buttonpress(XEvent *e)
Monitor *m;
XButtonPressedEvent *ev = &e->xbutton;
dwm_cursor_set_visible(1);
if (selmon && ev->window == selmon->softwin && ev->button == Button1) {
dwm_handle_softbar_click(ev->x);
return;
}
click = ClkRootWin;
/* focus monitor if necessary */
if (!((c = wintoclient(ev->window)) && c->iskbd)
@@ -2073,6 +2081,52 @@ flush_pending_softkey(void)
}
}
static long long last_mouse_ms = 0;
static int cursor_hidden = 0;
static void
dwm_cursor_set_visible(int show)
{
typedef void (*xfixes_cursor_fn)(Display *, Window);
static int xfixes_init = 0;
static xfixes_cursor_fn fn_hide = NULL;
static xfixes_cursor_fn fn_show = NULL;
if (!dpy || !root)
return;
if (!xfixes_init) {
xfixes_init = 1;
void *h = dlopen("libXfixes.so.3", RTLD_LAZY | RTLD_LOCAL);
if (h) {
fn_hide = (xfixes_cursor_fn)dlsym(h, "XFixesHideCursor");
fn_show = (xfixes_cursor_fn)dlsym(h, "XFixesShowCursor");
}
}
if (show) {
last_mouse_ms = dwm_now_ms();
if (cursor_hidden && fn_show) {
fn_show(dpy, root);
cursor_hidden = 0;
XFlush(dpy);
}
} else {
if (!cursor_hidden && fn_hide) {
fn_hide(dpy, root);
cursor_hidden = 1;
XFlush(dpy);
}
}
}
static void
dwm_handle_softbar_click(int x)
{
if (!selmon)
return;
softkey_pending = (x < selmon->ww / 2) ? SOFTKEY_LEFT : SOFTKEY_RIGHT;
flush_pending_softkey();
}
static int
is_star_key(KeySym ks, unsigned int keycode)
{
@@ -2181,6 +2235,8 @@ keypress(XEvent *e)
ev = &e->xkey;
keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
if (cursor_hidden == 0 && (dwm_now_ms() - last_mouse_ms) > 4000)
dwm_cursor_set_visible(0);
if (is_screen_off()) {
wake_phone();
@@ -2324,6 +2380,8 @@ keyrelease(XEvent *e)
ev = &e->xkey;
keysym = XKeycodeToKeysym(dpy, (KeyCode)ev->keycode, 0);
if (cursor_hidden == 0 && (dwm_now_ms() - last_mouse_ms) > 4000)
dwm_cursor_set_visible(0);
markreleased(keysym);
@@ -2485,6 +2543,7 @@ motionnotify(XEvent *e)
Monitor *m;
XMotionEvent *ev = &e->xmotion;
dwm_cursor_set_visible(1);
if (ev->window != root)
return;
if ((m = recttomon(ev->x_root, ev->y_root, 1, 1)) != mon && mon) {
@@ -3108,6 +3167,7 @@ setup(void)
load_plugins();
grabkeys();
focus(NULL);
dwm_cursor_set_visible(0);
}
@@ -3384,7 +3444,7 @@ updatebars(void)
XSetWindowAttributes softwa = {
.override_redirect = True,
.background_pixmap = ParentRelative,
.event_mask = ExposureMask
.event_mask = ExposureMask|ButtonPressMask
};
int sh_bar = 26;
m->softwin = XCreateWindow(dpy, root, m->wx, m->my + m->mh - sh_bar, m->ww, sh_bar, 0,
+43 -13
View File
@@ -296,8 +296,13 @@ class PhoneController {
std::string outDev = readActiveOutputDevice();
bool outMuted = (readIntFile("/tmp/sxmo_out_muted", 0) == 1);
// 1. Primary output volume (Speaker or Headphones if Headphones are active, linear 0..100%)
if (outDev == "Headphones") {
// 1. Primary output volume (Speaker, Headphones, or Bluetooth, linear 0..100%)
if (outDev == "Bluetooth") {
int btPct = readIntFile(getSxmoCfgDir() + "/bluetooth_vol", 80);
btPct = std::clamp(((btPct + 2) / 5) * 5, 0, 100);
items_.push_back({ControlId::SpeakerVol, kIconHeadphones, kIconSoundOff,
"Bluetooth", true, 0, 100, 5, btPct});
} else if (outDev == "Headphones") {
int hpPct = readIntFile(getSxmoCfgDir() + "/headphones_vol", -1);
if (hpPct < 0 || hpPct > 100) {
long rx1 = alsa_.getInteger("RX1 Digital Volume", 78);
@@ -365,10 +370,12 @@ class PhoneController {
items_.push_back({ControlId::Flashlight, kIconFlashlight, kIconFlashlight,
"Flashlight", false, 0, 1, 1, (torchCur > 0) ? 1 : 0});
// 7. Audio Output Route / Mute (0=Muted, 1=Speaker, 2=Earpiece, 3=Headphones)
// 7. Audio Output Route / Mute (0=Muted, 1=Speaker, 2=Earpiece, 3=Headphones, 4=Bluetooth)
int outMode = 1;
if (outMuted) {
outMode = 0;
} else if (outDev == "Bluetooth") {
outMode = 4;
} else if (outDev == "Earpiece") {
outMode = 2;
} else if (outDev == "Headphones") {
@@ -376,11 +383,11 @@ class PhoneController {
} else {
outMode = 1;
}
const char* outIcon = (outMode == 3) ? kIconHeadphones
const char* outIcon = (outMode == 3 || outMode == 4) ? kIconHeadphones
: (outMode == 2) ? kIconEarpiece
: kIconSoundOn;
items_.push_back({ControlId::SoundMute, outIcon, kIconSoundOff,
"Output", false, 0, 3, 1, outMode});
"Output", false, 0, 4, 1, outMode});
// 8. Microphone on/off (toggle)
unsigned int dec1 = alsa_.getEnum("DEC1 MUX", 1);
@@ -435,8 +442,10 @@ class PhoneController {
ControlItem& it = items_[idx];
if (it.isSlider) {
it.value = std::clamp(it.value + dir * it.stepVal, it.minVal, it.maxVal);
} else if (it.id == ControlId::RingerMode || it.id == ControlId::SoundMute) {
} else if (it.id == ControlId::RingerMode) {
it.value = (it.value + dir + 4) % 4;
} else if (it.id == ControlId::SoundMute) {
it.value = (it.value + dir + 5) % 5;
} else if (it.id == ControlId::VibrateStrength) {
it.value = ((it.value - 1 + dir + 3) % 3) + 1;
} else {
@@ -450,9 +459,12 @@ class PhoneController {
return;
}
ControlItem& it = items_[idx];
if (it.id == ControlId::RingerMode || it.id == ControlId::SoundMute) {
if (it.id == ControlId::RingerMode) {
it.value = (it.value + 1) % 4;
apply(it);
} else if (it.id == ControlId::SoundMute) {
it.value = (it.value + 1) % 5;
apply(it);
} else if (it.id == ControlId::VibrateStrength) {
it.value = (it.value % 3) + 1;
apply(it);
@@ -479,6 +491,10 @@ class PhoneController {
if (dev.empty()) {
dev = readLine(getSxmoCfgDir() + "/audio_out_device");
}
if (dev.find("Bluetooth") != std::string::npos || dev.find("bluetooth") != std::string::npos ||
dev.find("bluez") != std::string::npos) {
return "Bluetooth";
}
if (dev.find("Earpiece") != std::string::npos || dev.find("earpiece") != std::string::npos) {
return "Earpiece";
}
@@ -589,7 +605,15 @@ class PhoneController {
std::string cfg = getSxmoCfgDir();
::mkdir(cfg.c_str(), 0755);
std::string outDev = readActiveOutputDevice();
if (outDev == "Headphones") {
if (outDev == "Bluetooth") {
writeIntFile(cfg + "/bluetooth_vol", it.value);
writeIntFile("/tmp/sxmo_out_muted", (it.value <= 0) ? 1 : 0);
char cmd[160];
std::snprintf(cmd, sizeof(cmd),
"sxmo_audio.sh vol set %d Bluetooth >/dev/null 2>&1",
it.value);
runAsyncCmd(cmd);
} else if (outDev == "Headphones") {
writeIntFile(cfg + "/headphones_vol", it.value);
writeIntFile("/tmp/sxmo_out_muted", (it.value <= 0) ? 1 : 0);
long hw = (it.value <= 0) ? 0 : (52 + std::lround((it.value * 32.0) / 100.0));
@@ -670,10 +694,11 @@ class PhoneController {
runAsyncCmd("sxmo_audio.sh vol mute >/dev/null 2>&1");
} else {
writeIntFile("/tmp/sxmo_out_muted", 0);
const char* targetDev = (it.value == 2) ? "Earpiece"
const char* targetDev = (it.value == 4) ? "Bluetooth"
: (it.value == 3) ? "Headphones"
: (it.value == 2) ? "Earpiece"
: "Speaker";
it.iconOn = (it.value == 3) ? kIconHeadphones
it.iconOn = (it.value == 3 || it.value == 4) ? kIconHeadphones
: (it.value == 2) ? kIconEarpiece
: kIconSoundOn;
{
@@ -681,7 +706,12 @@ class PhoneController {
if (ofs) ofs << targetDev << "\n";
}
if (!items_.empty() && items_[0].id == ControlId::SpeakerVol) {
if (it.value == 3) {
if (it.value == 4) {
int btPct = readIntFile(getSxmoCfgDir() + "/bluetooth_vol", 80);
items_[0].label = "Bluetooth";
items_[0].iconOn = kIconHeadphones;
items_[0].value = std::clamp(((btPct + 2) / 5) * 5, 0, 100);
} else if (it.value == 3) {
int hpPct = readIntFile(getSxmoCfgDir() + "/headphones_vol", 80);
items_[0].label = "Headphones";
items_[0].iconOn = kIconHeadphones;
@@ -954,8 +984,8 @@ static int xdrawer_run_main(int argc, char** argv) {
: ((it.value == 1) ? &colYellow : &colMuted);
drawPango(layoutSmall, rCol, kWinWidth - stW - 6, ry, rowH, stStr);
} else if (it.id == ControlId::SoundMute) {
const char* oModes[4] = {"Muted", "Speaker", "Earpiece", "Headset"};
std::string stStr = std::string("< ") + oModes[std::clamp(it.value, 0, 3)] + " >";
const char* oModes[5] = {"Muted", "Speaker", "Earpiece", "Headset", "Bluetooth"};
std::string stStr = std::string("< ") + oModes[std::clamp(it.value, 0, 4)] + " >";
int stW = pangoWidth(layoutSmall, stStr);
XftColor* oCol = (it.value > 0) ? (isSel ? &colYellow : &colGreen) : &colMuted;
drawPango(layoutSmall, oCol, kWinWidth - stW - 6, ry, rowH, stStr);