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