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