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