File: XMLRegistry.cpp

package info (click to toggle)
darkradiant 3.9.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 41,080 kB
  • sloc: cpp: 264,743; ansic: 10,659; python: 1,852; xml: 1,650; sh: 92; makefile: 21
file content (358 lines) | stat: -rw-r--r-- 10,596 bytes parent folder | download | duplicates (2)
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
#include "XMLRegistry.h"

#include <iostream>
#include <stdexcept>
#include "itextstream.h"

#include "os/file.h"
#include "os/path.h"

#include "version.h"
#include "string/string.h"
#include "string/encoding.h"
#include "module/StaticModule.h"
#include "settings/SettingsManager.h"

namespace registry
{

namespace
{
	const char* const RKEY_SKIP_REGISTRY_SAVE = "user/skipRegistrySaveOnShutdown";
}

XMLRegistry::XMLRegistry() :
    _queryCounter(0),
    _changesSinceLastSave(0),
    _shutdown(false)
{}

void XMLRegistry::shutdown()
{
    rMessage() << "XMLRegistry Shutdown: " << _queryCounter << " queries processed." << std::endl;

    saveToDisk();

    _shutdown = true;
    _autosaveTimer.reset();
}

void XMLRegistry::saveToDisk()
{
    // Save the user tree to the settings path, this contains all
    // settings that have been modified during runtime
    if (!get(RKEY_SKIP_REGISTRY_SAVE).empty())
    {
        return;
    }

    std::lock_guard<std::mutex> lock(_writeLock);

    // Make a deep copy of the user tree by copy-constructing it
    RegistryTree copiedTree(_userTree);

    // Get the version-specific folder we can store our settings files in
    settings::SettingsManager manager(module::GlobalModuleRegistry().getApplicationContext());
    auto settingsPath = manager.getCurrentVersionSettingsFolder();

    // Replace the version tag and set it to the current DarkRadiant version
    copiedTree.deleteXPath("user//version");
    copiedTree.set("user/version", RADIANT_VERSION);

    // Export the user-defined filter definitions to a separate file
    copiedTree.exportToFile("user/ui/filtersystem/filters", settingsPath + "filters.xml");
    copiedTree.deleteXPath("user/ui/filtersystem/filters");

    // Export the colour schemes and remove them from the registry
    copiedTree.exportToFile("user/ui/colourschemes", settingsPath + "colours.xml");
    copiedTree.deleteXPath("user/ui/colourschemes");

    // Export the input definitions into the user's settings folder and remove them as well
    copiedTree.exportToFile("user/ui/input", settingsPath + "input.xml");
    copiedTree.deleteXPath("user/ui/input");

    // Delete all nodes marked as "transient", they are NOT exported into the user's xml file
    copiedTree.deleteXPath("user/*[@transient='1']");

    // Remove any remaining upgradePaths (from older registry files)
    copiedTree.deleteXPath("user/upgradePaths");
    // Remove legacy <interface> node
    copiedTree.deleteXPath("user/ui/interface");

    // Save the remaining /darkradiant/user tree to user.xml so that the current settings are preserved
    copiedTree.exportToFile("user", settingsPath + "user.xml");

    _changesSinceLastSave = 0;
}

xml::NodeList XMLRegistry::findXPath(const std::string& path)
{
    // Query the user tree first
    xml::NodeList results = _userTree.findXPath(path);
    xml::NodeList stdResults = _standardTree.findXPath(path);

    // Append the stdResults to the results
    std::copy(stdResults.begin(), stdResults.end(), std::back_inserter(results));

    _queryCounter++;

    return results;
}

void XMLRegistry::dump() const
{
    rConsole() << "User Tree:" << std::endl;
    _userTree.dump();
    rConsole() << "Default Tree:" << std::endl;
    _standardTree.dump();
}

void XMLRegistry::exportToFile(const std::string& key, const std::string& filename)
{
    // Only the usertree should be exported, so pass the call to this tree
    _userTree.exportToFile(key, filename);
}

sigc::signal<void> XMLRegistry::signalForKey(const std::string& key) const
{
    return _keySignals[key]; // will return existing or default-construct
}

bool XMLRegistry::keyExists(const std::string& key)
{
    // Pass the query on to findXPath which queries the subtrees
    xml::NodeList result = findXPath(key);
    return !result.empty();
}

void XMLRegistry::deleteXPath(const std::string& path)
{
    std::lock_guard<std::mutex> lock(_writeLock);

    assert(!_shutdown);

    auto numDeletedNodes = _userTree.deleteXPath(path);
    numDeletedNodes += _standardTree.deleteXPath(path);

    if (numDeletedNodes > 0)
    {
        _changesSinceLastSave++;
    }
}

xml::Node XMLRegistry::createKeyWithName(const std::string& path,
                                         const std::string& key,
                                         const std::string& name)
{
    std::lock_guard<std::mutex> lock(_writeLock);

    assert(!_shutdown);

    _changesSinceLastSave++;

    // The key will be created in the user tree (the default tree is read-only)
    return _userTree.createKeyWithName(path, key, name);
}

xml::Node XMLRegistry::createKey(const std::string& key)
{
    std::lock_guard<std::mutex> lock(_writeLock);

    assert(!_shutdown);

    _changesSinceLastSave++;

    return _userTree.createKey(key);
}

void XMLRegistry::setAttribute(const std::string& path,
    const std::string& attrName, const std::string& attrValue)
{
    std::lock_guard<std::mutex> lock(_writeLock);

    assert(!_shutdown);

    _changesSinceLastSave++;

    _userTree.setAttribute(path, attrName, attrValue);
}

std::string XMLRegistry::getAttribute(const std::string& path, const std::string& attrName)
{
    // Pass the query to the findXPath method, which queries the user tree first
    if (xml::NodeList nodeList = findXPath(path); !nodeList.empty()) {
        return nodeList[0].getAttributeValue(attrName);
    }
    return std::string();
}

std::string XMLRegistry::get(const std::string& key)
{
    if (const xml::NodeList nodeList = findXPath(key); !nodeList.empty()) {
        if (const auto content = nodeList[0].getContent(); !content.empty()) {
            return string::utf8_to_mb(content);
        }
        else {
            return string::utf8_to_mb(nodeList[0].getAttributeValue("value"));
        }
    }
    return {};
}

void XMLRegistry::set(const std::string& key, const std::string& value)
{
    {
        std::lock_guard<std::mutex> lock(_writeLock);

        assert(!_shutdown);

        // Create or set the value in the user tree, the default tree stays untouched
        // Convert the string to UTF-8 before storing it into the RegistryTree
        _userTree.set(key, string::mb_to_utf8(value));

        _changesSinceLastSave++;
    }

    // Notify the observers
    emitSignalForKey(key);
}

void XMLRegistry::import(const std::string& importFilePath, const std::string& parentKey, Tree tree)
{
    std::lock_guard<std::mutex> lock(_writeLock);

    assert(!_shutdown);

    switch (tree)
    {
        case treeUser:
            _userTree.importFromFile(importFilePath, parentKey);
            break;
        case treeStandard:
            _standardTree.importFromFile(importFilePath, parentKey);
            break;
    }

    _changesSinceLastSave++;
}

void XMLRegistry::emitSignalForKey(const std::string& changedKey)
{
    // Do not default-construct a signal, just emit if there is one already
    KeySignals::const_iterator i = _keySignals.find(changedKey);

    if (i != _keySignals.end())
    {
        i->second.emit();
    }
}

void XMLRegistry::loadUserFileFromSettingsPath(const settings::SettingsManager& settingsManager,
    const std::string& filename, const std::string& baseXPath)
{
    auto userSettingsFile = settingsManager.getExistingSettingsFile(filename);

    if (os::fileOrDirExists(userSettingsFile))
    {
        try
        {
            import(userSettingsFile, baseXPath, Registry::treeUser);
        }
        catch (const std::exception& e)
        {
            // User files may become corrupted, in which case we should just
            // skip them and move on (as if the user-modified file simply did
            // not exist).
            rError() << "XMLRegistry: user settings file " << filename
                     << " could not be parsed and was skipped (" << e.what() << ")" << std::endl;
        }
    }
    else
    {
        rMessage() << "XMLRegistry: file " << filename << " not present in "
            << settingsManager.getBaseSettingsPath() << std::endl;
    }
}

// RegisterableModule implementation
const std::string& XMLRegistry::getName() const
{
    static std::string _name(MODULE_XMLREGISTRY);
    return _name;
}

const StringSet& XMLRegistry::getDependencies() const
{
    static StringSet _dependencies; // no dependencies
    return _dependencies;
}

void XMLRegistry::initialiseModule(const IApplicationContext& ctx)
{
    // Load the XML files from the runtime data directory
    std::string base = ctx.getRuntimeDataPath();

    rMessage() << "XMLRegistry: looking for XML files in " << base << std::endl;

    try
    {
        // Load all of the required XML files
        import(base + "user.xml", "", Registry::treeStandard);
        import(base + "colours.xml", "user/ui", Registry::treeStandard);
        import(base + "input.xml", "user/ui", Registry::treeStandard);
        import(base + "menu.xml", "user/ui", Registry::treeStandard);
        import(base + "commandsystem.xml", "user/ui", Registry::treeStandard);

        // Load the debug.xml file only if the relevant key is set in user.xml
        if (get("user/debug") == "1")
        {
            import(base + "debug.xml", "", Registry::treeStandard);
        }
    }
    catch (std::runtime_error& e)
    {
        rConsoleError() << "XML registry population failed:\n\n" << e.what() << std::endl;
    }

    // Load user preferences, these overwrite any values that have defined before
    settings::SettingsManager manager(ctx);

    loadUserFileFromSettingsPath(manager, "user.xml", "");
    loadUserFileFromSettingsPath(manager, "colours.xml", "user/ui");
    loadUserFileFromSettingsPath(manager, "input.xml", "user/ui");
    loadUserFileFromSettingsPath(manager, "filters.xml", "user/ui/filtersystem");

    // Subscribe to the post-module-shutdown signal to save changes to disk
    module::GlobalModuleRegistry().signal_allModulesUninitialised().connect(
        sigc::mem_fun(this, &XMLRegistry::shutdown));

    _autosaveTimer.reset(new util::Timer(2000,
        sigc::mem_fun(this, &XMLRegistry::onAutoSaveTimerIntervalReached)));

    module::GlobalModuleRegistry().signal_allModulesInitialised().connect([this]()
    {
        _autosaveTimer->start();
    });
}

void XMLRegistry::shutdownModule()
{
    _autosaveTimer->stop();
}

void XMLRegistry::onAutoSaveTimerIntervalReached()
{
    {
        std::lock_guard<std::mutex> lock(_writeLock);
        if (_changesSinceLastSave == 0) {
            return;
        }
    }

    saveToDisk();
}

// Static module instance
module::StaticModuleRegistration<XMLRegistry> xmlRegistryModule;

}