1 /**
2  * Copyright (C) Francesco Fusco. All rights reserved.
3  * License: https://github.com/Fushko/gammy#license
4  */
5 
6 #include "cfg.h"
7 #include "utils.h"
8 #include "defs.h"
9 #include <fstream>
10 #include <iostream>
11 
getDefault()12 json getDefault()
13 {
14 	return
15 	{
16 		{"brt_auto", true},
17 		{"brt_fps", 60},
18 		{"brt_step", brt_steps_max},
19 		{"brt_min", brt_steps_max / 2},
20 		{"brt_max", brt_steps_max},
21 		{"brt_offset", brt_steps_max / 3},
22 		{"brt_speed", 1000},
23 		{"brt_threshold", 8},
24 		{"brt_polling_rate", 100},
25 		{"brt_extend", false},
26 
27 		{"temp_auto", false},
28 		{"temp_fps", 45},
29 		{"temp_step", 0},
30 		{"temp_high", temp_k_min},
31 		{"temp_low", 3400},
32 		{"temp_speed", 60.0},
33 		{"temp_sunrise", "06:00:00"},
34 		{"temp_sunset", "16:00:00"},
35 
36 		{"log_level", plog::warning},
37 		{"wnd_show_on_startup", false},
38 		{"wnd_x", -1},
39 		{"wnd_y", -1}
40 	};
41 }
42 
43 json cfg = getDefault();
44 
read()45 void config::read()
46 {
47 	const auto path = config::getPath();
48 	LOGV << "Reading from: " << path;
49 
50 	std::ifstream file(path, std::fstream::in | std::fstream::app);
51 
52 	if (!file.good() || !file.is_open()) {
53 		LOGE << "Unable to open config";
54 		return;
55 	}
56 
57 	file.seekg(0, std::ios::end);
58 
59 	if (file.tellg() == 0) {
60 		config::write();
61 		return;
62 	}
63 
64 	file.seekg(0);
65 
66 	json tmp;
67 
68 	try {
69 		file >> tmp;
70 	} catch (json::exception &e) {
71 		LOGE << e.what() << " - Resetting config...";
72 		cfg = getDefault();
73 		config::write();
74 		return;
75 	}
76 
77 	cfg.update(tmp);
78 
79 	LOGV << "Config parsed";
80 }
81 
write()82 void config::write()
83 {
84 	const auto path = config::getPath();
85 	LOGV << "Writing to: " << path;
86 
87 	std::ofstream file(path, std::ofstream::out);
88 
89 	if (!file.good() || !file.is_open()) {
90 		LOGE << "Unable to open config";
91 		return;
92 	}
93 
94 	try {
95 		file << std::setw(4) << cfg;
96 	} catch (json::exception &e) {
97 		LOGE << e.what() << " id: " << e.id;
98 		return;
99 	}
100 
101 	LOGV << "Config set";
102 }
103 
104 #ifdef _WIN32
105 #include <Windows.h>
getPath()106 std::wstring config::getPath()
107 {
108 	wchar_t buf[FILENAME_MAX] {};
109 	GetModuleFileNameW(nullptr, buf, FILENAME_MAX);
110 
111 	std::wstring path(buf);
112 	std::wstring appname = L"gammy.exe";
113 
114 	path.erase(path.find(appname), appname.length());
115 	path += L"gammyconf.txt";
116 	return path;
117 }
118 #else
getPath()119 std::string config::getPath()
120 {
121 	const char *home   = getenv("XDG_CONFIG_HOME");
122 	const char *format = "/";
123 
124 	if (!home) {
125 		format = "/.config/";
126 		home = getenv("HOME");
127 	}
128 
129 	std::stringstream ss;
130 	ss << home << format << config_name;
131 	return ss.str();
132 }
133 #endif
134