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