ocarina/core/settings.c
Anna Schumaker e1f13a7ef4 core/file: Create new functions for reading data from files
The readd(), readu(), and readhu() functions are all used to read
various forms of integers.  The readl() and readw() are for reading
either lines or individual whitespace-delimited words

Signed-off-by: Anna Schumaker <Anna@NoWheyCreamery.com>
2018-02-21 16:01:15 -05:00

87 lines
1.8 KiB
C

/*
* Copyright 2015 (c) Anna Schumaker.
*/
#include <core/file.h>
#include <core/settings.h>
static GHashTable *gui_settings = NULL;
static struct file gui_settings_file = FILE_INIT_DATA("", "settings", 0);
static void __settings_save_item(gpointer key, gpointer value, gpointer data)
{
file_writef(&gui_settings_file, "%s %u\n", (const gchar *)key,
GPOINTER_TO_UINT(value));
}
static void __settings_save()
{
file_open(&gui_settings_file, OPEN_WRITE);
file_writef(&gui_settings_file, "%u\n", g_hash_table_size(gui_settings));
g_hash_table_foreach(gui_settings, __settings_save_item, NULL);
file_close(&gui_settings_file);
}
static void __settings_read()
{
unsigned int num, i, value;
gchar *key;
num = file_readu(&gui_settings_file);
for (i = 0; i < num; i++) {
key = file_readw(&gui_settings_file);
value = file_readu(&gui_settings_file);
g_hash_table_insert(gui_settings, key, GUINT_TO_POINTER(value));
}
}
void settings_init()
{
gui_settings = g_hash_table_new_full(g_str_hash, g_str_equal,
g_free, NULL);
if (file_open(&gui_settings_file, OPEN_READ))
__settings_read();
file_close(&gui_settings_file);
}
void settings_deinit()
{
g_hash_table_destroy(gui_settings);
gui_settings = NULL;
}
void settings_set(const gchar *key, unsigned int value)
{
if (gui_settings && key) {
g_hash_table_replace(gui_settings, g_strdup(key),
GUINT_TO_POINTER(value));
__settings_save();
}
}
unsigned int settings_get(const gchar *key)
{
if (gui_settings && key)
return GPOINTER_TO_UINT(g_hash_table_lookup(gui_settings, key));
return 0;
}
bool settings_has(const gchar *key)
{
if (gui_settings && key)
return g_hash_table_contains(gui_settings, key);
return false;
}
#ifdef CONFIG_TESTING
GHashTable *test_get_settings()
{
return gui_settings;
}
#endif /* CONFIG_TESTING */