libsaria: Added preferences

Right now I only store boolean values, but I think I've coded this in a
way to make adding new values easy.
This commit is contained in:
Bryan Schumaker 2011-11-07 08:30:53 -05:00
parent 0f2d682216
commit b6f21d5705
3 changed files with 115 additions and 0 deletions

19
include/libsaria/prefs.h Normal file
View File

@ -0,0 +1,19 @@
#ifndef LIBSARIA_PREFS_H
#define LIBSARIA_PREFS_H
#include <string>
using namespace std;
namespace libsaria
{
namespace prefs
{
void load();
void set(string, bool);
bool get_bool(string);
}
}
#endif /* LIBSARIA_PREFS_H */

View File

@ -2,6 +2,7 @@
#include <libsaria/libsaria.h>
#include <libsaria/audio.h>
#include <libsaria/path.h>
#include <libsaria/prefs.h>
#include <libsaria/print.h>
#include <libsaria/library.h>
@ -16,6 +17,7 @@ namespace libsaria
println(get_saria_dir());
make_saria_dir();
libsaria::library::load();
libsaria::prefs::load();
}
void quit()

94
libsaria/prefs.cpp Normal file
View File

@ -0,0 +1,94 @@
#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()
{
InFile in("preferences");
unsigned int 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;
}
}