]> git.lyx.org Git - lyx.git/blob - src/support/FileName.cpp
Account for old versions of Pygments
[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 #endif
287         return true;
288 }
289
290
291 string FileName::toFilesystemEncoding() const
292 {
293         // This doesn't work on Windows for non ascii file names.
294         QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
295         return string(encoded.begin(), encoded.end());
296 }
297
298
299 string FileName::toSafeFilesystemEncoding(os::file_access how) const
300 {
301         // This will work on Windows for non ascii file names.
302         QString const safe_path =
303                 toqstr(os::safe_internal_path(absFileName(), how));
304         QByteArray const encoded = QFile::encodeName(safe_path);
305         return string(encoded.begin(), encoded.end());
306 }
307
308
309 FileName FileName::fromFilesystemEncoding(string const & name)
310 {
311         QByteArray const encoded(name.c_str(), name.length());
312         return FileName(fromqstr(QFile::decodeName(encoded)));
313 }
314
315
316 bool FileName::exists() const
317 {
318         return !empty() && d->fi.exists();
319 }
320
321
322 bool FileName::isSymLink() const
323 {
324         return !empty() && d->fi.isSymLink();
325 }
326
327
328 //QFileInfo caching info might fool this test if file was changed meanwhile.
329 //refresh() helps, but we don't want to put it blindly here, because it might
330 //trigger slowdown on networked file systems.
331 bool FileName::isFileEmpty() const
332 {
333         LASSERT(!empty(), return true);
334         return d->fi.size() == 0;
335 }
336
337
338 bool FileName::isDirectory() const
339 {
340         return !empty() && d->fi.isDir();
341 }
342
343
344 bool FileName::isReadOnly() const
345 {
346         LASSERT(!empty(), return true);
347         return d->fi.isReadable() && !d->fi.isWritable();
348 }
349
350
351 bool FileName::isReadableDirectory() const
352 {
353         return isDirectory() && d->fi.isReadable();
354 }
355
356
357 string FileName::onlyFileName() const
358 {
359         return fromqstr(d->fi.fileName());
360 }
361
362
363 string FileName::onlyFileNameWithoutExt() const
364 {
365         return fromqstr(d->fi.completeBaseName());
366 }
367
368
369 string FileName::extension() const
370 {
371         return fromqstr(d->fi.suffix());
372 }
373
374
375 bool FileName::hasExtension(const string & ext)
376 {
377         return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
378 }
379
380
381 FileName FileName::onlyPath() const
382 {
383         FileName path;
384         if (empty())
385                 return path;
386         path.d->fi.setFile(d->fi.path());
387         path.d->name = fromqstr(path.d->fi.absoluteFilePath());
388         return path;
389 }
390
391
392 FileName FileName::parentPath() const
393 {
394         FileName path;
395         // return empty path for parent of root dir
396         // parent of empty path is empty too
397         if (empty() || d->fi.isRoot())
398                 return path;
399         path.d->fi.setFile(d->fi.path());
400         path.d->name = fromqstr(path.d->fi.absoluteFilePath());
401         return path;
402 }
403
404
405 bool FileName::isReadableFile() const
406 {
407         return !empty() && d->fi.isFile() && d->fi.isReadable();
408 }
409
410
411 bool FileName::isWritable() const
412 {
413         return !empty() && d->fi.isWritable();
414 }
415
416
417 bool FileName::isDirWritable() const
418 {
419         LASSERT(isDirectory(), return false);
420         QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
421         QTemporaryFile qt_tmp(tmp.absoluteFilePath());
422         if (qt_tmp.open()) {
423                 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
424                 return true;
425         }
426         LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
427         return false;
428 }
429
430
431 FileNameList FileName::dirList(string const & ext) const
432 {
433         FileNameList dirlist;
434         if (!isDirectory()) {
435                 LYXERR0("Directory '" << *this << "' does not exist!");
436                 return dirlist;
437         }
438
439         // If the directory is specified without a trailing '/', absoluteDir()
440         // would return the parent dir, so we must use absoluteFilePath() here.
441         QDir dir = d->fi.absoluteFilePath();
442
443         if (!ext.empty()) {
444                 QString filter;
445                 switch (ext[0]) {
446                 case '.': filter = "*" + toqstr(ext); break;
447                 case '*': filter = toqstr(ext); break;
448                 default: filter = "*." + toqstr(ext);
449                 }
450                 dir.setNameFilters(QStringList(filter));
451                 LYXERR(Debug::FILES, "filtering on extension "
452                         << fromqstr(filter) << " is requested.");
453         }
454
455         QFileInfoList list = dir.entryInfoList();
456         for (int i = 0; i != list.size(); ++i) {
457                 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
458                 dirlist.push_back(fi);
459                 LYXERR(Debug::FILES, "found file " << fi);
460         }
461
462         return dirlist;
463 }
464
465
466 FileName FileName::getcwd()
467 {
468         // return makeAbsPath("."); would create an infinite loop
469         QFileInfo fi(".");
470         return FileName(fromqstr(fi.absoluteFilePath()));
471 }
472
473
474 FileName FileName::tempPath()
475 {
476         return FileName(os::internal_path(fromqstr(QDir::tempPath())));
477 }
478
479
480 void FileName::refresh() const
481 {
482         d->refresh();
483 }
484
485
486 time_t FileName::lastModified() const
487 {
488         // QFileInfo caches information about the file. So, in case this file has
489         // been touched between the object creation and now, we refresh the file
490         // information.
491         d->refresh();
492         return d->fi.lastModified().toTime_t();
493 }
494
495
496 bool FileName::chdir() const
497 {
498         return QDir::setCurrent(d->fi.absoluteFilePath());
499 }
500
501
502 bool FileName::link(FileName const & name) const
503 {
504         return QFile::link(toqstr(absFileName()), toqstr(name.absFileName()));
505 }
506
507
508 unsigned long checksum_ifstream_fallback(char const * file)
509 {
510         unsigned long result = 0;
511         //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
512         ifstream ifs(file, ios_base::in | ios_base::binary);
513         if (!ifs)
514                 return result;
515
516         istreambuf_iterator<char> beg(ifs);
517         istreambuf_iterator<char> end;
518         boost::crc_32_type crc;
519         crc = for_each(beg, end, crc);
520         result = crc.checksum();
521         return result;
522 }
523
524 unsigned long FileName::checksum() const
525 {
526         unsigned long result = 0;
527
528         if (!exists()) {
529                 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
530                 return result;
531         }
532         // a directory may be passed here so we need to test it. (bug 3622)
533         if (isDirectory()) {
534                 LYXERR0('"' << absFileName() << "\" is a directory!");
535                 return result;
536         }
537
538         // This is used in the debug output at the end of the method.
539         static QTime t;
540         if (lyxerr.debugging(Debug::FILES))
541                 t.restart();
542
543 #if QT_VERSION >= 0x999999
544         // First version of checksum uses Qt4.4 mmap support.
545         // FIXME: This code is not ready with Qt4.4.2,
546         // see http://www.lyx.org/trac/ticket/5293
547         // FIXME: should we check if the MapExtension extension is supported?
548         // see QAbstractFileEngine::supportsExtension() and 
549         // QAbstractFileEngine::MapExtension)
550         QFile qf(fi.filePath());
551         if (!qf.open(QIODevice::ReadOnly))
552                 return result;
553         qint64 size = fi.size();
554         uchar * ubeg = qf.map(0, size);
555         uchar * uend = ubeg + size;
556         boost::crc_32_type ucrc;
557         ucrc.process_block(ubeg, uend);
558         qf.unmap(ubeg);
559         qf.close();
560         result = ucrc.checksum();
561
562 #else // QT_VERSION
563
564         string const encoded = toSafeFilesystemEncoding();
565         char const * file = encoded.c_str();
566
567  #ifdef SUM_WITH_MMAP
568         //LYXERR(Debug::FILES, "using mmap (lightning fast)");
569
570         int fd = open(file, O_RDONLY);
571         if (!fd)
572                 return result;
573
574         struct stat info;
575         if (fstat(fd, &info)){
576                 // fstat fails on samba shares (bug 5891)
577                 close(fd);
578                 return checksum_ifstream_fallback(file);
579         }
580
581         void * mm = mmap(0, info.st_size, PROT_READ,
582                          MAP_PRIVATE, fd, 0);
583         // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
584         if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
585                 close(fd);
586                 return result;
587         }
588
589         char * beg = static_cast<char*>(mm);
590         char * end = beg + info.st_size;
591
592         boost::crc_32_type crc;
593         crc.process_block(beg, end);
594         result = crc.checksum();
595
596         munmap(mm, info.st_size);
597         close(fd);
598
599  #else // no SUM_WITH_MMAP
600         result = checksum_ifstream_fallback(file);
601  #endif // SUM_WITH_MMAP
602 #endif // QT_VERSION
603
604         LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
605                 << result << " lasted " << t.elapsed() << " ms.");
606         return result;
607 }
608
609
610 bool FileName::removeFile() const
611 {
612         bool const success = QFile::remove(d->fi.absoluteFilePath());
613         d->refresh();
614         if (!success && exists())
615                 LYXERR0("Could not delete file " << *this);
616         return success;
617 }
618
619
620 static bool rmdir(QFileInfo const & fi)
621 {
622         QDir dir(fi.absoluteFilePath());
623         QFileInfoList list = dir.entryInfoList();
624         bool success = true;
625         for (int i = 0; i != list.size(); ++i) {
626                 if (list.at(i).fileName() == ".")
627                         continue;
628                 if (list.at(i).fileName() == "..")
629                         continue;
630                 bool removed;
631                 if (list.at(i).isDir()) {
632                         LYXERR(Debug::FILES, "Removing dir " 
633                                 << fromqstr(list.at(i).absoluteFilePath()));
634                         removed = rmdir(list.at(i));
635                 }
636                 else {
637                         LYXERR(Debug::FILES, "Removing file " 
638                                 << fromqstr(list.at(i).absoluteFilePath()));
639                         removed = dir.remove(list.at(i).fileName());
640                 }
641                 if (!removed) {
642                         success = false;
643                         LYXERR0("Could not delete "
644                                 << fromqstr(list.at(i).absoluteFilePath()));
645                 }
646         } 
647         QDir parent = fi.absolutePath();
648         success &= parent.rmdir(fi.fileName());
649         return success;
650 }
651
652
653 bool FileName::destroyDirectory() const
654 {
655         bool const success = rmdir(d->fi);
656         if (!success)
657                 LYXERR0("Could not delete " << *this);
658
659         return success;
660 }
661
662
663 // Only used in non Win32 platforms
664 static int mymkdir(char const * pathname, unsigned long int mode)
665 {
666         // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
667 #if HAVE_MKDIR
668 # if MKDIR_TAKES_ONE_ARG
669         // MinGW32
670         return ::mkdir(pathname);
671         // FIXME: "Permissions of created directories are ignored on this system."
672 # else
673         // POSIX
674         return ::mkdir(pathname, mode_t(mode));
675 # endif
676 #elif defined(_WIN32)
677         // plain Windows 32
678         return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
679         // FIXME: "Permissions of created directories are ignored on this system."
680 #elif HAVE__MKDIR
681         return ::_mkdir(pathname);
682         // FIXME: "Permissions of created directories are ignored on this system."
683 #else
684 #   error "Don't know how to create a directory on this system."
685 #endif
686
687 }
688
689
690 bool FileName::createDirectory(int permission) const
691 {
692         LASSERT(!empty(), return false);
693 #ifdef Q_OS_WIN32
694         // FIXME: "Permissions of created directories are ignored on this system."
695         return createPath();
696 #else
697         return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
698 #endif
699 }
700
701
702 bool FileName::createPath() const
703 {
704         LASSERT(!empty(), return false);
705         LYXERR(Debug::FILES, "creating path '" << *this << "'.");
706         if (isDirectory())
707                 return false;
708
709         QDir dir;
710         bool success = dir.mkpath(d->fi.absoluteFilePath());
711         if (!success)
712                 LYXERR0("Cannot create path '" << *this << "'!");
713         return success;
714 }
715
716
717 docstring const FileName::absoluteFilePath() const
718 {
719         return qstring_to_ucs4(d->fi.absoluteFilePath());
720 }
721
722
723 docstring FileName::displayName(int threshold) const
724 {
725         return makeDisplayPath(absFileName(), threshold);
726 }
727
728
729 docstring FileName::fileContents(string const & encoding) const
730 {
731         if (!isReadableFile()) {
732                 LYXERR0("File '" << *this << "' is not readable!");
733                 return docstring();
734         }
735
736         QFile file(d->fi.absoluteFilePath());
737         if (!file.open(QIODevice::ReadOnly)) {
738                 LYXERR0("File '" << *this
739                         << "' could not be opened in read only mode!");
740                 return docstring();
741         }
742         QByteArray contents = file.readAll();
743         file.close();
744
745         if (contents.isEmpty()) {
746                 LYXERR(Debug::FILES, "File '" << *this
747                         << "' is either empty or some error happened while reading it.");
748                 return docstring();
749         }
750
751         QString s;
752         if (encoding.empty() || encoding == "UTF-8")
753                 s = QString::fromUtf8(contents.data());
754         else if (encoding == "ascii")
755 #if (QT_VERSION < 0x050000)
756                 s = QString::fromAscii(contents.data());
757 #else
758                 s = QString::fromLatin1(contents.data());
759 #endif
760         else if (encoding == "local8bit")
761                 s = QString::fromLocal8Bit(contents.data());
762         else if (encoding == "latin1")
763                 s = QString::fromLatin1(contents.data());
764
765         return qstring_to_ucs4(s);
766 }
767
768
769 void FileName::changeExtension(string const & extension)
770 {
771         // FIXME: use Qt native methods...
772         string const oldname = absFileName();
773         string::size_type const last_slash = oldname.rfind('/');
774         string::size_type last_dot = oldname.rfind('.');
775         if (last_dot < last_slash && last_slash != string::npos)
776                 last_dot = string::npos;
777
778         string ext;
779         // Make sure the extension starts with a dot
780         if (!extension.empty() && extension[0] != '.')
781                 ext= '.' + extension;
782         else
783                 ext = extension;
784
785         set(oldname.substr(0, last_dot) + ext);
786 }
787
788
789 docstring const FileName::relPath(string const & path) const
790 {
791         // FIXME UNICODE
792         return makeRelPath(absoluteFilePath(), from_utf8(path));
793 }
794
795
796 // Note: According to Qt, QFileInfo::operator== is undefined when
797 // both files do not exist (Qt4.5 gives true for all non-existent
798 // files, while Qt4.4 compares the filenames).
799 // see:
800 // http://www.qtsoftware.com/developer/task-tracker/
801 //   index_html?id=248471&method=entry.
802 bool equivalent(FileName const & l, FileName const & r)
803 {
804         // FIXME: In future use Qt.
805         // Qt 4.4: We need to solve this warning from Qt documentation:
806         // * Long and short file names that refer to the same file on Windows are
807         //   treated as if they referred to different files.
808         // This is supposed to be fixed for Qt5.
809         FileName const lhs(os::internal_path(l.absFileName()));
810         FileName const rhs(os::internal_path(r.absFileName()));
811
812         if (lhs.empty())
813                 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
814                 return rhs.empty();
815
816         if (rhs.empty())
817                 // Avoid unnecessary checks below.
818                 return false;
819
820         lhs.d->refresh();
821         rhs.d->refresh();
822
823         if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
824                 // Qt already checks if the filesystem is case sensitive or not.
825                 // see note above why the extra check with fileName is needed.
826                 return lhs.d->fi == rhs.d->fi
827                         && lhs.d->fi.fileName() == rhs.d->fi.fileName();
828         }
829
830         // FIXME: When/if QFileInfo support symlink comparison, remove this code.
831         QFileInfo fi1(lhs.d->fi);
832         if (fi1.isSymLink())
833                 fi1 = QFileInfo(fi1.symLinkTarget());
834         QFileInfo fi2(rhs.d->fi);
835         if (fi2.isSymLink())
836                 fi2 = QFileInfo(fi2.symLinkTarget());
837         // see note above why the extra check with fileName is needed.
838         return fi1 == fi2 && fi1.fileName() == fi2.fileName();
839 }
840
841
842 bool operator==(FileName const & lhs, FileName const & rhs)
843 {
844         return os::isFilesystemCaseSensitive()
845                 ? lhs.absFileName() == rhs.absFileName()
846                 : !QString::compare(toqstr(lhs.absFileName()),
847                                 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
848 }
849
850
851 bool operator!=(FileName const & lhs, FileName const & rhs)
852 {
853         return !(operator==(lhs, rhs));
854 }
855
856
857 bool operator<(FileName const & lhs, FileName const & rhs)
858 {
859         return lhs.absFileName() < rhs.absFileName();
860 }
861
862
863 bool operator>(FileName const & lhs, FileName const & rhs)
864 {
865         return lhs.absFileName() > rhs.absFileName();
866 }
867
868
869 ostream & operator<<(ostream & os, FileName const & filename)
870 {
871         return os << filename.absFileName();
872 }
873
874
875 /////////////////////////////////////////////////////////////////////
876 //
877 // DocFileName
878 //
879 /////////////////////////////////////////////////////////////////////
880
881
882 DocFileName::DocFileName()
883         : save_abs_path_(true)
884 {}
885
886
887 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
888         : FileName(abs_filename), save_abs_path_(save_abs)
889 {}
890
891
892 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
893         : FileName(abs_filename), save_abs_path_(save_abs)
894 {}
895
896
897 void DocFileName::set(string const & name, string const & buffer_path)
898 {
899         save_abs_path_ = isAbsolute(name);
900         if (save_abs_path_)
901                 FileName::set(name);
902         else
903                 FileName::set(makeAbsPath(name, buffer_path).absFileName());
904 }
905
906
907 void DocFileName::erase()
908 {
909         FileName::erase();
910 }
911
912
913 string DocFileName::relFileName(string const & path) const
914 {
915         // FIXME UNICODE
916         return to_utf8(relPath(path));
917 }
918
919
920 string DocFileName::outputFileName(string const & path) const
921 {
922         return save_abs_path_ ? absFileName() : relFileName(path);
923 }
924
925
926 string DocFileName::mangledFileName(string const & dir) const
927 {
928         // Concurrent access to these variables is possible.
929
930         // We need to make sure that every DocFileName instance for a given
931         // filename returns the same mangled name.
932         typedef map<string, string> MangledMap;
933         static MangledMap mangledNames;
934         static Mutex mangledMutex;
935         // this locks both access to mangledNames and counter below 
936         Mutex::Locker lock(&mangledMutex);
937         MangledMap::const_iterator const it = mangledNames.find(absFileName());
938         if (it != mangledNames.end())
939                 return (*it).second;
940
941         string const name = absFileName();
942         // Now the real work
943         string mname = os::internal_path(name);
944         // Remove the extension.
945         mname = support::changeExtension(name, string());
946         // The mangled name must be a valid LaTeX name.
947         // The list of characters to keep is probably over-restrictive,
948         // but it is not really a problem.
949         // Apart from non-ASCII characters, at least the following characters
950         // are forbidden: '/', '.', ' ', and ':'.
951         // On windows it is not possible to create files with '<', '>' or '?'
952         // in the name.
953         static string const keep = "abcdefghijklmnopqrstuvwxyz"
954                                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
955                                    "+-0123456789;=";
956         string::size_type pos = 0;
957         while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
958                 mname[pos++] = '_';
959         // Add the extension back on
960         mname = support::changeExtension(mname, getExtension(name));
961
962         // Prepend a counter to the filename. This is necessary to make
963         // the mangled name unique.
964         static int counter = 0;
965         ostringstream s;
966         s << counter++ << mname;
967         mname = s.str();
968
969         // MiKTeX's YAP (version 2.4.1803) crashes if the file name
970         // is longer than about 160 characters. MiKTeX's pdflatex
971         // is even pickier. A maximum length of 100 has been proven to work.
972         // If dir.size() > max length, all bets are off for YAP. We truncate
973         // the filename nevertheless, keeping a minimum of 10 chars.
974
975         string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
976
977         // If the mangled file name is too long, hack it to fit.
978         // We know we're guaranteed to have a unique file name because
979         // of the counter.
980         if (mname.size() > max_length) {
981                 int const half = (int(max_length) / 2) - 2;
982                 if (half > 0) {
983                         mname = mname.substr(0, half) + "___" +
984                                 mname.substr(mname.size() - half);
985                 }
986         }
987
988         mangledNames[absFileName()] = mname;
989         return mname;
990 }
991
992
993 string DocFileName::unzippedFileName() const
994 {
995         return support::unzippedFileName(absFileName());
996 }
997
998
999 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1000 {
1001         return static_cast<FileName const &>(lhs)
1002                 == static_cast<FileName const &>(rhs)
1003                 && lhs.saveAbsPath() == rhs.saveAbsPath();
1004 }
1005
1006
1007 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1008 {
1009         return !(lhs == rhs);
1010 }
1011
1012 } // namespace support
1013 } // namespace lyx