]> git.lyx.org Git - features.git/blob - src/support/FileName.cpp
Improve LaTeX format detection
[features.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/qstring_helpers.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         LASSERT(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         LASSERT(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         LASSERT(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) const
221 {
222         LYXERR(Debug::FILES, "Copying " << name);
223         QFile::remove(name.d->fi.absoluteFilePath());
224         bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
225         if (!success)
226                 LYXERR0("FileName::copyTo(): Could not copy file "
227                         << *this << " to " << name);
228         return success;
229 }
230
231
232 bool FileName::renameTo(FileName const & name) const
233 {
234         bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
235         if (!success)
236                 LYXERR0("Could not rename file " << *this << " to " << name);
237         return success;
238 }
239
240
241 bool FileName::moveTo(FileName const & name) const
242 {
243         QFile::remove(name.d->fi.absoluteFilePath());
244
245         bool success = QFile::rename(d->fi.absoluteFilePath(),
246                 name.d->fi.absoluteFilePath());
247         if (!success)
248                 LYXERR0("Could not move file " << *this << " to " << name);
249         return success;
250 }
251
252
253 bool FileName::changePermission(unsigned long int mode) const
254 {
255 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
256         if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
257                 LYXERR0("File " << *this << ": cannot change permission to "
258                         << mode << ".");
259                 return false;
260         }
261 #endif
262         return true;
263 }
264
265
266 string FileName::toFilesystemEncoding() const
267 {
268         // This doesn't work on Windows for non ascii file names.
269         QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
270         return string(encoded.begin(), encoded.end());
271 }
272
273
274 string FileName::toSafeFilesystemEncoding(os::file_access how) const
275 {
276         // This will work on Windows for non ascii file names.
277         QString const safe_path =
278                 toqstr(os::safe_internal_path(absFileName(), how));
279         QByteArray const encoded = QFile::encodeName(safe_path);
280         return string(encoded.begin(), encoded.end());
281 }
282
283
284 FileName FileName::fromFilesystemEncoding(string const & name)
285 {
286         QByteArray const encoded(name.c_str(), name.length());
287         return FileName(fromqstr(QFile::decodeName(encoded)));
288 }
289
290
291 bool FileName::exists() const
292 {
293         return !empty() && d->fi.exists();
294 }
295
296
297 bool FileName::isSymLink() const
298 {
299         return !empty() && d->fi.isSymLink();
300 }
301
302
303 bool FileName::isFileEmpty() const
304 {
305         LASSERT(!empty(), return true);
306         return d->fi.size() == 0;
307 }
308
309
310 bool FileName::isDirectory() const
311 {
312         return !empty() && d->fi.isDir();
313 }
314
315
316 bool FileName::isReadOnly() const
317 {
318         LASSERT(!empty(), return true);
319         return d->fi.isReadable() && !d->fi.isWritable();
320 }
321
322
323 bool FileName::isReadableDirectory() const
324 {
325         return isDirectory() && d->fi.isReadable();
326 }
327
328
329 string FileName::onlyFileName() const
330 {
331         return fromqstr(d->fi.fileName());
332 }
333
334
335 string FileName::onlyFileNameWithoutExt() const
336 {
337         return fromqstr(d->fi.completeBaseName());
338 }
339
340
341 string FileName::extension() const
342 {
343         return fromqstr(d->fi.suffix());
344 }
345
346
347 bool FileName::hasExtension(const string & ext)
348 {
349         return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
350 }
351
352
353 FileName FileName::onlyPath() const
354 {
355         FileName path;
356         if (empty())
357                 return path;
358         path.d->fi.setFile(d->fi.path());
359         path.d->name = fromqstr(path.d->fi.absoluteFilePath());
360         return path;
361 }
362
363
364 FileName FileName::parentPath() const
365 {
366         FileName path;
367         // return empty path for parent of root dir
368         // parent of empty path is empty too
369         if (empty() || d->fi.isRoot())
370                 return path;
371         path.d->fi.setFile(d->fi.path());
372         path.d->name = fromqstr(path.d->fi.absoluteFilePath());
373         return path;
374 }
375
376
377 bool FileName::isReadableFile() const
378 {
379         return !empty() && d->fi.isFile() && d->fi.isReadable();
380 }
381
382
383 bool FileName::isWritable() const
384 {
385         return !empty() && d->fi.isWritable();
386 }
387
388
389 bool FileName::isDirWritable() const
390 {
391         LASSERT(isDirectory(), return false);
392         QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
393         QTemporaryFile qt_tmp(tmp.absoluteFilePath());
394         if (qt_tmp.open()) {
395                 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
396                 return true;
397         }
398         LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
399         return false;
400 }
401
402
403 FileNameList FileName::dirList(string const & ext) const
404 {
405         FileNameList dirlist;
406         if (!isDirectory()) {
407                 LYXERR0("Directory '" << *this << "' does not exist!");
408                 return dirlist;
409         }
410
411         // If the directory is specified without a trailing '/', absoluteDir()
412         // would return the parent dir, so we must use absoluteFilePath() here.
413         QDir dir = d->fi.absoluteFilePath();
414
415         if (!ext.empty()) {
416                 QString filter;
417                 switch (ext[0]) {
418                 case '.': filter = "*" + toqstr(ext); break;
419                 case '*': filter = toqstr(ext); break;
420                 default: filter = "*." + toqstr(ext);
421                 }
422                 dir.setNameFilters(QStringList(filter));
423                 LYXERR(Debug::FILES, "filtering on extension "
424                         << fromqstr(filter) << " is requested.");
425         }
426
427         QFileInfoList list = dir.entryInfoList();
428         for (int i = 0; i != list.size(); ++i) {
429                 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
430                 dirlist.push_back(fi);
431                 LYXERR(Debug::FILES, "found file " << fi);
432         }
433
434         return dirlist;
435 }
436
437
438 static string createTempFile(QString const & mask)
439 {
440         // FIXME: This is not safe. QTemporaryFile creates a file in open(),
441         //        but the file is deleted when qt_tmp goes out of scope.
442         //        Therefore the next call to createTempFile() may create the
443         //        same file again. To make this safe the QTemporaryFile object
444         //        needs to be kept for the whole life time of the temp file name.
445         QTemporaryFile qt_tmp(mask);
446         if (qt_tmp.open()) {
447                 string const temp_file = fromqstr(qt_tmp.fileName());
448                 LYXERR(Debug::FILES, "Temporary file `" << temp_file << "' created.");
449                 return temp_file;
450         }
451         LYXERR(Debug::FILES, "Unable to create temporary file with following template: "
452                 << qt_tmp.fileTemplate());
453         return string();
454 }
455
456
457 FileName FileName::tempName(FileName const & temp_dir, string const & mask)
458 {
459         QFileInfo tmp_fi(QDir(temp_dir.d->fi.absoluteFilePath()), toqstr(mask));
460         LYXERR(Debug::FILES, "Temporary file in " << tmp_fi.absoluteFilePath());
461         return FileName(createTempFile(tmp_fi.absoluteFilePath()));
462 }
463
464
465 FileName FileName::tempName(string const & mask)
466 {
467         return tempName(package().temp_dir(), mask);
468 }
469
470
471 FileName FileName::getcwd()
472 {
473         // return makeAbsPath("."); would create an infinite loop
474         QFileInfo fi(".");
475         return FileName(fromqstr(fi.absoluteFilePath()));
476 }
477
478
479 FileName FileName::tempPath()
480 {
481         return FileName(os::internal_path(fromqstr(QDir::tempPath())));
482 }
483
484
485 void FileName::refresh() const
486 {
487         d->refresh();
488 }
489
490
491 time_t FileName::lastModified() const
492 {
493         // QFileInfo caches information about the file. So, in case this file has
494         // been touched between the object creation and now, we refresh the file
495         // information.
496         d->refresh();
497         return d->fi.lastModified().toTime_t();
498 }
499
500
501 bool FileName::chdir() const
502 {
503         return QDir::setCurrent(d->fi.absoluteFilePath());
504 }
505
506
507 unsigned long checksum_ifstream_fallback(char const * file)
508 {
509         unsigned long result = 0;
510         //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
511         ifstream ifs(file, ios_base::in | ios_base::binary);
512         if (!ifs)
513                 return result;
514
515         istreambuf_iterator<char> beg(ifs);
516         istreambuf_iterator<char> end;
517         boost::crc_32_type crc;
518         crc = for_each(beg, end, crc);
519         result = crc.checksum();
520         return result;
521 }
522
523 unsigned long FileName::checksum() const
524 {
525         unsigned long result = 0;
526
527         if (!exists()) {
528                 //LYXERR0("File \"" << absFileName() << "\" does not exist!");
529                 return result;
530         }
531         // a directory may be passed here so we need to test it. (bug 3622)
532         if (isDirectory()) {
533                 LYXERR0('"' << absFileName() << "\" is a directory!");
534                 return result;
535         }
536
537         // This is used in the debug output at the end of the method.
538         static QTime t;
539         if (lyxerr.debugging(Debug::FILES))
540                 t.restart();
541
542 #if QT_VERSION >= 0x999999
543         // First version of checksum uses Qt4.4 mmap support.
544         // FIXME: This code is not ready with Qt4.4.2,
545         // see http://www.lyx.org/trac/ticket/5293
546         // FIXME: should we check if the MapExtension extension is supported?
547         // see QAbstractFileEngine::supportsExtension() and 
548         // QAbstractFileEngine::MapExtension)
549         QFile qf(fi.filePath());
550         if (!qf.open(QIODevice::ReadOnly))
551                 return result;
552         qint64 size = fi.size();
553         uchar * ubeg = qf.map(0, size);
554         uchar * uend = ubeg + size;
555         boost::crc_32_type ucrc;
556         ucrc.process_block(ubeg, uend);
557         qf.unmap(ubeg);
558         qf.close();
559         result = ucrc.checksum();
560
561 #else // QT_VERSION
562
563         string const encoded = toSafeFilesystemEncoding();
564         char const * file = encoded.c_str();
565
566  #ifdef SUM_WITH_MMAP
567         //LYXERR(Debug::FILES, "using mmap (lightning fast)");
568
569         int fd = open(file, O_RDONLY);
570         if (!fd)
571                 return result;
572
573         struct stat info;
574         if (fstat(fd, &info)){
575                 // fstat fails on samba shares (bug 5891)
576                 close(fd);
577                 return checksum_ifstream_fallback(file);
578         }
579
580         void * mm = mmap(0, info.st_size, PROT_READ,
581                          MAP_PRIVATE, fd, 0);
582         // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
583         if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
584                 close(fd);
585                 return result;
586         }
587
588         char * beg = static_cast<char*>(mm);
589         char * end = beg + info.st_size;
590
591         boost::crc_32_type crc;
592         crc.process_block(beg, end);
593         result = crc.checksum();
594
595         munmap(mm, info.st_size);
596         close(fd);
597
598  #else // no SUM_WITH_MMAP
599         result = checksum_ifstream_fallback(file);
600  #endif // SUM_WITH_MMAP
601 #endif // QT_VERSION
602
603         LYXERR(Debug::FILES, "Checksumming \"" << absFileName() << "\" "
604                 << result << " lasted " << t.elapsed() << " ms.");
605         return result;
606 }
607
608
609 bool FileName::removeFile() const
610 {
611         bool const success = QFile::remove(d->fi.absoluteFilePath());
612         d->refresh();
613         if (!success && exists())
614                 LYXERR0("Could not delete file " << *this);
615         return success;
616 }
617
618
619 static bool rmdir(QFileInfo const & fi)
620 {
621         QDir dir(fi.absoluteFilePath());
622         QFileInfoList list = dir.entryInfoList();
623         bool success = true;
624         for (int i = 0; i != list.size(); ++i) {
625                 if (list.at(i).fileName() == ".")
626                         continue;
627                 if (list.at(i).fileName() == "..")
628                         continue;
629                 bool removed;
630                 if (list.at(i).isDir()) {
631                         LYXERR(Debug::FILES, "Removing dir " 
632                                 << fromqstr(list.at(i).absoluteFilePath()));
633                         removed = rmdir(list.at(i));
634                 }
635                 else {
636                         LYXERR(Debug::FILES, "Removing file " 
637                                 << fromqstr(list.at(i).absoluteFilePath()));
638                         removed = dir.remove(list.at(i).fileName());
639                 }
640                 if (!removed) {
641                         success = false;
642                         LYXERR0("Could not delete "
643                                 << fromqstr(list.at(i).absoluteFilePath()));
644                 }
645         } 
646         QDir parent = fi.absolutePath();
647         success &= parent.rmdir(fi.fileName());
648         return success;
649 }
650
651
652 bool FileName::destroyDirectory() const
653 {
654         bool const success = rmdir(d->fi);
655         if (!success)
656                 LYXERR0("Could not delete " << *this);
657
658         return success;
659 }
660
661
662 // Only used in non Win32 platforms
663 static int mymkdir(char const * pathname, unsigned long int mode)
664 {
665         // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
666 #if HAVE_MKDIR
667 # if MKDIR_TAKES_ONE_ARG
668         // MinGW32
669         return ::mkdir(pathname);
670         // FIXME: "Permissions of created directories are ignored on this system."
671 # else
672         // POSIX
673         return ::mkdir(pathname, mode_t(mode));
674 # endif
675 #elif defined(_WIN32)
676         // plain Windows 32
677         return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
678         // FIXME: "Permissions of created directories are ignored on this system."
679 #elif HAVE__MKDIR
680         return ::_mkdir(pathname);
681         // FIXME: "Permissions of created directories are ignored on this system."
682 #else
683 #   error "Don't know how to create a directory on this system."
684 #endif
685
686 }
687
688
689 bool FileName::createDirectory(int permission) const
690 {
691         LASSERT(!empty(), return false);
692 #ifdef Q_OS_WIN32
693         // FIXME: "Permissions of created directories are ignored on this system."
694         return createPath();
695 #else
696         return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
697 #endif
698 }
699
700
701 bool FileName::createPath() const
702 {
703         LASSERT(!empty(), return false);
704         LYXERR(Debug::FILES, "creating path '" << *this << "'.");
705         if (isDirectory())
706                 return false;
707
708         QDir dir;
709         bool success = dir.mkpath(d->fi.absoluteFilePath());
710         if (!success)
711                 LYXERR0("Cannot create path '" << *this << "'!");
712         return success;
713 }
714
715
716 docstring const FileName::absoluteFilePath() const
717 {
718         return qstring_to_ucs4(d->fi.absoluteFilePath());
719 }
720
721
722 docstring FileName::displayName(int threshold) const
723 {
724         return makeDisplayPath(absFileName(), threshold);
725 }
726
727
728 docstring FileName::fileContents(string const & encoding) const
729 {
730         if (!isReadableFile()) {
731                 LYXERR0("File '" << *this << "' is not readable!");
732                 return docstring();
733         }
734
735         QFile file(d->fi.absoluteFilePath());
736         if (!file.open(QIODevice::ReadOnly)) {
737                 LYXERR0("File '" << *this
738                         << "' could not be opened in read only mode!");
739                 return docstring();
740         }
741         QByteArray contents = file.readAll();
742         file.close();
743
744         if (contents.isEmpty()) {
745                 LYXERR(Debug::FILES, "File '" << *this
746                         << "' is either empty or some error happened while reading it.");
747                 return docstring();
748         }
749
750         QString s;
751         if (encoding.empty() || encoding == "UTF-8")
752                 s = QString::fromUtf8(contents.data());
753         else if (encoding == "ascii")
754 #if (QT_VERSION < 0x050000)
755                 s = QString::fromAscii(contents.data());
756 #else
757                 s = QString::fromLatin1(contents.data());
758 #endif
759         else if (encoding == "local8bit")
760                 s = QString::fromLocal8Bit(contents.data());
761         else if (encoding == "latin1")
762                 s = QString::fromLatin1(contents.data());
763
764         return qstring_to_ucs4(s);
765 }
766
767
768 void FileName::changeExtension(string const & extension)
769 {
770         // FIXME: use Qt native methods...
771         string const oldname = absFileName();
772         string::size_type const last_slash = oldname.rfind('/');
773         string::size_type last_dot = oldname.rfind('.');
774         if (last_dot < last_slash && last_slash != string::npos)
775                 last_dot = string::npos;
776
777         string ext;
778         // Make sure the extension starts with a dot
779         if (!extension.empty() && extension[0] != '.')
780                 ext= '.' + extension;
781         else
782                 ext = extension;
783
784         set(oldname.substr(0, last_dot) + ext);
785 }
786
787
788 docstring const FileName::relPath(string const & path) const
789 {
790         // FIXME UNICODE
791         return makeRelPath(absoluteFilePath(), from_utf8(path));
792 }
793
794
795 // Note: According to Qt, QFileInfo::operator== is undefined when
796 // both files do not exist (Qt4.5 gives true for all non-existent
797 // files, while Qt4.4 compares the filenames).
798 // see:
799 // http://www.qtsoftware.com/developer/task-tracker/
800 //   index_html?id=248471&method=entry.
801 bool equivalent(FileName const & l, FileName const & r)
802 {
803         // FIXME: In future use Qt.
804         // Qt 4.4: We need to solve this warning from Qt documentation:
805         // * Long and short file names that refer to the same file on Windows are
806         //   treated as if they referred to different files.
807         // This is supposed to be fixed for Qt5.
808         FileName const lhs(os::internal_path(l.absFileName()));
809         FileName const rhs(os::internal_path(r.absFileName()));
810
811         if (lhs.empty())
812                 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
813                 return rhs.empty();
814
815         if (rhs.empty())
816                 // Avoid unnecessary checks below.
817                 return false;
818
819         lhs.d->refresh();
820         rhs.d->refresh();
821
822         if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
823                 // Qt already checks if the filesystem is case sensitive or not.
824                 // see note above why the extra check with fileName is needed.
825                 return lhs.d->fi == rhs.d->fi
826                         && lhs.d->fi.fileName() == rhs.d->fi.fileName();
827         }
828
829         // FIXME: When/if QFileInfo support symlink comparison, remove this code.
830         QFileInfo fi1(lhs.d->fi);
831         if (fi1.isSymLink())
832                 fi1 = QFileInfo(fi1.symLinkTarget());
833         QFileInfo fi2(rhs.d->fi);
834         if (fi2.isSymLink())
835                 fi2 = QFileInfo(fi2.symLinkTarget());
836         // see note above why the extra check with fileName is needed.
837         return fi1 == fi2 && fi1.fileName() == fi2.fileName();
838 }
839
840
841 bool operator==(FileName const & lhs, FileName const & rhs)
842 {
843         return os::isFilesystemCaseSensitive()
844                 ? lhs.absFileName() == rhs.absFileName()
845                 : !QString::compare(toqstr(lhs.absFileName()),
846                                 toqstr(rhs.absFileName()), Qt::CaseInsensitive);
847 }
848
849
850 bool operator!=(FileName const & lhs, FileName const & rhs)
851 {
852         return !(operator==(lhs, rhs));
853 }
854
855
856 bool operator<(FileName const & lhs, FileName const & rhs)
857 {
858         return lhs.absFileName() < rhs.absFileName();
859 }
860
861
862 bool operator>(FileName const & lhs, FileName const & rhs)
863 {
864         return lhs.absFileName() > rhs.absFileName();
865 }
866
867
868 ostream & operator<<(ostream & os, FileName const & filename)
869 {
870         return os << filename.absFileName();
871 }
872
873
874 /////////////////////////////////////////////////////////////////////
875 //
876 // DocFileName
877 //
878 /////////////////////////////////////////////////////////////////////
879
880
881 DocFileName::DocFileName()
882         : save_abs_path_(true)
883 {}
884
885
886 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
887         : FileName(abs_filename), save_abs_path_(save_abs)
888 {}
889
890
891 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
892         : FileName(abs_filename), save_abs_path_(save_abs)
893 {}
894
895
896 void DocFileName::set(string const & name, string const & buffer_path)
897 {
898         save_abs_path_ = isAbsolute(name);
899         if (save_abs_path_)
900                 FileName::set(name);
901         else
902                 FileName::set(makeAbsPath(name, buffer_path).absFileName());
903 }
904
905
906 void DocFileName::erase()
907 {
908         FileName::erase();
909 }
910
911
912 string DocFileName::relFileName(string const & path) const
913 {
914         // FIXME UNICODE
915         return to_utf8(relPath(path));
916 }
917
918
919 string DocFileName::outputFileName(string const & path) const
920 {
921         return save_abs_path_ ? absFileName() : relFileName(path);
922 }
923
924
925 string DocFileName::mangledFileName(string const & dir) const
926 {
927         // We need to make sure that every DocFileName instance for a given
928         // filename returns the same mangled name.
929         typedef map<string, string> MangledMap;
930         static MangledMap mangledNames;
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