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"
25 #include <boost/filesystem/exception.hpp>
26 #include <boost/filesystem/operations.hpp>
37 using std::ostringstream;
40 namespace fs = boost::filesystem;
44 #include <boost/filesystem/config.hpp>
45 #include <boost/detail/workaround.hpp>
46 #include <boost/throw_exception.hpp>
48 #ifdef HAVE_SYS_TYPES_H
49 # include <sys/types.h>
51 #ifdef HAVE_SYS_STAT_H
52 # include <sys/stat.h>
58 // BOOST_POSIX or BOOST_WINDOWS specify which API to use.
59 # if !defined( BOOST_WINDOWS ) && !defined( BOOST_POSIX )
60 # if defined(_WIN32) || defined(__WIN32__) || defined(WIN32) || defined(__CYGWIN__)
61 # define BOOST_WINDOWS
67 #if defined (BOOST_WINDOWS)
68 # define WIN32_LEAN_AND_MEAN
75 static bool copy_file(std::string const & source, std::string const & target, bool noclobber)
79 int const infile = ::open(source.c_str(), O_RDONLY);
83 struct stat source_stat;
84 int const ret = ::fstat(infile, &source_stat);
90 int const flags = O_WRONLY | O_CREAT | (noclobber ? O_EXCL : O_TRUNC);
92 int const outfile = ::open(target.c_str(), flags, source_stat.st_mode);
99 std::size_t const buf_sz = 32768;
105 in = ::read(infile, buf, buf_sz);
108 } else if (in == 0) {
111 out = ::write(outfile, buf, in);
123 if (in == -1 || out == -1)
128 if (::CopyFile(source.c_str(), target.c_str(), noclobber) == 0) {
129 // CopyFile is probably not setting errno so this is most
142 /////////////////////////////////////////////////////////////////////
146 /////////////////////////////////////////////////////////////////////
149 FileName::FileName(string const & abs_filename)
150 : name_(abs_filename)
152 BOOST_ASSERT(empty() || absolutePath(name_));
154 BOOST_ASSERT(!contains(name_, '\\'));
159 void FileName::set(string const & name)
162 BOOST_ASSERT(absolutePath(name_));
164 BOOST_ASSERT(!contains(name_, '\\'));
169 void FileName::erase()
175 bool FileName::copyTo(FileName const & name, bool noclobber) const
178 copy_file(toFilesystemEncoding(), name.toFilesystemEncoding(), noclobber);
187 string FileName::toFilesystemEncoding() const
189 QByteArray const encoded = QFile::encodeName(toqstr(name_));
190 return string(encoded.begin(), encoded.end());
194 FileName FileName::fromFilesystemEncoding(string const & name)
196 QByteArray const encoded(name.c_str(), name.length());
197 return FileName(fromqstr(QFile::decodeName(encoded)));
201 bool FileName::exists() const
203 return QFileInfo(toqstr(name_)).exists();
207 bool FileName::isSymLink() const
209 return QFileInfo(toqstr(name_)).isSymLink();
213 bool FileName::isFileEmpty() const
215 return QFileInfo(toqstr(name_)).size() == 0;
219 bool FileName::isDirectory() const
221 return QFileInfo(toqstr(name_)).isDir();
225 bool FileName::isReadOnly() const
227 QFileInfo const fi(toqstr(name_));
228 return fi.isReadable() && !fi.isWritable();
232 bool FileName::isReadableDirectory() const
234 QFileInfo const fi(toqstr(name_));
235 return fi.isDir() && fi.isReadable();
239 std::string FileName::onlyFileName() const
241 return support::onlyFilename(absFilename());
245 FileName FileName::onlyPath() const
247 return FileName(support::onlyPath(absFilename()));
251 bool FileName::isReadableFile() const
253 QFileInfo const fi(toqstr(name_));
254 return fi.isFile() && fi.isReadable();
258 bool FileName::isWritable() const
260 QFileInfo const fi(toqstr(name_));
261 return fi.isWritable();
265 bool FileName::isDirWritable() const
267 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
269 FileName const tmpfl(tempName(*this, "lyxwritetest"));
279 FileName FileName::tempName(FileName const & dir, std::string const & mask)
281 return support::tempName(dir, mask);
285 std::time_t FileName::lastModified() const
287 return fs::last_write_time(toFilesystemEncoding());
291 bool FileName::destroyDirectory() const
294 return fs::remove_all(toFilesystemEncoding()) > 0;
295 } catch (fs::filesystem_error const & fe){
296 lyxerr << "Could not delete " << *this << ". (" << fe.what() << ")"
303 bool FileName::createDirectory(int permission) const
305 BOOST_ASSERT(!empty());
306 return mkdir(*this, permission) == 0;
310 docstring FileName::displayName(int threshold) const
312 return makeDisplayPath(absFilename(), threshold);
316 string FileName::fileContents() const
319 string const encodedname = toFilesystemEncoding();
320 ifstream ifs(encodedname.c_str());
328 lyxerr << "LyX was not able to read file '" << *this << '\'' << std::endl;
333 string FileName::guessFormatFromContents() const
335 // the different filetypes and what they contain in one of the first lines
336 // (dots are any characters). (Herbert 20020131)
339 // EPS %!PS-Adobe-3.0 EPSF...
346 // PBM P1... or P4 (B/W)
347 // PGM P2... or P5 (Grayscale)
348 // PPM P3... or P6 (color)
349 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
350 // SGI \001\332... (decimal 474)
352 // TIFF II... or MM...
354 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
355 // ...static char *...
356 // XWD \000\000\000\151 (0x00006900) decimal 105
358 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
359 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
360 // Z \037\235 UNIX compress
363 if (empty() || !isReadableFile())
366 ifstream ifs(toFilesystemEncoding().c_str());
368 // Couldn't open file...
372 static string const gzipStamp = "\037\213";
375 static string const zipStamp = "PK";
378 static string const compressStamp = "\037\235";
380 // Maximum strings to read
381 int const max_count = 50;
386 bool firstLine = true;
387 while ((count++ < max_count) && format.empty()) {
389 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
390 << "\tFile type not recognised before EOF!");
395 string const stamp = str.substr(0, 2);
396 if (firstLine && str.size() >= 2) {
397 // at first we check for a zipped file, because this
398 // information is saved in the first bytes of the file!
399 // also some graphic formats which save the information
400 // in the first line, too.
401 if (prefixIs(str, gzipStamp)) {
404 } else if (stamp == zipStamp) {
407 } else if (stamp == compressStamp) {
411 } else if (stamp == "BM") {
414 } else if (stamp == "\001\332") {
418 // Don't need to use str.at(0), str.at(1) because
419 // we already know that str.size() >= 2
420 } else if (str[0] == 'P') {
436 } else if ((stamp == "II") || (stamp == "MM")) {
439 } else if (prefixIs(str,"%TGIF")) {
442 } else if (prefixIs(str,"#FIG")) {
445 } else if (prefixIs(str,"GIF")) {
448 } else if (str.size() > 3) {
449 int const c = ((str[0] << 24) & (str[1] << 16) &
450 (str[2] << 8) & str[3]);
461 else if (contains(str,"EPSF"))
462 // dummy, if we have wrong file description like
463 // %!PS-Adobe-2.0EPSF"
466 else if (contains(str, "Grace"))
469 else if (contains(str, "JFIF"))
472 else if (contains(str, "%PDF"))
475 else if (contains(str, "PNG"))
478 else if (contains(str, "%!PS-Adobe")) {
481 if (contains(str,"EPSF"))
487 else if (contains(str, "_bits[]"))
490 else if (contains(str, "XPM") || contains(str, "static char *"))
493 else if (contains(str, "BITPIX"))
497 if (!format.empty()) {
498 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
502 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
503 << "\tCouldn't find a known format!");
508 bool FileName::isZippedFile() const
510 string const type = guessFormatFromContents();
511 return contains("gzip zip compress", type) && !type.empty();
515 bool operator==(FileName const & lhs, FileName const & rhs)
517 return lhs.absFilename() == rhs.absFilename();
521 bool operator!=(FileName const & lhs, FileName const & rhs)
523 return lhs.absFilename() != rhs.absFilename();
527 bool operator<(FileName const & lhs, FileName const & rhs)
529 return lhs.absFilename() < rhs.absFilename();
533 bool operator>(FileName const & lhs, FileName const & rhs)
535 return lhs.absFilename() > rhs.absFilename();
539 std::ostream & operator<<(std::ostream & os, FileName const & filename)
541 return os << filename.absFilename();
545 /////////////////////////////////////////////////////////////////////
549 /////////////////////////////////////////////////////////////////////
552 DocFileName::DocFileName()
553 : save_abs_path_(true)
557 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
558 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
562 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
563 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
567 void DocFileName::set(string const & name, string const & buffer_path)
569 save_abs_path_ = absolutePath(name);
570 name_ = save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename();
571 zipped_valid_ = false;
575 void DocFileName::erase()
578 zipped_valid_ = false;
582 string const DocFileName::relFilename(string const & path) const
585 return to_utf8(makeRelPath(from_utf8(name_), from_utf8(path)));
589 string const DocFileName::outputFilename(string const & path) const
592 return save_abs_path_ ? name_ : to_utf8(makeRelPath(from_utf8(name_), from_utf8(path)));
596 string const DocFileName::mangledFilename(std::string const & dir) const
598 // We need to make sure that every DocFileName instance for a given
599 // filename returns the same mangled name.
600 typedef map<string, string> MangledMap;
601 static MangledMap mangledNames;
602 MangledMap::const_iterator const it = mangledNames.find(name_);
603 if (it != mangledNames.end())
607 string mname = os::internal_path(name_);
608 // Remove the extension.
609 mname = changeExtension(name_, string());
610 // The mangled name must be a valid LaTeX name.
611 // The list of characters to keep is probably over-restrictive,
612 // but it is not really a problem.
613 // Apart from non-ASCII characters, at least the following characters
614 // are forbidden: '/', '.', ' ', and ':'.
615 // On windows it is not possible to create files with '<', '>' or '?'
617 static string const keep = "abcdefghijklmnopqrstuvwxyz"
618 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
620 string::size_type pos = 0;
621 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
623 // Add the extension back on
624 mname = changeExtension(mname, getExtension(name_));
626 // Prepend a counter to the filename. This is necessary to make
627 // the mangled name unique.
628 static int counter = 0;
629 std::ostringstream s;
630 s << counter++ << mname;
633 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
634 // is longer than about 160 characters. MiKTeX's pdflatex
635 // is even pickier. A maximum length of 100 has been proven to work.
636 // If dir.size() > max length, all bets are off for YAP. We truncate
637 // the filename nevertheless, keeping a minimum of 10 chars.
639 string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
641 // If the mangled file name is too long, hack it to fit.
642 // We know we're guaranteed to have a unique file name because
644 if (mname.size() > max_length) {
645 int const half = (int(max_length) / 2) - 2;
647 mname = mname.substr(0, half) + "___" +
648 mname.substr(mname.size() - half);
652 mangledNames[name_] = mname;
657 bool DocFileName::isZipped() const
659 if (!zipped_valid_) {
660 zipped_ = isZippedFile();
661 zipped_valid_ = true;
667 string const DocFileName::unzippedFilename() const
669 return unzippedFileName(name_);
673 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
675 return lhs.absFilename() == rhs.absFilename()
676 && lhs.saveAbsPath() == rhs.saveAbsPath();
680 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
682 return !(lhs == rhs);
685 } // namespace support