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