File: save_handler.cc

package info (click to toggle)
widelands 1:19+repack-3
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 370,608 kB
  • ctags: 20,609
  • sloc: cpp: 108,404; ansic: 18,695; python: 5,155; sh: 487; xml: 460; makefile: 233
file content (223 lines) | stat: -rw-r--r-- 6,808 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
/*
 * Copyright (C) 2002-2009, 2015 by the Widelands Development Team
 *
 * 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 "logic/save_handler.h"

#include <cstring>
#include <memory>

#include <boost/algorithm/string.hpp>
#include <boost/format.hpp>

#include "base/log.h"
#include "base/macros.h"
#include "base/scoped_timer.h"
#include "base/time_string.h"
#include "base/wexception.h"
#include "game_io/game_saver.h"
#include "io/filesystem/filesystem.h"
#include "logic/game.h"
#include "logic/game_controller.h"
#include "wlapplication.h"
#include "wui/interactive_base.h"

using Widelands::GameSaver;

/**
* Check if autosave is not needed.
 */
void SaveHandler::think(Widelands::Game& game) {
	uint32_t realtime = SDL_GetTicks();
	initialize(realtime);
	std::string filename = autosave_filename_;

	if (!allow_saving_) {
		return;
	}
	if (game.is_replay()) {
		return;
	}

	// Are we saving now?
	if (saving_next_tick_ || save_requested_) {
		if (save_requested_) {
			// Requested by user
			if (!save_filename_.empty()) {
				filename = save_filename_;
			}
			log("Gamesave: save requested: %s\n", filename.c_str());
			save_requested_ = false;
			save_filename_ = "";
		} else {
			// Autosave ...
			// Roll savefiles
			int32_t number_of_rolls =
			   g_options.pull_section("global").get_int("rolling_autosave", 5) - 1;
			log("Autosave: Rolling savefiles (count): %d\n", number_of_rolls + 1);
			std::string filename_previous = create_file_name(
			   get_base_dir(), (boost::format("%s_%02d") % filename % number_of_rolls).str());
			if (number_of_rolls > 0 && g_fs->file_exists(filename_previous)) {
				g_fs->fs_unlink(filename_previous);
				log("Autosave: Deleted %s\n", filename_previous.c_str());
			}
			number_of_rolls--;
			while (number_of_rolls >= 0) {
				const std::string filename_next = create_file_name(
				   get_base_dir(), (boost::format("%s_%02d") % filename % number_of_rolls).str());
				if (g_fs->file_exists(filename_next)) {
					g_fs->fs_rename(filename_next, filename_previous);
					log("Autosave: Rolled %s to %s\n", filename_next.c_str(), filename_previous.c_str());
				}
				filename_previous = filename_next;
				number_of_rolls--;
			}
			filename = (boost::format("%s_00") % autosave_filename_).str();
			log("Autosave: saving as %s\n", filename.c_str());
		}

		// Saving now
		const std::string complete_filename = create_file_name(get_base_dir(), filename);
		std::string backup_filename;

		// always overwrite a file
		if (g_fs->file_exists(complete_filename)) {
			filename += "2";
			backup_filename = create_file_name(get_base_dir(), filename);
			if (g_fs->file_exists(backup_filename)) {
				g_fs->fs_unlink(backup_filename);
			}
			g_fs->fs_rename(complete_filename, backup_filename);
		}

		std::string error;
		if (!save_game(game, complete_filename, &error)) {
			log("Autosave: ERROR! - %s\n", error.c_str());
			game.get_ibase()->log_message(_("Saving failed!"));

			// if backup file was created, move it back
			if (backup_filename.length() > 0) {
				if (g_fs->file_exists(complete_filename)) {
					g_fs->fs_unlink(complete_filename);
				}
				g_fs->fs_rename(backup_filename, complete_filename);
			}
			// Wait 30 seconds until next save try
			last_saved_realtime_ = last_saved_realtime_ + 30000;
			return;
		} else {
			// if backup file was created, time to remove it
			if (backup_filename.length() > 0 && g_fs->file_exists(backup_filename))
				g_fs->fs_unlink(backup_filename);
		}

		log("Autosave: save took %d ms\n", SDL_GetTicks() - realtime);
		game.get_ibase()->log_message(_("Game saved"));
		last_saved_realtime_ = realtime;
		saving_next_tick_ = false;

	} else {
		// Perhaps save is due now?
		const int32_t autosave_interval_in_seconds =
		   g_options.pull_section("global").get_int("autosave", DEFAULT_AUTOSAVE_INTERVAL * 60);
		if (autosave_interval_in_seconds <= 0) {
			return;  // no autosave requested
		}

		const int32_t elapsed = (realtime - last_saved_realtime_) / 1000;
		if (elapsed < autosave_interval_in_seconds) {
			return;
		}

		// check if game is paused (in any way)
		if (game.game_controller()->is_paused_or_zero_speed()) {
			// Wait 30 seconds until next save try
			last_saved_realtime_ = last_saved_realtime_ + 30000;
			return;
		}
		log("Autosave: %d s interval elapsed, current gametime: %s, saving...\n", elapsed,
		    gametimestring(game.get_gametime(), true).c_str());

		saving_next_tick_ = true;
		game.get_ibase()->log_message(_("Saving gameā€¦"));
	}
}

/**
* Initialize autosave timer
 */
void SaveHandler::initialize(uint32_t realtime) {
	if (initialized_)
		return;

	last_saved_realtime_ = realtime;
	initialized_ = true;
}

/*
 * Calculate the name of the save file
 */
std::string SaveHandler::create_file_name(const std::string& dir,
                                          const std::string& filename) const {
	// Append directory name.
	std::string complete_filename = dir + g_fs->file_separator() + filename;
	// Trim it for preceding/trailing whitespaces in user input
	boost::trim(complete_filename);

	// Now check if the extension matches (ignoring case)
	if (!boost::iends_with(filename, WLGF_SUFFIX)) {
		complete_filename += WLGF_SUFFIX;
	}

	return complete_filename;
}

/*
 * Save the game
 *
 * returns true if saved
 */
bool SaveHandler::save_game(Widelands::Game& game,
                            const std::string& complete_filename,
                            std::string* const error) {
	ScopedTimer save_timer("SaveHandler::save_game() took %ums");

	bool const binary = !g_options.pull_section("global").get_bool("nozip", false);
	// Make sure that the base directory exists
	g_fs->ensure_directory_exists(get_base_dir());

	// Make a filesystem out of this
	std::unique_ptr<FileSystem> fs;
	if (!binary) {
		fs.reset(g_fs->create_sub_file_system(complete_filename, FileSystem::DIR));
	} else {
		fs.reset(g_fs->create_sub_file_system(complete_filename, FileSystem::ZIP));
	}

	bool result = true;
	GameSaver gs(*fs, game);
	try {
		gs.save();
	} catch (const std::exception& e) {
		if (error)
			*error = e.what();
		result = false;
	}

	return result;
}