ocarina/libsaria/prefs.cpp
Bryan Schumaker da118b2281 libsaria: Switch to the new OutFile() class
The new class is more convenient to work with since it's the output
stream with my save protocol built in.  I should have done this earlier!
2011-12-25 22:34:12 -05:00

128 lines
2.2 KiB
C++

#include <map>
using namespace std;
#include <libsaria/files.h>
#include <libsaria/prefs.h>
enum pref_t {
BOOL,
FLOAT,
};
struct Preference {
pref_t type;
union value {
bool boolean;
float floating;
} value_u;
};
static map<string, Preference> preferences;
static void load_pref(InFile &in)
{
Preference p;
string key;
in >> key >> (unsigned int &)p.type;
switch (p.type) {
case BOOL:
in >> p.value_u.boolean;
println("preferences[" + key + "] = %d", p.value_u.boolean);
break;
case FLOAT:
in >> p.value_u.floating;
println("preferences[" + key + "] = %f", p.value_u.floating);
break;
default:
break;
}
preferences[key] = p;
}
static void save_pref(string key, struct Preference &p, OutFile &out)
{
out << key << p.type;
switch (p.type) {
case BOOL:
out << p.value_u.boolean;
break;
case FLOAT:
out << p.value_u.floating;
break;
}
out << "\n";
}
static void save()
{
map<string, Preference>::iterator it;
OutFile out("preferences");
out << preferences.size() << "\n";
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 = 0;
InFile in("preferences");
if (!in.good())
return;
in >> size;
println("Preferences size: %d", size);
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);
}
void prefs::set(string key, float value)
{
struct Preference p;
p.type = FLOAT;
p.value_u.floating = 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;
}
float prefs::get_float(string key, float dfault)
{
map<string, Preference>::iterator it;
it = preferences.find(key);
if (it == preferences.end())
return dfault;
if (it->second.type != FLOAT)
return dfault;
return it->second.value_u.floating;
}
}