]> git.lyx.org Git - lyx.git/blob - src/support/FileName.cpp
Use more informative descriptions fro Springer layouts
[lyx.git] / src / support / FileName.cpp
1 /**
2  * \file FileName.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "support/FileName.h"
14 #include "support/FileNameList.h"
15
16 #include "support/debug.h"
17 #include "support/filetools.h"
18 #include "support/lassert.h"
19 #include "support/lstrings.h"
20 #include "support/mutex.h"
21 #include "support/os.h"
22 #include "support/Package.h"
23 #include "support/qstring_helpers.h"
24
25 #include <QDateTime>
26 #include <QDir>
27 #include <QFile>
28 #include <QFileInfo>
29 #include <QList>
30 #include <QTemporaryFile>
31 #include <QTime>
32
33 #include <boost/crc.hpp>
34
35 #include <algorithm>
36 #include <iterator>
37 #include <fstream>
38 #include <iomanip>
39 #include <map>
40 #include <sstream>
41
42 #ifdef HAVE_SYS_TYPES_H
43 # include <sys/types.h>
44 #endif
45 #ifdef HAVE_SYS_STAT_H
46 # include <sys/stat.h>
47 #endif
48 #ifdef HAVE_UNISTD_H
49 # include <unistd.h>
50 #endif
51 #ifdef HAVE_DIRECT_H
52 # include <direct.h>
53 #endif
54 #ifdef _WIN32
55 # include <windows.h>
56 #endif
57
58 #include <cerrno>
59 #include <fcntl.h>
60
61 // Three implementations of checksum(), depending on having mmap support or not.
62 #if defined(HAVE_MMAP) && defined(HAVE_MUNMAP)
63 #define SUM_WITH_MMAP
64 #include <sys/mman.h>
65 #endif // SUM_WITH_MMAP
66
67 using namespace std;
68 using namespace lyx::support;
69
70 // OK, this is ugly, but it is the only workaround I found to compile
71 // with gcc (any version) on a system which uses a non-GNU toolchain.
72 // The problem is that gcc uses a weak symbol for a particular
73 // instantiation and that the system linker usually does not
74 // understand those weak symbols (seen on HP-UX, tru64, AIX and
75 // others). Thus we force an explicit instanciation of this particular
76 // template (JMarc)
77 template struct boost::detail::crc_table_t<32, 0x04C11DB7, true>;
78
79 namespace lyx {
80 namespace support {
81
82 /////////////////////////////////////////////////////////////////////
83 //
84 // FileName::Private
85 //
86 /////////////////////////////////////////////////////////////////////
87
88 struct FileName::Private
89 {
90         Private() {}
91
92         Private(string const & abs_filename) : fi(toqstr(handleTildeName(abs_filename)))
93         {
94                 name = fromqstr(fi.absoluteFilePath());
95                 fi.setCaching(fi.exists() ? true : false);
96         }
97         ///
98         inline void refresh()
99         {
100                 fi.refresh();
101         }
102
103         static
104         bool isFilesystemEqual(QString const & lhs, QString const & rhs)
105         {
106                 return QString::compare(lhs, rhs, os::isFilesystemCaseSensitive() ?
107                         Qt::CaseSensitive : Qt::CaseInsensitive) == 0;
108         }
109
110         static
111         string const handleTildeName(string const & name)
112         {
113                 return name == "~" ? Package::get_home_dir().absFileName() :
114                         prefixIs(name, "~/") ? Package::get_home_dir().absFileName() + name.substr(1) :
115                         name;
116         }
117
118         /// The absolute file name in UTF-8 encoding.
119         std::string name;
120         ///
121         QFileInfo fi;
122 };
123
124 /////////////////////////////////////////////////////////////////////
125 //
126 // FileName
127 //
128 /////////////////////////////////////////////////////////////////////
129
130
131 FileName::FileName() : d(new Private)
132 {
133 }
134
135
136 FileName::FileName(string const & abs_filename)
137         : d(abs_filename.empty() ? new Private : new Private(abs_filename))
138 {
139         //LYXERR(Debug::FILES, "FileName(" << abs_filename << ')');
140         LATTEST(empty() || isAbsolute(d->name));
141 }
142
143
144 FileName::~FileName()
145 {
146         delete d;
147 }
148
149
150 FileName::FileName(FileName const & rhs) : d(new Private)
151 {
152         d->name = rhs.d->name;
153         d->fi = rhs.d->fi;
154 }
155
156
157 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
158 {
159         set(rhs, suffix);
160 }
161
162
163 FileName & FileName::operator=(FileName const & rhs)
164 {
165         if (&rhs == this)
166                 return *this;
167         d->name = rhs.d->name;
168         d->fi = rhs.d->fi;
169         return *this;
170 }
171
172
173 bool FileName::empty() const
174 {
175         return d->name.empty();
176 }
177
178
179 bool FileName::isAbsolute(string const & name)
180 {
181         QFileInfo fi(toqstr(Private::handleTildeName(name)));
182         return fi.isAbsolute();
183 }
184
185
186 string FileName::absFileName() const
187 {
188         return d->name;
189 }
190
191
192 string FileName::realPath() const
193 {
194         return os::real_path(absFileName());
195 }
196
197
198 void FileName::set(string const & name)
199 {
200         d->fi.setFile(toqstr(Private::handleTildeName(name)));
201         d->name = fromqstr(d->fi.absoluteFilePath());
202         //LYXERR(Debug::FILES, "FileName::set(" << name << ')');
203         LATTEST(empty() || isAbsolute(d->name));
204 }
205
206
207 void FileName::set(FileName const & rhs, string const & suffix)
208 {
209         if (!rhs.d->fi.isDir())
210                 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
211         else
212                 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
213         d->name = fromqstr(d->fi.absoluteFilePath());
214         //LYXERR(Debug::FILES, "FileName::set(" << d->name << ')');
215         LATTEST(empty() || isAbsolute(d->name));
216 }
217
218
219 void FileName::erase()
220 {
221         d->name.clear();
222         d->fi = QFileInfo();
223 }
224
225
226 bool FileName::copyTo(FileName const & name, bool keepsymlink) const
227 {
228         FileNameSet visited;
229         return copyTo(name, keepsymlink, visited);
230 }
231
232
233 bool FileName::copyTo(FileName const & name, bool keepsymlink,
234                       FileName::FileNameSet & visited) const
235 {
236         LYXERR(Debug::FILES, "Copying " << name << " keep symlink: " << keepsymlink);
237         if (keepsymlink && name.isSymLink()) {
238                 visited.insert(*this);
239                 FileName const target(fromqstr(name.d->fi.symLinkTarget()));
240                 if (visited.find(target) != visited.end()) {
241                         LYXERR(Debug::FILES, "Found circular symlink: " << target);
242                         return false;
243                 }
244                 return copyTo(target, true);
245         }
246         QFile::remove(name.d->fi.absoluteFilePath());
247         bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
248         if (!success)
249                 LYXERR0("FileName::copyTo(): Could not copy file "
250                         << *this << " to " << name);
251         return success;
252 }
253
254
255 bool FileName::renameTo(FileName const & name) const
256 {
257         LYXERR(Debug::FILES, "Renaming " << name << " as " << *this);
258         bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
259         if (!success)
260                 LYXERR0("Could not rename file " << *this << " to " << name);
261         return success;
262 }
263
264
265 bool FileName::moveTo(FileName const & name) const
266 {
267         LYXERR(Debug::FILES, "Moving " << *this << " to " << name);
268         QFile::remove(name.d->fi.absoluteFilePath());
269
270         bool success = QFile::rename(d->fi.absoluteFilePath(),
271                 name.d->fi.absoluteFilePath());
272         if (!success)
273                 LYXERR0("Could not move file " << *this << " to " << name);
274         return success;
275 }
276
277
278 bool FileName::changePermission(unsigned long int mode) const
279 {
280 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
281         if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
282                 LYXERR0("File " << *this << ": cannot change permission to "
283                         << mode << ".");
284                 return false;
285         }
286 #else
287         // squash warning
288         (void) mode;
289 #endif
290         return true;
291 }
292
293
294 string FileName::toFilesystemEncoding() const
295 {
296         // This doesn't work on Windows for non ascii file names.
297         QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
298         return string(encoded.begin(), encoded.end());
299 }
300
301
302 string FileName::toSafeFilesystemEncoding(os::file_access how) const
303 {
304         // This will work on Windows for non ascii file names.
305         QString const safe_path =
306                 toqstr(os::safe_internal_path(absFileName(), how));
307         QByteArray const encoded = QFile::encodeName(safe_path);
308         return string(encoded.begin(), encoded.end());
309 }
310
311
312 FileName FileName::fromFilesystemEncoding(string const & name)
313 {
314         QByteArray const encoded(name.c_str(), name.length());
315         return FileName(fromqstr(QFile::decodeName(encoded)));
316 }
317
318
319 bool FileName::exists() const
320 {
321         return !empty() && d->fi.exists();
322 }
323
324
325 bool FileName::isSymLink() const
326 {
327         return !empty() && d->fi.isSymLink();
328 }
329
330
331 //QFileInfo caching info might fool this test if file was changed meanwhile.
332 //refresh() helps, but we don't want to put it blindly here, because it might
333 //trigger slowdown on networked file systems.
334 bool FileName::isFileEmpty() const
335 {
336         LASSERT(!empty(), return true);
337         return d->fi.size() == 0;
338 }
339
340
341 bool FileName::isDirectory() const
342 {
343         return !empty() && d->fi.isDir();
344 }
345
346
347 bool FileName::isReadOnly() const
348 {
349         LASSERT(!empty(), return true);
350         return d->fi.isReadable() && !d->fi.isWritable();
351 }
352
353
354 bool FileName::isReadableDirectory() const
355 {
356         return isDirectory() && d->fi.isReadable();
357 }
358
359
360 string FileName::onlyFileName() const
361 {
362         return fromqstr(d->fi.fileName());
363 }
364
365
366 string FileName::onlyFileNameWithoutExt() const
367 {
368         return fromqstr(d->fi.completeBaseName());
369 }
370
371
372 string FileName::extension() const
373 {
374         return fromqstr(d->fi.suffix());
375 }
376
377
378 bool FileName::hasExtension(const string & ext)
379 {
380         return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
381 }
382
383
384 FileName FileName::onlyPath() const
385 {
386         FileName path;
387         if (empty())
388                 return path;
389         path.d->fi.setFile(d->fi.path());
390         path.d->name = fromqstr(path.d->fi.absoluteFilePath());
391         return path;
392 }
393
394
395 FileName FileName::parentPath() const
396 {
397         FileName path;
398         // return empty path for parent of root dir
399         // parent of empty path is empty too
400         if (empty() || d->fi.isRoot())
401                 return path;
402         path.d->fi.setFile(d->fi.path());
403         path.d->name = fromqstr(path.d->fi.absoluteFilePath());
404         return path;
405 }
406
407
408 bool FileName::isReadableFile() const
409 {
410         return !empty() && d->fi.isFile() && d->fi.isReadable();
411 }
412
413
414 bool FileName::isWritable() const
415 {
416         return !empty() && d->fi.isWritable();
417 }
418
419
420 bool FileName::isDirWritable() const
421 {
422         LASSERT(isDirectory(), return false);
423         QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
424         QTemporaryFile qt_tmp(tmp.absoluteFilePath());
425         if (qt_tmp.open()) {
426                 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
427                 return true;
428         }
429         LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
430         return false;
431 }
432
433
434 FileNameList FileName::dirList(string const & ext) const
435 {
436         FileNameList dirlist;
437         if (!isDirectory()) {
438                 LYXERR0("Directory '" << *this << "' does not exist!");
439                 return dirlist;
440         }
441
442         // If the directory is specified without a trailing '/', absoluteDir()
443         // would return the parent dir, so we must use absoluteFilePath() here.
444         QDir dir = d->fi.absoluteFilePath();
445
446         if (!ext.empty()) {
447                 QString filter;
448                 switch (ext[0]) {
449                 case '.': filter = "*" + toqstr(ext); break;
450                 case '*': filter = toqstr(ext); break;
451                 default: filter = "*." + toqstr(ext);
452                 }
453                 dir.setNameFilters(QStringList(filter));
454                 LYXERR(Debug::FILES, "filtering on extension "
455                         << fromqstr(filter) << " is requested.");
456         }
457
458         QFileInfoList list = dir.entryInfoList();
459         for (int i = 0; i != list.size(); ++i) {
460                 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
461                 dirlist.push_back(fi);
462                 LYXERR(Debug::FILES, "found file " << fi);
463         }
464
465         return dirlist;
466 }
467
468
469 FileName FileName::getcwd()
470 {
471         // return makeAbsPath("."); would create an infinite loop
472         QFileInfo fi(".");
473         return FileName(fromqstr(fi.absoluteFilePath()));
474 }
475
476
477 FileName FileName::tempPath()
478 {
479         return FileName(os::internal_path(fromqstr(QDir::tempPath())));
480 }
481
482
483 void FileName::refresh() const
484 {
485         d->refresh();
486 }
487
488
489 time_t FileName::lastModified() const
490 {
491         // QFileInfo caches information about the file. So, in case this file has
492         // been touched between the object creation and now, we refresh the file
493         // information.
494         d->refresh();
495         return d->fi.lastModified().toTime_t();
496 }
497
498
499 bool FileName::chdir() const
500 {
501         return QDir::setCurrent(d->fi.absoluteFilePath());
502 }
503
504
505 bool FileName::link(FileName const & name) const
506 {
507         return QFile::link(toqstr(absFileName()), toqstr(name.absFileName()));
508 }
509
510
511 unsigned long checksum_ifstream_fallback(char const * file)
512 {
513         unsigned long result = 0;
514         //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
515         ifstream ifs(file, ios_base::in | ios_base::binary);
516         if (!ifs)
517                 return result;
518
519         istreambuf_iterator<char> beg(ifs);
520         istreambuf_iterator<char> end;
521         boost::crc_32_type crc;
522         crc = for_each(beg, end, crc);
523         result = crc.checksum();
524         return result;
525 }
526
527 unsigned long FileName::checksum() const
528 {
529         unsigned long result = 0;
530
531         if (!exists()) {
532                 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
533                 return result;
534         }
535         // a directory may be passed here so we need to test it. (bug 3622)
536         if (isDirectory()) {
537                 LYXERR0('"' << absFileName() << "\" is a directory!");
538                 return result;
539         }
540
541         // This is used in the debug output at the end of the method.
542         static QTime t;
543         if (lyxerr.debugging(Debug::FILES))
544                 t.restart();
545
546 #if QT_VERSION >= 0x999999
547         // First version of checksum uses Qt4.4 mmap support.
548         // FIXME: This code is not ready with Qt4.4.2,
549         // see http://www.lyx.org/trac/ticket/5293
550         // FIXME: should we check if the MapExtension extension is supported?
551         // see QAbstractFileEngine::supportsExtension() and
552         // QAbstractFileEngine::MapExtension)
553         QFile qf(fi.filePath());
554         if (!qf.open(QIODevice::ReadOnly))
555                 return result;
556         qint64 size = fi.size();
557         uchar * ubeg = qf.map(0, size);
558         uchar * uend = ubeg + size;
559         boost::crc_32_type ucrc;
560         ucrc.process_block(ubeg, uend);
561         qf.unmap(ubeg);
562         qf.close();
563         result = ucrc.checksum();
564
565 #else // QT_VERSION
566
567         string const encoded = toSafeFilesystemEncoding();
568         char const * file = encoded.c_str();
569
570  #ifdef SUM_WITH_MMAP
571         //LYXERR(Debug::FILES, "using mmap (lightning fast)");
572
573         int fd = open(file, O_RDONLY);
574         if (!fd)
575                 return result;
576
577         struct stat info;
578         if (fstat(fd, &info)){
579                 // fstat fails on samba shares (bug 5891)
580                 close(fd);
581                 return checksum_ifstream_fallback(file);
582         }
583
584         void * mm = mmap(0, info.st_size, PROT_READ,
585                          MAP_PRIVATE, fd, 0);
586         // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
587         if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
588                 close(fd);
589                 return result;
590         }
591
592         char * beg = static_cast<char*>(mm);
593         char * end = beg + info.st_size;
594
595         boost::crc_32_type crc;
596         crc.process_block(beg, end);
597         result = crc.checksum();
598
599         munmap(mm, info.st_size);
600         close(fd);
601
602  #else // no SUM_WITH_MMAP
603         result = checksum_ifstream_fallback(file);
604  #endif // SUM_WITH_MMAP
605 #endif // QT_VERSION
606
607         LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
608                 << result << " lasted " << t.elapsed() << " ms.");
609         return result;
610 }
611
612
613 bool FileName::removeFile() const
614 {
615         bool const success = QFile::remove(d->fi.absoluteFilePath());
616         d->refresh();
617         if (!success && exists())
618                 LYXERR0("Could not delete file " << *this);
619         return success;
620 }
621
622
623 static bool rmdir(QFileInfo const & fi)
624 {
625         QDir dir(fi.absoluteFilePath());
626         QFileInfoList list = dir.entryInfoList();
627         bool success = true;
628         for (int i = 0; i != list.size(); ++i) {
629                 if (list.at(i).fileName() == ".")
630                         continue;
631                 if (list.at(i).fileName() == "..")
632                         continue;
633                 bool removed;
634                 if (list.at(i).isDir()) {
635                         LYXERR(Debug::FILES, "Removing dir "
636                                 << fromqstr(list.at(i).absoluteFilePath()));
637                         removed = rmdir(list.at(i));
638                 }
639                 else {
640                         LYXERR(Debug::FILES, "Removing file "
641                                 << fromqstr(list.at(i).absoluteFilePath()));
642                         removed = dir.remove(list.at(i).fileName());
643                 }
644                 if (!removed) {
645                         success = false;
646                         LYXERR0("Could not delete "
647                                 << fromqstr(list.at(i).absoluteFilePath()));
648                 }
649         }
650         QDir parent = fi.absolutePath();
651         success &= parent.rmdir(fi.fileName());
652         return success;
653 }
654
655
656 bool FileName::destroyDirectory() const
657 {
658         bool const success = rmdir(d->fi);
659         if (!success)
660                 LYXERR0("Could not delete " << *this);
661
662         return success;
663 }
664
665
666 // Only used in non Win32 platforms
667 #ifndef Q_OS_WIN32
668 static int mymkdir(char const * pathname, unsigned long int mode)
669 {
670         // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
671 # if HAVE_MKDIR
672 #  if MKDIR_TAKES_ONE_ARG
673         // MinGW32
674         return ::mkdir(pathname);
675         // FIXME: "Permissions of created directories are ignored on this system."
676 #  else
677         // POSIX
678         return ::mkdir(pathname, mode_t(mode));
679 #  endif
680 # elif defined(_WIN32)
681         // plain Windows 32
682         return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
683         // FIXME: "Permissions of created directories are ignored on this system."
684 # elif HAVE__MKDIR
685         return ::_mkdir(pathname);
686         // FIXME: "Permissions of created directories are ignored on this system."
687 # else
688 #   error "Don't know how to create a directory on this system."
689 # endif
690 }
691 #endif
692
693
694 bool FileName::createDirectory(int permission) const
695 {
696         LASSERT(!empty(), return false);
697 #ifdef Q_OS_WIN32
698         // FIXME: "Permissions of created directories are ignored on this system."
699         (void) permission;
700         return createPath();
701 #else
702         return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
703 #endif
704 }
705
706
707 bool FileName::createPath() const
708 {
709         LASSERT(!empty(), return false);
710         LYXERR(Debug::FILES, "creating path '" << *this << "'.");
711         if (isDirectory())
712                 return false;
713
714         QDir dir;
715         bool success = dir.mkpath(d->fi.absoluteFilePath());
716         if (!success)
717                 LYXERR0("Cannot create path '" << *this << "'!");
718         return success;
719 }
720
721
722 docstring const FileName::absoluteFilePath() const
723 {
724         return qstring_to_ucs4(d->fi.absoluteFilePath());
725 }
726
727
728 docstring FileName::displayName(int threshold) const
729 {
730         return makeDisplayPath(absFileName(), threshold);
731 }
732
733
734 docstring FileName::fileContents(string const & encoding) const
735 {
736         if (!isReadableFile()) {
737                 LYXERR0("File '" << *this << "' is not readable!");
738                 return docstring();
739         }
740
741         QFile file(d->fi.absoluteFilePath());
742         if (!file.open(QIODevice::ReadOnly)) {
743                 LYXERR0("File '" << *this
744                         << "' could not be opened in read only mode!");
745                 return docstring();
746         }
747         QByteArray contents = file.readAll();
748         file.close();
749
750         if (contents.isEmpty()) {
751                 LYXERR(Debug::FILES, "File '" << *this
752                         << "' is either empty or some error happened while reading it.");
753                 return docstring();
754         }
755
756         QString s;
757         if (encoding.empty() || encoding == "UTF-8")
758                 s = QString::fromUtf8(contents.data());
759         else if (encoding == "ascii")
760 #if (QT_VERSION < 0x050000)
761                 s = QString::fromAscii(contents.data());
762 #else
763                 s = QString::fromLatin1(contents.data());
764 #endif
765         else if (encoding == "local8bit")
766                 s = QString::fromLocal8Bit(contents.data());
767         else if (encoding == "latin1")
768                 s = QString::fromLatin1(contents.data());
769
770         return qstring_to_ucs4(s);
771 }
772
773
774 void FileName::changeExtension(string const & extension)
775 {
776         // FIXME: use Qt native methods...
777         string const oldname = absFileName();
778         string::size_type const last_slash = oldname.rfind('/');
779         string::size_type last_dot = oldname.rfind('.');
780         if (last_dot < last_slash && last_slash != string::npos)
781                 last_dot = string::npos;
782
783         string ext;
784         // Make sure the extension starts with a dot
785         if (!extension.empty() && extension[0] != '.')
786                 ext= '.' + extension;
787         else
788                 ext = extension;
789
790         set(oldname.substr(0, last_dot) + ext);
791 }
792
793
794 docstring const FileName::relPath(string const & path) const
795 {
796         // FIXME UNICODE
797         return makeRelPath(absoluteFilePath(), from_utf8(path));
798 }
799
800
801 // Note: According to Qt, QFileInfo::operator== is undefined when
802 // both files do not exist (Qt4.5 gives true for all non-existent
803 // files, while Qt4.4 compares the filenames).
804 // see:
805 // http://www.qtsoftware.com/developer/task-tracker/
806 //   index_html?id=248471&method=entry.
807 bool equivalent(FileName const & l, FileName const & r)
808 {
809         // FIXME: In future use Qt.
810         // Qt 4.4: We need to solve this warning from Qt documentation:
811         // * Long and short file names that refer to the same file on Windows are
812         //   treated as if they referred to different files.
813         // This is supposed to be fixed for Qt5.
814         FileName const lhs(os::internal_path(l.absFileName()));
815         FileName const rhs(os::internal_path(r.absFileName()));
816
817         if (lhs.empty())
818                 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
819                 return rhs.empty();
820
821         if (rhs.empty())
822                 // Avoid unnecessary checks below.
823                 return false;
824
825         lhs.d->refresh();
826         rhs.d->refresh();
827
828         if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
829                 // Qt already checks if the filesystem is case sensitive or not.
830                 // see note above why the extra check with fileName is needed.
831                 return lhs.d->fi == rhs.d->fi
832                         && lhs.d->fi.fileName() == rhs.d->fi.fileName();
833         }
834
835         // FIXME: When/if QFileInfo support symlink comparison, remove this code.
836         QFileInfo fi1(lhs.d->fi);
837         if (fi1.isSymLink())
838                 fi1 = QFileInfo(fi1.symLinkTarget());
839         QFileInfo fi2(rhs.d->fi);
840         if (fi2.isSymLink())
841                 fi2 = QFileInfo(fi2.symLinkTarget());
842         // see note above why the extra check with fileName is needed.
843         return fi1 == fi2 && fi1.fileName() == fi2.fileName();
844 }
845
846
847 bool operator==(FileName const & lhs, FileName const & rhs)
848 {
849         return os::isFilesystemCaseSensitive()
850                 ? lhs.absFileName() == rhs.absFileName()
851                 : !QString::compare(toqstr(lhs.absFileName()),
852                                 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
853 }
854
855
856 bool operator!=(FileName const & lhs, FileName const & rhs)
857 {
858         return !(operator==(lhs, rhs));
859 }
860
861
862 bool operator<(FileName const & lhs, FileName const & rhs)
863 {
864         return lhs.absFileName() < rhs.absFileName();
865 }
866
867
868 bool operator>(FileName const & lhs, FileName const & rhs)
869 {
870         return lhs.absFileName() > rhs.absFileName();
871 }
872
873
874 ostream & operator<<(ostream & os, FileName const & filename)
875 {
876         return os << filename.absFileName();
877 }
878
879
880 /////////////////////////////////////////////////////////////////////
881 //
882 // DocFileName
883 //
884 /////////////////////////////////////////////////////////////////////
885
886
887 DocFileName::DocFileName()
888         : save_abs_path_(true)
889 {}
890
891
892 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
893         : FileName(abs_filename), save_abs_path_(save_abs)
894 {}
895
896
897 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
898         : FileName(abs_filename), save_abs_path_(save_abs)
899 {}
900
901
902 void DocFileName::set(string const & name, string const & buffer_path)
903 {
904         save_abs_path_ = isAbsolute(name);
905         if (save_abs_path_)
906                 FileName::set(name);
907         else
908                 FileName::set(makeAbsPath(name, buffer_path).absFileName());
909 }
910
911
912 void DocFileName::erase()
913 {
914         FileName::erase();
915 }
916
917
918 string DocFileName::relFileName(string const & path) const
919 {
920         // FIXME UNICODE
921         return to_utf8(relPath(path));
922 }
923
924
925 string DocFileName::outputFileName(string const & path) const
926 {
927         return save_abs_path_ ? absFileName() : relFileName(path);
928 }
929
930
931 string DocFileName::mangledFileName(string const & dir) const
932 {
933         // Concurrent access to these variables is possible.
934
935         // We need to make sure that every DocFileName instance for a given
936         // filename returns the same mangled name.
937         typedef map<string, string> MangledMap;
938         static MangledMap mangledNames;
939         static Mutex mangledMutex;
940         // this locks both access to mangledNames and counter below
941         Mutex::Locker lock(&mangledMutex);
942         MangledMap::const_iterator const it = mangledNames.find(absFileName());
943         if (it != mangledNames.end())
944                 return (*it).second;
945
946         string const name = absFileName();
947         // Now the real work
948         string mname = os::internal_path(name);
949         // Remove the extension.
950         mname = support::changeExtension(name, string());
951         // The mangled name must be a valid LaTeX name.
952         // The list of characters to keep is probably over-restrictive,
953         // but it is not really a problem.
954         // Apart from non-ASCII characters, at least the following characters
955         // are forbidden: '/', '.', ' ', and ':'.
956         // On windows it is not possible to create files with '<', '>' or '?'
957         // in the name.
958         static string const keep = "abcdefghijklmnopqrstuvwxyz"
959                                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
960                                    "+-0123456789;=";
961         string::size_type pos = 0;
962         while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
963                 mname[pos++] = '_';
964         // Add the extension back on
965         mname = support::changeExtension(mname, getExtension(name));
966
967         // Prepend a counter to the filename. This is necessary to make
968         // the mangled name unique.
969         static int counter = 0;
970         ostringstream s;
971         s << counter++ << mname;
972         mname = s.str();
973
974         // MiKTeX's YAP (version 2.4.1803) crashes if the file name
975         // is longer than about 160 characters. MiKTeX's pdflatex
976         // is even pickier. A maximum length of 100 has been proven to work.
977         // If dir.size() > max length, all bets are off for YAP. We truncate
978         // the filename nevertheless, keeping a minimum of 10 chars.
979
980         string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
981
982         // If the mangled file name is too long, hack it to fit.
983         // We know we're guaranteed to have a unique file name because
984         // of the counter.
985         if (mname.size() > max_length) {
986                 int const half = (int(max_length) / 2) - 2;
987                 if (half > 0) {
988                         mname = mname.substr(0, half) + "___" +
989                                 mname.substr(mname.size() - half);
990                 }
991         }
992
993         mangledNames[absFileName()] = mname;
994         return mname;
995 }
996
997
998 string DocFileName::unzippedFileName() const
999 {
1000         return support::unzippedFileName(absFileName());
1001 }
1002
1003
1004 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1005 {
1006         return static_cast<FileName const &>(lhs)
1007                 == static_cast<FileName const &>(rhs)
1008                 && lhs.saveAbsPath() == rhs.saveAbsPath();
1009 }
1010
1011
1012 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1013 {
1014         return !(lhs == rhs);
1015 }
1016
1017 } // namespace support
1018 } // namespace lyx