]> git.lyx.org Git - lyx.git/blob - src/support/FileName.cpp
Fix problem with python and change of PATH
[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/qstring_helpers.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 #include <boost/scoped_array.hpp>
35
36 #include <algorithm>
37 #include <iterator>
38 #include <fstream>
39 #include <iomanip>
40 #include <map>
41 #include <sstream>
42
43 #ifdef HAVE_SYS_TYPES_H
44 # include <sys/types.h>
45 #endif
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
48 #endif
49 #ifdef HAVE_UNISTD_H
50 # include <unistd.h>
51 #endif
52 #ifdef HAVE_DIRECT_H
53 # include <direct.h>
54 #endif
55 #ifdef _WIN32
56 # include <windows.h>
57 #endif
58
59 #include <cerrno>
60 #include <fcntl.h>
61
62 // Three implementations of checksum(), depending on having mmap support or not.
63 #if defined(HAVE_MMAP) && defined(HAVE_MUNMAP)
64 #define SUM_WITH_MMAP
65 #include <sys/mman.h>
66 #endif // SUM_WITH_MMAP
67
68 using namespace std;
69 using namespace lyx::support;
70
71 // OK, this is ugly, but it is the only workaround I found to compile
72 // with gcc (any version) on a system which uses a non-GNU toolchain.
73 // The problem is that gcc uses a weak symbol for a particular
74 // instantiation and that the system linker usually does not
75 // understand those weak symbols (seen on HP-UX, tru64, AIX and
76 // others). Thus we force an explicit instanciation of this particular
77 // template (JMarc)
78 template struct boost::detail::crc_table_t<32, 0x04C11DB7, true>;
79
80 namespace lyx {
81 namespace support {
82
83 /////////////////////////////////////////////////////////////////////
84 //
85 // FileName::Private
86 //
87 /////////////////////////////////////////////////////////////////////
88
89 struct FileName::Private
90 {
91         Private() {}
92
93         Private(string const & abs_filename) : fi(toqstr(abs_filename))
94         {
95                 name = fromqstr(fi.absoluteFilePath());
96                 fi.setCaching(fi.exists() ? true : false);
97         }
98         ///
99         inline void refresh() 
100         {
101                 fi.refresh();
102         }
103
104
105         static
106         bool isFilesystemEqual(QString const & lhs, QString const & rhs)
107         {
108                 return QString::compare(lhs, rhs, os::isFilesystemCaseSensitive() ?
109                         Qt::CaseSensitive : Qt::CaseInsensitive) == 0;
110         }
111
112         /// The absolute file name in UTF-8 encoding.
113         std::string name;
114         ///
115         QFileInfo fi;
116 };
117
118 /////////////////////////////////////////////////////////////////////
119 //
120 // FileName
121 //
122 /////////////////////////////////////////////////////////////////////
123
124
125 FileName::FileName() : d(new Private)
126 {
127 }
128
129
130 FileName::FileName(string const & abs_filename)
131         : d(abs_filename.empty() ? new Private : new Private(abs_filename))
132 {
133         //LYXERR(Debug::FILES, "FileName(" << abs_filename << ')');
134         LATTEST(empty() || isAbsolute(d->name));
135 }
136
137
138 FileName::~FileName()
139 {
140         delete d;
141 }
142
143
144 FileName::FileName(FileName const & rhs) : d(new Private)
145 {
146         d->name = rhs.d->name;
147         d->fi = rhs.d->fi;
148 }
149
150
151 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
152 {
153         set(rhs, suffix);
154 }
155
156
157 FileName & FileName::operator=(FileName const & rhs)
158 {
159         if (&rhs == this)
160                 return *this;
161         d->name = rhs.d->name;
162         d->fi = rhs.d->fi;
163         return *this;
164 }
165
166
167 bool FileName::empty() const
168 {
169         return d->name.empty();
170 }
171
172
173 bool FileName::isAbsolute(string const & name)
174 {
175         QFileInfo fi(toqstr(name));
176         return fi.isAbsolute();
177 }
178
179
180 string FileName::absFileName() const
181 {
182         return d->name;
183 }
184
185
186 string FileName::realPath() const
187 {
188         return os::real_path(absFileName());
189 }
190
191
192 void FileName::set(string const & name)
193 {
194         d->fi.setFile(toqstr(name));
195         d->name = fromqstr(d->fi.absoluteFilePath());
196         //LYXERR(Debug::FILES, "FileName::set(" << name << ')');
197         LATTEST(empty() || isAbsolute(d->name));
198 }
199
200
201 void FileName::set(FileName const & rhs, string const & suffix)
202 {
203         if (!rhs.d->fi.isDir())
204                 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
205         else
206                 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
207         d->name = fromqstr(d->fi.absoluteFilePath());
208         //LYXERR(Debug::FILES, "FileName::set(" << d->name << ')');
209         LATTEST(empty() || isAbsolute(d->name));
210 }
211
212
213 void FileName::erase()
214 {
215         d->name.clear();
216         d->fi = QFileInfo();
217 }
218
219
220 bool FileName::copyTo(FileName const & name) const
221 {
222         LYXERR(Debug::FILES, "Copying " << name);
223         QFile::remove(name.d->fi.absoluteFilePath());
224         bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
225         if (!success)
226                 LYXERR0("FileName::copyTo(): Could not copy file "
227                         << *this << " to " << name);
228         return success;
229 }
230
231
232 bool FileName::renameTo(FileName const & name) const
233 {
234         bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
235         if (!success)
236                 LYXERR0("Could not rename file " << *this << " to " << name);
237         return success;
238 }
239
240
241 bool FileName::moveTo(FileName const & name) const
242 {
243         QFile::remove(name.d->fi.absoluteFilePath());
244
245         bool success = QFile::rename(d->fi.absoluteFilePath(),
246                 name.d->fi.absoluteFilePath());
247         if (!success)
248                 LYXERR0("Could not move file " << *this << " to " << name);
249         return success;
250 }
251
252
253 bool FileName::changePermission(unsigned long int mode) const
254 {
255 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
256         if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
257                 LYXERR0("File " << *this << ": cannot change permission to "
258                         << mode << ".");
259                 return false;
260         }
261 #endif
262         return true;
263 }
264
265
266 string FileName::toFilesystemEncoding() const
267 {
268         // This doesn't work on Windows for non ascii file names.
269         QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
270         return string(encoded.begin(), encoded.end());
271 }
272
273
274 string FileName::toSafeFilesystemEncoding(os::file_access how) const
275 {
276         // This will work on Windows for non ascii file names.
277         QString const safe_path =
278                 toqstr(os::safe_internal_path(absFileName(), how));
279         QByteArray const encoded = QFile::encodeName(safe_path);
280         return string(encoded.begin(), encoded.end());
281 }
282
283
284 FileName FileName::fromFilesystemEncoding(string const & name)
285 {
286         QByteArray const encoded(name.c_str(), name.length());
287         return FileName(fromqstr(QFile::decodeName(encoded)));
288 }
289
290
291 bool FileName::exists() const
292 {
293         return !empty() && d->fi.exists();
294 }
295
296
297 bool FileName::isSymLink() const
298 {
299         return !empty() && d->fi.isSymLink();
300 }
301
302
303 bool FileName::isFileEmpty() const
304 {
305         LASSERT(!empty(), return true);
306         return d->fi.size() == 0;
307 }
308
309
310 bool FileName::isDirectory() const
311 {
312         return !empty() && d->fi.isDir();
313 }
314
315
316 bool FileName::isReadOnly() const
317 {
318         LASSERT(!empty(), return true);
319         return d->fi.isReadable() && !d->fi.isWritable();
320 }
321
322
323 bool FileName::isReadableDirectory() const
324 {
325         return isDirectory() && d->fi.isReadable();
326 }
327
328
329 string FileName::onlyFileName() const
330 {
331         return fromqstr(d->fi.fileName());
332 }
333
334
335 string FileName::onlyFileNameWithoutExt() const
336 {
337         return fromqstr(d->fi.completeBaseName());
338 }
339
340
341 string FileName::extension() const
342 {
343         return fromqstr(d->fi.suffix());
344 }
345
346
347 bool FileName::hasExtension(const string & ext)
348 {
349         return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
350 }
351
352
353 FileName FileName::onlyPath() const
354 {
355         FileName path;
356         if (empty())
357                 return path;
358         path.d->fi.setFile(d->fi.path());
359         path.d->name = fromqstr(path.d->fi.absoluteFilePath());
360         return path;
361 }
362
363
364 FileName FileName::parentPath() const
365 {
366         FileName path;
367         // return empty path for parent of root dir
368         // parent of empty path is empty too
369         if (empty() || d->fi.isRoot())
370                 return path;
371         path.d->fi.setFile(d->fi.path());
372         path.d->name = fromqstr(path.d->fi.absoluteFilePath());
373         return path;
374 }
375
376
377 bool FileName::isReadableFile() const
378 {
379         return !empty() && d->fi.isFile() && d->fi.isReadable();
380 }
381
382
383 bool FileName::isWritable() const
384 {
385         return !empty() && d->fi.isWritable();
386 }
387
388
389 bool FileName::isDirWritable() const
390 {
391         LASSERT(isDirectory(), return false);
392         QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
393         QTemporaryFile qt_tmp(tmp.absoluteFilePath());
394         if (qt_tmp.open()) {
395                 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
396                 return true;
397         }
398         LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
399         return false;
400 }
401
402
403 FileNameList FileName::dirList(string const & ext) const
404 {
405         FileNameList dirlist;
406         if (!isDirectory()) {
407                 LYXERR0("Directory '" << *this << "' does not exist!");
408                 return dirlist;
409         }
410
411         // If the directory is specified without a trailing '/', absoluteDir()
412         // would return the parent dir, so we must use absoluteFilePath() here.
413         QDir dir = d->fi.absoluteFilePath();
414
415         if (!ext.empty()) {
416                 QString filter;
417                 switch (ext[0]) {
418                 case '.': filter = "*" + toqstr(ext); break;
419                 case '*': filter = toqstr(ext); break;
420                 default: filter = "*." + toqstr(ext);
421                 }
422                 dir.setNameFilters(QStringList(filter));
423                 LYXERR(Debug::FILES, "filtering on extension "
424                         << fromqstr(filter) << " is requested.");
425         }
426
427         QFileInfoList list = dir.entryInfoList();
428         for (int i = 0; i != list.size(); ++i) {
429                 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
430                 dirlist.push_back(fi);
431                 LYXERR(Debug::FILES, "found file " << fi);
432         }
433
434         return dirlist;
435 }
436
437
438 static string createTempFile(QString const & mask)
439 {
440         // FIXME: This is not safe. QTemporaryFile creates a file in open(),
441         //        but the file is deleted when qt_tmp goes out of scope.
442         //        Therefore the next call to createTempFile() may create the
443         //        same file again. To make this safe the QTemporaryFile object
444         //        needs to be kept for the whole life time of the temp file name.
445         //        This can be achieved by using the TempFile class.
446         QTemporaryFile qt_tmp(mask + ".XXXXXXXXXXXX");
447         if (qt_tmp.open()) {
448                 string const temp_file = fromqstr(qt_tmp.fileName());
449                 LYXERR(Debug::FILES, "Temporary file `" << temp_file << "' created.");
450                 return temp_file;
451         }
452         LYXERR(Debug::FILES, "Unable to create temporary file with following template: "
453                 << qt_tmp.fileTemplate());
454         return string();
455 }
456
457
458 FileName FileName::tempName(FileName const & temp_dir, string const & mask)
459 {
460         QFileInfo tmp_fi(QDir(temp_dir.d->fi.absoluteFilePath()), toqstr(mask));
461         LYXERR(Debug::FILES, "Temporary file in " << tmp_fi.absoluteFilePath());
462         return FileName(createTempFile(tmp_fi.absoluteFilePath()));
463 }
464
465
466 FileName FileName::tempName(string const & mask)
467 {
468         return tempName(package().temp_dir(), mask);
469 }
470
471
472 FileName FileName::getcwd()
473 {
474         // return makeAbsPath("."); would create an infinite loop
475         QFileInfo fi(".");
476         return FileName(fromqstr(fi.absoluteFilePath()));
477 }
478
479
480 FileName FileName::tempPath()
481 {
482         return FileName(os::internal_path(fromqstr(QDir::tempPath())));
483 }
484
485
486 void FileName::refresh() const
487 {
488         d->refresh();
489 }
490
491
492 time_t FileName::lastModified() const
493 {
494         // QFileInfo caches information about the file. So, in case this file has
495         // been touched between the object creation and now, we refresh the file
496         // information.
497         d->refresh();
498         return d->fi.lastModified().toTime_t();
499 }
500
501
502 bool FileName::chdir() const
503 {
504         return QDir::setCurrent(d->fi.absoluteFilePath());
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         // We need to make sure that every DocFileName instance for a given
929         // filename returns the same mangled name.
930         typedef map<string, string> MangledMap;
931         static MangledMap mangledNames;
932         MangledMap::const_iterator const it = mangledNames.find(absFileName());
933         if (it != mangledNames.end())
934                 return (*it).second;
935
936         string const name = absFileName();
937         // Now the real work
938         string mname = os::internal_path(name);
939         // Remove the extension.
940         mname = support::changeExtension(name, string());
941         // The mangled name must be a valid LaTeX name.
942         // The list of characters to keep is probably over-restrictive,
943         // but it is not really a problem.
944         // Apart from non-ASCII characters, at least the following characters
945         // are forbidden: '/', '.', ' ', and ':'.
946         // On windows it is not possible to create files with '<', '>' or '?'
947         // in the name.
948         static string const keep = "abcdefghijklmnopqrstuvwxyz"
949                                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
950                                    "+-0123456789;=";
951         string::size_type pos = 0;
952         while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
953                 mname[pos++] = '_';
954         // Add the extension back on
955         mname = support::changeExtension(mname, getExtension(name));
956
957         // Prepend a counter to the filename. This is necessary to make
958         // the mangled name unique.
959         static int counter = 0;
960         ostringstream s;
961         s << counter++ << mname;
962         mname = s.str();
963
964         // MiKTeX's YAP (version 2.4.1803) crashes if the file name
965         // is longer than about 160 characters. MiKTeX's pdflatex
966         // is even pickier. A maximum length of 100 has been proven to work.
967         // If dir.size() > max length, all bets are off for YAP. We truncate
968         // the filename nevertheless, keeping a minimum of 10 chars.
969
970         string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
971
972         // If the mangled file name is too long, hack it to fit.
973         // We know we're guaranteed to have a unique file name because
974         // of the counter.
975         if (mname.size() > max_length) {
976                 int const half = (int(max_length) / 2) - 2;
977                 if (half > 0) {
978                         mname = mname.substr(0, half) + "___" +
979                                 mname.substr(mname.size() - half);
980                 }
981         }
982
983         mangledNames[absFileName()] = mname;
984         return mname;
985 }
986
987
988 string DocFileName::unzippedFileName() const
989 {
990         return support::unzippedFileName(absFileName());
991 }
992
993
994 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
995 {
996         return static_cast<FileName const &>(lhs)
997                 == static_cast<FileName const &>(rhs)
998                 && lhs.saveAbsPath() == rhs.saveAbsPath();
999 }
1000
1001
1002 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1003 {
1004         return !(lhs == rhs);
1005 }
1006
1007 } // namespace support
1008 } // namespace lyx