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