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>
39 using std::ostringstream;
45 #include <boost/filesystem/config.hpp>
46 #include <boost/detail/workaround.hpp>
47 #include <boost/throw_exception.hpp>
49 #ifdef HAVE_SYS_TYPES_H
50 # include <sys/types.h>
52 #ifdef HAVE_SYS_STAT_H
53 # include <sys/stat.h>
59 // BOOST_POSIX or BOOST_WINDOWS specify which API to use.
60 # if !defined( BOOST_WINDOWS ) && !defined( BOOST_POSIX )
61 # if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__)
62 # define BOOST_WINDOWS
68 #if defined (BOOST_WINDOWS)
69 # define WIN32_LEAN_AND_MEAN
76 static bool copy_file(std::string const & source, std::string const & target, bool noclobber)
80 int const infile = ::open(source.c_str(), O_RDONLY);
84 struct stat source_stat;
85 int const ret = ::fstat(infile, &source_stat);
91 int const flags = O_WRONLY | O_CREAT | (noclobber ? O_EXCL : O_TRUNC);
93 int const outfile = ::open(target.c_str(), flags, source_stat.st_mode);
100 std::size_t const buf_sz = 32768;
106 in = ::read(infile, buf, buf_sz);
109 } else if (in == 0) {
112 out = ::write(outfile, buf, in);
124 if (in == -1 || out == -1)
129 if (::CopyFile(source.c_str(), target.c_str(), noclobber) == 0) {
130 // CopyFile is probably not setting errno so this is most
143 /////////////////////////////////////////////////////////////////////
147 /////////////////////////////////////////////////////////////////////
150 FileName::FileName(string const & abs_filename)
151 : name_(abs_filename)
153 BOOST_ASSERT(empty() || absolutePath(name_));
155 BOOST_ASSERT(!contains(name_, '\\'));
160 void FileName::set(string const & name)
163 BOOST_ASSERT(absolutePath(name_));
165 BOOST_ASSERT(!contains(name_, '\\'));
170 void FileName::erase()
176 bool FileName::copyTo(FileName const & name, bool noclobber) const
179 copy_file(toFilesystemEncoding(), name.toFilesystemEncoding(), noclobber);
188 string FileName::toFilesystemEncoding() const
190 QByteArray const encoded = QFile::encodeName(toqstr(name_));
191 return string(encoded.begin(), encoded.end());
195 FileName FileName::fromFilesystemEncoding(string const & name)
197 QByteArray const encoded(name.c_str(), name.length());
198 return FileName(fromqstr(QFile::decodeName(encoded)));
202 bool FileName::exists() const
204 return QFileInfo(toqstr(name_)).exists();
208 bool FileName::isSymLink() const
210 return QFileInfo(toqstr(name_)).isSymLink();
214 bool FileName::isFileEmpty() const
216 return QFileInfo(toqstr(name_)).size() == 0;
220 bool FileName::isDirectory() const
222 return QFileInfo(toqstr(name_)).isDir();
226 bool FileName::isReadOnly() const
228 QFileInfo const fi(toqstr(name_));
229 return fi.isReadable() && !fi.isWritable();
233 bool FileName::isReadableDirectory() const
235 QFileInfo const fi(toqstr(name_));
236 return fi.isDir() && fi.isReadable();
240 std::string FileName::onlyFileName() const
242 return support::onlyFilename(absFilename());
246 FileName FileName::onlyPath() const
248 return FileName(support::onlyPath(absFilename()));
252 bool FileName::isReadableFile() const
254 QFileInfo const fi(toqstr(name_));
255 return fi.isFile() && fi.isReadable();
259 bool FileName::isWritable() const
261 QFileInfo const fi(toqstr(name_));
262 return fi.isWritable();
266 bool FileName::isDirWritable() const
268 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
270 FileName const tmpfl(tempName(*this, "lyxwritetest"));
280 FileName FileName::tempName(FileName const & dir, std::string const & mask)
282 return support::tempName(dir, mask);
286 std::time_t FileName::lastModified() const
288 return QFileInfo(toqstr(name_)).lastModified().toTime_t();
292 static bool rmdir(QFileInfo const & fi)
294 QDir dir(fi.absoluteFilePath());
295 QFileInfoList list = dir.entryInfoList();
296 for (int i = 0; i < list.size(); ++i) {
297 if (list.at(i).fileName() == ".")
299 if (list.at(i).fileName() == "..")
301 if (list.at(i).isDir()) {
302 LYXERR(Debug::FILES, "Erasing dir "
303 << fromqstr(list.at(i).absoluteFilePath()) << endl);
304 if (!rmdir(list.at(i)))
308 LYXERR(Debug::FILES, "Erasing file "
309 << fromqstr(list.at(i).absoluteFilePath()) << endl);
310 dir.remove(list.at(i).fileName());
313 QDir parent = fi.absolutePath();
314 return parent.rmdir(fi.fileName());
318 bool FileName::destroyDirectory() const
320 bool const success = rmdir(QFileInfo(toqstr(name_)));
322 lyxerr << "Could not delete " << *this << "." << endl;
328 bool FileName::createDirectory(int permission) const
330 BOOST_ASSERT(!empty());
331 return mkdir(*this, permission) == 0;
335 docstring FileName::displayName(int threshold) const
337 return makeDisplayPath(absFilename(), threshold);
341 string FileName::fileContents() const
344 string const encodedname = toFilesystemEncoding();
345 ifstream ifs(encodedname.c_str());
353 lyxerr << "LyX was not able to read file '" << *this << '\'' << std::endl;
358 string FileName::guessFormatFromContents() const
360 // the different filetypes and what they contain in one of the first lines
361 // (dots are any characters). (Herbert 20020131)
364 // EPS %!PS-Adobe-3.0 EPSF...
371 // PBM P1... or P4 (B/W)
372 // PGM P2... or P5 (Grayscale)
373 // PPM P3... or P6 (color)
374 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
375 // SGI \001\332... (decimal 474)
377 // TIFF II... or MM...
379 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
380 // ...static char *...
381 // XWD \000\000\000\151 (0x00006900) decimal 105
383 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
384 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
385 // Z \037\235 UNIX compress
388 if (empty() || !isReadableFile())
391 ifstream ifs(toFilesystemEncoding().c_str());
393 // Couldn't open file...
397 static string const gzipStamp = "\037\213";
400 static string const zipStamp = "PK";
403 static string const compressStamp = "\037\235";
405 // Maximum strings to read
406 int const max_count = 50;
411 bool firstLine = true;
412 while ((count++ < max_count) && format.empty()) {
414 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
415 << "\tFile type not recognised before EOF!");
420 string const stamp = str.substr(0, 2);
421 if (firstLine && str.size() >= 2) {
422 // at first we check for a zipped file, because this
423 // information is saved in the first bytes of the file!
424 // also some graphic formats which save the information
425 // in the first line, too.
426 if (prefixIs(str, gzipStamp)) {
429 } else if (stamp == zipStamp) {
432 } else if (stamp == compressStamp) {
436 } else if (stamp == "BM") {
439 } else if (stamp == "\001\332") {
443 // Don't need to use str.at(0), str.at(1) because
444 // we already know that str.size() >= 2
445 } else if (str[0] == 'P') {
461 } else if ((stamp == "II") || (stamp == "MM")) {
464 } else if (prefixIs(str,"%TGIF")) {
467 } else if (prefixIs(str,"#FIG")) {
470 } else if (prefixIs(str,"GIF")) {
473 } else if (str.size() > 3) {
474 int const c = ((str[0] << 24) & (str[1] << 16) &
475 (str[2] << 8) & str[3]);
486 else if (contains(str,"EPSF"))
487 // dummy, if we have wrong file description like
488 // %!PS-Adobe-2.0EPSF"
491 else if (contains(str, "Grace"))
494 else if (contains(str, "JFIF"))
497 else if (contains(str, "%PDF"))
500 else if (contains(str, "PNG"))
503 else if (contains(str, "%!PS-Adobe")) {
506 if (contains(str,"EPSF"))
512 else if (contains(str, "_bits[]"))
515 else if (contains(str, "XPM") || contains(str, "static char *"))
518 else if (contains(str, "BITPIX"))
522 if (!format.empty()) {
523 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
527 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
528 << "\tCouldn't find a known format!");
533 bool FileName::isZippedFile() const
535 string const type = guessFormatFromContents();
536 return contains("gzip zip compress", type) && !type.empty();
540 bool operator==(FileName const & lhs, FileName const & rhs)
542 return lhs.absFilename() == rhs.absFilename();
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 std::ostream & operator<<(std::ostream & os, FileName const & filename)
566 return os << filename.absFilename();
570 /////////////////////////////////////////////////////////////////////
574 /////////////////////////////////////////////////////////////////////
577 DocFileName::DocFileName()
578 : save_abs_path_(true)
582 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
583 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
587 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
588 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
592 void DocFileName::set(string const & name, string const & buffer_path)
594 save_abs_path_ = absolutePath(name);
595 name_ = save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename();
596 zipped_valid_ = false;
600 void DocFileName::erase()
603 zipped_valid_ = false;
607 string const DocFileName::relFilename(string const & path) const
610 return to_utf8(makeRelPath(from_utf8(name_), from_utf8(path)));
614 string const DocFileName::outputFilename(string const & path) const
617 return save_abs_path_ ? name_ : to_utf8(makeRelPath(from_utf8(name_), from_utf8(path)));
621 string const DocFileName::mangledFilename(std::string const & dir) const
623 // We need to make sure that every DocFileName instance for a given
624 // filename returns the same mangled name.
625 typedef map<string, string> MangledMap;
626 static MangledMap mangledNames;
627 MangledMap::const_iterator const it = mangledNames.find(name_);
628 if (it != mangledNames.end())
632 string mname = os::internal_path(name_);
633 // Remove the extension.
634 mname = changeExtension(name_, string());
635 // The mangled name must be a valid LaTeX name.
636 // The list of characters to keep is probably over-restrictive,
637 // but it is not really a problem.
638 // Apart from non-ASCII characters, at least the following characters
639 // are forbidden: '/', '.', ' ', and ':'.
640 // On windows it is not possible to create files with '<', '>' or '?'
642 static string const keep = "abcdefghijklmnopqrstuvwxyz"
643 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
645 string::size_type pos = 0;
646 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
648 // Add the extension back on
649 mname = changeExtension(mname, getExtension(name_));
651 // Prepend a counter to the filename. This is necessary to make
652 // the mangled name unique.
653 static int counter = 0;
654 std::ostringstream s;
655 s << counter++ << mname;
658 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
659 // is longer than about 160 characters. MiKTeX's pdflatex
660 // is even pickier. A maximum length of 100 has been proven to work.
661 // If dir.size() > max length, all bets are off for YAP. We truncate
662 // the filename nevertheless, keeping a minimum of 10 chars.
664 string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
666 // If the mangled file name is too long, hack it to fit.
667 // We know we're guaranteed to have a unique file name because
669 if (mname.size() > max_length) {
670 int const half = (int(max_length) / 2) - 2;
672 mname = mname.substr(0, half) + "___" +
673 mname.substr(mname.size() - half);
677 mangledNames[name_] = mname;
682 bool DocFileName::isZipped() const
684 if (!zipped_valid_) {
685 zipped_ = isZippedFile();
686 zipped_valid_ = true;
692 string const DocFileName::unzippedFilename() const
694 return unzippedFileName(name_);
698 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
700 return lhs.absFilename() == rhs.absFilename()
701 && lhs.saveAbsPath() == rhs.saveAbsPath();
705 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
707 return !(lhs == rhs);
710 } // namespace support