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/FileNameList.h"
16 #include "support/debug.h"
17 #include "support/filetools.h"
18 #include "support/lstrings.h"
19 #include "support/lyxlib.h"
20 #include "support/os.h"
21 #include "support/qstring_helpers.h"
30 #include <boost/assert.hpp>
37 #ifdef HAVE_SYS_TYPES_H
38 # include <sys/types.h>
40 #ifdef HAVE_SYS_STAT_H
41 # include <sys/stat.h>
62 /////////////////////////////////////////////////////////////////////
66 /////////////////////////////////////////////////////////////////////
68 struct FileName::Private
72 Private(string const & abs_filename) : fi(toqstr(abs_filename))
74 fi.setCaching(fi.exists() ? true : false);
80 /////////////////////////////////////////////////////////////////////
84 /////////////////////////////////////////////////////////////////////
87 FileName::FileName() : d(new Private)
92 FileName::FileName(string const & abs_filename)
93 : d(abs_filename.empty() ? new Private : new Private(abs_filename))
104 FileName::FileName(FileName const & rhs) : d(new Private)
110 FileName & FileName::operator=(FileName const & rhs)
117 bool FileName::empty() const
119 return d->fi.absoluteFilePath().isEmpty();
123 string FileName::absFilename() const
125 return fromqstr(d->fi.absoluteFilePath());
129 void FileName::set(string const & name)
131 d->fi.setFile(toqstr(name));
132 BOOST_ASSERT(d->fi.isAbsolute());
136 void FileName::erase()
142 bool FileName::copyTo(FileName const & name, bool overwrite) const
145 QFile::remove(name.d->fi.absoluteFilePath());
146 bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
148 lyxerr << "FileName::copyTo(): Could not copy file "
149 << *this << " to " << name << endl;
154 bool FileName::renameTo(FileName const & name) const
156 bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
158 LYXERR0("Could not rename file " << *this << " to " << name);
163 bool FileName::moveTo(FileName const & name) const
165 if (name.exists() && !name.removeFile())
168 bool success = QFile::rename(d->fi.absoluteFilePath(),
169 name.d->fi.absoluteFilePath());
171 LYXERR0("Could not move file " << *this << " to " << name);
176 bool FileName::changePermission(unsigned long int mode) const
179 LYXERR0("File " << *this << " is not writable!");
183 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
184 if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
185 LYXERR0("File " << *this << ": cannot change permission to "
194 string FileName::toFilesystemEncoding() const
196 QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
197 return string(encoded.begin(), encoded.end());
201 FileName FileName::fromFilesystemEncoding(string const & name)
203 QByteArray const encoded(name.c_str(), name.length());
204 return FileName(fromqstr(QFile::decodeName(encoded)));
208 bool FileName::exists() const
210 return d->fi.exists();
214 bool FileName::isSymLink() const
216 return d->fi.isSymLink();
220 bool FileName::isFileEmpty() const
222 return d->fi.size() == 0;
226 bool FileName::isDirectory() const
228 return d->fi.isDir();
232 bool FileName::isReadOnly() const
234 return d->fi.isReadable() && !d->fi.isWritable();
238 bool FileName::isReadableDirectory() const
240 return d->fi.isDir() && d->fi.isReadable();
244 string FileName::onlyFileName() const
246 return support::onlyFilename(absFilename());
250 FileName FileName::onlyPath() const
252 return FileName(support::onlyPath(absFilename()));
256 bool FileName::isReadableFile() const
258 return d->fi.isFile() && d->fi.isReadable();
262 bool FileName::isWritable() const
264 return d->fi.isWritable();
268 bool FileName::isDirWritable() const
270 LYXERR(Debug::FILES, "isDirWriteable: " << *this);
272 FileName const tmpfl(tempName(*this, "lyxwritetest"));
282 FileNameList FileName::dirList(string const & ext) const
284 FileNameList dirlist;
285 if (!isDirectory()) {
286 LYXERR0("Directory '" << *this << "' does not exist!");
290 QDir dir = d->fi.absoluteDir();
295 case '.': filter = "*" + toqstr(ext); break;
296 case '*': filter = toqstr(ext); break;
297 default: filter = "*." + toqstr(ext);
299 dir.setNameFilters(QStringList(filter));
300 LYXERR(Debug::FILES, "filtering on extension "
301 << fromqstr(filter) << " is requested.");
304 QFileInfoList list = dir.entryInfoList();
305 for (int i = 0; i != list.size(); ++i) {
306 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
307 dirlist.push_back(fi);
308 LYXERR(Debug::FILES, "found file " << fi);
315 FileName FileName::tempName(FileName const & dir, string const & mask)
317 return support::tempName(dir, mask);
321 time_t FileName::lastModified() const
323 return d->fi.lastModified().toTime_t();
327 bool FileName::chdir() const
329 return QDir::setCurrent(d->fi.absoluteFilePath());
333 extern unsigned long sum(char const * file);
335 unsigned long FileName::checksum() const
338 LYXERR0("File \"" << absFilename() << "\" does not exist!");
341 // a directory may be passed here so we need to test it. (bug 3622)
343 LYXERR0('"' << absFilename() << "\" is a directory!");
346 if (!lyxerr.debugging(Debug::FILES))
347 return sum(absFilename().c_str());
351 unsigned long r = sum(absFilename().c_str());
352 lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
353 << t.elapsed() << " ms." << endl;
358 bool FileName::removeFile() const
360 bool const success = QFile::remove(d->fi.absoluteFilePath());
361 if (!success && exists())
362 LYXERR0("Could not delete file " << *this);
367 static bool rmdir(QFileInfo const & fi)
369 QDir dir(fi.absoluteFilePath());
370 QFileInfoList list = dir.entryInfoList();
372 for (int i = 0; i != list.size(); ++i) {
373 if (list.at(i).fileName() == ".")
375 if (list.at(i).fileName() == "..")
378 if (list.at(i).isDir()) {
379 LYXERR(Debug::FILES, "Removing dir "
380 << fromqstr(list.at(i).absoluteFilePath()));
381 removed = rmdir(list.at(i));
384 LYXERR(Debug::FILES, "Removing file "
385 << fromqstr(list.at(i).absoluteFilePath()));
386 removed = dir.remove(list.at(i).fileName());
390 LYXERR0("Could not delete "
391 << fromqstr(list.at(i).absoluteFilePath()));
394 QDir parent = fi.absolutePath();
395 success &= parent.rmdir(fi.fileName());
400 bool FileName::destroyDirectory() const
402 bool const success = rmdir(d->fi);
404 LYXERR0("Could not delete " << *this);
410 static int mymkdir(char const * pathname, unsigned long int mode)
412 // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
414 # if MKDIR_TAKES_ONE_ARG
416 return ::mkdir(pathname);
417 // FIXME: "Permissions of created directories are ignored on this system."
420 return ::mkdir(pathname, mode_t(mode));
422 #elif defined(_WIN32)
424 return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
425 // FIXME: "Permissions of created directories are ignored on this system."
427 return ::_mkdir(pathname);
428 // FIXME: "Permissions of created directories are ignored on this system."
430 # error "Don't know how to create a directory on this system."
436 bool FileName::createDirectory(int permission) const
438 BOOST_ASSERT(!empty());
439 return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
443 bool FileName::createPath() const
445 BOOST_ASSERT(!empty());
450 bool success = dir.mkpath(d->fi.absoluteFilePath());
452 LYXERR0("Cannot create path '" << *this << "'!");
457 docstring const FileName::absoluteFilePath() const
459 return qstring_to_ucs4(d->fi.absoluteFilePath());
463 docstring FileName::displayName(int threshold) const
465 return makeDisplayPath(absFilename(), threshold);
469 docstring FileName::fileContents(string const & encoding) const
471 if (!isReadableFile()) {
472 LYXERR0("File '" << *this << "' is not redable!");
476 QFile file(d->fi.absoluteFilePath());
477 if (!file.open(QIODevice::ReadOnly)) {
478 LYXERR0("File '" << *this
479 << "' could not be opened in read only mode!");
482 QByteArray contents = file.readAll();
485 if (contents.isEmpty()) {
486 LYXERR(Debug::FILES, "File '" << *this
487 << "' is either empty or some error happened while reading it.");
492 if (encoding.empty() || encoding == "UTF-8")
493 s = QString::fromUtf8(contents.data());
494 else if (encoding == "ascii")
495 s = QString::fromAscii(contents.data());
496 else if (encoding == "local8bit")
497 s = QString::fromLocal8Bit(contents.data());
498 else if (encoding == "latin1")
499 s = QString::fromLatin1(contents.data());
501 return qstring_to_ucs4(s);
505 void FileName::changeExtension(string const & extension)
507 // FIXME: use Qt native methods...
508 string const oldname = absFilename();
509 string::size_type const last_slash = oldname.rfind('/');
510 string::size_type last_dot = oldname.rfind('.');
511 if (last_dot < last_slash && last_slash != string::npos)
512 last_dot = string::npos;
515 // Make sure the extension starts with a dot
516 if (!extension.empty() && extension[0] != '.')
517 ext= '.' + extension;
521 set(oldname.substr(0, last_dot) + ext);
525 string FileName::guessFormatFromContents() const
527 // the different filetypes and what they contain in one of the first lines
528 // (dots are any characters). (Herbert 20020131)
531 // EPS %!PS-Adobe-3.0 EPSF...
538 // PBM P1... or P4 (B/W)
539 // PGM P2... or P5 (Grayscale)
540 // PPM P3... or P6 (color)
541 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
542 // SGI \001\332... (decimal 474)
544 // TIFF II... or MM...
546 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
547 // ...static char *...
548 // XWD \000\000\000\151 (0x00006900) decimal 105
550 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
551 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
552 // Z \037\235 UNIX compress
555 if (empty() || !isReadableFile())
558 ifstream ifs(toFilesystemEncoding().c_str());
560 // Couldn't open file...
564 static string const gzipStamp = "\037\213";
567 static string const zipStamp = "PK";
570 static string const compressStamp = "\037\235";
572 // Maximum strings to read
573 int const max_count = 50;
578 bool firstLine = true;
579 while ((count++ < max_count) && format.empty()) {
581 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
582 << "\tFile type not recognised before EOF!");
587 string const stamp = str.substr(0, 2);
588 if (firstLine && str.size() >= 2) {
589 // at first we check for a zipped file, because this
590 // information is saved in the first bytes of the file!
591 // also some graphic formats which save the information
592 // in the first line, too.
593 if (prefixIs(str, gzipStamp)) {
596 } else if (stamp == zipStamp) {
599 } else if (stamp == compressStamp) {
603 } else if (stamp == "BM") {
606 } else if (stamp == "\001\332") {
610 // Don't need to use str.at(0), str.at(1) because
611 // we already know that str.size() >= 2
612 } else if (str[0] == 'P') {
628 } else if ((stamp == "II") || (stamp == "MM")) {
631 } else if (prefixIs(str,"%TGIF")) {
634 } else if (prefixIs(str,"#FIG")) {
637 } else if (prefixIs(str,"GIF")) {
640 } else if (str.size() > 3) {
641 int const c = ((str[0] << 24) & (str[1] << 16) &
642 (str[2] << 8) & str[3]);
653 else if (contains(str,"EPSF"))
654 // dummy, if we have wrong file description like
655 // %!PS-Adobe-2.0EPSF"
658 else if (contains(str, "Grace"))
661 else if (contains(str, "JFIF"))
664 else if (contains(str, "%PDF"))
667 else if (contains(str, "PNG"))
670 else if (contains(str, "%!PS-Adobe")) {
673 if (contains(str,"EPSF"))
679 else if (contains(str, "_bits[]"))
682 else if (contains(str, "XPM") || contains(str, "static char *"))
685 else if (contains(str, "BITPIX"))
689 if (!format.empty()) {
690 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
694 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
695 << "\tCouldn't find a known format!");
700 bool FileName::isZippedFile() const
702 string const type = guessFormatFromContents();
703 return contains("gzip zip compress", type) && !type.empty();
707 docstring const FileName::relPath(string const & path) const
710 return makeRelPath(absoluteFilePath(), from_utf8(path));
714 bool operator==(FileName const & lhs, FileName const & rhs)
716 return lhs.absFilename() == rhs.absFilename();
720 bool operator!=(FileName const & lhs, FileName const & rhs)
722 return lhs.absFilename() != rhs.absFilename();
726 bool operator<(FileName const & lhs, FileName const & rhs)
728 return lhs.absFilename() < rhs.absFilename();
732 bool operator>(FileName const & lhs, FileName const & rhs)
734 return lhs.absFilename() > rhs.absFilename();
738 ostream & operator<<(ostream & os, FileName const & filename)
740 return os << filename.absFilename();
744 /////////////////////////////////////////////////////////////////////
748 /////////////////////////////////////////////////////////////////////
751 DocFileName::DocFileName()
752 : save_abs_path_(true)
756 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
757 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
761 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
762 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
766 void DocFileName::set(string const & name, string const & buffer_path)
768 save_abs_path_ = absolutePath(name);
769 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
770 zipped_valid_ = false;
774 void DocFileName::erase()
777 zipped_valid_ = false;
781 string DocFileName::relFilename(string const & path) const
784 return to_utf8(relPath(path));
788 string DocFileName::outputFilename(string const & path) const
790 return save_abs_path_ ? absFilename() : relFilename(path);
794 string DocFileName::mangledFilename(string const & dir) const
796 // We need to make sure that every DocFileName instance for a given
797 // filename returns the same mangled name.
798 typedef map<string, string> MangledMap;
799 static MangledMap mangledNames;
800 MangledMap::const_iterator const it = mangledNames.find(absFilename());
801 if (it != mangledNames.end())
804 string const name = absFilename();
806 string mname = os::internal_path(name);
807 // Remove the extension.
808 mname = support::changeExtension(name, string());
809 // The mangled name must be a valid LaTeX name.
810 // The list of characters to keep is probably over-restrictive,
811 // but it is not really a problem.
812 // Apart from non-ASCII characters, at least the following characters
813 // are forbidden: '/', '.', ' ', and ':'.
814 // On windows it is not possible to create files with '<', '>' or '?'
816 static string const keep = "abcdefghijklmnopqrstuvwxyz"
817 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
819 string::size_type pos = 0;
820 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
822 // Add the extension back on
823 mname = support::changeExtension(mname, getExtension(name));
825 // Prepend a counter to the filename. This is necessary to make
826 // the mangled name unique.
827 static int counter = 0;
829 s << counter++ << mname;
832 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
833 // is longer than about 160 characters. MiKTeX's pdflatex
834 // is even pickier. A maximum length of 100 has been proven to work.
835 // If dir.size() > max length, all bets are off for YAP. We truncate
836 // the filename nevertheless, keeping a minimum of 10 chars.
838 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
840 // If the mangled file name is too long, hack it to fit.
841 // We know we're guaranteed to have a unique file name because
843 if (mname.size() > max_length) {
844 int const half = (int(max_length) / 2) - 2;
846 mname = mname.substr(0, half) + "___" +
847 mname.substr(mname.size() - half);
851 mangledNames[absFilename()] = mname;
856 bool DocFileName::isZipped() const
858 if (!zipped_valid_) {
859 zipped_ = isZippedFile();
860 zipped_valid_ = true;
866 string DocFileName::unzippedFilename() const
868 return unzippedFileName(absFilename());
872 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
874 return lhs.absFilename() == rhs.absFilename()
875 && lhs.saveAbsPath() == rhs.saveAbsPath();
879 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
881 return !(lhs == rhs);
884 } // namespace support