aboutsummaryrefslogtreecommitdiffstatshomepage
path: root/config.vala
blob: c36d5330dd10db507ab277219b493129636809ac (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
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;
	}
}