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