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