aboutsummaryrefslogtreecommitdiff
path: root/common/ini-file.cpp
blob: 4c4acc9e60d2f103ef0dc9c249330d4f89962518 (plain)
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
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
/* ScummVM - Graphic Adventure Engine
 *
 * ScummVM is the legal property of its developers, whose names
 * are too numerous to list here. Please refer to the COPYRIGHT
 * file distributed with this source distribution.
 *
 * This program is free software; you can redistribute it and/or
 * modify it under the terms of the GNU General Public License
 * as published by the Free Software Foundation; either version 2
 * of the License, or (at your option) any later version.
 *
 * This program is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with this program; if not, write to the Free Software
 * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
 *
 */

#include "common/ini-file.h"
#include "common/file.h"
#include "common/savefile.h"
#include "common/system.h"
#include "common/textconsole.h"

namespace Common {

bool INIFile::isValidName(const String &name) const {
	if (_allowNonEnglishCharacters)
		return true;
	const char *p = name.c_str();
	while (*p && (isAlnum(*p) || *p == '-' || *p == '_' || *p == '.' || *p == ' '))
		p++;
	return *p == 0;
}

INIFile::INIFile() {
	_allowNonEnglishCharacters = false;
}

void INIFile::clear() {
	_sections.clear();
}

bool INIFile::loadFromFile(const String &filename) {
	File file;
	if (file.open(filename))
		return loadFromStream(file);
	else
		return false;
}

bool INIFile::loadFromSaveFile(const String &filename) {
	assert(g_system);
	SaveFileManager *saveFileMan = g_system->getSavefileManager();
	SeekableReadStream *loadFile;

	assert(saveFileMan);
	if (!(loadFile = saveFileMan->openForLoading(filename)))
		return false;

	bool status = loadFromStream(*loadFile);
	delete loadFile;
	return status;
}

bool INIFile::loadFromStream(SeekableReadStream &stream) {
	Section section;
	KeyValue kv;
	String comment;
	int lineno = 0;

	// TODO: Detect if a section occurs multiple times (or likewise, if
	// a key occurs multiple times inside one section).

	while (!stream.eos() && !stream.err()) {
		lineno++;

		// Read a line
		String line = stream.readLine();

		if (line.size() == 0) {
			// Do nothing
		} else if (line[0] == '#' || line[0] == ';' || line.hasPrefix("//")) {
			// Accumulate comments here. Once we encounter either the start
			// of a new section, or a key-value-pair, we associate the value
			// of the 'comment' variable with that entity. The semicolon and
			// C++-style comments are used for Living Books games in Mohawk.
			comment += line;
			comment += "\n";
		} else if (line[0] == '(') {
			// HACK: The following is a hack added by Kirben to support the
			// "map.ini" used in the HE SCUMM game "SPY Fox in Hold the Mustard".
			//
			// It would be nice if this hack could be restricted to that game,
			// but the current design of this class doesn't allow to do that
			// in a nice fashion (a "isMustard" parameter is *not* a nice
			// solution).
			comment += line;
			comment += "\n";
		} else if (line[0] == '[') {
			// It's a new section which begins here.
			const char *p = line.c_str() + 1;
			// Get the section name, and check whether it's valid (that
			// is, verify that it only consists of alphanumerics,
			// periods, dashes and underscores). Mohawk Living Books games
			// can have periods in their section names.
			while (*p && ((_allowNonEnglishCharacters && *p != ']') || isAlnum(*p) || *p == '-' || *p == '_' || *p == '.' || *p == ' '))
				p++;

			if (*p == '\0')
				error("INIFile::loadFromStream: missing ] in line %d", lineno);
			else if (*p != ']')
				error("INIFile::loadFromStream: Invalid character '%c' occurred in section name in line %d", *p, lineno);

			// Previous section is finished now, store it.
			if (!section.name.empty())
				_sections.push_back(section);

			section.name = String(line.c_str() + 1, p);
			section.keys.clear();
			section.comment = comment;
			comment.clear();

			if (!isValidName(section.name)) {
				warning("Invalid section name: %s", section.name.c_str());
				return false;
			}
		} else {
			// This line should be a line with a 'key=value' pair, or an empty one.

			// Skip leading whitespaces
			const char *t = line.c_str();
			while (isSpace(*t))
				t++;

			// Skip empty lines / lines with only whitespace
			if (*t == 0)
				continue;

			// If no section has been set, this config file is invalid!
			if (section.name.empty()) {
				error("INIFile::loadFromStream: Key/value pair found outside a section in line %d", lineno);
			}

			// Split string at '=' into 'key' and 'value'. First, find the "=" delimeter.
			const char *p = strchr(t, '=');
			if (!p) {
				warning("Config file buggy: Junk found in line line %d: '%s'", lineno, t);
				kv.key = String(t);
				kv.value.clear();
			}  else {
				// Extract the key/value pair
				kv.key = String(t, p);
				kv.value = String(p + 1);
			}

			// Trim of spaces
			kv.key.trim();
			kv.value.trim();

			// Store comment
			kv.comment = comment;
			comment.clear();

			if (!isValidName(kv.key)) {
				warning("Invalid key name: %s", kv.key.c_str());
				return false;
			}

			section.keys.push_back(kv);
		}
	}

	// Save last section
	if (!section.name.empty())
		_sections.push_back(section);

	return (!stream.err() || stream.eos());
}

bool INIFile::saveToFile(const String &filename) {
	DumpFile file;
	if (file.open(filename))
		return saveToStream(file);
	else
		return false;
}

bool INIFile::saveToSaveFile(const String &filename) {
	assert(g_system);
	SaveFileManager *saveFileMan = g_system->getSavefileManager();
	WriteStream *saveFile;

	assert(saveFileMan);
	if (!(saveFile = saveFileMan->openForSaving(filename)))
		return false;

	bool status = saveToStream(*saveFile);
	delete saveFile;
	return status;
}

bool INIFile::saveToStream(WriteStream &stream) {
	for (List<Section>::iterator i = _sections.begin(); i != _sections.end(); ++i) {
		// Write out the section comment, if any
		if (! i->comment.empty()) {
			stream.writeString(i->comment);
		}

		// Write out the section name
		stream.writeByte('[');
		stream.writeString(i->name);
		stream.writeByte(']');
		stream.writeByte('\n');

		// Write out the key/value pairs
		for (List<KeyValue>::iterator kv = i->keys.begin(); kv != i->keys.end(); ++kv) {
			// Write out the comment, if any
			if (! kv->comment.empty()) {
				stream.writeString(kv->comment);
			}
			// Write out the key/value pair
			stream.writeString(kv->key);
			stream.writeByte('=');
			stream.writeString(kv->value);
			stream.writeByte('\n');
		}
	}

	stream.flush();
	return !stream.err();
}

void INIFile::addSection(const String &section) {
	Section *s = getSection(section);
	if (s)
		return;

	Section newSection;
	newSection.name = section;
	_sections.push_back(newSection);
}

void INIFile::removeSection(const String &section) {
	if (!isValidName(section)) {
		warning("Invalid section name: %s", section.c_str());
		return;
	}

	for (List<Section>::iterator i = _sections.begin(); i != _sections.end(); ++i) {
		if (section.equalsIgnoreCase(i->name)) {
			_sections.erase(i);
			return;
		}
	}
}

bool INIFile::hasSection(const String &section) const {
	if (!isValidName(section)) {
		warning("Invalid section name: %s", section.c_str());
		return false;
	}

	const Section *s = getSection(section);
	return s != nullptr;
}

void INIFile::renameSection(const String &oldName, const String &newName) {
	if (!isValidName(oldName)) {
		warning("Invalid section name: %s", oldName.c_str());
		return;
	}

	if (!isValidName(newName)) {
		warning("Invalid section name: %s", newName.c_str());
		return;
	}

	Section *os = getSection(oldName);
	const Section *ns = getSection(newName);
	if (os) {
		// HACK: For now we just print a warning, for more info see the TODO
		// below.
		if (ns)
			warning("INIFile::renameSection: Section name \"%s\" already used", newName.c_str());
		else
			os->name = newName;
	}
	// TODO: Check here whether there already is a section with the
	// new name. Not sure how to cope with that case, we could:
	// - simply remove the existing "newName" section
	// - error out
	// - merge the two sections "oldName" and "newName"
}


bool INIFile::hasKey(const String &key, const String &section) const {
	if (!isValidName(key)) {
		warning("Invalid key name: %s", key.c_str());
		return false;
	}

	if (!isValidName(section)) {
		warning("Invalid section name: %s", section.c_str());
		return false;
	}

	const Section *s = getSection(section);
	if (!s)
		return false;
	return s->hasKey(key);
}

void INIFile::removeKey(const String &key, const String &section) {
	if (!isValidName(key)) {
		warning("Invalid key name: %s", key.c_str());
		return;
	}

	if (!isValidName(section)) {
		warning("Invalid section name: %s", section.c_str());
		return;
	}

	Section *s = getSection(section);
	if (s)
		 s->removeKey(key);
}

bool INIFile::getKey(const String &key, const String &section, String &value) const {
	if (!isValidName(key)) {
		warning("Invalid key name: %s", key.c_str());
		return false;
	}

	if (!isValidName(section)) {
		warning("Invalid section name: %s", section.c_str());
		return false;
	}
	const Section *s = getSection(section);
	if (!s)
		return false;
	const KeyValue *kv = s->getKey(key);
	if (!kv)
		return false;
	value = kv->value;
	return true;
}

void INIFile::setKey(const String &key, const String &section, const String &value) {
	if (!isValidName(key)) {
		warning("Invalid key name: %s", key.c_str());
		return;
	}

	if (!isValidName(section)) {
		warning("Invalid section name: %s", section.c_str());
		return;
	}

	// TODO: Verify that value is valid, too. In particular, it shouldn't
	// contain CR or LF...

	Section *s = getSection(section);
	if (!s) {
		KeyValue newKV;
		newKV.key = key;
		newKV.value = value;

		Section newSection;
		newSection.name = section;
		newSection.keys.push_back(newKV);

		_sections.push_back(newSection);
	} else {
		s->setKey(key, value);
	}
}

const INIFile::SectionKeyList INIFile::getKeys(const String &section) const {
	const Section *s = getSection(section);

	return s->getKeys();
}

INIFile::Section *INIFile::getSection(const String &section) {
	for (List<Section>::iterator i = _sections.begin(); i != _sections.end(); ++i) {
		if (section.equalsIgnoreCase(i->name)) {
			return &(*i);
		}
	}
	return nullptr;
}

const INIFile::Section *INIFile::getSection(const String &section) const {
	for (List<Section>::const_iterator i = _sections.begin(); i != _sections.end(); ++i) {
		if (section.equalsIgnoreCase(i->name)) {
			return &(*i);
		}
	}
	return nullptr;
}

bool INIFile::Section::hasKey(const String &key) const {
	return getKey(key) != nullptr;
}

const INIFile::KeyValue* INIFile::Section::getKey(const String &key) const {
	for (List<KeyValue>::const_iterator i = keys.begin(); i != keys.end(); ++i) {
		if (key.equalsIgnoreCase(i->key)) {
			return &(*i);
		}
	}
	return nullptr;
}

void INIFile::Section::setKey(const String &key, const String &value) {
	for (List<KeyValue>::iterator i = keys.begin(); i != keys.end(); ++i) {
		if (key.equalsIgnoreCase(i->key)) {
			i->value = value;
			return;
		}
	}

	KeyValue newKV;
	newKV.key = key;
	newKV.value = value;
	keys.push_back(newKV);
}

void INIFile::Section::removeKey(const String &key) {
	for (List<KeyValue>::iterator i = keys.begin(); i != keys.end(); ++i) {
		if (key.equalsIgnoreCase(i->key)) {
			keys.erase(i);
			return;
		}
	}
}

void INIFile::allowNonEnglishCharacters() {
	_allowNonEnglishCharacters = true;
}

} // End of namespace Common