ResidualVM logo ResidualVM website - Forums - Contact us BuildBot - Doxygen - Wiki curved edge

default-saves.cpp

Go to the documentation of this file.
00001 /* ScummVM - Graphic Adventure Engine
00002  *
00003  * ScummVM is the legal property of its developers, whose names
00004  * are too numerous to list here. Please refer to the COPYRIGHT
00005  * file distributed with this source distribution.
00006  *
00007  * This program is free software; you can redistribute it and/or
00008  * modify it under the terms of the GNU General Public License
00009  * as published by the Free Software Foundation; either version 2
00010  * of the License, or (at your option) any later version.
00011  *
00012  * This program is distributed in the hope that it will be useful,
00013  * but WITHOUT ANY WARRANTY; without even the implied warranty of
00014  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
00015  * GNU General Public License for more details.
00016  *
00017  * You should have received a copy of the GNU General Public License
00018  * along with this program; if not, write to the Free Software
00019  * Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA.
00020  *
00021  */
00022 
00023 // This define lets us use the system function remove() on Symbian, which
00024 // is disabled by default due to a macro conflict.
00025 // See backends/platform/symbian/src/portdefs.h .
00026 #define SYMBIAN_USE_SYSTEM_REMOVE
00027 
00028 #include "common/scummsys.h"
00029 
00030 #if defined(USE_CLOUD) && defined(USE_LIBCURL)
00031 #include "backends/cloud/cloudmanager.h"
00032 #endif
00033 #include "common/file.h"
00034 #include "common/system.h"
00035 
00036 #if !defined(DISABLE_DEFAULT_SAVEFILEMANAGER)
00037 
00038 #include "backends/saves/default/default-saves.h"
00039 
00040 #include "common/savefile.h"
00041 #include "common/util.h"
00042 #include "common/fs.h"
00043 #include "common/archive.h"
00044 #include "common/config-manager.h"
00045 #include "common/zlib.h"
00046 
00047 #include <errno.h>  // for removeSavefile()
00048 
00049 #if defined(USE_CLOUD) && defined(USE_LIBCURL)
00050 const char *DefaultSaveFileManager::TIMESTAMPS_FILENAME = "timestamps";
00051 #endif
00052 
00053 DefaultSaveFileManager::DefaultSaveFileManager() {
00054 }
00055 
00056 DefaultSaveFileManager::DefaultSaveFileManager(const Common::String &defaultSavepath) {
00057     ConfMan.registerDefault("savepath", defaultSavepath);
00058 }
00059 
00060 
00061 void DefaultSaveFileManager::checkPath(const Common::FSNode &dir) {
00062     clearError();
00063     if (!dir.exists()) {
00064         if (!dir.createDirectory()) {
00065             setError(Common::kPathDoesNotExist, "Failed to create directory '"+dir.getPath()+"'");
00066         }
00067     } else if (!dir.isDirectory()) {
00068         setError(Common::kPathNotDirectory, "The savepath '"+dir.getPath()+"' is not a directory");
00069     }
00070 }
00071 
00072 void DefaultSaveFileManager::updateSavefilesList(Common::StringArray &lockedFiles) {
00073     //make it refresh the cache next time it lists the saves
00074     _cachedDirectory = "";
00075 
00076     //remember the locked files list because some of these files don't exist yet
00077     _lockedFiles = lockedFiles;
00078 }
00079 
00080 Common::StringArray DefaultSaveFileManager::listSavefiles(const Common::String &pattern) {
00081     // Assure the savefile name cache is up-to-date.
00082     assureCached(getSavePath());
00083     if (getError().getCode() != Common::kNoError)
00084         return Common::StringArray();
00085 
00086     Common::HashMap<Common::String, bool> locked;
00087     for (Common::StringArray::const_iterator i = _lockedFiles.begin(), end = _lockedFiles.end(); i != end; ++i) {
00088         locked[*i] = true;
00089     }
00090 
00091     Common::StringArray results;
00092     for (SaveFileCache::const_iterator file = _saveFileCache.begin(), end = _saveFileCache.end(); file != end; ++file) {
00093         if (!locked.contains(file->_key) && file->_key.matchString(pattern, true)) {
00094             results.push_back(file->_key);
00095         }
00096     }
00097     return results;
00098 }
00099 
00100 Common::InSaveFile *DefaultSaveFileManager::openRawFile(const Common::String &filename) {
00101     // Assure the savefile name cache is up-to-date.
00102     assureCached(getSavePath());
00103     if (getError().getCode() != Common::kNoError)
00104         return nullptr;
00105 
00106     SaveFileCache::const_iterator file = _saveFileCache.find(filename);
00107     if (file == _saveFileCache.end()) {
00108         return nullptr;
00109     } else {
00110         // Open the file for loading.
00111         Common::SeekableReadStream *sf = file->_value.createReadStream();
00112         return sf;
00113     }
00114 }
00115 
00116 Common::InSaveFile *DefaultSaveFileManager::openForLoading(const Common::String &filename) {
00117     // Assure the savefile name cache is up-to-date.
00118     assureCached(getSavePath());
00119     if (getError().getCode() != Common::kNoError)
00120         return nullptr;
00121 
00122     for (Common::StringArray::const_iterator i = _lockedFiles.begin(), end = _lockedFiles.end(); i != end; ++i) {
00123         if (filename == *i) {
00124             return nullptr; //file is locked, no loading available
00125         }
00126     }
00127 
00128     SaveFileCache::const_iterator file = _saveFileCache.find(filename);
00129     if (file == _saveFileCache.end()) {
00130         return nullptr;
00131     } else {
00132         // Open the file for loading.
00133         Common::SeekableReadStream *sf = file->_value.createReadStream();
00134         return Common::wrapCompressedReadStream(sf);
00135     }
00136 }
00137 
00138 Common::OutSaveFile *DefaultSaveFileManager::openForSaving(const Common::String &filename, bool compress) {
00139     // Assure the savefile name cache is up-to-date.
00140     const Common::String savePathName = getSavePath();
00141     assureCached(savePathName);
00142     if (getError().getCode() != Common::kNoError)
00143         return nullptr;
00144 
00145     for (Common::StringArray::const_iterator i = _lockedFiles.begin(), end = _lockedFiles.end(); i != end; ++i) {
00146         if (filename == *i) {
00147             return nullptr; //file is locked, no saving available
00148         }
00149     }
00150 
00151 #if defined(USE_CLOUD) && defined(USE_LIBCURL)
00152     // Update file's timestamp
00153     Common::HashMap<Common::String, uint32> timestamps = loadTimestamps();
00154     timestamps[filename] = INVALID_TIMESTAMP;
00155     saveTimestamps(timestamps);
00156 #endif
00157 
00158     // Obtain node.
00159     SaveFileCache::const_iterator file = _saveFileCache.find(filename);
00160     Common::FSNode fileNode;
00161 
00162     // If the file did not exist before, we add it to the cache.
00163     if (file == _saveFileCache.end()) {
00164         const Common::FSNode savePath(savePathName);
00165         fileNode = savePath.getChild(filename);
00166     } else {
00167         fileNode = file->_value;
00168     }
00169 
00170     // Open the file for saving.
00171     Common::WriteStream *const sf = fileNode.createWriteStream();
00172     if (!sf)
00173         return nullptr;
00174     Common::OutSaveFile *const result = new Common::OutSaveFile(compress ? Common::wrapCompressedWriteStream(sf) : sf);
00175 
00176     // Add file to cache now that it exists.
00177     _saveFileCache[filename] = Common::FSNode(fileNode.getPath());
00178 
00179     return result;
00180 }
00181 
00182 bool DefaultSaveFileManager::removeSavefile(const Common::String &filename) {
00183     // Assure the savefile name cache is up-to-date.
00184     assureCached(getSavePath());
00185     if (getError().getCode() != Common::kNoError)
00186         return false;
00187 
00188 #if defined(USE_CLOUD) && defined(USE_LIBCURL)
00189     // Update file's timestamp
00190     Common::HashMap<Common::String, uint32> timestamps = loadTimestamps();
00191     Common::HashMap<Common::String, uint32>::iterator it = timestamps.find(filename);
00192     if (it != timestamps.end()) {
00193         timestamps.erase(it);
00194         saveTimestamps(timestamps);
00195     }
00196 #endif
00197 
00198     // Obtain node if exists.
00199     SaveFileCache::const_iterator file = _saveFileCache.find(filename);
00200     if (file == _saveFileCache.end()) {
00201         return false;
00202     } else {
00203         const Common::FSNode fileNode = file->_value;
00204         // Remove from cache, this invalidates the 'file' iterator.
00205         _saveFileCache.erase(file);
00206         file = _saveFileCache.end();
00207 
00208         // FIXME: remove does not exist on all systems. If your port fails to
00209         // compile because of this, please let us know (scummvm-devel).
00210         // There is a nicely portable workaround, too: Make this method overloadable.
00211         if (remove(fileNode.getPath().c_str()) != 0) {
00212             if (errno == EACCES)
00213                 setError(Common::kWritePermissionDenied, "Search or write permission denied: "+fileNode.getName());
00214 
00215             if (errno == ENOENT)
00216                 setError(Common::kPathDoesNotExist, "removeSavefile: '"+fileNode.getName()+"' does not exist or path is invalid");
00217 
00218             return false;
00219         } else {
00220             return true;
00221         }
00222     }
00223 }
00224 
00225 Common::String DefaultSaveFileManager::getSavePath() const {
00226 
00227     Common::String dir;
00228 
00229     // Try to use game specific savepath from config
00230     dir = ConfMan.get("savepath");
00231 
00232     // Work around a bug (#999122) in the original 0.6.1 release of
00233     // ScummVM, which would insert a bad savepath value into config files.
00234     if (dir == "None") {
00235         ConfMan.removeKey("savepath", ConfMan.getActiveDomainName());
00236         ConfMan.flushToDisk();
00237         dir = ConfMan.get("savepath");
00238     }
00239 
00240     return dir;
00241 }
00242 
00243 void DefaultSaveFileManager::assureCached(const Common::String &savePathName) {
00244     // Check that path exists and is usable.
00245     checkPath(Common::FSNode(savePathName));
00246 
00247 #if defined(USE_CLOUD) && defined(USE_LIBCURL)
00248     Common::Array<Common::String> files = CloudMan.getSyncingFiles(); //returns empty array if not syncing
00249     if (!files.empty()) updateSavefilesList(files); //makes this cache invalid
00250     else _lockedFiles = files;
00251 #endif
00252 
00253     if (_cachedDirectory == savePathName) {
00254         return;
00255     }
00256 
00257     _saveFileCache.clear();
00258     _cachedDirectory.clear();
00259 
00260     if (getError().getCode() != Common::kNoError) {
00261         warning("DefaultSaveFileManager::assureCached: Can not cache path '%s': '%s'", savePathName.c_str(), getErrorDesc().c_str());
00262         return;
00263     }
00264 
00265     // FSNode can cache its members, thus create it after checkPath to reflect
00266     // actual file system state.
00267     const Common::FSNode savePath(savePathName);
00268 
00269     Common::FSList children;
00270     if (!savePath.getChildren(children, Common::FSNode::kListFilesOnly)) {
00271         return;
00272     }
00273 
00274     // Build the savefile name cache.
00275     for (Common::FSList::const_iterator file = children.begin(), end = children.end(); file != end; ++file) {
00276         if (_saveFileCache.contains(file->getName())) {
00277             warning("DefaultSaveFileManager::assureCached: Name clash when building cache, ignoring file '%s'", file->getName().c_str());
00278         } else {
00279             _saveFileCache[file->getName()] = *file;
00280         }
00281     }
00282 
00283     // Only now store that we cached 'savePathName' to indicate we successfully
00284     // cached the directory.
00285     _cachedDirectory = savePathName;
00286 }
00287 
00288 #if defined(USE_CLOUD) && defined(USE_LIBCURL)
00289 
00290 Common::HashMap<Common::String, uint32> DefaultSaveFileManager::loadTimestamps() {
00291     Common::HashMap<Common::String, uint32> timestamps;
00292 
00293     //refresh the files list
00294     Common::Array<Common::String> files;
00295     g_system->getSavefileManager()->updateSavefilesList(files);
00296 
00297     //start with listing all the files in saves/ directory and setting invalid timestamp to them
00298     Common::StringArray localFiles = g_system->getSavefileManager()->listSavefiles("*");
00299     for (uint32 i = 0; i < localFiles.size(); ++i)
00300         timestamps[localFiles[i]] = INVALID_TIMESTAMP;
00301 
00302     //now actually load timestamps from file
00303     Common::InSaveFile *file = g_system->getSavefileManager()->openRawFile(TIMESTAMPS_FILENAME);
00304     if (!file) {
00305         warning("DefaultSaveFileManager: failed to open '%s' file to load timestamps", TIMESTAMPS_FILENAME);
00306         return timestamps;
00307     }
00308 
00309     while (!file->eos()) {
00310         //read filename into buffer (reading until the first ' ')
00311         Common::String buffer;
00312         while (!file->eos()) {
00313             byte b = file->readByte();
00314             if (b == ' ') break;
00315             buffer += (char)b;
00316         }
00317 
00318         //read timestamp info buffer (reading until ' ' or some line ending char)
00319         Common::String filename = buffer;
00320         while (true) {
00321             bool lineEnded = false;
00322             buffer = "";
00323             while (!file->eos()) {
00324                 byte b = file->readByte();
00325                 if (b == ' ' || b == '\n' || b == '\r') {
00326                     lineEnded = (b == '\n');
00327                     break;
00328                 }
00329                 buffer += (char)b;
00330             }
00331 
00332             if (buffer == "" && file->eos()) break;
00333             if (!lineEnded) filename += " " + buffer;
00334             else break;
00335         }
00336 
00337         //parse timestamp
00338         uint32 timestamp = buffer.asUint64();
00339         if (buffer == "" || timestamp == 0) break;
00340         if (timestamps.contains(filename))
00341             timestamps[filename] = timestamp;
00342     }
00343 
00344     delete file;
00345     return timestamps;
00346 }
00347 
00348 void DefaultSaveFileManager::saveTimestamps(Common::HashMap<Common::String, uint32> &timestamps) {
00349     Common::DumpFile f;
00350     Common::String filename = concatWithSavesPath(TIMESTAMPS_FILENAME);
00351     if (!f.open(filename, true)) {
00352         warning("DefaultSaveFileManager: failed to open '%s' file to save timestamps", filename.c_str());
00353         return;
00354     }
00355 
00356     for (Common::HashMap<Common::String, uint32>::iterator i = timestamps.begin(); i != timestamps.end(); ++i) {
00357         uint32 v = i->_value;
00358         if (v < 1) v = 1; // 0 timestamp is treated as EOF up there, so we should never save zeros
00359 
00360         Common::String data = i->_key + Common::String::format(" %u\n", v);
00361         if (f.write(data.c_str(), data.size()) != data.size()) {
00362             warning("DefaultSaveFileManager: failed to write timestamps data into '%s'", filename.c_str());
00363             return;
00364         }
00365     }
00366 
00367     f.flush();
00368     f.finalize();
00369     f.close();
00370 }
00371 
00372 #endif // ifdef USE_LIBCURL
00373 
00374 Common::String DefaultSaveFileManager::concatWithSavesPath(Common::String name) {
00375     DefaultSaveFileManager *manager = dynamic_cast<DefaultSaveFileManager *>(g_system->getSavefileManager());
00376     Common::String path = (manager ? manager->getSavePath() : ConfMan.get("savepath"));
00377     if (path.size() > 0 && (path.lastChar() == '/' || path.lastChar() == '\\'))
00378         return path + name;
00379 
00380     //simple heuristic to determine which path separator to use
00381     int backslashes = 0;
00382     for (uint32 i = 0; i < path.size(); ++i)
00383         if (path[i] == '/') --backslashes;
00384         else if (path[i] == '\\') ++backslashes;
00385 
00386     if (backslashes > 0) return path + '\\' + name;
00387     return path + '/' + name;
00388 }
00389 
00390 #endif // !defined(DISABLE_DEFAULT_SAVEFILEMANAGER)


Generated on Sat Sep 26 2020 05:00:46 for ResidualVM by doxygen 1.7.1
curved edge   curved edge