1 /*
2     Copyright © 2020, Inochi2D Project
3     Distributed under the 2-Clause BSD License, see LICENSE file.
4     
5     Authors: Luna Nielsen
6 */
7 module creator.core.settings;
8 import std.json;
9 import std.file;
10 import std.path : buildPath;
11 import creator.core.path;
12 
13 private {
14     JSONValue settings = JSONValue(string[string].init);
15 }
16 
17 string incSettingsPath() {
18     return buildPath(incGetAppConfigPath(), "settings.json");
19 }
20 
21 /**
22     Load settings from settings file
23 */
24 void incSettingsLoad() {
25     if (exists(incSettingsPath())) {
26         settings = parseJSON(readText(incSettingsPath()));
27     }
28 }
29 
30 /**
31     Saves settings from settings store
32 */
33 void incSettingsSave() {
34     write(incSettingsPath(), settings.toString());
35 }
36 
37 /**
38     Sets a setting
39 */
40 void incSettingsSet(T)(string name, T value) if (!is(T == string[]))  {
41     settings[name] = value;
42 }
43 
44 /**
45     Gets a value from the settings store
46 */
47 T incSettingsGet(T)(string name) if (!is(T == string[])) {
48     if (name in settings) {
49         return settings[name].get!T;
50     }
51     return T.init;
52 }
53 
54 /**
55     Gets a value from the settings store
56 */
57 T incSettingsGet(T)(string name) if (is(T == string[])) {
58     if (name in settings) {
59         string[] values;
60         foreach(value; settings[name].array) {
61             values ~= value.get!string;
62         }
63         return values;
64     }
65     return T.init;
66 }
67 
68 /**
69     Sets a setting
70 */
71 void incSettingsSet(T)(string name, T value) if (is(T == string[]))  {
72     JSONValue[] data;
73     foreach(i; 0..value.length) {
74         data ~= JSONValue(value[i]);
75     }
76     settings[name] = JSONValue(data);
77 }
78 
79 /**
80     Gets a value from the settings store, with custom default value
81 */
82 T incSettingsGet(T)(string name, T default_) {
83     if (name in settings) {
84         return settings[name].get!T;
85     }
86     return default_;
87 }
88 
89 /**
90     Gets whether a setting is obtainable
91 */
92 bool incSettingsCanGet(string name) {
93     return (name in settings) !is null;
94 }