forked from Blondazz/KeyOverlay
-
Notifications
You must be signed in to change notification settings - Fork 6
Expand file tree
/
Copy pathConfig.cs
More file actions
82 lines (74 loc) · 2.44 KB
/
Config.cs
File metadata and controls
82 lines (74 loc) · 2.44 KB
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
using System;
using System.Collections.Generic;
using System.IO;
namespace KeyOverlay
{
public class Config
{
private string name;
private Dictionary<string, Dictionary<string, string>> config;
private FileSystemWatcher watcher;
private Action callback;
public Config(string name, Action callback)
{
this.name = name;
this.callback = callback;
Load();
watcher = new FileSystemWatcher();
watcher.Path = ".";
watcher.NotifyFilter = NotifyFilters.LastWrite | NotifyFilters.LastAccess;
watcher.Filter = name;
watcher.Changed += new FileSystemEventHandler(OnChanged);
watcher.EnableRaisingEvents = true;
}
public Dictionary<string, string> this[string key] => config[key];
private void Read()
{
var objectDict = new Dictionary<string, Dictionary<string, string>>();
var lines = File.ReadAllLines(name);
var current = "";
foreach (var line in lines)
{
if (line == "") continue;
if (line.StartsWith("["))
{
current = line.Substring(1, line.Length - 2);
objectDict.Add(current, new());
}
else
{
var key = line.Split('=')[0];
var value = line.Split('=')[1];
objectDict[current].Add(key, value);
}
}
this.config = objectDict;
}
private void Check()
{
string[] required = { "General", "Keys" };
string[] optional = { "Display", "Size", "Colors" };
foreach (var name in required)
{
if (!config.ContainsKey(name)) throw new InvalidDataException("Missing required data from config file");
}
foreach (var name in optional)
{
if (!config.ContainsKey(name)) config.Add(name, new());
}
}
public void Load()
{
config = new();
Read();
Check();
}
private void OnChanged(object source, FileSystemEventArgs e)
{
// funky event *before* the file is actually saved
System.Threading.Thread.Sleep(100);
Load();
callback();
}
}
}