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 // adapted from zlib-1.2.3/contrib/minizip/miniunz.c
444 static int makedir(char * newdir, unsigned long int mode)
448 int len = (int)strlen(newdir);
453 buffer = (char*)malloc(len+1);
454 strcpy(buffer,newdir);
456 if (buffer[len-1] == '/')
457 buffer[len-1] = '\0';
458 if (mymkdir(buffer, mode) == 0) {
467 while(*p && *p != '\\' && *p != '/')
471 if (mymkdir(buffer, mode) != 0) {
484 bool FileName::createPath() const
486 BOOST_ASSERT(!empty());
491 bool success = dir.mkpath(d->fi.absoluteFilePath());
493 LYXERR0("Cannot create path '" << *this << "'!");
498 docstring const FileName::absoluteFilePath() const
500 return qstring_to_ucs4(d->fi.absoluteFilePath());
504 docstring FileName::displayName(int threshold) const
506 return makeDisplayPath(absFilename(), threshold);
510 docstring FileName::fileContents(string const & encoding) const
512 if (!isReadableFile()) {
513 LYXERR0("File '" << *this << "' is not redable!");
517 QFile file(d->fi.absoluteFilePath());
518 if (!file.open(QIODevice::ReadOnly)) {
519 LYXERR0("File '" << *this
520 << "' could not be opened in read only mode!");
523 QByteArray contents = file.readAll();
526 if (contents.isEmpty()) {
527 LYXERR(Debug::FILES, "File '" << *this
528 << "' is either empty or some error happened while reading it.");
533 if (encoding.empty() || encoding == "UTF-8")
534 s = QString::fromUtf8(contents.data());
535 else if (encoding == "ascii")
536 s = QString::fromAscii(contents.data());
537 else if (encoding == "local8bit")
538 s = QString::fromLocal8Bit(contents.data());
539 else if (encoding == "latin1")
540 s = QString::fromLatin1(contents.data());
542 return qstring_to_ucs4(s);
546 void FileName::changeExtension(string const & extension)
548 // FIXME: use Qt native methods...
549 string const oldname = absFilename();
550 string::size_type const last_slash = oldname.rfind('/');
551 string::size_type last_dot = oldname.rfind('.');
552 if (last_dot < last_slash && last_slash != string::npos)
553 last_dot = string::npos;
556 // Make sure the extension starts with a dot
557 if (!extension.empty() && extension[0] != '.')
558 ext= '.' + extension;
562 set(oldname.substr(0, last_dot) + ext);
566 string FileName::guessFormatFromContents() const
568 // the different filetypes and what they contain in one of the first lines
569 // (dots are any characters). (Herbert 20020131)
572 // EPS %!PS-Adobe-3.0 EPSF...
579 // PBM P1... or P4 (B/W)
580 // PGM P2... or P5 (Grayscale)
581 // PPM P3... or P6 (color)
582 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
583 // SGI \001\332... (decimal 474)
585 // TIFF II... or MM...
587 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
588 // ...static char *...
589 // XWD \000\000\000\151 (0x00006900) decimal 105
591 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
592 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
593 // Z \037\235 UNIX compress
596 if (empty() || !isReadableFile())
599 ifstream ifs(toFilesystemEncoding().c_str());
601 // Couldn't open file...
605 static string const gzipStamp = "\037\213";
608 static string const zipStamp = "PK";
611 static string const compressStamp = "\037\235";
613 // Maximum strings to read
614 int const max_count = 50;
619 bool firstLine = true;
620 while ((count++ < max_count) && format.empty()) {
622 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
623 << "\tFile type not recognised before EOF!");
628 string const stamp = str.substr(0, 2);
629 if (firstLine && str.size() >= 2) {
630 // at first we check for a zipped file, because this
631 // information is saved in the first bytes of the file!
632 // also some graphic formats which save the information
633 // in the first line, too.
634 if (prefixIs(str, gzipStamp)) {
637 } else if (stamp == zipStamp) {
640 } else if (stamp == compressStamp) {
644 } else if (stamp == "BM") {
647 } else if (stamp == "\001\332") {
651 // Don't need to use str.at(0), str.at(1) because
652 // we already know that str.size() >= 2
653 } else if (str[0] == 'P') {
669 } else if ((stamp == "II") || (stamp == "MM")) {
672 } else if (prefixIs(str,"%TGIF")) {
675 } else if (prefixIs(str,"#FIG")) {
678 } else if (prefixIs(str,"GIF")) {
681 } else if (str.size() > 3) {
682 int const c = ((str[0] << 24) & (str[1] << 16) &
683 (str[2] << 8) & str[3]);
694 else if (contains(str,"EPSF"))
695 // dummy, if we have wrong file description like
696 // %!PS-Adobe-2.0EPSF"
699 else if (contains(str, "Grace"))
702 else if (contains(str, "JFIF"))
705 else if (contains(str, "%PDF"))
708 else if (contains(str, "PNG"))
711 else if (contains(str, "%!PS-Adobe")) {
714 if (contains(str,"EPSF"))
720 else if (contains(str, "_bits[]"))
723 else if (contains(str, "XPM") || contains(str, "static char *"))
726 else if (contains(str, "BITPIX"))
730 if (!format.empty()) {
731 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
735 LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
736 << "\tCouldn't find a known format!");
741 bool FileName::isZippedFile() const
743 string const type = guessFormatFromContents();
744 return contains("gzip zip compress", type) && !type.empty();
748 docstring const FileName::relPath(string const & path) const
751 return makeRelPath(absoluteFilePath(), from_utf8(path));
755 bool operator==(FileName const & lhs, FileName const & rhs)
757 return lhs.absFilename() == rhs.absFilename();
761 bool operator!=(FileName const & lhs, FileName const & rhs)
763 return lhs.absFilename() != rhs.absFilename();
767 bool operator<(FileName const & lhs, FileName const & rhs)
769 return lhs.absFilename() < rhs.absFilename();
773 bool operator>(FileName const & lhs, FileName const & rhs)
775 return lhs.absFilename() > rhs.absFilename();
779 ostream & operator<<(ostream & os, FileName const & filename)
781 return os << filename.absFilename();
785 /////////////////////////////////////////////////////////////////////
789 /////////////////////////////////////////////////////////////////////
792 DocFileName::DocFileName()
793 : save_abs_path_(true)
797 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
798 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
802 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
803 : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
807 void DocFileName::set(string const & name, string const & buffer_path)
809 save_abs_path_ = absolutePath(name);
810 FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
811 zipped_valid_ = false;
815 void DocFileName::erase()
818 zipped_valid_ = false;
822 string DocFileName::relFilename(string const & path) const
825 return to_utf8(relPath(path));
829 string DocFileName::outputFilename(string const & path) const
831 return save_abs_path_ ? absFilename() : relFilename(path);
835 string DocFileName::mangledFilename(string const & dir) const
837 // We need to make sure that every DocFileName instance for a given
838 // filename returns the same mangled name.
839 typedef map<string, string> MangledMap;
840 static MangledMap mangledNames;
841 MangledMap::const_iterator const it = mangledNames.find(absFilename());
842 if (it != mangledNames.end())
845 string const name = absFilename();
847 string mname = os::internal_path(name);
848 // Remove the extension.
849 mname = support::changeExtension(name, string());
850 // The mangled name must be a valid LaTeX name.
851 // The list of characters to keep is probably over-restrictive,
852 // but it is not really a problem.
853 // Apart from non-ASCII characters, at least the following characters
854 // are forbidden: '/', '.', ' ', and ':'.
855 // On windows it is not possible to create files with '<', '>' or '?'
857 static string const keep = "abcdefghijklmnopqrstuvwxyz"
858 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
860 string::size_type pos = 0;
861 while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
863 // Add the extension back on
864 mname = support::changeExtension(mname, getExtension(name));
866 // Prepend a counter to the filename. This is necessary to make
867 // the mangled name unique.
868 static int counter = 0;
870 s << counter++ << mname;
873 // MiKTeX's YAP (version 2.4.1803) crashes if the file name
874 // is longer than about 160 characters. MiKTeX's pdflatex
875 // is even pickier. A maximum length of 100 has been proven to work.
876 // If dir.size() > max length, all bets are off for YAP. We truncate
877 // the filename nevertheless, keeping a minimum of 10 chars.
879 string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
881 // If the mangled file name is too long, hack it to fit.
882 // We know we're guaranteed to have a unique file name because
884 if (mname.size() > max_length) {
885 int const half = (int(max_length) / 2) - 2;
887 mname = mname.substr(0, half) + "___" +
888 mname.substr(mname.size() - half);
892 mangledNames[absFilename()] = mname;
897 bool DocFileName::isZipped() const
899 if (!zipped_valid_) {
900 zipped_ = isZippedFile();
901 zipped_valid_ = true;
907 string DocFileName::unzippedFilename() const
909 return unzippedFileName(absFilename());
913 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
915 return lhs.absFilename() == rhs.absFilename()
916 && lhs.saveAbsPath() == rhs.saveAbsPath();
920 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
922 return !(lhs == rhs);
925 } // namespace support