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