ocarina/libsaria/prefs.cpp

99 lines
1.6 KiB
C++

#include <map>
using namespace std;
#include <libsaria/files.h>
#include <libsaria/prefs.h>
enum pref_t {
BOOL,
};
struct Preference {
pref_t type;
union value {
bool boolean;
} value_u;
};
static map<string, Preference> preferences;
static void load_pref(InFile &in)
{
Preference p;
string key = in.read_str();
p.type = (pref_t)in.read_ui();
switch (p.type) {
case BOOL:
p.value_u.boolean = in.read_int();
break;
default:
break;
}
preferences[key] = p;
}
static void save_pref(string key, struct Preference &p, OutFile &out)
{
out.write_str(key, false);
out.write_ui(p.type, false);
switch (p.type) {
case BOOL:
out.write_int(p.value_u.boolean, true);
break;
default:
out.write_str("", true);
}
}
static void save()
{
map<string, Preference>::iterator it;
OutFile out("preferences");
out.write_ui(preferences.size(), true);
for (it = preferences.begin(); it != preferences.end(); it++)
save_pref(it->first, it->second, out);
}
static void set_preference(string key, struct Preference &p)
{
preferences[key] = p;
save();
}
namespace libsaria
{
void prefs::load()
{
unsigned int size;
InFile in("preferences");
if (!in.good())
return;
size = in.read_ui();
for (unsigned int i = 0; i < size; i++)
load_pref(in);
}
void prefs::set(string key, bool value)
{
struct Preference p;
p.type = BOOL;
p.value_u.boolean = value;
set_preference(key, p);
}
bool prefs::get_bool(string key)
{
map<string, Preference>::iterator it;
it = preferences.find(key);
if (it == preferences.end())
return false;
if (it->second.type != BOOL)
return false;
return it->second.value_u.boolean;
}
}