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