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