forked from endless-sky/endless-sky-editor
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathDataWriter.cpp
110 lines (76 loc) · 1.92 KB
/
DataWriter.cpp
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
/* DataWriter.h
Copyright (c) 2014 by Michael Zahniser
Endless Sky 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 3 of the License, or (at your option) any later version.
Endless Sky 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.
*/
#include "DataWriter.h"
#include "DataNode.h"
using namespace std;
const QString DataWriter::space = " ";
DataWriter::DataWriter(const QString &path)
: before(&indent), file(path)
{
if(file.open(QFile::WriteOnly))
{
out.setDevice(&file);
out.setCodec("UTF-8");
}
}
void DataWriter::Write(const DataNode &node)
{
for(int i = 0; i < node.Size(); ++i)
WriteToken(node.Token(i));
Write();
if(node.begin() != node.end())
{
BeginChild();
{
for(const DataNode &child : node)
Write(child);
}
EndChild();
}
}
void DataWriter::Write()
{
out << '\n';
before = &indent;
}
void DataWriter::BeginChild()
{
indent += '\t';
}
void DataWriter::EndChild()
{
indent.chop(1);
}
void DataWriter::WriteComment(const QString &str)
{
out << indent << "# " << str << '\n';
}
void DataWriter::WriteRaw(const QString &str)
{
out << str;
}
void DataWriter::WriteToken(const QString &str, QChar quote)
{
bool hasSpace = str.isEmpty() || (quote == '"');
bool hasQuote = (quote == '`');
for(QChar c : str)
{
hasSpace |= (c <= ' ');
hasQuote |= (c == '"');
}
out << *before;
if(hasSpace && hasQuote)
out << '`' << str << '`';
else if(hasSpace)
out << '"' << str << '"';
else
out << str;
before = &space;
}