From 9703e09fb5cd151217ad17dbafd25338585b7ed7 Mon Sep 17 00:00:00 2001 From: Wolfgang Müller Date: Sat, 20 Jul 2019 21:58:18 +0200 Subject: Initial public release --- config.vala | 108 ++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++ 1 file changed, 108 insertions(+) create mode 100644 config.vala (limited to 'config.vala') diff --git a/config.vala b/config.vala new file mode 100644 index 0000000..c36d533 --- /dev/null +++ b/config.vala @@ -0,0 +1,108 @@ +class Config { + + KeyFile? keyfile = new KeyFile(); + string[] warnings = {}; + + public Config() { + var path = Path.build_filename(Environment.get_user_config_dir(), PROGRAM_NAME, "config"); + try { + keyfile.load_from_file(path, NONE); + } catch (Error e) { + // We want to ignore a legitimately missing file, since we fall back to defaults. + if (!(e is FileError.NOENT)) { + append_warning(path + ": " + e.message); + keyfile = null; + } + } + } + + public void append_warning(string message) { + warning(message); + + warnings += "• " + Markup.escape_text(message); + } + + void check_error(KeyFileError e) { + if (!(e is KeyFileError.KEY_NOT_FOUND || e is KeyFileError.GROUP_NOT_FOUND)) { + append_warning(e.message); + } + } + + public string[] done() { + if (keyfile == null) { + return warnings; + } + + string[] keys = {}; + try { + foreach(var group in keyfile.get_groups()) { + foreach(var key in keyfile.get_keys(group)) { + keys += string.join(".", group, key); + } + } + } catch (KeyFileError e) { + // purposefully ignored + } + + if (keys.length > 0) { + string k = keys.length > 1 ? "keys" : "key"; + append_warning("Unknown %s in config: %s".printf(k, string.joinv(", ", keys))); + } + + return warnings; + } + + public string? value(string group, string key, string? fallback) { + if (keyfile == null) { return fallback; } + + try { + string value = keyfile.get_value(group, key); + keyfile.remove_key(group, key); + return value; + } catch (KeyFileError e) { + check_error(e); + return fallback; + } + } + + public int? integer(string group, string key, int? fallback) { + if (keyfile == null) { return fallback; } + + try { + int integer = keyfile.get_integer(group, key); + keyfile.remove_key(group, key); + return integer; + } catch (KeyFileError e) { + check_error(e); + return fallback; + } + } + + public bool? boolean(string group, string key, bool? fallback) { + if (keyfile == null) { return fallback; } + + try { + bool boolean = keyfile.get_boolean(group, key); + keyfile.remove_key(group, key); + return boolean; + } catch (KeyFileError e) { + check_error(e); + return fallback; + } + } + + public Gdk.RGBA? colour(string key, string? fallback) { + string value = value("colours", key, fallback); + if (value == null) { + return null; + } + + var rgba = Gdk.RGBA(); + if (!rgba.parse(value)) { + append_warning("invalid colour: " + value); + return null; + } + + return rgba; + } +} -- cgit v1.2.3-2-gb3c3