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