]> git.mxchange.org Git - simgear.git/blob - simgear/misc/sg_dir.cxx
Use wide-string APIs on Windows.
[simgear.git] / simgear / misc / sg_dir.cxx
1 // Written by James Turner, started July 2010.
2 //
3 // Copyright (C) 2010  Curtis L. Olson - http://www.flightgear.org/~curt
4 //
5 // This library is free software; you can redistribute it and/or
6 // modify it under the terms of the GNU Library General Public
7 // License as published by the Free Software Foundation; either
8 // version 2 of the License, or (at your option) any later version.
9 //
10 // This library is distributed in the hope that it will be useful,
11 // but WITHOUT ANY WARRANTY; without even the implied warranty of
12 // MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
13 // Library General Public License for more details.
14 //
15 // You should have received a copy of the GNU General Public License
16 // along with this program; if not, write to the Free Software
17 // Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.
18 //
19 // $Id$
20
21 #include <simgear_config.h>
22 #include <simgear/compiler.h>
23
24 #include <simgear/misc/sg_dir.hxx>
25 #include <simgear/structure/exception.hxx>
26 #include <math.h>
27 #include <stdlib.h>
28 #include <cstdio>
29
30 #ifdef _WIN32
31 #  define WIN32_LEAN_AND_MEAN
32 #  include <windows.h>
33 #  include <direct.h>
34 #  include <Shlwapi.h>
35 #else
36 #  include <sys/types.h>
37 #  include <dirent.h>
38 #  include <sys/stat.h>
39 #  include <unistd.h>
40 #  include <errno.h>
41 #endif
42
43 #include <simgear/misc/strutils.hxx>
44 #include <simgear/debug/logstream.hxx>
45 #include <boost/foreach.hpp>
46
47 #include <cstring>
48 #include <cstdlib>
49 #include <iostream>
50 #include <algorithm> // for std::sort
51
52 using std::string;
53
54 namespace simgear
55 {
56
57 Dir::Dir() :
58     _removeOnDestroy(false)
59 {
60 }
61
62 Dir::Dir(const SGPath& path) :
63   _path(path),
64   _removeOnDestroy(false)
65 {
66     _path.set_cached(false); // disable caching, so create/remove work
67 }
68
69 Dir::Dir(const Dir& rel, const SGPath& relPath) :
70   _path(rel.file(relPath.utf8Str())),
71   _removeOnDestroy(false)
72 {
73     _path.set_cached(false); // disable caching, so create/remove work
74 }
75
76 Dir::~Dir()
77 {
78     if (_removeOnDestroy) {
79         remove(true);
80     }
81 }
82
83 void Dir::setRemoveOnDestroy()
84 {
85     _removeOnDestroy = true;
86 }
87
88 Dir Dir::current()
89 {
90 #if defined(SG_WINDOWS)
91     wchar_t* buf = _wgetcwd(NULL, 0);
92 #else
93     char *buf = ::getcwd(NULL, 0);
94 #endif
95     if (!buf) {
96         if  (errno == 2) throw sg_exception("The current directory is invalid");
97         else throw sg_exception(strerror(errno));
98     }
99
100     SGPath p(buf);
101     free(buf);
102     return Dir(p);
103 }
104
105 Dir Dir::tempDir(const std::string& templ)
106 {
107 #ifdef HAVE_MKDTEMP
108     char buf[1024];
109     const char* tempPath = ::getenv("TMPDIR");
110     if (!tempPath) {
111         tempPath = "/tmp";
112     }
113     SGPath p(tempPath);
114     p.append(templ);
115     // Mac OS-X / BSD manual says any number of 'X's, but GLibc manual
116     // says exactly six, so that's what I'm going with
117     p.concat("-XXXXXX");
118     std::string s = p.local8BitStr();
119     ::snprintf(buf, 1024, "%s", s.c_str());
120     if (!mkdtemp(buf)) {
121         SG_LOG(SG_IO, SG_WARN, "mkdtemp failed:" << strerror(errno));
122         return Dir();
123     }
124     
125     return Dir(SGPath(buf));
126 #else
127 #if defined(SG_WINDOWS)
128         std::wstring wideTemplate = simgear::strutils::convertUtf8ToWString(templ);
129         wchar_t* buf = _wtempnam(0, wideTemplate.c_str());
130         SGPath p(buf);
131         free(buf); // unlike tempnam(), _wtempnam mallocs its result buffer
132 #else
133     SGPath p(tempnam(0, templ.c_str()));
134 #endif
135     Dir t(p);
136     if (!t.create(0700)) {
137         SG_LOG(SG_IO, SG_WARN, "failed to create temporary directory at " << p);
138     }
139     
140     return t;
141 #endif
142 }
143
144 static bool pathSortPredicate(const SGPath& p1, const SGPath& p2)
145 {
146   return p1.file() < p2.file();
147 }
148
149 PathList Dir::children(int types, const std::string& nameFilter) const
150 {
151   PathList result;
152   if (types == 0) {
153     types = TYPE_FILE | TYPE_DIR | NO_DOT_OR_DOTDOT;
154   }
155   
156 #if defined(SG_WINDOWS)
157   std::wstring search(_path.wstr());
158   if (nameFilter.empty()) {
159     search += simgear::strutils::convertUtf8ToWString("\\*"); // everything
160   } else {
161     search += simgear::strutils::convertUtf8ToWString("\\*" + nameFilter);
162   }
163   
164   WIN32_FIND_DATAW fData;
165   HANDLE find = FindFirstFileW(search.c_str(), &fData);
166   if (find == INVALID_HANDLE_VALUE) {
167           int err = GetLastError();
168           if (err != ERROR_FILE_NOT_FOUND) {
169                 SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: FindFirstFile failed:" << 
170                         _path << " with error:" << err);
171           }
172     return result;
173   }
174   
175   bool done = false;
176   for (bool done = false; !done; done = (FindNextFileW(find, &fData) == 0)) {
177     if (fData.dwFileAttributes & FILE_ATTRIBUTE_HIDDEN) {
178       if (!(types & INCLUDE_HIDDEN)) {
179         continue;
180       }
181     }
182     
183         std::string utf8File = simgear::strutils::convertWStringToUtf8(fData.cFileName);
184     if (fData.dwFileAttributes & FILE_ATTRIBUTE_DIRECTORY) {
185           if (types & NO_DOT_OR_DOTDOT) {
186                 if ((utf8File == ".") || (utf8File == "..")) {
187                   continue;
188                 }
189           }
190
191       if (!(types & TYPE_DIR)) {
192         continue;
193       }
194         } else if ((fData.dwFileAttributes & FILE_ATTRIBUTE_DEVICE) ||
195                                 (fData.dwFileAttributes & FILE_ATTRIBUTE_REPARSE_POINT))
196         {
197                 continue; // always ignore device files
198     } else if (!(types & TYPE_FILE)) {
199        continue;
200     }
201
202     result.push_back(file(utf8File));
203   }
204
205   FindClose(find);
206 #else
207     std::string ps = _path.local8BitStr();
208   DIR* dp = opendir(ps.c_str());
209   if (!dp) {
210     SG_LOG(SG_GENERAL, SG_WARN, "Dir::children: opendir failed:" << _path);
211     return result;
212   }
213   
214   int filterLen = nameFilter.size();
215   
216   while (true) {
217     struct dirent* entry = readdir(dp);
218     if (!entry) {
219       break; // done iteration
220     }
221     
222     // skip hidden files (names beginning with '.') unless requested
223     if (!(types & INCLUDE_HIDDEN) && (entry->d_name[0] == '.') &&
224          strcmp(entry->d_name, ".") && strcmp(entry->d_name, "..")) {
225       continue;
226     }
227     
228     SGPath f = file(entry->d_name);
229     if (!f.exists()) {
230       continue; // stat() failed
231     }
232     
233     if (f.isDir()) {
234       // directory handling
235       if (!(types & TYPE_DIR)) {
236         continue;
237       }
238       
239       if (types & NO_DOT_OR_DOTDOT) {
240         if (!strcmp(entry->d_name, ".") || !strcmp(entry->d_name, "..")) {
241           continue;
242         }
243       }
244     } else if (f.isFile()) {
245       // regular file handling
246       if (!(types & TYPE_FILE)) {
247         continue;
248       }
249     } else {
250       // block device /fifo/char file, ignore
251       continue;
252     }
253
254     if (!nameFilter.empty()) {
255       int nameLen = strlen(entry->d_name);
256       if (nameLen < filterLen) {
257         continue; // name is shorter than the filter
258       }
259     
260       char* nameSuffix = entry->d_name + (nameLen - filterLen);
261       if (strcmp(nameSuffix, nameFilter.c_str())) {
262         continue;
263       }
264     }
265     
266   // passed all criteria, add to our result vector
267     result.push_back(file(entry->d_name));
268   }
269   
270   closedir(dp);
271 #endif
272
273   // File system order is random. Make things deterministic,
274   // so it's the same for every user.
275   std::sort(result.begin(), result.end(), pathSortPredicate);
276
277   return result;
278 }
279
280 bool Dir::isEmpty() const
281 {
282 #if defined(SG_WINDOWS)
283   std::wstring ps = _path.wstr();
284   return PathIsDirectoryEmptyW( ps.c_str() );
285 #else
286   std::string ps = _path.local8BitStr();
287   DIR* dp = opendir( ps.c_str() );
288   if (!dp) return true;
289
290   int n = 0;
291   dirent* d;
292   while( (d = readdir(dp)) !=NULL && (n < 4) ) n++;
293   closedir(dp);
294
295   return (n == 2); // '.' and '..' always exist
296 #endif
297 }
298
299 bool Dir::exists() const
300 {
301   return _path.isDir();
302 }
303
304 SGPath Dir::file(const std::string& name) const
305 {
306   SGPath childPath = _path;
307   childPath.set_cached(true);
308   childPath.append(name);
309   return childPath;  
310 }
311
312 bool Dir::create(mode_t mode)
313 {
314     if (exists()) {
315         return false; // already exists
316     }
317     
318 // recursively create parent directories
319     Dir pr(parent());
320     if (!pr.path().isNull() && !pr.exists()) {
321         bool ok = pr.create(mode);
322         if (!ok) {
323             return false;
324         }
325     }
326     
327 // finally, create ourselves
328 #if defined(SG_WINDOWS)
329         std::wstring ps = _path.wstr();
330         int err = _wmkdir(ps.c_str());
331 #else
332     std::string ps = _path.local8BitStr();
333     int err = mkdir(ps.c_str(), mode);
334 #endif
335     if (err) {
336         SG_LOG(SG_IO, SG_WARN,  "directory creation failed: (" << _path << ") " << strerror(errno) );
337     }
338     
339     return (err == 0);
340 }
341
342 bool Dir::removeChildren() const
343 {
344     bool ok;
345     PathList cs = children(NO_DOT_OR_DOTDOT | INCLUDE_HIDDEN | TYPE_FILE | TYPE_DIR);
346     BOOST_FOREACH(SGPath path, cs) {
347         if (path.isDir()) {
348             Dir childDir(path);
349             ok = childDir.remove(true);
350         } else {
351             ok = path.remove();
352         }
353         
354         if (!ok) {
355             SG_LOG(SG_IO, SG_WARN, "failed to remove:" << path);
356             return false;
357         }
358     } // of child iteration
359     
360     return true;
361 }
362
363 bool Dir::remove(bool recursive)
364 {
365     if (!exists()) {
366         SG_LOG(SG_IO, SG_WARN, "attempt to remove non-existant dir:" << _path);
367         return false;
368     }
369     
370     if (recursive) {
371         if (!removeChildren()) {
372             SG_LOG(SG_IO, SG_WARN, "Dir at:" << _path << " failed to remove children");
373             return false;
374         }
375     } // of recursive deletion
376
377 #if defined(SG_WINDOWS)
378         std::wstring ps = _path.wstr();
379     int err = _wrmdir(ps.c_str());
380 #else
381         std::string ps = _path.local8BitStr();
382     int err = rmdir(ps.c_str());
383 #endif
384     if (err) {
385         SG_LOG(SG_IO, SG_WARN, "rmdir failed:" << _path << ":" << strerror(errno));
386     }
387     return (err == 0);
388 }
389
390 Dir Dir::parent() const
391 {
392     return Dir(_path.dir());
393 }
394
395 } // of namespace simgear