3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * \author Angus Leeming
8 * Full author contact details are available in file CREDITS.
13 #include "support/FileName.h"
14 #include "support/filetools.h"
15 #include "support/lstrings.h"
16 #include "support/os.h"
17 #include "support/qstring_helpers.h"
28 #include <boost/assert.hpp>
35 #ifdef HAVE_SYS_TYPES_H
36 # include <sys/types.h>
38 #ifdef HAVE_SYS_STAT_H
39 # include <sys/stat.h>
48 using std::ostringstream;
55 /////////////////////////////////////////////////////////////////////
59 /////////////////////////////////////////////////////////////////////
61 struct FileName::Private
65 Private(string const & abs_filename) : fi(toqstr(abs_filename))
71 /////////////////////////////////////////////////////////////////////
75 /////////////////////////////////////////////////////////////////////
78 FileName::FileName() : d(new Private)
82 FileName::FileName(string const & abs_filename)
83 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
85 BOOST_ASSERT(empty());
87 BOOST_ASSERT(!contains(abs_filename, '\\'));
92 FileName::FileName(FileName const & rhs) : d(new Private)
98 FileName & FileName::operator=(FileName const & rhs)
105 bool FileName::empty() const
107 return d->fi.absoluteFilePath().isEmpty();
111 string FileName::absFilename() const
113 return fromqstr(d->fi.absoluteFilePath());
117 void FileName::set(string const & name)
119 d->fi.setFile(toqstr(name));
120 BOOST_ASSERT(d->fi.isAbsolute());
122 BOOST_ASSERT(!contains(name, '\\'));
127 void FileName::erase()
133 bool FileName::copyTo(FileName const & name, bool overwrite) const
136 QFile::remove(name.d->fi.absoluteFilePath());
137 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
139 lyxerr << "FileName::copyTo(): Could not copy file "
140 << *this << " to " << name << endl;
145 string FileName::toFilesystemEncoding() const
147 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
148 return string(encoded.begin(), encoded.end());
152 FileName FileName::fromFilesystemEncoding(string const & name)
154 QByteArray const encoded(name.c_str(), name.length());
155 return FileName(fromqstr(QFile::decodeName(encoded)));
159 bool FileName::exists() const
161 return d->fi.exists();
165 bool FileName::isSymLink() const
167 return d->fi.isSymLink();
171 bool FileName::isFileEmpty() const
173 return d->fi.size() == 0;
177 bool FileName::isDirectory() const
179 return d->fi.isDir();
183 bool FileName::isReadOnly() const
185 return d->fi.isReadable() && !d->fi.isWritable();
189 bool FileName::isReadableDirectory() const
191 return d->fi.isDir() && d->fi.isReadable();
195 std::string FileName::onlyFileName() const
197 return support::onlyFilename(absFilename());
201 FileName FileName::onlyPath() const
203 return FileName(support::onlyPath(absFilename()));
207 bool FileName::isReadableFile() const
209 return d->fi.isFile() && d->fi.isReadable();
213 bool FileName::isWritable() const
215 return d->fi.isWritable();
219 bool FileName::isDirWritable() const
221 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
223 FileName const tmpfl(tempName(*this, "lyxwritetest"));
233 FileName FileName::tempName(FileName const & dir, std::string const & mask)
235 return support::tempName(dir, mask);
239 std::time_t FileName::lastModified() const
241 return d->fi.lastModified().toTime_t();
245 bool FileName::removeFile() const
247 bool const success = QFile::remove(d->fi.absoluteFilePath());
249 lyxerr << "FileName::removeFile(): Could not delete file "
250 << *this << "." << endl;
255 static bool rmdir(QFileInfo const & fi)
257 QDir dir(fi.absoluteFilePath());
258 QFileInfoList list = dir.entryInfoList();
259 bool global_success = true;
260 for (int i = 0; i < list.size(); ++i) {
261 if (list.at(i).fileName() == ".")
263 if (list.at(i).fileName() == "..")
266 if (list.at(i).isDir()) {
267 LYXERR(Debug::FILES, "Erasing dir "
268 << fromqstr(list.at(i).absoluteFilePath()));
269 success = rmdir(list.at(i));
272 LYXERR(Debug::FILES, "Erasing file "
273 << fromqstr(list.at(i).absoluteFilePath()));
274 success = dir.remove(list.at(i).fileName());
277 global_success = false;
278 lyxerr << "Could not delete "
279 << fromqstr(list.at(i).absoluteFilePath()) << "." << endl;
282 QDir parent = fi.absolutePath();
283 global_success |= parent.rmdir(fi.fileName());
284 return global_success;
288 bool FileName::destroyDirectory() const
290 bool const success = rmdir(d->fi);
292 lyxerr << "Could not delete " << *this << "." << endl;
298 bool FileName::createDirectory(int permission) const
300 BOOST_ASSERT(!empty());
301 return mkdir(*this, permission) == 0;
305 std::vector<FileName> FileName::dirList(std::string const & ext)
307 std::vector<FileName> dirlist;
308 if (!exists() || !isDirectory()) {
309 lyxerr << "FileName::dirList(): Directory \"" << absFilename()
310 << "\" does not exist!" << endl;
314 QDir dir(d->fi.absoluteFilePath());
319 case '.': filter = "*" + toqstr(ext); break;
320 case '*': filter = toqstr(ext); break;
321 default: filter = "*." + toqstr(ext);
323 dir.setNameFilters(QStringList(filter));
324 LYXERR(Debug::FILES, "FileName::dirList(): filtering on extension "
325 << fromqstr(filter) << " is requested." << endl);
328 QFileInfoList list = dir.entryInfoList();
329 for (int i = 0; i < list.size(); ++i) {
331 fi.d->fi = list.at(i);
332 dirlist.push_back(fi);
333 LYXERR(Debug::FILES, "FileName::dirList(): found file "
334 << fi.absFilename() << endl);
341 docstring FileName::displayName(int threshold) const
343 return makeDisplayPath(absFilename(), threshold);
347 string FileName::fileContents() const
350 string const encodedname = toFilesystemEncoding();
351 ifstream ifs(encodedname.c_str());
359 lyxerr << "LyX was not able to read file '" << *this << '\'' << std::endl;
364 string FileName::guessFormatFromContents() const
366 // the different filetypes and what they contain in one of the first lines
367 // (dots are any characters). (Herbert 20020131)
370 // EPS %!PS-Adobe-3.0 EPSF...
377 // PBM P1... or P4 (B/W)
378 // PGM P2... or P5 (Grayscale)
379 // PPM P3... or P6 (color)
380 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
381 // SGI \001\332... (decimal 474)
383 // TIFF II... or MM...
385 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
386 // ...static char *...
387 // XWD \000\000\000\151 (0x00006900) decimal 105
389 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
390 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
391 // Z \037\235 UNIX compress
394 if (empty() || !isReadableFile())
397 ifstream ifs(toFilesystemEncoding().c_str());
399 // Couldn't open file...
403 static string const gzipStamp = "\037\213";
406 static string const zipStamp = "PK";
409 static string const compressStamp = "\037\235";
411 // Maximum strings to read
412 int const max_count = 50;
417 bool firstLine = true;
418 while ((count++ < max_count) && format.empty()) {
420 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
421 << "\tFile type not recognised before EOF!");
426 string const stamp = str.substr(0, 2);
427 if (firstLine && str.size() >= 2) {
428 // at first we check for a zipped file, because this
429 // information is saved in the first bytes of the file!
430 // also some graphic formats which save the information
431 // in the first line, too.
432 if (prefixIs(str, gzipStamp)) {
435 } else if (stamp == zipStamp) {
438 } else if (stamp == compressStamp) {
442 } else if (stamp == "BM") {
445 } else if (stamp == "\001\332") {
449 // Don't need to use str.at(0), str.at(1) because
450 // we already know that str.size() >= 2
451 } else if (str[0] == 'P') {
467 } else if ((stamp == "II") || (stamp == "MM")) {
470 } else if (prefixIs(str,"%TGIF")) {
473 } else if (prefixIs(str,"#FIG")) {
476 } else if (prefixIs(str,"GIF")) {
479 } else if (str.size() > 3) {
480 int const c = ((str[0] << 24) & (str[1] << 16) &
481 (str[2] << 8) & str[3]);
492 else if (contains(str,"EPSF"))
493 // dummy, if we have wrong file description like
494 // %!PS-Adobe-2.0EPSF"
497 else if (contains(str, "Grace"))
500 else if (contains(str, "JFIF"))
503 else if (contains(str, "%PDF"))
506 else if (contains(str, "PNG"))
509 else if (contains(str, "%!PS-Adobe")) {
512 if (contains(str,"EPSF"))
518 else if (contains(str, "_bits[]"))
521 else if (contains(str, "XPM") || contains(str, "static char *"))
524 else if (contains(str, "BITPIX"))
528 if (!format.empty()) {
529 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
533 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
534 << "\tCouldn't find a known format!");
539 bool FileName::isZippedFile() const
541 string const type = guessFormatFromContents();
542 return contains("gzip zip compress", type) && !type.empty();
546 bool operator==(FileName const & lhs, FileName const & rhs)
548 return lhs.absFilename() == rhs.absFilename();
552 bool operator!=(FileName const & lhs, FileName const & rhs)
554 return lhs.absFilename() != rhs.absFilename();
558 bool operator<(FileName const & lhs, FileName const & rhs)
560 return lhs.absFilename() < rhs.absFilename();
564 bool operator>(FileName const & lhs, FileName const & rhs)
566 return lhs.absFilename() > rhs.absFilename();
570 std::ostream & operator<<(std::ostream & os, FileName const & filename)
572 return os << filename.absFilename();
576 /////////////////////////////////////////////////////////////////////
580 /////////////////////////////////////////////////////////////////////
583 DocFileName::DocFileName()
584 : save_abs_path_(true)
588 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
589 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
593 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
594 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
598 void DocFileName::set(string const & name, string const & buffer_path)
600 save_abs_path_ = absolutePath(name);
601 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
602 zipped_valid_ = false;
606 void DocFileName::erase()
609 zipped_valid_ = false;
613 string const DocFileName::relFilename(string const & path) const
616 return to_utf8(makeRelPath(qstring_to_ucs4(d->fi.absoluteFilePath()), from_utf8(path)));
620 string const DocFileName::outputFilename(string const & path) const
622 return save_abs_path_ ? absFilename() : relFilename(path);
626 string const DocFileName::mangledFilename(std::string const & dir) const
628 // We need to make sure that every DocFileName instance for a given
629 // filename returns the same mangled name.
630 typedef map<string, string> MangledMap;
631 static MangledMap mangledNames;
632 MangledMap::const_iterator const it = mangledNames.find(absFilename());
633 if (it != mangledNames.end())
636 string const name = absFilename();
638 string mname = os::internal_path(name);
639 // Remove the extension.
640 mname = changeExtension(name, string());
641 // The mangled name must be a valid LaTeX name.
642 // The list of characters to keep is probably over-restrictive,
643 // but it is not really a problem.
644 // Apart from non-ASCII characters, at least the following characters
645 // are forbidden: '/', '.', ' ', and ':'.
646 // On windows it is not possible to create files with '<', '>' or '?'
648 static string const keep = "abcdefghijklmnopqrstuvwxyz"
649 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
651 string::size_type pos = 0;
652 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
654 // Add the extension back on
655 mname = changeExtension(mname, getExtension(name));
657 // Prepend a counter to the filename. This is necessary to make
658 // the mangled name unique.
659 static int counter = 0;
660 std::ostringstream s;
661 s << counter++ << mname;
664 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
665 // is longer than about 160 characters. MiKTeX's pdflatex
666 // is even pickier. A maximum length of 100 has been proven to work.
667 // If dir.size() > max length, all bets are off for YAP. We truncate
668 // the filename nevertheless, keeping a minimum of 10 chars.
670 string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
672 // If the mangled file name is too long, hack it to fit.
673 // We know we're guaranteed to have a unique file name because
675 if (mname.size() > max_length) {
676 int const half = (int(max_length) / 2) - 2;
678 mname = mname.substr(0, half) + "___" +
679 mname.substr(mname.size() - half);
683 mangledNames[absFilename()] = mname;
688 bool DocFileName::isZipped() const
690 if (!zipped_valid_) {
691 zipped_ = isZippedFile();
692 zipped_valid_ = true;
698 string const DocFileName::unzippedFilename() const
700 return unzippedFileName(absFilename());
704 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
706 return lhs.absFilename() == rhs.absFilename()
707 && lhs.saveAbsPath() == rhs.saveAbsPath();
711 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
713 return !(lhs == rhs);
716 } // namespace support