Add ReMEdy native 240x320 J2ME (MIDP 2.0 / CLDC 1.1 / M3G 3D) emulator and file manager integration

This commit is contained in:
Luxferre committed 2026-10-28 12:41:00 +02:00
1 parent 3b9f2ee28d
commit 66769d7c2e
39 files changed
+15412 -15

No files matched your search

+905
View File
@@ -0,0 +1,905 @@
// SPDX-License-Identifier: GPL-2.0-only
// ReMEdy J2ME (MIDP 2.0 / CLDC 1.1) Emulator for Bananarchy Linux
// Part 1: ZIP/JAR Reader, JAD/MANIFEST.MF Parser, and RMS (RecordStore) Engine
#ifndef BANANARCHY_REMEDY_ZIP_RMS_HPP
#define BANANARCHY_REMEDY_ZIP_RMS_HPP
#include <algorithm>
#include <cctype>
#include <cstdint>
#include <cstdio>
#include <cstdlib>
#include <cstring>
#include <ctime>
#include <curl/curl.h>
#include <dirent.h>
#include <fstream>
#include <map>
#include <sstream>
#include <string>
#include <sys/stat.h>
#include <unistd.h>
#include <unordered_map>
#include <vector>
#include <zlib.h>
namespace remedy {
inline int64_t nowMs() {
struct timespec ts {};
clock_gettime(CLOCK_MONOTONIC, &ts);
return static_cast<int64_t>(ts.tv_sec) * 1000LL + ts.tv_nsec / 1000000LL;
}
inline int64_t wallTimeMs() {
struct timespec ts {};
clock_gettime(CLOCK_REALTIME, &ts);
return static_cast<int64_t>(ts.tv_sec) * 1000LL + ts.tv_nsec / 1000000LL;
}
inline std::string trimStr(const std::string& s) {
size_t b = 0;
while (b < s.size() &&
(s[b] == ' ' || s[b] == '\t' || s[b] == '\r' || s[b] == '\n')) {
++b;
}
size_t e = s.size();
while (e > b &&
(s[e - 1] == ' ' || s[e - 1] == '\t' || s[e - 1] == '\r' ||
s[e - 1] == '\n')) {
--e;
}
return s.substr(b, e - b);
}
inline std::string toLowerStr(std::string s) {
for (char& c : s) {
c = static_cast<char>(std::tolower(static_cast<unsigned char>(c)));
}
return s;
}
inline void ensureDir(const std::string& path) {
std::string cur;
for (size_t i = 0; i < path.size(); ++i) {
cur.push_back(path[i]);
if (path[i] == '/' && cur.size() > 1) {
::mkdir(cur.c_str(), 0755);
}
}
if (!cur.empty()) {
::mkdir(cur.c_str(), 0755);
}
}
inline std::string getHomeDir() {
const char* h = std::getenv("HOME");
return (h && h[0]) ? h : "/home/user";
}
inline std::string getDataRootDir() {
const char* xdg = std::getenv("XDG_DATA_HOME");
std::string base = (xdg && xdg[0]) ? xdg : (getHomeDir() + "/.local/share");
return base + "/sxmo/remedy";
}
inline std::string getConfigPath() {
const char* xdg = std::getenv("XDG_CONFIG_HOME");
std::string base = (xdg && xdg[0]) ? xdg : (getHomeDir() + "/.config");
return base + "/sxmo/remedy.cfg";
}
inline std::string sanitizePathToken(const std::string& s) {
std::string out;
out.reserve(s.size());
for (unsigned char c : s) {
if (std::isalnum(c) || c == '_' || c == '-' || c == '.') {
out.push_back(static_cast<char>(c));
} else {
out.push_back('_');
}
}
if (out.empty()) out = "default";
return out;
}
inline std::string dirnameOf(const std::string& p) {
size_t sl = p.rfind('/');
if (sl == std::string::npos) return ".";
if (sl == 0) return "/";
return p.substr(0, sl);
}
inline std::string basenameOf(const std::string& p) {
size_t sl = p.rfind('/');
return (sl == std::string::npos) ? p : p.substr(sl + 1);
}
inline std::string stripExtension(const std::string& p) {
std::string b = basenameOf(p);
size_t dot = b.rfind('.');
if (dot != std::string::npos && dot > 0) {
return b.substr(0, dot);
}
return b;
}
inline std::string getExtLower(const std::string& p) {
size_t dot = p.rfind('.');
if (dot == std::string::npos || dot + 1 >= p.size()) return "";
return toLowerStr(p.substr(dot + 1));
}
inline uint16_t readLe16(const uint8_t* p) {
return static_cast<uint16_t>(p[0]) | (static_cast<uint16_t>(p[1]) << 8);
}
inline uint32_t readLe32(const uint8_t* p) {
return static_cast<uint32_t>(p[0]) |
(static_cast<uint32_t>(p[1]) << 8) |
(static_cast<uint32_t>(p[2]) << 16) |
(static_cast<uint32_t>(p[3]) << 24);
}
// ---------------------------------------------------------------------------
// ZIP / JAR Archive Reader
// ---------------------------------------------------------------------------
struct ZipEntryMeta {
std::string name;
uint16_t method = 0;
uint32_t compSize = 0;
uint32_t uncompSize = 0;
uint32_t localHeaderOffset = 0;
};
class ZipArchive {
public:
bool openFile(const std::string& path) {
entries_.clear();
exactMap_.clear();
lowerMap_.clear();
std::ifstream in(path, std::ios::binary | std::ios::ate);
if (!in.is_open()) return false;
std::streamsize sz = in.tellg();
if (sz <= 0 || sz > 64 * 1024 * 1024) return false;
in.seekg(0, std::ios::beg);
raw_.resize(static_cast<size_t>(sz));
if (!in.read(reinterpret_cast<char*>(raw_.data()), sz)) return false;
return parseArchive();
}
bool isOpen() const { return !raw_.empty(); }
const std::vector<ZipEntryMeta>& entries() const { return entries_; }
static std::string normalizeEntryPath(const std::string& path) {
std::string clean;
clean.reserve(path.size());
for (char c : path) {
if (c == '\\') c = '/';
clean.push_back(c);
}
while (!clean.empty() && clean.front() == '/') {
clean.erase(clean.begin());
}
// Resolve "./" and "../" segments
std::vector<std::string> parts;
std::stringstream ss(clean);
std::string seg;
while (std::getline(ss, seg, '/')) {
if (seg.empty() || seg == ".") continue;
if (seg == "..") {
if (!parts.empty()) parts.pop_back();
} else {
parts.push_back(seg);
}
}
std::string out;
for (size_t i = 0; i < parts.size(); ++i) {
if (i > 0) out.push_back('/');
out += parts[i];
}
return out;
}
bool hasEntry(const std::string& name) const {
std::string norm = normalizeEntryPath(name);
if (exactMap_.find(norm) != exactMap_.end()) return true;
return lowerMap_.find(toLowerStr(norm)) != lowerMap_.end();
}
bool extractEntry(const std::string& name, std::vector<uint8_t>* out) const {
if (!out) return false;
out->clear();
std::string norm = normalizeEntryPath(name);
size_t idx = 0;
auto it = exactMap_.find(norm);
if (it != exactMap_.end()) {
idx = it->second;
} else {
auto lit = lowerMap_.find(toLowerStr(norm));
if (lit == lowerMap_.end()) return false;
idx = lit->second;
}
return extractByIndex(idx, out);
}
bool extractByIndex(size_t idx, std::vector<uint8_t>* out) const {
if (!out || idx >= entries_.size()) return false;
const ZipEntryMeta& e = entries_[idx];
if (e.localHeaderOffset + 30 > raw_.size()) return false;
const uint8_t* lh = raw_.data() + e.localHeaderOffset;
if (readLe32(lh) != 0x04034b50u) return false;
uint16_t fnLen = readLe16(lh + 26);
uint16_t extraLen = readLe16(lh + 28);
size_t dataOff = e.localHeaderOffset + 30u + fnLen + extraLen;
if (dataOff + e.compSize > raw_.size()) return false;
const uint8_t* compPtr = raw_.data() + dataOff;
if (e.method == 0) {
out->assign(compPtr, compPtr + e.compSize);
return true;
} else if (e.method == 8) {
out->resize(e.uncompSize > 0 ? e.uncompSize : (e.compSize * 4 + 256));
z_stream strm {};
strm.next_in = const_cast<Bytef*>(compPtr);
strm.avail_in = e.compSize;
if (inflateInit2(&strm, -MAX_WBITS) != Z_OK) return false;
size_t totalOut = 0;
int ret = Z_OK;
while (ret == Z_OK) {
if (totalOut >= out->size()) {
out->resize(out->size() * 2 + 4096);
}
strm.next_out = out->data() + totalOut;
strm.avail_out = static_cast<uInt>(out->size() - totalOut);
ret = inflate(&strm, Z_NO_FLUSH);
totalOut = strm.total_out;
if (ret == Z_STREAM_END) break;
if (ret != Z_OK && ret != Z_BUF_ERROR) {
inflateEnd(&strm);
return false;
}
if (strm.avail_in == 0 && ret == Z_BUF_ERROR) break;
}
inflateEnd(&strm);
out->resize(totalOut);
return true;
}
return false;
}
private:
std::vector<uint8_t> raw_;
std::vector<ZipEntryMeta> entries_;
std::unordered_map<std::string, size_t> exactMap_;
std::unordered_map<std::string, size_t> lowerMap_;
void registerEntry(const ZipEntryMeta& meta) {
size_t idx = entries_.size();
entries_.push_back(meta);
exactMap_[meta.name] = idx;
lowerMap_[toLowerStr(meta.name)] = idx;
}
bool parseArchive() {
if (raw_.size() < 22) return false;
// Search backwards for End of Central Directory (0x06054b50)
size_t minOff = (raw_.size() > 65557) ? (raw_.size() - 65557) : 0;
ssize_t eocdOff = -1;
for (ssize_t i = static_cast<ssize_t>(raw_.size()) - 22;
i >= static_cast<ssize_t>(minOff); --i) {
if (readLe32(raw_.data() + i) == 0x06054b50u) {
eocdOff = i;
break;
}
}
if (eocdOff >= 0) {
const uint8_t* eocd = raw_.data() + eocdOff;
uint16_t numEntries = readLe16(eocd + 10);
uint32_t cdSize = readLe32(eocd + 12);
uint32_t cdOff = readLe32(eocd + 16);
if (static_cast<size_t>(cdOff) + cdSize <= raw_.size()) {
size_t pos = cdOff;
for (uint16_t i = 0; i < numEntries && pos + 46 <= raw_.size(); ++i) {
const uint8_t* cfh = raw_.data() + pos;
if (readLe32(cfh) != 0x02014b50u) break;
uint16_t method = readLe16(cfh + 10);
uint32_t compSz = readLe32(cfh + 20);
uint32_t uncompSz = readLe32(cfh + 24);
uint16_t fnLen = readLe16(cfh + 28);
uint16_t extraLen = readLe16(cfh + 30);
uint16_t commentLen = readLe16(cfh + 32);
uint32_t lhOff = readLe32(cfh + 42);
if (pos + 46 + fnLen > raw_.size()) break;
std::string name(reinterpret_cast<const char*>(cfh + 46), fnLen);
name = normalizeEntryPath(name);
if (!name.empty()) {
ZipEntryMeta m;
m.name = name;
m.method = method;
m.compSize = compSz;
m.uncompSize = uncompSz;
m.localHeaderOffset = lhOff;
registerEntry(m);
}
pos += 46u + fnLen + extraLen + commentLen;
}
if (!entries_.empty()) return true;
}
}
// Fallback sequential scan of local file headers
size_t pos = 0;
while (pos + 30 <= raw_.size()) {
const uint8_t* lh = raw_.data() + pos;
if (readLe32(lh) != 0x04034b50u) break;
uint16_t method = readLe16(lh + 8);
uint32_t compSz = readLe32(lh + 18);
uint32_t uncompSz = readLe32(lh + 22);
uint16_t fnLen = readLe16(lh + 26);
uint16_t extraLen = readLe16(lh + 28);
if (pos + 30u + fnLen + extraLen + compSz > raw_.size()) break;
std::string name(reinterpret_cast<const char*>(lh + 30), fnLen);
name = normalizeEntryPath(name);
if (!name.empty()) {
ZipEntryMeta m;
m.name = name;
m.method = method;
m.compSize = compSz;
m.uncompSize = uncompSz;
m.localHeaderOffset = static_cast<uint32_t>(pos);
registerEntry(m);
}
pos += 30u + fnLen + extraLen + compSz;
}
return !entries_.empty();
}
};
// ---------------------------------------------------------------------------
// Manifest & JAD Parser + Suite Metadata
// ---------------------------------------------------------------------------
struct MidletEntry {
int index = 1;
std::string title;
std::string iconPath;
std::string mainClass;
};
struct MidletSuiteInfo {
std::string jarPath;
std::string jadPath;
std::string suiteName;
std::string vendor;
std::string version;
std::string description;
std::string jarUrl;
std::vector<MidletEntry> midlets;
std::unordered_map<std::string, std::string> properties;
std::string getProperty(const std::string& key) const {
auto it = properties.find(key);
if (it != properties.end()) return it->second;
return "";
}
std::string suiteStorageKey() const {
std::string base = suiteName.empty() ? stripExtension(jarPath) : suiteName;
if (!vendor.empty()) base += "_" + vendor;
return sanitizePathToken(base);
}
};
inline void parseManifestText(
const std::string& text,
std::unordered_map<std::string, std::string>* outProps) {
if (!outProps) return;
std::istringstream ss(text);
std::string rawLine;
std::string lastKey;
while (std::getline(ss, rawLine)) {
if (!rawLine.empty() && rawLine.back() == '\r') {
rawLine.pop_back();
}
// Strip UTF-8 BOM if present
if (rawLine.size() >= 3 &&
static_cast<unsigned char>(rawLine[0]) == 0xEF &&
static_cast<unsigned char>(rawLine[1]) == 0xBB &&
static_cast<unsigned char>(rawLine[2]) == 0xBF) {
rawLine.erase(0, 3);
}
if (rawLine.empty()) {
lastKey.clear();
continue;
}
if (rawLine[0] == ' ' && !lastKey.empty()) {
(*outProps)[lastKey] += rawLine.substr(1);
continue;
}
size_t colon = rawLine.find(':');
if (colon == std::string::npos) continue;
std::string k = trimStr(rawLine.substr(0, colon));
std::string v = trimStr(rawLine.substr(colon + 1));
if (!k.empty()) {
(*outProps)[k] = v;
lastKey = k;
}
}
}
inline size_t curlWriteVector(void* ptr, size_t size, size_t nmemb,
void* userdata) {
size_t total = size * nmemb;
auto* vec = static_cast<std::vector<uint8_t>*>(userdata);
const auto* bytes = static_cast<const uint8_t*>(ptr);
vec->insert(vec->end(), bytes, bytes + total);
return total;
}
inline bool downloadUrlToFile(const std::string& url,
const std::string& dstPath) {
CURL* curl = curl_easy_init();
if (!curl) return false;
std::vector<uint8_t> body;
curl_easy_setopt(curl, CURLOPT_URL, url.c_str());
curl_easy_setopt(curl, CURLOPT_FOLLOWLOCATION, 1L);
curl_easy_setopt(curl, CURLOPT_TIMEOUT, 20L);
curl_easy_setopt(curl, CURLOPT_CONNECTTIMEOUT, 10L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYPEER, 0L);
curl_easy_setopt(curl, CURLOPT_SSL_VERIFYHOST, 0L);
curl_easy_setopt(curl, CURLOPT_USERAGENT,
"Nokia8110-4G/2.0 (Bananarchy; ReMEdy/1.0) Profile/MIDP-2.0 Configuration/CLDC-1.1");
curl_easy_setopt(curl, CURLOPT_WRITEFUNCTION, curlWriteVector);
curl_easy_setopt(curl, CURLOPT_WRITEDATA, &body);
CURLcode res = curl_easy_perform(curl);
long code = 0;
curl_easy_getinfo(curl, CURLINFO_RESPONSE_CODE, &code);
curl_easy_cleanup(curl);
if (res != CURLE_OK || code < 200 || code >= 400 || body.size() < 22) {
return false;
}
ensureDir(dirnameOf(dstPath));
std::ofstream out(dstPath, std::ios::binary | std::ios::trunc);
if (!out.is_open()) return false;
out.write(reinterpret_cast<const char*>(body.data()),
static_cast<std::streamsize>(body.size()));
return out.good();
}
inline void extractMidletEntriesFromProps(MidletSuiteInfo* info) {
if (!info) return;
info->midlets.clear();
for (int i = 1; i <= 32; ++i) {
std::string key = "MIDlet-" + std::to_string(i);
auto it = info->properties.find(key);
if (it == info->properties.end()) continue;
const std::string& val = it->second;
std::vector<std::string> parts;
std::stringstream ss(val);
std::string seg;
while (std::getline(ss, seg, ',')) {
parts.push_back(trimStr(seg));
}
if (parts.size() >= 3 && !parts[2].empty()) {
MidletEntry me;
me.index = i;
me.title = parts[0].empty() ? parts[2] : parts[0];
me.iconPath = parts[1];
me.mainClass = parts[2];
for (char& c : me.mainClass) {
if (c == '.') c = '/';
}
info->midlets.push_back(me);
} else if (parts.size() == 1 && !parts[0].empty()) {
MidletEntry me;
me.index = i;
me.title = parts[0];
me.mainClass = parts[0];
for (char& c : me.mainClass) {
if (c == '.') c = '/';
}
info->midlets.push_back(me);
}
}
info->suiteName = info->getProperty("MIDlet-Name");
info->vendor = info->getProperty("MIDlet-Vendor");
info->version = info->getProperty("MIDlet-Version");
info->description = info->getProperty("MIDlet-Description");
info->jarUrl = info->getProperty("MIDlet-Jar-URL");
}
inline bool loadSuiteFromJarOrJad(const std::string& inputPath,
ZipArchive* outJar,
MidletSuiteInfo* outInfo,
std::string* outError = nullptr) {
if (!outJar || !outInfo) return false;
*outInfo = MidletSuiteInfo{};
std::string ext = getExtLower(inputPath);
std::unordered_map<std::string, std::string> jadProps;
std::string resolvedJarPath = inputPath;
if (ext == "jad") {
outInfo->jadPath = inputPath;
std::ifstream in(inputPath);
if (!in.is_open()) {
if (outError) *outError = "Cannot open JAD file";
return false;
}
std::ostringstream ss;
ss << in.rdbuf();
parseManifestText(ss.str(), &jadProps);
std::string dir = dirnameOf(inputPath);
std::string baseNoExt = stripExtension(inputPath);
std::string siblingJar = dir + "/" + baseNoExt + ".jar";
std::string siblingJarUpper = dir + "/" + baseNoExt + ".JAR";
std::string jarUrl = jadProps["MIDlet-Jar-URL"];
struct stat st {};
if (::stat(siblingJar.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
resolvedJarPath = siblingJar;
} else if (::stat(siblingJarUpper.c_str(), &st) == 0 &&
S_ISREG(st.st_mode)) {
resolvedJarPath = siblingJarUpper;
} else if (!jarUrl.empty()) {
if (jarUrl.rfind("http://", 0) == 0 || jarUrl.rfind("https://", 0) == 0) {
std::string cacheJar = getDataRootDir() + "/cache/" +
sanitizePathToken(baseNoExt) + ".jar";
if (::stat(cacheJar.c_str(), &st) != 0 || st.st_size < 22) {
if (!downloadUrlToFile(jarUrl, cacheJar)) {
if (outError) *outError = "Failed to download JAR from JAD URL";
return false;
}
}
resolvedJarPath = cacheJar;
} else {
std::string relJar = dir + "/" + basenameOf(jarUrl);
if (::stat(relJar.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
resolvedJarPath = relJar;
} else if (::stat(jarUrl.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
resolvedJarPath = jarUrl;
}
}
}
} else {
// Check if a sibling .jad exists alongside the .jar to merge properties
std::string dir = dirnameOf(inputPath);
std::string baseNoExt = stripExtension(inputPath);
std::string siblingJad = dir + "/" + baseNoExt + ".jad";
struct stat st {};
if (::stat(siblingJad.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
outInfo->jadPath = siblingJad;
std::ifstream in(siblingJad);
if (in.is_open()) {
std::ostringstream ss;
ss << in.rdbuf();
parseManifestText(ss.str(), &jadProps);
}
}
}
outInfo->jarPath = resolvedJarPath;
if (!outJar->openFile(resolvedJarPath)) {
if (outError) *outError = "Invalid or missing JAR archive";
return false;
}
std::vector<uint8_t> mfBytes;
if (outJar->extractEntry("META-INF/MANIFEST.MF", &mfBytes)) {
std::string mfText(reinterpret_cast<const char*>(mfBytes.data()),
mfBytes.size());
parseManifestText(mfText, &outInfo->properties);
}
// JAD properties override/supplement MANIFEST.MF properties
for (const auto& kv : jadProps) {
outInfo->properties[kv.first] = kv.second;
}
extractMidletEntriesFromProps(outInfo);
if (outInfo->suiteName.empty()) {
outInfo->suiteName = stripExtension(resolvedJarPath);
}
if (outInfo->vendor.empty()) {
outInfo->vendor = "J2ME MIDlet";
}
if (outInfo->version.empty()) {
outInfo->version = "1.0";
}
return true;
}
// Fast metadata peek for the ROM/JAR Browser
inline bool peekJarOrJadSummary(const std::string& path,
std::string* outTitle,
std::string* outSubtitle) {
std::string ext = getExtLower(path);
std::unordered_map<std::string, std::string> props;
if (ext == "jad") {
std::ifstream in(path);
if (!in.is_open()) return false;
std::ostringstream ss;
ss << in.rdbuf();
parseManifestText(ss.str(), &props);
} else if (ext == "jar") {
ZipArchive za;
if (!za.openFile(path)) return false;
std::vector<uint8_t> mf;
if (za.extractEntry("META-INF/MANIFEST.MF", &mf)) {
parseManifestText(
std::string(reinterpret_cast<const char*>(mf.data()), mf.size()),
&props);
}
} else {
return false;
}
std::string name = props["MIDlet-Name"];
std::string vendor = props["MIDlet-Vendor"];
std::string ver = props["MIDlet-Version"];
if (name.empty()) {
auto it = props.find("MIDlet-1");
if (it != props.end()) {
size_t comma = it->second.find(',');
name = trimStr(comma == std::string::npos ? it->second
: it->second.substr(0, comma));
}
}
if (outTitle) *outTitle = name.empty() ? stripExtension(path) : name;
if (outSubtitle) {
std::string sub;
if (!vendor.empty()) sub = vendor;
if (!ver.empty()) {
if (!sub.empty()) sub += " v";
else sub = "v";
sub += ver;
}
*outSubtitle = sub;
}
return true;
}
// ---------------------------------------------------------------------------
// RMS (javax.microedition.rms.RecordStore) Persistent Storage Engine
// ---------------------------------------------------------------------------
struct RmsStoreData {
std::string name;
int32_t version = 1;
int32_t nextRecordId = 1;
int64_t lastModified = 0;
int32_t openCount = 0;
std::map<int32_t, std::vector<uint8_t>> records;
};
class RmsManager {
public:
void setSuiteKey(const std::string& key) {
suiteKey_ = sanitizePathToken(key);
stores_.clear();
}
std::string suiteRmsDir() const {
return getDataRootDir() + "/rms/" +
(suiteKey_.empty() ? "default" : suiteKey_);
}
std::string storeFilePath(const std::string& storeName) const {
return suiteRmsDir() + "/" + sanitizePathToken(storeName) + ".rms";
}
RmsStoreData* openStore(const std::string& storeName, bool createIfNecessary) {
auto it = stores_.find(storeName);
if (it != stores_.end()) {
it->second.openCount++;
return &it->second;
}
std::string path = storeFilePath(storeName);
struct stat st {};
if (::stat(path.c_str(), &st) == 0 && S_ISREG(st.st_mode)) {
RmsStoreData data;
data.name = storeName;
if (loadStoreFromDisk(path, &data)) {
data.openCount = 1;
stores_[storeName] = std::move(data);
return &stores_[storeName];
}
}
if (!createIfNecessary) return nullptr;
RmsStoreData data;
data.name = storeName;
data.version = 1;
data.nextRecordId = 1;
data.lastModified = wallTimeMs();
data.openCount = 1;
saveStoreToDisk(path, data);
stores_[storeName] = std::move(data);
return &stores_[storeName];
}
bool closeStore(const std::string& storeName) {
auto it = stores_.find(storeName);
if (it == stores_.end()) return false;
saveStoreToDisk(storeFilePath(storeName), it->second);
if (it->second.openCount > 0) {
it->second.openCount--;
}
return true;
}
bool deleteStore(const std::string& storeName) {
stores_.erase(storeName);
std::string path = storeFilePath(storeName);
return ::unlink(path.c_str()) == 0;
}
std::vector<std::string> listStores() const {
std::vector<std::string> names;
std::string dir = suiteRmsDir();
DIR* d = ::opendir(dir.c_str());
if (!d) return names;
struct dirent* de = nullptr;
while ((de = ::readdir(d)) != nullptr) {
std::string fn = de->d_name;
if (fn.size() > 4 && fn.substr(fn.size() - 4) == ".rms") {
names.push_back(fn.substr(0, fn.size() - 4));
}
}
::closedir(d);
std::sort(names.begin(), names.end());
return names;
}
int32_t addRecord(RmsStoreData* s, const uint8_t* bytes, size_t len) {
if (!s) return -1;
int32_t id = s->nextRecordId++;
if (bytes && len > 0) {
s->records[id].assign(bytes, bytes + len);
} else {
s->records[id].clear();
}
s->version++;
s->lastModified = wallTimeMs();
saveStoreToDisk(storeFilePath(s->name), *s);
return id;
}
bool setRecord(RmsStoreData* s, int32_t id, const uint8_t* bytes, size_t len) {
if (!s || id <= 0) return false;
auto it = s->records.find(id);
if (it == s->records.end()) {
// Some MIDlets call setRecord(1, ...) directly after ensuring record 1
if (id >= s->nextRecordId) s->nextRecordId = id + 1;
}
if (bytes && len > 0) {
s->records[id].assign(bytes, bytes + len);
} else {
s->records[id].clear();
}
s->version++;
s->lastModified = wallTimeMs();
saveStoreToDisk(storeFilePath(s->name), *s);
return true;
}
bool getRecord(RmsStoreData* s, int32_t id, std::vector<uint8_t>* out) const {
if (!s) return false;
auto it = s->records.find(id);
if (it == s->records.end()) return false;
if (out) *out = it->second;
return true;
}
int32_t getRecordSize(RmsStoreData* s, int32_t id) const {
if (!s) return -1;
auto it = s->records.find(id);
if (it == s->records.end()) return -1;
return static_cast<int32_t>(it->second.size());
}
bool deleteRecord(RmsStoreData* s, int32_t id) {
if (!s) return false;
auto it = s->records.find(id);
if (it == s->records.end()) return false;
s->records.erase(it);
s->version++;
s->lastModified = wallTimeMs();
saveStoreToDisk(storeFilePath(s->name), *s);
return true;
}
int32_t getSize(const RmsStoreData* s) const {
if (!s) return 0;
int32_t total = 32;
for (const auto& kv : s->records) {
total += 8 + static_cast<int32_t>(kv.second.size());
}
return total;
}
void flushAll() {
for (const auto& kv : stores_) {
saveStoreToDisk(storeFilePath(kv.first), kv.second);
}
}
int clearAllSuiteStores() {
stores_.clear();
std::string dir = suiteRmsDir();
DIR* d = ::opendir(dir.c_str());
if (!d) return 0;
int removed = 0;
struct dirent* de = nullptr;
while ((de = ::readdir(d)) != nullptr) {
std::string fn = de->d_name;
if (fn == "." || fn == "..") continue;
std::string full = dir + "/" + fn;
if (::unlink(full.c_str()) == 0) ++removed;
}
::closedir(d);
return removed;
}
private:
std::string suiteKey_ = "default";
std::unordered_map<std::string, RmsStoreData> stores_;
static bool loadStoreFromDisk(const std::string& path, RmsStoreData* out) {
std::ifstream in(path, std::ios::binary);
if (!in.is_open() || !out) return false;
char magic[4] = {};
if (!in.read(magic, 4) || std::memcmp(magic, "RRMS", 4) != 0) return false;
uint32_t count = 0;
in.read(reinterpret_cast<char*>(&out->version), sizeof(int32_t));
in.read(reinterpret_cast<char*>(&out->nextRecordId), sizeof(int32_t));
in.read(reinterpret_cast<char*>(&out->lastModified), sizeof(int64_t));
in.read(reinterpret_cast<char*>(&count), sizeof(uint32_t));
if (!in.good() || count > 65536) return false;
out->records.clear();
for (uint32_t i = 0; i < count; ++i) {
int32_t recId = 0;
uint32_t recLen = 0;
if (!in.read(reinterpret_cast<char*>(&recId), sizeof(int32_t))) break;
if (!in.read(reinterpret_cast<char*>(&recLen), sizeof(uint32_t))) break;
if (recLen > 16 * 1024 * 1024) break;
std::vector<uint8_t> buf(recLen);
if (recLen > 0 &&
!in.read(reinterpret_cast<char*>(buf.data()), recLen)) {
break;
}
out->records[recId] = std::move(buf);
if (recId >= out->nextRecordId) {
out->nextRecordId = recId + 1;
}
}
return true;
}
static bool saveStoreToDisk(const std::string& path,
const RmsStoreData& data) {
ensureDir(dirnameOf(path));
std::ofstream out(path, std::ios::binary | std::ios::trunc);
if (!out.is_open()) return false;
out.write("RRMS", 4);
uint32_t count = static_cast<uint32_t>(data.records.size());
out.write(reinterpret_cast<const char*>(&data.version), sizeof(int32_t));
out.write(reinterpret_cast<const char*>(&data.nextRecordId),
sizeof(int32_t));
out.write(reinterpret_cast<const char*>(&data.lastModified),
sizeof(int64_t));
out.write(reinterpret_cast<const char*>(&count), sizeof(uint32_t));
for (const auto& kv : data.records) {
int32_t recId = kv.first;
uint32_t recLen = static_cast<uint32_t>(kv.second.size());
out.write(reinterpret_cast<const char*>(&recId), sizeof(int32_t));
out.write(reinterpret_cast<const char*>(&recLen), sizeof(uint32_t));
if (recLen > 0) {
out.write(reinterpret_cast<const char*>(kv.second.data()), recLen);
}
}
return out.good();
}
};
} // namespace remedy
#endif // BANANARCHY_REMEDY_ZIP_RMS_HPP