/
AutoSaver.cpp
353 lines (284 loc) · 10.2 KB
/
AutoSaver.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
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
#include "AutoSaver.h"
#include "i18n.h"
#include <numeric>
#include <iostream>
#include "imapfilechangetracker.h"
#include "itextstream.h"
#include "iscenegraph.h"
#include "iradiant.h"
#include "iregistry.h"
#include "igame.h"
#include "ipreferencesystem.h"
#include "icommandsystem.h"
#include "registry/registry.h"
#include "os/file.h"
#include "os/path.h"
#include "os/dir.h"
#include "os/fs.h"
#include "gamelib.h"
#include <limits.h>
#include "string/string.h"
#include "string/convert.h"
#include "module/StaticModule.h"
#include "messages/NotificationMessage.h"
#include "messages/AutomaticMapSaveRequest.h"
#include "map/Map.h"
#include <fmt/format.h>
namespace map
{
namespace
{
// Registry key names
const char* GKEY_MAP_EXTENSION = "/mapFormat/fileExtension";
std::string constructSnapshotName(const fs::path& snapshotPath, const std::string& mapName, int num)
{
std::string mapExt = game::current::getValue<std::string>(GKEY_MAP_EXTENSION);
// Construct the base name without numbered extension
std::string filename = (snapshotPath / mapName).string();
// Now append the number and the map extension to the map name
filename += ".";
filename += string::to_string(num);
filename += ".";
filename += mapExt;
return filename;
}
}
AutoMapSaver::AutoMapSaver() :
_snapshotsEnabled(false),
_savedChangeCount(0)
{}
void AutoMapSaver::registryKeyChanged()
{
_snapshotsEnabled = registry::getValue<bool>(RKEY_AUTOSAVE_SNAPSHOTS_ENABLED);
}
void AutoMapSaver::clearChanges()
{
_savedChangeCount = 0;
}
void AutoMapSaver::saveSnapshot()
{
// Original GtkRadiant comments:
// we need to do the following
// 1. make sure the snapshot directory exists (create it if it doesn't)
// 2. find out what the lastest save is based on number
// 3. inc that and save the map
// Construct the fs::path class out of the full map path (throws on fail)
fs::path fullPath = GlobalMapModule().getMapName();
// Append the the snapshot folder to the path
fs::path snapshotPath = fullPath;
snapshotPath.remove_filename();
snapshotPath /= GlobalRegistry().get(RKEY_AUTOSAVE_SNAPSHOTS_FOLDER);
// Retrieve the mapname
std::string mapName = fullPath.filename().string();
// Map existing snapshots (snapshot num => path)
std::map<int, std::string> existingSnapshots;
// Check if the folder exists and create it if necessary
if (os::fileOrDirExists(snapshotPath.string()) || os::makeDirectory(snapshotPath.string()))
{
collectExistingSnapshots(existingSnapshots, snapshotPath, mapName);
int highestNum = existingSnapshots.empty() ? 0 : existingSnapshots.rbegin()->first + 1;
std::string filename = constructSnapshotName(snapshotPath, mapName, highestNum);
rMessage() << "Autosaving snapshot to " << filename << std::endl;
// Dump to map to the next available filename
GlobalCommandSystem().executeCommand("SaveAutomaticBackup", filename);
handleSnapshotSizeLimit(existingSnapshots, snapshotPath, mapName);
}
else
{
rError() << "Snapshot save failed.. unable to create directory";
rError() << snapshotPath << std::endl;
}
}
void AutoMapSaver::handleSnapshotSizeLimit(const std::map<int, std::string>& existingSnapshots,
const fs::path& snapshotPath, const std::string& mapName)
{
std::size_t maxSnapshotFolderSize =
registry::getValue<std::size_t>(RKEY_AUTOSAVE_MAX_SNAPSHOT_FOLDER_SIZE);
// Sanity check in case there is something weird going on in the registry
if (maxSnapshotFolderSize == 0)
{
maxSnapshotFolderSize = 100;
}
// Sum up the total folder size
std::size_t folderSize = 0;
for (const std::pair<int, std::string>& pair : existingSnapshots)
{
folderSize += os::getFileSize(pair.second);
}
std::size_t maxSize = maxSnapshotFolderSize * 1024 * 1024;
// The key containing the previously calculated size
std::string mapKey = RKEY_AUTOSAVE_SNAPSHOT_FOLDER_SIZE_HISTORY;
mapKey += "/map[@name='" + mapName + "']";
// Display a warning, if the folder size exceeds the limit
if (folderSize > maxSize)
{
std::size_t prevSize = string::convert<std::size_t>(GlobalRegistry().getAttribute(mapKey, "size"), 0);
// Save the size for the next time we hit it
GlobalRegistry().deleteXPath(mapKey);
// Create a new key and store the size
GlobalRegistry().createKeyWithName(RKEY_AUTOSAVE_SNAPSHOT_FOLDER_SIZE_HISTORY, "map", mapName);
GlobalRegistry().setAttribute(mapKey, "size", string::to_string(folderSize));
// Now should we display a message?
if (prevSize > maxSize)
{
rMessage() << "User has already been notified about the snapshot size exceeding limits." << std::endl;
return;
}
rMessage() << "AutoSaver: The snapshot files in " << snapshotPath <<
" take up more than " << maxSnapshotFolderSize << " MB. You might consider cleaning it up." << std::endl;
// Notify the user
radiant::NotificationMessage::SendWarning(
fmt::format(_("The snapshots saved for this map are exceeding the configured size limit."
"\nConsider cleaning up the folder {0}"), snapshotPath.string()));
}
else
{
// Folder size is within limits (again), delete the size info from the registry
GlobalRegistry().deleteXPath(mapKey);
}
}
void AutoMapSaver::collectExistingSnapshots(std::map<int, std::string>& existingSnapshots,
const fs::path& snapshotPath, const std::string& mapName)
{
for (int num = 0; num < INT_MAX; num++)
{
// Construct the base name without numbered extension
std::string filename = constructSnapshotName(snapshotPath, mapName, num);
if (!os::fileOrDirExists(filename))
{
return; // We've found an unused filename, break the loop
}
existingSnapshots.insert(std::make_pair(num, filename));
}
}
bool AutoMapSaver::runAutosaveCheck()
{
// Check, if changes have been made since the last autosave
if (!GlobalSceneGraph().root() || _savedChangeCount == GlobalSceneGraph().root()->getUndoChangeTracker().getCurrentChangeCount())
{
return false;
}
AutomaticMapSaveRequest request;
GlobalRadiantCore().getMessageBus().sendMessage(request);
if (request.isDenied())
{
rMessage() << "Auto save skipped: " << request.getReason() << std::endl;
return false;
}
return true;
}
void AutoMapSaver::performAutosave()
{
// Remember the change tracking counter
_savedChangeCount = GlobalSceneGraph().root()->getUndoChangeTracker().getCurrentChangeCount();
// only snapshot if not working on an unnamed map
if (_snapshotsEnabled && !GlobalMapModule().isUnnamed())
{
try
{
saveSnapshot();
}
catch (fs::filesystem_error& f)
{
rError() << "AutoSaver::saveSnapshot: " << f.what() << std::endl;
}
}
else
{
if (GlobalMapModule().isUnnamed())
{
// Get the maps path (within the mod path)
auto autoSaveFilename = GlobalGameManager().getMapPath();
// Try to create the map folder, in case there doesn't exist one
os::makeDirectory(autoSaveFilename);
// Append the "autosave.map" to the filename
autoSaveFilename += "autosave.";
autoSaveFilename += game::current::getValue<std::string>(GKEY_MAP_EXTENSION);
rMessage() << "Autosaving unnamed map to " << autoSaveFilename << std::endl;
// Invoke the save call
GlobalCommandSystem().executeCommand("SaveAutomaticBackup", autoSaveFilename);
}
else
{
// Construct the new filename (e.g. "test_autosave.map")
auto filename = GlobalMapModule().getMapName();
auto extension = os::getExtension(filename);
// Cut off the extension
filename = filename.substr(0, filename.rfind('.'));
filename += "_autosave";
filename += "." + extension;
rMessage() << "Autosaving map to " << filename << std::endl;
// Invoke the save call
GlobalCommandSystem().executeCommand("SaveAutomaticBackup", filename);
}
}
}
void AutoMapSaver::constructPreferences()
{
// Add a page to the given group
IPreferencePage& page = GlobalPreferenceSystem().getPage(_("Settings/Autosave"));
page.appendCheckBox(_("Save Snapshots"), RKEY_AUTOSAVE_SNAPSHOTS_ENABLED);
page.appendEntry(_("Snapshot folder (relative to map folder)"), RKEY_AUTOSAVE_SNAPSHOTS_FOLDER);
page.appendEntry(_("Max total Snapshot size per map (MB)"), RKEY_AUTOSAVE_MAX_SNAPSHOT_FOLDER_SIZE);
}
void AutoMapSaver::onMapEvent(IMap::MapEvent ev)
{
// We reset our change count regardless of whether a map
// is loaded or unloaded
switch (ev)
{
case IMap::MapLoading:
case IMap::MapLoaded:
case IMap::MapUnloading:
case IMap::MapUnloaded:
clearChanges();
break;
default:
break;
};
}
const std::string& AutoMapSaver::getName() const
{
static std::string _name(MODULE_AUTOSAVER);
return _name;
}
const StringSet& AutoMapSaver::getDependencies() const
{
static StringSet _dependencies;
if (_dependencies.empty())
{
_dependencies.insert(MODULE_MAP);
_dependencies.insert(MODULE_PREFERENCESYSTEM);
_dependencies.insert(MODULE_XMLREGISTRY);
}
return _dependencies;
}
void AutoMapSaver::initialiseModule(const IApplicationContext& ctx)
{
rMessage() << getName() << "::initialiseModule called." << std::endl;
_signalConnections.push_back(GlobalRegistry().signalForKey(RKEY_AUTOSAVE_SNAPSHOTS_ENABLED).connect(
sigc::mem_fun(this, &AutoMapSaver::registryKeyChanged)
));
// Get notified when the map is loaded afresh
_signalConnections.push_back(GlobalMapModule().signal_mapEvent().connect(
sigc::mem_fun(*this, &AutoMapSaver::onMapEvent)
));
// Refresh all values from the registry right now (this might also start the timer)
registryKeyChanged();
// Add the autosave options after all the modules are done. A cheap solution to let
// the options appear below the Enabled / Interval setting added by the UI
module::GlobalModuleRegistry().signal_allModulesInitialised().connect(
sigc::mem_fun(*this, &AutoMapSaver::constructPreferences)
);
}
void AutoMapSaver::shutdownModule()
{
// Unsubscribe from all connections
for (sigc::connection& connection : _signalConnections)
{
connection.disconnect();
}
_signalConnections.clear();
}
module::StaticModuleRegistration<AutoMapSaver> staticAutoSaverModule;
} // namespace map