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