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