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