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