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