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