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