]> git.lyx.org Git - lyx.git/blob - src/support/FileName.cpp
5ba2af2524ae62eae10d5ac38a2a5bf110246b03
[lyx.git] / src / support / FileName.cpp
1 /**
2  * \file FileName.cpp
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * \author Angus Leeming
7  *
8  * Full author contact details are available in file CREDITS.
9  */
10
11 #include <config.h>
12
13 #include "support/FileName.h"
14 #include "support/FileNameList.h"
15
16 #include "support/debug.h"
17 #include "support/filetools.h"
18 #include "support/lassert.h"
19 #include "support/lstrings.h"
20 #include "support/qstring_helpers.h"
21 #include "support/os.h"
22 #include "support/Package.h"
23 #include "support/qstring_helpers.h"
24
25 #include <QDateTime>
26 #include <QDir>
27 #include <QFile>
28 #include <QFileInfo>
29 #include <QList>
30 #include <QTemporaryFile>
31 #include <QTime>
32
33 #include <boost/crc.hpp>
34 #include <boost/scoped_array.hpp>
35
36 #include <algorithm>
37 #include <iterator>
38 #include <fstream>
39 #include <iomanip>
40 #include <map>
41 #include <sstream>
42
43 #ifdef HAVE_SYS_TYPES_H
44 # include <sys/types.h>
45 #endif
46 #ifdef HAVE_SYS_STAT_H
47 # include <sys/stat.h>
48 #endif
49 #ifdef HAVE_UNISTD_H
50 # include <unistd.h>
51 #endif
52 #ifdef HAVE_DIRECT_H
53 # include <direct.h>
54 #endif
55 #ifdef _WIN32
56 # include <windows.h>
57 #endif
58
59 #include <cerrno>
60 #include <fcntl.h>
61
62 // Three implementations of checksum(), depending on having mmap support or not.
63 #if defined(HAVE_MMAP) && defined(HAVE_MUNMAP)
64 #define SUM_WITH_MMAP
65 #include <sys/mman.h>
66 #endif // SUM_WITH_MMAP
67
68 using namespace std;
69 using namespace lyx::support;
70
71 // OK, this is ugly, but it is the only workaround I found to compile
72 // with gcc (any version) on a system which uses a non-GNU toolchain.
73 // The problem is that gcc uses a weak symbol for a particular
74 // instantiation and that the system linker usually does not
75 // understand those weak symbols (seen on HP-UX, tru64, AIX and
76 // others). Thus we force an explicit instanciation of this particular
77 // template (JMarc)
78 template struct boost::detail::crc_table_t<32, 0x04C11DB7, true>;
79
80 namespace lyx {
81 namespace support {
82
83 /////////////////////////////////////////////////////////////////////
84 //
85 // FileName::Private
86 //
87 /////////////////////////////////////////////////////////////////////
88
89 struct FileName::Private
90 {
91         Private() {}
92
93         Private(string const & abs_filename) : fi(toqstr(abs_filename))
94         {
95                 name = fromqstr(fi.absoluteFilePath());
96                 fi.setCaching(fi.exists() ? true : false);
97         }
98         ///
99         inline void refresh() 
100         {
101 // There seems to be a bug in Qt >= 4.2.0 and < 4.5.0, that causes problems with
102 // QFileInfo::refresh() on *nix. So we recreate the object in that case.
103 #if defined(_WIN32) || (QT_VERSION >= 0x040500)
104                 fi.refresh();
105 #else
106                 fi = QFileInfo(fi.absoluteFilePath());
107 #endif
108         }
109
110
111         static
112         bool isFilesystemEqual(QString const & lhs, QString const & rhs)
113         {
114                 return QString::compare(lhs, rhs, os::isFilesystemCaseSensitive() ?
115                         Qt::CaseSensitive : Qt::CaseInsensitive) == 0;
116         }
117
118         /// The absolute file name in UTF-8 encoding.
119         std::string name;
120         ///
121         QFileInfo fi;
122 };
123
124 /////////////////////////////////////////////////////////////////////
125 //
126 // FileName
127 //
128 /////////////////////////////////////////////////////////////////////
129
130
131 FileName::FileName() : d(new Private)
132 {
133 }
134
135
136 FileName::FileName(string const & abs_filename)
137         : d(abs_filename.empty() ? new Private : new Private(abs_filename))
138 {
139         //LYXERR(Debug::FILES, "FileName(" << abs_filename << ')');
140         LASSERT(empty() || isAbsolute(d->name), /**/);
141 }
142
143
144 FileName::~FileName()
145 {
146         delete d;
147 }
148
149
150 FileName::FileName(FileName const & rhs) : d(new Private)
151 {
152         d->name = rhs.d->name;
153         d->fi = rhs.d->fi;
154 }
155
156
157 FileName::FileName(FileName const & rhs, string const & suffix) : d(new Private)
158 {
159         set(rhs, suffix);
160 }
161
162
163 FileName & FileName::operator=(FileName const & rhs)
164 {
165         if (&rhs == this)
166                 return *this;
167         d->name = rhs.d->name;
168         d->fi = rhs.d->fi;
169         return *this;
170 }
171
172
173 bool FileName::empty() const
174 {
175         return d->name.empty();
176 }
177
178
179 bool FileName::isAbsolute(string const & name)
180 {
181         QFileInfo fi(toqstr(name));
182         return fi.isAbsolute();
183 }
184
185
186 string FileName::absFilename() const
187 {
188         return d->name;
189 }
190
191
192 string FileName::realPath() const
193 {
194         return os::real_path(absFilename());
195 }
196
197
198 void FileName::set(string const & name)
199 {
200         d->fi.setFile(toqstr(name));
201         d->name = fromqstr(d->fi.absoluteFilePath());
202         //LYXERR(Debug::FILES, "FileName::set(" << name << ')');
203         LASSERT(empty() || isAbsolute(d->name), /**/);
204 }
205
206
207 void FileName::set(FileName const & rhs, string const & suffix)
208 {
209         if (!rhs.d->fi.isDir())
210                 d->fi.setFile(rhs.d->fi.filePath() + toqstr(suffix));
211         else
212                 d->fi.setFile(QDir(rhs.d->fi.absoluteFilePath()), toqstr(suffix));
213         d->name = fromqstr(d->fi.absoluteFilePath());
214         //LYXERR(Debug::FILES, "FileName::set(" << d->name << ')');
215         LASSERT(empty() || isAbsolute(d->name), /**/);
216 }
217
218
219 void FileName::erase()
220 {
221         d->name.clear();
222         d->fi = QFileInfo();
223 }
224
225
226 bool FileName::copyTo(FileName const & name) const
227 {
228         LYXERR(Debug::FILES, "Copying " << name);
229         QFile::remove(name.d->fi.absoluteFilePath());
230         bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
231         if (!success)
232                 LYXERR0("FileName::copyTo(): Could not copy file "
233                         << *this << " to " << name);
234         return success;
235 }
236
237
238 bool FileName::renameTo(FileName const & name) const
239 {
240         bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
241         if (!success)
242                 LYXERR0("Could not rename file " << *this << " to " << name);
243         return success;
244 }
245
246
247 bool FileName::moveTo(FileName const & name) const
248 {
249         QFile::remove(name.d->fi.absoluteFilePath());
250
251         bool success = QFile::rename(d->fi.absoluteFilePath(),
252                 name.d->fi.absoluteFilePath());
253         if (!success)
254                 LYXERR0("Could not move file " << *this << " to " << name);
255         return success;
256 }
257
258
259 bool FileName::changePermission(unsigned long int mode) const
260 {
261 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
262         if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
263                 LYXERR0("File " << *this << ": cannot change permission to "
264                         << mode << ".");
265                 return false;
266         }
267 #endif
268         return true;
269 }
270
271
272 string FileName::toFilesystemEncoding() const
273 {
274         // This doesn't work on Windows for non ascii file names.
275         QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
276         return string(encoded.begin(), encoded.end());
277 }
278
279
280 string FileName::toSafeFilesystemEncoding() const
281 {
282         // This will work on Windows for non ascii file names.
283         QString const safe_path = toqstr(os::safe_internal_path(absFilename()));
284         QByteArray const encoded = QFile::encodeName(safe_path);
285         return string(encoded.begin(), encoded.end());
286 }
287
288
289 FileName FileName::fromFilesystemEncoding(string const & name)
290 {
291         QByteArray const encoded(name.c_str(), name.length());
292         return FileName(fromqstr(QFile::decodeName(encoded)));
293 }
294
295
296 bool FileName::exists() const
297 {
298         return !empty() && d->fi.exists();
299 }
300
301
302 bool FileName::isSymLink() const
303 {
304         return !empty() && d->fi.isSymLink();
305 }
306
307
308 bool FileName::isFileEmpty() const
309 {
310         LASSERT(!empty(), return true);
311         return d->fi.size() == 0;
312 }
313
314
315 bool FileName::isDirectory() const
316 {
317         return !empty() && d->fi.isDir();
318 }
319
320
321 bool FileName::isReadOnly() const
322 {
323         LASSERT(!empty(), return true);
324         return d->fi.isReadable() && !d->fi.isWritable();
325 }
326
327
328 bool FileName::isReadableDirectory() const
329 {
330         return isDirectory() && d->fi.isReadable();
331 }
332
333
334 string FileName::onlyFileName() const
335 {
336         return fromqstr(d->fi.fileName());
337 }
338
339
340 string FileName::onlyFileNameWithoutExt() const
341 {
342         return fromqstr(d->fi.completeBaseName());
343 }
344
345
346 string FileName::extension() const
347 {
348         return fromqstr(d->fi.suffix());
349 }
350
351
352 bool FileName::hasExtension(const string & ext)
353 {
354         return Private::isFilesystemEqual(d->fi.suffix(), toqstr(ext));
355 }
356
357
358 FileName FileName::onlyPath() const
359 {
360         FileName path;
361         if (empty())
362                 return path;
363         path.d->fi.setFile(d->fi.path());
364         path.d->name = fromqstr(path.d->fi.absoluteFilePath());
365         return path;
366 }
367
368
369 bool FileName::isReadableFile() const
370 {
371         return !empty() && d->fi.isFile() && d->fi.isReadable();
372 }
373
374
375 bool FileName::isWritable() const
376 {
377         return !empty() && d->fi.isWritable();
378 }
379
380
381 bool FileName::isDirWritable() const
382 {
383         LASSERT(isDirectory(), return false);
384         QFileInfo tmp(QDir(d->fi.absoluteFilePath()), "lyxwritetest");
385         QTemporaryFile qt_tmp(tmp.absoluteFilePath());
386         if (qt_tmp.open()) {
387                 LYXERR(Debug::FILES, "Directory " << *this << " is writable");
388                 return true;
389         }
390         LYXERR(Debug::FILES, "Directory " << *this << " is not writable");
391         return false;
392 }
393
394
395 FileNameList FileName::dirList(string const & ext) const
396 {
397         FileNameList dirlist;
398         if (!isDirectory()) {
399                 LYXERR0("Directory '" << *this << "' does not exist!");
400                 return dirlist;
401         }
402
403         // If the directory is specified without a trailing '/', absoluteDir()
404         // would return the parent dir, so we must use absoluteFilePath() here.
405         QDir dir = d->fi.absoluteFilePath();
406
407         if (!ext.empty()) {
408                 QString filter;
409                 switch (ext[0]) {
410                 case '.': filter = "*" + toqstr(ext); break;
411                 case '*': filter = toqstr(ext); break;
412                 default: filter = "*." + toqstr(ext);
413                 }
414                 dir.setNameFilters(QStringList(filter));
415                 LYXERR(Debug::FILES, "filtering on extension "
416                         << fromqstr(filter) << " is requested.");
417         }
418
419         QFileInfoList list = dir.entryInfoList();
420         for (int i = 0; i != list.size(); ++i) {
421                 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
422                 dirlist.push_back(fi);
423                 LYXERR(Debug::FILES, "found file " << fi);
424         }
425
426         return dirlist;
427 }
428
429
430 static string createTempFile(QString const & mask)
431 {
432         QTemporaryFile qt_tmp(mask);
433         if (qt_tmp.open()) {
434                 string const temp_file = fromqstr(qt_tmp.fileName());
435                 LYXERR(Debug::FILES, "Temporary file `" << temp_file << "' created.");
436                 return temp_file;
437         }
438         LYXERR(Debug::FILES, "Unable to create temporary file with following template: "
439                 << qt_tmp.fileTemplate());
440         return string();
441 }
442
443
444 FileName FileName::tempName(FileName const & temp_dir, string const & mask)
445 {
446         QFileInfo tmp_fi(QDir(temp_dir.d->fi.absoluteFilePath()), toqstr(mask));
447         LYXERR(Debug::FILES, "Temporary file in " << tmp_fi.absoluteFilePath());
448         return FileName(createTempFile(tmp_fi.absoluteFilePath()));
449 }
450
451
452 FileName FileName::tempName(string const & mask)
453 {
454         return tempName(package().temp_dir(), mask);
455 }
456
457
458 FileName FileName::getcwd()
459 {
460         // return makeAbsPath("."); would create an infinite loop
461         QFileInfo fi(".");
462         return FileName(fromqstr(fi.absoluteFilePath()));
463 }
464
465
466 FileName FileName::tempPath()
467 {
468         return FileName(os::internal_path(fromqstr(QDir::tempPath())));
469 }
470
471
472 void FileName::refresh() const
473 {
474         d->refresh();
475 }
476
477
478 time_t FileName::lastModified() const
479 {
480         // QFileInfo caches information about the file. So, in case this file has
481         // been touched between the object creation and now, we refresh the file
482         // information.
483         d->refresh();
484         return d->fi.lastModified().toTime_t();
485 }
486
487
488 bool FileName::chdir() const
489 {
490         return QDir::setCurrent(d->fi.absoluteFilePath());
491 }
492
493
494 unsigned long FileName::checksum() const
495 {
496         unsigned long result = 0;
497
498         if (!exists()) {
499                 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
500                 return result;
501         }
502         // a directory may be passed here so we need to test it. (bug 3622)
503         if (isDirectory()) {
504                 LYXERR0('"' << absFilename() << "\" is a directory!");
505                 return result;
506         }
507
508         // This is used in the debug output at the end of the method.
509         static QTime t;
510         if (lyxerr.debugging(Debug::FILES))
511                 t.restart();
512
513 #if QT_VERSION >= 0x999999
514         // First version of checksum uses Qt4.4 mmap support.
515         // FIXME: This code is not ready with Qt4.4.2,
516         // see http://www.lyx.org/trac/ticket/5293
517         // FIXME: should we check if the MapExtension extension is supported?
518         // see QAbstractFileEngine::supportsExtension() and 
519         // QAbstractFileEngine::MapExtension)
520         QFile qf(fi.filePath());
521         if (!qf.open(QIODevice::ReadOnly))
522                 return result;
523         qint64 size = fi.size();
524         uchar * ubeg = qf.map(0, size);
525         uchar * uend = ubeg + size;
526         boost::crc_32_type ucrc;
527         ucrc.process_block(ubeg, uend);
528         qf.unmap(ubeg);
529         qf.close();
530         result = ucrc.checksum();
531
532 #else // QT_VERSION
533
534         string const encoded = toSafeFilesystemEncoding();
535         char const * file = encoded.c_str();
536
537  #ifdef SUM_WITH_MMAP
538         //LYXERR(Debug::FILES, "using mmap (lightning fast)");
539
540         int fd = open(file, O_RDONLY);
541         if (!fd)
542                 return result;
543
544         struct stat info;
545         fstat(fd, &info);
546
547         void * mm = mmap(0, info.st_size, PROT_READ,
548                          MAP_PRIVATE, fd, 0);
549         // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
550         if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
551                 close(fd);
552                 return result;
553         }
554
555         char * beg = static_cast<char*>(mm);
556         char * end = beg + info.st_size;
557
558         boost::crc_32_type crc;
559         crc.process_block(beg, end);
560         result = crc.checksum();
561
562         munmap(mm, info.st_size);
563         close(fd);
564
565  #else // no SUM_WITH_MMAP
566
567         //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
568         ifstream ifs(file, ios_base::in | ios_base::binary);
569         if (!ifs)
570                 return result;
571
572         istreambuf_iterator<char> beg(ifs);
573         istreambuf_iterator<char> end;
574         boost::crc_32_type crc;
575         crc = for_each(beg, end, crc);
576         result = crc.checksum();
577
578  #endif // SUM_WITH_MMAP
579 #endif // QT_VERSION
580
581         LYXERR(Debug::FILES, "Checksumming \"" << absFilename() << "\" "
582                 << result << " lasted " << t.elapsed() << " ms.");
583         return result;
584 }
585
586
587 bool FileName::removeFile() const
588 {
589         bool const success = QFile::remove(d->fi.absoluteFilePath());
590         d->refresh();
591         if (!success && exists())
592                 LYXERR0("Could not delete file " << *this);
593         return success;
594 }
595
596
597 static bool rmdir(QFileInfo const & fi)
598 {
599         QDir dir(fi.absoluteFilePath());
600         QFileInfoList list = dir.entryInfoList();
601         bool success = true;
602         for (int i = 0; i != list.size(); ++i) {
603                 if (list.at(i).fileName() == ".")
604                         continue;
605                 if (list.at(i).fileName() == "..")
606                         continue;
607                 bool removed;
608                 if (list.at(i).isDir()) {
609                         LYXERR(Debug::FILES, "Removing dir " 
610                                 << fromqstr(list.at(i).absoluteFilePath()));
611                         removed = rmdir(list.at(i));
612                 }
613                 else {
614                         LYXERR(Debug::FILES, "Removing file " 
615                                 << fromqstr(list.at(i).absoluteFilePath()));
616                         removed = dir.remove(list.at(i).fileName());
617                 }
618                 if (!removed) {
619                         success = false;
620                         LYXERR0("Could not delete "
621                                 << fromqstr(list.at(i).absoluteFilePath()));
622                 }
623         } 
624         QDir parent = fi.absolutePath();
625         success &= parent.rmdir(fi.fileName());
626         return success;
627 }
628
629
630 bool FileName::destroyDirectory() const
631 {
632         bool const success = rmdir(d->fi);
633         if (!success)
634                 LYXERR0("Could not delete " << *this);
635
636         return success;
637 }
638
639
640 // Only used in non Win32 platforms
641 static int mymkdir(char const * pathname, unsigned long int mode)
642 {
643         // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
644 #if HAVE_MKDIR
645 # if MKDIR_TAKES_ONE_ARG
646         // MinGW32
647         return ::mkdir(pathname);
648         // FIXME: "Permissions of created directories are ignored on this system."
649 # else
650         // POSIX
651         return ::mkdir(pathname, mode_t(mode));
652 # endif
653 #elif defined(_WIN32)
654         // plain Windows 32
655         return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
656         // FIXME: "Permissions of created directories are ignored on this system."
657 #elif HAVE__MKDIR
658         return ::_mkdir(pathname);
659         // FIXME: "Permissions of created directories are ignored on this system."
660 #else
661 #   error "Don't know how to create a directory on this system."
662 #endif
663
664 }
665
666
667 bool FileName::createDirectory(int permission) const
668 {
669         LASSERT(!empty(), return false);
670 #ifdef Q_OS_WIN32
671         // FIXME: "Permissions of created directories are ignored on this system."
672         return createPath();
673 #else
674         return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
675 #endif
676 }
677
678
679 bool FileName::createPath() const
680 {
681         LASSERT(!empty(), return false);
682         LYXERR(Debug::FILES, "creating path '" << *this << "'.");
683         if (isDirectory())
684                 return false;
685
686         QDir dir;
687         bool success = dir.mkpath(d->fi.absoluteFilePath());
688         if (!success)
689                 LYXERR0("Cannot create path '" << *this << "'!");
690         return success;
691 }
692
693
694 docstring const FileName::absoluteFilePath() const
695 {
696         return qstring_to_ucs4(d->fi.absoluteFilePath());
697 }
698
699
700 docstring FileName::displayName(int threshold) const
701 {
702         return makeDisplayPath(absFilename(), threshold);
703 }
704
705
706 docstring FileName::fileContents(string const & encoding) const
707 {
708         if (!isReadableFile()) {
709                 LYXERR0("File '" << *this << "' is not redable!");
710                 return docstring();
711         }
712
713         QFile file(d->fi.absoluteFilePath());
714         if (!file.open(QIODevice::ReadOnly)) {
715                 LYXERR0("File '" << *this
716                         << "' could not be opened in read only mode!");
717                 return docstring();
718         }
719         QByteArray contents = file.readAll();
720         file.close();
721
722         if (contents.isEmpty()) {
723                 LYXERR(Debug::FILES, "File '" << *this
724                         << "' is either empty or some error happened while reading it.");
725                 return docstring();
726         }
727
728         QString s;
729         if (encoding.empty() || encoding == "UTF-8")
730                 s = QString::fromUtf8(contents.data());
731         else if (encoding == "ascii")
732                 s = QString::fromAscii(contents.data());
733         else if (encoding == "local8bit")
734                 s = QString::fromLocal8Bit(contents.data());
735         else if (encoding == "latin1")
736                 s = QString::fromLatin1(contents.data());
737
738         return qstring_to_ucs4(s);
739 }
740
741
742 void FileName::changeExtension(string const & extension)
743 {
744         // FIXME: use Qt native methods...
745         string const oldname = absFilename();
746         string::size_type const last_slash = oldname.rfind('/');
747         string::size_type last_dot = oldname.rfind('.');
748         if (last_dot < last_slash && last_slash != string::npos)
749                 last_dot = string::npos;
750
751         string ext;
752         // Make sure the extension starts with a dot
753         if (!extension.empty() && extension[0] != '.')
754                 ext= '.' + extension;
755         else
756                 ext = extension;
757
758         set(oldname.substr(0, last_dot) + ext);
759 }
760
761
762 string FileName::guessFormatFromContents() const
763 {
764         // the different filetypes and what they contain in one of the first lines
765         // (dots are any characters).           (Herbert 20020131)
766         // AGR  Grace...
767         // BMP  BM...
768         // EPS  %!PS-Adobe-3.0 EPSF...
769         // FIG  #FIG...
770         // FITS ...BITPIX...
771         // GIF  GIF...
772         // JPG  JFIF
773         // PDF  %PDF-...
774         // PNG  .PNG...
775         // PBM  P1... or P4     (B/W)
776         // PGM  P2... or P5     (Grayscale)
777         // PPM  P3... or P6     (color)
778         // PS   %!PS-Adobe-2.0 or 1.0,  no "EPSF"!
779         // SGI  \001\332...     (decimal 474)
780         // TGIF %TGIF...
781         // TIFF II... or MM...
782         // XBM  ..._bits[]...
783         // XPM  /* XPM */    sometimes missing (f.ex. tgif-export)
784         //      ...static char *...
785         // XWD  \000\000\000\151        (0x00006900) decimal 105
786         //
787         // GZIP \037\213        http://www.ietf.org/rfc/rfc1952.txt
788         // ZIP  PK...                   http://www.halyava.ru/document/ind_arch.htm
789         // Z    \037\235                UNIX compress
790
791         // paranoia check
792         if (empty() || !isReadableFile())
793                 return string();
794
795         ifstream ifs(toFilesystemEncoding().c_str());
796         if (!ifs)
797                 // Couldn't open file...
798                 return string();
799
800         // gnuzip
801         static string const gzipStamp = "\037\213";
802
803         // PKZIP
804         static string const zipStamp = "PK";
805
806         // compress
807         static string const compressStamp = "\037\235";
808
809         // Maximum strings to read
810         int const max_count = 50;
811         int count = 0;
812
813         string str;
814         string format;
815         bool firstLine = true;
816         while ((count++ < max_count) && format.empty()) {
817                 if (ifs.eof()) {
818                         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
819                                 << "\tFile type not recognised before EOF!");
820                         break;
821                 }
822
823                 getline(ifs, str);
824                 string const stamp = str.substr(0, 2);
825                 if (firstLine && str.size() >= 2) {
826                         // at first we check for a zipped file, because this
827                         // information is saved in the first bytes of the file!
828                         // also some graphic formats which save the information
829                         // in the first line, too.
830                         if (prefixIs(str, gzipStamp)) {
831                                 format =  "gzip";
832
833                         } else if (stamp == zipStamp) {
834                                 format =  "zip";
835
836                         } else if (stamp == compressStamp) {
837                                 format =  "compress";
838
839                         // the graphics part
840                         } else if (stamp == "BM") {
841                                 format =  "bmp";
842
843                         } else if (stamp == "\001\332") {
844                                 format =  "sgi";
845
846                         // PBM family
847                         // Don't need to use str.at(0), str.at(1) because
848                         // we already know that str.size() >= 2
849                         } else if (str[0] == 'P') {
850                                 switch (str[1]) {
851                                 case '1':
852                                 case '4':
853                                         format =  "pbm";
854                                     break;
855                                 case '2':
856                                 case '5':
857                                         format =  "pgm";
858                                     break;
859                                 case '3':
860                                 case '6':
861                                         format =  "ppm";
862                                 }
863                                 break;
864
865                         } else if ((stamp == "II") || (stamp == "MM")) {
866                                 format =  "tiff";
867
868                         } else if (prefixIs(str,"%TGIF")) {
869                                 format =  "tgif";
870
871                         } else if (prefixIs(str,"#FIG")) {
872                                 format =  "fig";
873
874                         } else if (prefixIs(str,"GIF")) {
875                                 format =  "gif";
876
877                         } else if (str.size() > 3) {
878                                 int const c = ((str[0] << 24) & (str[1] << 16) &
879                                                (str[2] << 8)  & str[3]);
880                                 if (c == 105) {
881                                         format =  "xwd";
882                                 }
883                         }
884
885                         firstLine = false;
886                 }
887
888                 if (!format.empty())
889                     break;
890                 else if (contains(str,"EPSF"))
891                         // dummy, if we have wrong file description like
892                         // %!PS-Adobe-2.0EPSF"
893                         format = "eps";
894
895                 else if (contains(str, "Grace"))
896                         format = "agr";
897
898                 else if (contains(str, "JFIF"))
899                         format = "jpg";
900
901                 else if (contains(str, "%PDF"))
902                         format = "pdf";
903
904                 else if (contains(str, "PNG"))
905                         format = "png";
906
907                 else if (contains(str, "%!PS-Adobe")) {
908                         // eps or ps
909                         ifs >> str;
910                         if (contains(str,"EPSF"))
911                                 format = "eps";
912                         else
913                             format = "ps";
914                 }
915
916                 else if (contains(str, "_bits[]"))
917                         format = "xbm";
918
919                 else if (contains(str, "XPM") || contains(str, "static char *"))
920                         format = "xpm";
921
922                 else if (contains(str, "BITPIX"))
923                         format = "fits";
924         }
925
926         // Dia knows also compressed form
927         if ((format == "gzip") && (!compare_ascii_no_case(extension(), "dia")))
928                 format="dia";
929
930         if (!format.empty()) {
931                 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
932                 return format;
933         }
934
935         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
936                 << "\tCouldn't find a known format!");
937         return string();
938 }
939
940
941 bool FileName::isZippedFile() const
942 {
943         string const type = guessFormatFromContents();
944         return contains("gzip zip compress", type) && !type.empty();
945 }
946
947
948 docstring const FileName::relPath(string const & path) const
949 {
950         // FIXME UNICODE
951         return makeRelPath(absoluteFilePath(), from_utf8(path));
952 }
953
954
955 // Note: According to Qt, QFileInfo::operator== is undefined when
956 // both files do not exist (Qt4.5 gives true for all non-existent
957 // files, while Qt4.4 compares the filenames).
958 // see:
959 // http://www.qtsoftware.com/developer/task-tracker/
960 //   index_html?id=248471&method=entry.
961 bool equivalent(FileName const & l, FileName const & r)
962 {
963         // FIXME: In future use Qt.
964         // Qt 4.4: We need to solve this warning from Qt documentation:
965         // * Long and short file names that refer to the same file on Windows are
966         //   treated as if they referred to different files.
967         // This is supposed to be fixed for Qt5.
968         FileName const lhs(os::internal_path(l.absFilename()));
969         FileName const rhs(os::internal_path(r.absFilename()));
970
971         if (lhs.empty())
972                 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
973                 return rhs.empty();
974
975         if (rhs.empty())
976                 // Avoid unnecessary checks below.
977                 return false;
978
979         lhs.d->refresh();
980         rhs.d->refresh();
981
982         if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
983                 // Qt already checks if the filesystem is case sensitive or not.
984                 // see note above why the extra check with fileName is needed.
985                 return lhs.d->fi == rhs.d->fi
986                         && lhs.d->fi.fileName() == rhs.d->fi.fileName();
987         }
988
989         // FIXME: When/if QFileInfo support symlink comparison, remove this code.
990         QFileInfo fi1(lhs.d->fi);
991         if (fi1.isSymLink())
992                 fi1 = QFileInfo(fi1.symLinkTarget());
993         QFileInfo fi2(rhs.d->fi);
994         if (fi2.isSymLink())
995                 fi2 = QFileInfo(fi2.symLinkTarget());
996         // see note above why the extra check with fileName is needed.
997         return fi1 == fi2 && fi1.fileName() == fi2.fileName();
998 }
999
1000
1001 bool operator==(FileName const & lhs, FileName const & rhs)
1002 {
1003         return os::isFilesystemCaseSensitive()
1004                 ? lhs.absFilename() == rhs.absFilename()
1005                 : !QString::compare(toqstr(lhs.absFilename()),
1006                                 toqstr(rhs.absFilename()), Qt::CaseInsensitive);
1007 }
1008
1009
1010 bool operator!=(FileName const & lhs, FileName const & rhs)
1011 {
1012         return !(operator==(lhs, rhs));
1013 }
1014
1015
1016 bool operator<(FileName const & lhs, FileName const & rhs)
1017 {
1018         return lhs.absFilename() < rhs.absFilename();
1019 }
1020
1021
1022 bool operator>(FileName const & lhs, FileName const & rhs)
1023 {
1024         return lhs.absFilename() > rhs.absFilename();
1025 }
1026
1027
1028 ostream & operator<<(ostream & os, FileName const & filename)
1029 {
1030         return os << filename.absFilename();
1031 }
1032
1033
1034 /////////////////////////////////////////////////////////////////////
1035 //
1036 // DocFileName
1037 //
1038 /////////////////////////////////////////////////////////////////////
1039
1040
1041 DocFileName::DocFileName()
1042         : save_abs_path_(true)
1043 {}
1044
1045
1046 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
1047         : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
1048 {}
1049
1050
1051 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
1052         : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
1053 {}
1054
1055
1056 void DocFileName::set(string const & name, string const & buffer_path)
1057 {
1058         save_abs_path_ = isAbsolute(name);
1059         if (save_abs_path_)
1060                 FileName::set(name);
1061         else
1062                 FileName::set(makeAbsPath(name, buffer_path).absFilename());
1063         zipped_valid_ = false;
1064 }
1065
1066
1067 void DocFileName::erase()
1068 {
1069         FileName::erase();
1070         zipped_valid_ = false;
1071 }
1072
1073
1074 string DocFileName::relFilename(string const & path) const
1075 {
1076         // FIXME UNICODE
1077         return to_utf8(relPath(path));
1078 }
1079
1080
1081 string DocFileName::outputFilename(string const & path) const
1082 {
1083         return save_abs_path_ ? absFilename() : relFilename(path);
1084 }
1085
1086
1087 string DocFileName::mangledFilename(string const & dir) const
1088 {
1089         // We need to make sure that every DocFileName instance for a given
1090         // filename returns the same mangled name.
1091         typedef map<string, string> MangledMap;
1092         static MangledMap mangledNames;
1093         MangledMap::const_iterator const it = mangledNames.find(absFilename());
1094         if (it != mangledNames.end())
1095                 return (*it).second;
1096
1097         string const name = absFilename();
1098         // Now the real work
1099         string mname = os::internal_path(name);
1100         // Remove the extension.
1101         mname = support::changeExtension(name, string());
1102         // The mangled name must be a valid LaTeX name.
1103         // The list of characters to keep is probably over-restrictive,
1104         // but it is not really a problem.
1105         // Apart from non-ASCII characters, at least the following characters
1106         // are forbidden: '/', '.', ' ', and ':'.
1107         // On windows it is not possible to create files with '<', '>' or '?'
1108         // in the name.
1109         static string const keep = "abcdefghijklmnopqrstuvwxyz"
1110                                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1111                                    "+,-0123456789;=";
1112         string::size_type pos = 0;
1113         while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
1114                 mname[pos++] = '_';
1115         // Add the extension back on
1116         mname = support::changeExtension(mname, getExtension(name));
1117
1118         // Prepend a counter to the filename. This is necessary to make
1119         // the mangled name unique.
1120         static int counter = 0;
1121         ostringstream s;
1122         s << counter++ << mname;
1123         mname = s.str();
1124
1125         // MiKTeX's YAP (version 2.4.1803) crashes if the file name
1126         // is longer than about 160 characters. MiKTeX's pdflatex
1127         // is even pickier. A maximum length of 100 has been proven to work.
1128         // If dir.size() > max length, all bets are off for YAP. We truncate
1129         // the filename nevertheless, keeping a minimum of 10 chars.
1130
1131         string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
1132
1133         // If the mangled file name is too long, hack it to fit.
1134         // We know we're guaranteed to have a unique file name because
1135         // of the counter.
1136         if (mname.size() > max_length) {
1137                 int const half = (int(max_length) / 2) - 2;
1138                 if (half > 0) {
1139                         mname = mname.substr(0, half) + "___" +
1140                                 mname.substr(mname.size() - half);
1141                 }
1142         }
1143
1144         mangledNames[absFilename()] = mname;
1145         return mname;
1146 }
1147
1148
1149 bool DocFileName::isZipped() const
1150 {
1151         if (!zipped_valid_) {
1152                 zipped_ = isZippedFile();
1153                 zipped_valid_ = true;
1154         }
1155         return zipped_;
1156 }
1157
1158
1159 string DocFileName::unzippedFilename() const
1160 {
1161         return unzippedFileName(absFilename());
1162 }
1163
1164
1165 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1166 {
1167         return static_cast<FileName const &>(lhs)
1168                 == static_cast<FileName const &>(rhs)
1169                 && lhs.saveAbsPath() == rhs.saveAbsPath();
1170 }
1171
1172
1173 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1174 {
1175         return !(lhs == rhs);
1176 }
1177
1178 } // namespace support
1179 } // namespace lyx