1 /* Copyright (C) 2016 Wildfire Games.
2  *
3  * Permission is hereby granted, free of charge, to any person obtaining
4  * a copy of this software and associated documentation files (the
5  * "Software"), to deal in the Software without restriction, including
6  * without limitation the rights to use, copy, modify, merge, publish,
7  * distribute, sublicense, and/or sell copies of the Software, and to
8  * permit persons to whom the Software is furnished to do so, subject to
9  * the following conditions:
10  *
11  * The above copyright notice and this permission notice shall be included
12  * in all copies or substantial portions of the Software.
13  *
14  * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
15  * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF
16  * MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT.
17  * IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY
18  * CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT,
19  * TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE
20  * SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
21  */
22 
23 /*
24  * 'tree' of VFS directories and files
25  */
26 
27 #include "precompiled.h"
28 #include "lib/file/vfs/vfs_tree.h"
29 
30 #include <cstdio>
31 
32 #include "lib/file/common/file_stats.h"
33 #include "lib/sysdep/cpu.h"
34 
35 
36 //-----------------------------------------------------------------------------
37 
VfsFile(const VfsPath & name,size_t size,time_t mtime,size_t priority,const PIFileLoader & loader)38 VfsFile::VfsFile(const VfsPath& name, size_t size, time_t mtime, size_t priority, const PIFileLoader& loader)
39 	: m_name(name), m_size(size), m_mtime(mtime), m_priority(priority), m_loader(loader)
40 {
41 }
42 
43 
44 
45 //-----------------------------------------------------------------------------
46 
VfsDirectory()47 VfsDirectory::VfsDirectory()
48 	: m_shouldPopulate(0)
49 {
50 }
51 
ShouldDelete(const VfsFile & file,const VfsFile & deletedFile)52 static bool ShouldDelete(const VfsFile& file, const VfsFile& deletedFile)
53 {
54 	// We only check priority here, a .DELETED file in a mod should not
55 	// delete files in that mod. For the same reason we ignore loose
56 	// .DELETED files next to an archive.
57 	return file.Priority() < deletedFile.Priority();
58 }
59 
ShouldReplaceWith(const VfsFile & previousFile,const VfsFile & newFile)60 static bool ShouldReplaceWith(const VfsFile& previousFile, const VfsFile& newFile)
61 {
62 	// 1) priority (override mods)
63 	if(newFile.Priority() < previousFile.Priority())
64 		return false;
65 	if(newFile.Priority() > previousFile.Priority())
66 		return true;
67 
68 	// 2) timestamp
69 	{
70 		const double howMuchNewer = difftime(newFile.MTime(), previousFile.MTime());
71 		const double threshold = 2.0;	// FAT timestamp resolution [seconds]
72 		if(howMuchNewer > threshold)	// newer
73 			return true;
74 		if(howMuchNewer < -threshold)	// older
75 			return false;
76 		// else: "equal" (tolerating small differences due to FAT's low
77 		// mtime resolution)
78 	}
79 
80 	// 3) precedence (efficiency of file provider)
81 	if(newFile.Loader()->Precedence() < previousFile.Loader()->Precedence())
82 		return false;
83 
84 	return true;
85 }
86 
87 
DeleteSubtree(const VfsFile & file)88 void VfsDirectory::DeleteSubtree(const VfsFile& file)
89 {
90 	ENSURE(file.Name().Extension() == L".DELETED");
91 
92 	const VfsPath basename = file.Name().Basename();
93 	std::map<VfsPath, VfsFile>::iterator fit = m_files.find(basename);
94 	if(fit != m_files.end() && ShouldDelete(fit->second, file))
95 		m_files.erase(basename);
96 
97 	std::map<VfsPath, VfsDirectory>::iterator dit = m_subdirectories.find(basename);
98 	if(dit != m_subdirectories.end() && dit->second.DeleteTree(file))
99 		m_subdirectories.erase(dit);
100 }
101 
DeleteTree(const VfsFile & file)102 bool VfsDirectory::DeleteTree(const VfsFile& file)
103 {
104 	for(std::map<VfsPath, VfsFile>::iterator it = m_files.begin(); it != m_files.end();)
105 		if(ShouldDelete(it->second, file))
106 			it = m_files.erase(it);
107 		else
108 			++it;
109 
110 	for(std::map<VfsPath, VfsDirectory>::iterator it = m_subdirectories.begin(); it != m_subdirectories.end();)
111 		if(it->second.DeleteTree(file))
112 			it = m_subdirectories.erase(it);
113 		else
114 			++it;
115 
116 	return m_files.empty() && m_subdirectories.empty();
117 }
118 
119 
AddFile(const VfsFile & file)120 VfsFile* VfsDirectory::AddFile(const VfsFile& file)
121 {
122 	std::pair<VfsPath, VfsFile> value = std::make_pair(file.Name(), file);
123 	std::pair<VfsFiles::iterator, bool> ret = m_files.insert(value);
124 	if(!ret.second)	// already existed
125 	{
126 		VfsFile& previousFile = ret.first->second;
127 		const VfsFile& newFile = value.second;
128 		if(ShouldReplaceWith(previousFile, newFile))
129 			previousFile = newFile;
130 	}
131 	else
132 	{
133 		stats_vfs_file_add(file.Size());
134 	}
135 
136 	return &(*ret.first).second;
137 }
138 
139 
140 // rationale: passing in a pre-constructed VfsDirectory and copying that into
141 // our map would be slower and less convenient for the caller.
AddSubdirectory(const VfsPath & name)142 VfsDirectory* VfsDirectory::AddSubdirectory(const VfsPath& name)
143 {
144 	std::pair<VfsPath, VfsDirectory> value = std::make_pair(name.string(), VfsDirectory());
145 	std::pair<VfsSubdirectories::iterator, bool> ret = m_subdirectories.insert(value);
146 	return &(*ret.first).second;
147 }
148 
149 
RemoveFile(const VfsPath & name)150 void VfsDirectory::RemoveFile(const VfsPath& name)
151 {
152 	m_files.erase(name.string());
153 }
154 
155 
GetFile(const VfsPath & name)156 VfsFile* VfsDirectory::GetFile(const VfsPath& name)
157 {
158 	VfsFiles::iterator it = m_files.find(name.string());
159 	if(it == m_files.end())
160 		return 0;
161 	return &it->second;
162 }
163 
GetSubdirectory(const VfsPath & name)164 VfsDirectory* VfsDirectory::GetSubdirectory(const VfsPath& name)
165 {
166 	VfsSubdirectories::iterator it = m_subdirectories.find(name.string());
167 	if(it == m_subdirectories.end())
168 		return 0;
169 	return &it->second;
170 }
171 
172 
SetAssociatedDirectory(const PRealDirectory & realDirectory)173 void VfsDirectory::SetAssociatedDirectory(const PRealDirectory& realDirectory)
174 {
175 	if(!cpu_CAS(&m_shouldPopulate, 0, 1))
176 		DEBUG_WARN_ERR(ERR::LOGIC);	// caller didn't check ShouldPopulate
177 	m_realDirectory = realDirectory;
178 }
179 
180 
ShouldPopulate()181 bool VfsDirectory::ShouldPopulate()
182 {
183 	return cpu_CAS(&m_shouldPopulate, 1, 0);	// test and reset
184 }
185 
186 
RequestRepopulate()187 void VfsDirectory::RequestRepopulate()
188 {
189 	m_shouldPopulate = 1;
190 }
191 
192 
Clear()193 void VfsDirectory::Clear()
194 {
195 	m_files.clear();
196 	m_subdirectories.clear();
197 	m_realDirectory.reset();
198 	m_shouldPopulate = 0;
199 }
200 
201 
202 //-----------------------------------------------------------------------------
203 
FileDescription(const VfsFile & file)204 std::wstring FileDescription(const VfsFile& file)
205 {
206 	wchar_t timestamp[25];
207 	const time_t mtime = file.MTime();
208 	wcsftime(timestamp, ARRAY_SIZE(timestamp), L"%a %b %d %H:%M:%S %Y", localtime(&mtime));
209 
210 	wchar_t buf[200];
211 	swprintf_s(buf, ARRAY_SIZE(buf), L"(%c; %6lu; %ls) %ls", file.Loader()->LocationCode(), (unsigned long)file.Size(), timestamp, file.Name().string().c_str());
212 	return buf;
213 }
214 
215 
FileDescriptions(const VfsDirectory & directory,size_t indentLevel)216 std::wstring FileDescriptions(const VfsDirectory& directory, size_t indentLevel)
217 {
218 	VfsDirectory::VfsFiles files = directory.Files();
219 
220 	std::wstring descriptions;
221 	descriptions.reserve(100*files.size());
222 
223 	const std::wstring indentation(4*indentLevel, ' ');
224 	for(VfsDirectory::VfsFiles::const_iterator it = files.begin(); it != files.end(); ++it)
225 	{
226 		const VfsFile& file = it->second;
227 		descriptions += indentation;
228 		descriptions += FileDescription(file);
229 		descriptions += L"\n";
230 	}
231 
232 	return descriptions;
233 }
234 
235 
DirectoryDescriptionR(std::wstring & descriptions,const VfsDirectory & directory,size_t indentLevel)236 void DirectoryDescriptionR(std::wstring& descriptions, const VfsDirectory& directory, size_t indentLevel)
237 {
238 	const std::wstring indentation(4*indentLevel, ' ');
239 
240 	const VfsDirectory::VfsSubdirectories& subdirectories = directory.Subdirectories();
241 	for(VfsDirectory::VfsSubdirectories::const_iterator it = subdirectories.begin(); it != subdirectories.end(); ++it)
242 	{
243 		const VfsPath& name = it->first;
244 		const VfsDirectory& subdirectory = it->second;
245 		descriptions += indentation;
246 		descriptions += std::wstring(L"[") + name.string() + L"]\n";
247 		descriptions += FileDescriptions(subdirectory, indentLevel+1);
248 
249 		DirectoryDescriptionR(descriptions, subdirectory, indentLevel+1);
250 	}
251 }
252