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