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