]> git.lyx.org Git - lyx.git/blob - src/support/FileName.cpp
Reorder a bit status messages, but they are still cleared at the end of LyXFunc
[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 void FileName::refresh() const
464 {
465         d->refresh();
466 }
467
468
469 time_t FileName::lastModified() const
470 {
471         // QFileInfo caches information about the file. So, in case this file has
472         // been touched between the object creation and now, we refresh the file
473         // information.
474         d->refresh();
475         return d->fi.lastModified().toTime_t();
476 }
477
478
479 bool FileName::chdir() const
480 {
481         return QDir::setCurrent(d->fi.absoluteFilePath());
482 }
483
484
485 unsigned long FileName::checksum() const
486 {
487         unsigned long result = 0;
488
489         if (!exists()) {
490                 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
491                 return result;
492         }
493         // a directory may be passed here so we need to test it. (bug 3622)
494         if (isDirectory()) {
495                 LYXERR0('"' << absFilename() << "\" is a directory!");
496                 return result;
497         }
498
499         // This is used in the debug output at the end of the method.
500         static QTime t;
501         if (lyxerr.debugging(Debug::FILES))
502                 t.restart();
503
504 #if QT_VERSION >= 0x999999
505         // First version of checksum uses Qt4.4 mmap support.
506         // FIXME: This code is not ready with Qt4.4.2,
507         // see http://www.lyx.org/trac/ticket/5293
508         // FIXME: should we check if the MapExtension extension is supported?
509         // see QAbstractFileEngine::supportsExtension() and 
510         // QAbstractFileEngine::MapExtension)
511         QFile qf(fi.filePath());
512         if (!qf.open(QIODevice::ReadOnly))
513                 return result;
514         qint64 size = fi.size();
515         uchar * ubeg = qf.map(0, size);
516         uchar * uend = ubeg + size;
517         boost::crc_32_type ucrc;
518         ucrc.process_block(ubeg, uend);
519         qf.unmap(ubeg);
520         qf.close();
521         result = ucrc.checksum();
522
523 #else // QT_VERSION
524
525         string const encoded = toFilesystemEncoding();
526         char const * file = encoded.c_str();
527
528  #ifdef SUM_WITH_MMAP
529         //LYXERR(Debug::FILES, "using mmap (lightning fast)");
530
531         int fd = open(file, O_RDONLY);
532         if (!fd)
533                 return result;
534
535         struct stat info;
536         fstat(fd, &info);
537
538         void * mm = mmap(0, info.st_size, PROT_READ,
539                          MAP_PRIVATE, fd, 0);
540         // Some platforms have the wrong type for MAP_FAILED (compaq cxx).
541         if (mm == reinterpret_cast<void*>(MAP_FAILED)) {
542                 close(fd);
543                 return result;
544         }
545
546         char * beg = static_cast<char*>(mm);
547         char * end = beg + info.st_size;
548
549         boost::crc_32_type crc;
550         crc.process_block(beg, end);
551         result = crc.checksum();
552
553         munmap(mm, info.st_size);
554         close(fd);
555
556  #else // no SUM_WITH_MMAP
557
558         //LYXERR(Debug::FILES, "lyx::sum() using istreambuf_iterator (fast)");
559         ifstream ifs(file, ios_base::in | ios_base::binary);
560         if (!ifs)
561                 return result;
562
563         istreambuf_iterator<char> beg(ifs);
564         istreambuf_iterator<char> end;
565         boost::crc_32_type crc;
566         crc = for_each(beg, end, crc);
567         result = crc.checksum();
568
569  #endif // SUM_WITH_MMAP
570 #endif // QT_VERSION
571
572         LYXERR(Debug::FILES, "Checksumming \"" << absFilename() << "\" "
573                 << result << " lasted " << t.elapsed() << " ms.");
574         return result;
575 }
576
577
578 bool FileName::removeFile() const
579 {
580         bool const success = QFile::remove(d->fi.absoluteFilePath());
581         d->refresh();
582         if (!success && exists())
583                 LYXERR0("Could not delete file " << *this);
584         return success;
585 }
586
587
588 static bool rmdir(QFileInfo const & fi)
589 {
590         QDir dir(fi.absoluteFilePath());
591         QFileInfoList list = dir.entryInfoList();
592         bool success = true;
593         for (int i = 0; i != list.size(); ++i) {
594                 if (list.at(i).fileName() == ".")
595                         continue;
596                 if (list.at(i).fileName() == "..")
597                         continue;
598                 bool removed;
599                 if (list.at(i).isDir()) {
600                         LYXERR(Debug::FILES, "Removing dir " 
601                                 << fromqstr(list.at(i).absoluteFilePath()));
602                         removed = rmdir(list.at(i));
603                 }
604                 else {
605                         LYXERR(Debug::FILES, "Removing file " 
606                                 << fromqstr(list.at(i).absoluteFilePath()));
607                         removed = dir.remove(list.at(i).fileName());
608                 }
609                 if (!removed) {
610                         success = false;
611                         LYXERR0("Could not delete "
612                                 << fromqstr(list.at(i).absoluteFilePath()));
613                 }
614         } 
615         QDir parent = fi.absolutePath();
616         success &= parent.rmdir(fi.fileName());
617         return success;
618 }
619
620
621 bool FileName::destroyDirectory() const
622 {
623         bool const success = rmdir(d->fi);
624         if (!success)
625                 LYXERR0("Could not delete " << *this);
626
627         return success;
628 }
629
630
631 // Only used in non Win32 platforms
632 static int mymkdir(char const * pathname, unsigned long int mode)
633 {
634         // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
635 #if HAVE_MKDIR
636 # if MKDIR_TAKES_ONE_ARG
637         // MinGW32
638         return ::mkdir(pathname);
639         // FIXME: "Permissions of created directories are ignored on this system."
640 # else
641         // POSIX
642         return ::mkdir(pathname, mode_t(mode));
643 # endif
644 #elif defined(_WIN32)
645         // plain Windows 32
646         return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
647         // FIXME: "Permissions of created directories are ignored on this system."
648 #elif HAVE__MKDIR
649         return ::_mkdir(pathname);
650         // FIXME: "Permissions of created directories are ignored on this system."
651 #else
652 #   error "Don't know how to create a directory on this system."
653 #endif
654
655 }
656
657
658 bool FileName::createDirectory(int permission) const
659 {
660         LASSERT(!empty(), return false);
661 #ifdef Q_OS_WIN32
662         // FIXME: "Permissions of created directories are ignored on this system."
663         return createPath();
664 #else
665         return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
666 #endif
667 }
668
669
670 bool FileName::createPath() const
671 {
672         LASSERT(!empty(), return false);
673         LYXERR(Debug::FILES, "creating path '" << *this << "'.");
674         if (isDirectory())
675                 return false;
676
677         QDir dir;
678         bool success = dir.mkpath(d->fi.absoluteFilePath());
679         if (!success)
680                 LYXERR0("Cannot create path '" << *this << "'!");
681         return success;
682 }
683
684
685 docstring const FileName::absoluteFilePath() const
686 {
687         return qstring_to_ucs4(d->fi.absoluteFilePath());
688 }
689
690
691 docstring FileName::displayName(int threshold) const
692 {
693         return makeDisplayPath(absFilename(), threshold);
694 }
695
696
697 docstring FileName::fileContents(string const & encoding) const
698 {
699         if (!isReadableFile()) {
700                 LYXERR0("File '" << *this << "' is not redable!");
701                 return docstring();
702         }
703
704         QFile file(d->fi.absoluteFilePath());
705         if (!file.open(QIODevice::ReadOnly)) {
706                 LYXERR0("File '" << *this
707                         << "' could not be opened in read only mode!");
708                 return docstring();
709         }
710         QByteArray contents = file.readAll();
711         file.close();
712
713         if (contents.isEmpty()) {
714                 LYXERR(Debug::FILES, "File '" << *this
715                         << "' is either empty or some error happened while reading it.");
716                 return docstring();
717         }
718
719         QString s;
720         if (encoding.empty() || encoding == "UTF-8")
721                 s = QString::fromUtf8(contents.data());
722         else if (encoding == "ascii")
723                 s = QString::fromAscii(contents.data());
724         else if (encoding == "local8bit")
725                 s = QString::fromLocal8Bit(contents.data());
726         else if (encoding == "latin1")
727                 s = QString::fromLatin1(contents.data());
728
729         return qstring_to_ucs4(s);
730 }
731
732
733 void FileName::changeExtension(string const & extension)
734 {
735         // FIXME: use Qt native methods...
736         string const oldname = absFilename();
737         string::size_type const last_slash = oldname.rfind('/');
738         string::size_type last_dot = oldname.rfind('.');
739         if (last_dot < last_slash && last_slash != string::npos)
740                 last_dot = string::npos;
741
742         string ext;
743         // Make sure the extension starts with a dot
744         if (!extension.empty() && extension[0] != '.')
745                 ext= '.' + extension;
746         else
747                 ext = extension;
748
749         set(oldname.substr(0, last_dot) + ext);
750 }
751
752
753 string FileName::guessFormatFromContents() const
754 {
755         // the different filetypes and what they contain in one of the first lines
756         // (dots are any characters).           (Herbert 20020131)
757         // AGR  Grace...
758         // BMP  BM...
759         // EPS  %!PS-Adobe-3.0 EPSF...
760         // FIG  #FIG...
761         // FITS ...BITPIX...
762         // GIF  GIF...
763         // JPG  JFIF
764         // PDF  %PDF-...
765         // PNG  .PNG...
766         // PBM  P1... or P4     (B/W)
767         // PGM  P2... or P5     (Grayscale)
768         // PPM  P3... or P6     (color)
769         // PS   %!PS-Adobe-2.0 or 1.0,  no "EPSF"!
770         // SGI  \001\332...     (decimal 474)
771         // TGIF %TGIF...
772         // TIFF II... or MM...
773         // XBM  ..._bits[]...
774         // XPM  /* XPM */    sometimes missing (f.ex. tgif-export)
775         //      ...static char *...
776         // XWD  \000\000\000\151        (0x00006900) decimal 105
777         //
778         // GZIP \037\213        http://www.ietf.org/rfc/rfc1952.txt
779         // ZIP  PK...                   http://www.halyava.ru/document/ind_arch.htm
780         // Z    \037\235                UNIX compress
781
782         // paranoia check
783         if (empty() || !isReadableFile())
784                 return string();
785
786         ifstream ifs(toFilesystemEncoding().c_str());
787         if (!ifs)
788                 // Couldn't open file...
789                 return string();
790
791         // gnuzip
792         static string const gzipStamp = "\037\213";
793
794         // PKZIP
795         static string const zipStamp = "PK";
796
797         // compress
798         static string const compressStamp = "\037\235";
799
800         // Maximum strings to read
801         int const max_count = 50;
802         int count = 0;
803
804         string str;
805         string format;
806         bool firstLine = true;
807         while ((count++ < max_count) && format.empty()) {
808                 if (ifs.eof()) {
809                         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
810                                 << "\tFile type not recognised before EOF!");
811                         break;
812                 }
813
814                 getline(ifs, str);
815                 string const stamp = str.substr(0, 2);
816                 if (firstLine && str.size() >= 2) {
817                         // at first we check for a zipped file, because this
818                         // information is saved in the first bytes of the file!
819                         // also some graphic formats which save the information
820                         // in the first line, too.
821                         if (prefixIs(str, gzipStamp)) {
822                                 format =  "gzip";
823
824                         } else if (stamp == zipStamp) {
825                                 format =  "zip";
826
827                         } else if (stamp == compressStamp) {
828                                 format =  "compress";
829
830                         // the graphics part
831                         } else if (stamp == "BM") {
832                                 format =  "bmp";
833
834                         } else if (stamp == "\001\332") {
835                                 format =  "sgi";
836
837                         // PBM family
838                         // Don't need to use str.at(0), str.at(1) because
839                         // we already know that str.size() >= 2
840                         } else if (str[0] == 'P') {
841                                 switch (str[1]) {
842                                 case '1':
843                                 case '4':
844                                         format =  "pbm";
845                                     break;
846                                 case '2':
847                                 case '5':
848                                         format =  "pgm";
849                                     break;
850                                 case '3':
851                                 case '6':
852                                         format =  "ppm";
853                                 }
854                                 break;
855
856                         } else if ((stamp == "II") || (stamp == "MM")) {
857                                 format =  "tiff";
858
859                         } else if (prefixIs(str,"%TGIF")) {
860                                 format =  "tgif";
861
862                         } else if (prefixIs(str,"#FIG")) {
863                                 format =  "fig";
864
865                         } else if (prefixIs(str,"GIF")) {
866                                 format =  "gif";
867
868                         } else if (str.size() > 3) {
869                                 int const c = ((str[0] << 24) & (str[1] << 16) &
870                                                (str[2] << 8)  & str[3]);
871                                 if (c == 105) {
872                                         format =  "xwd";
873                                 }
874                         }
875
876                         firstLine = false;
877                 }
878
879                 if (!format.empty())
880                     break;
881                 else if (contains(str,"EPSF"))
882                         // dummy, if we have wrong file description like
883                         // %!PS-Adobe-2.0EPSF"
884                         format = "eps";
885
886                 else if (contains(str, "Grace"))
887                         format = "agr";
888
889                 else if (contains(str, "JFIF"))
890                         format = "jpg";
891
892                 else if (contains(str, "%PDF"))
893                         format = "pdf";
894
895                 else if (contains(str, "PNG"))
896                         format = "png";
897
898                 else if (contains(str, "%!PS-Adobe")) {
899                         // eps or ps
900                         ifs >> str;
901                         if (contains(str,"EPSF"))
902                                 format = "eps";
903                         else
904                             format = "ps";
905                 }
906
907                 else if (contains(str, "_bits[]"))
908                         format = "xbm";
909
910                 else if (contains(str, "XPM") || contains(str, "static char *"))
911                         format = "xpm";
912
913                 else if (contains(str, "BITPIX"))
914                         format = "fits";
915         }
916
917         // Dia knows also compressed form
918         if ((format == "gzip") && (!compare_ascii_no_case(extension(), "dia")))
919                 format="dia";
920
921         if (!format.empty()) {
922                 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
923                 return format;
924         }
925
926         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
927                 << "\tCouldn't find a known format!");
928         return string();
929 }
930
931
932 bool FileName::isZippedFile() const
933 {
934         string const type = guessFormatFromContents();
935         return contains("gzip zip compress", type) && !type.empty();
936 }
937
938
939 docstring const FileName::relPath(string const & path) const
940 {
941         // FIXME UNICODE
942         return makeRelPath(absoluteFilePath(), from_utf8(path));
943 }
944
945
946 // Note: According to Qt, QFileInfo::operator== is undefined when
947 // both files do not exist (Qt4.5 gives true for all non-existent
948 // files, while Qt4.4 compares the filenames).
949 // see:
950 // http://www.qtsoftware.com/developer/task-tracker/
951 //   index_html?id=248471&method=entry.
952 bool equivalent(FileName const & l, FileName const & r)
953 {
954         // FIXME: In future use Qt.
955         // Qt 4.4: We need to solve this warning from Qt documentation:
956         // * Long and short file names that refer to the same file on Windows are
957         //   treated as if they referred to different files.
958         // This is supposed to be fixed for Qt5.
959         FileName const lhs(os::internal_path(l.absFilename()));
960         FileName const rhs(os::internal_path(r.absFilename()));
961
962         if (lhs.empty())
963                 // QFileInfo::operator==() returns false if the two QFileInfo are empty.
964                 return rhs.empty();
965
966         if (rhs.empty())
967                 // Avoid unnecessary checks below.
968                 return false;
969
970         lhs.d->refresh();
971         rhs.d->refresh();
972
973         if (!lhs.d->fi.isSymLink() && !rhs.d->fi.isSymLink()) {
974                 // Qt already checks if the filesystem is case sensitive or not.
975                 // see note above why the extra check with fileName is needed.
976                 return lhs.d->fi == rhs.d->fi
977                         && lhs.d->fi.fileName() == rhs.d->fi.fileName();
978         }
979
980         // FIXME: When/if QFileInfo support symlink comparison, remove this code.
981         QFileInfo fi1(lhs.d->fi);
982         if (fi1.isSymLink())
983                 fi1 = QFileInfo(fi1.symLinkTarget());
984         QFileInfo fi2(rhs.d->fi);
985         if (fi2.isSymLink())
986                 fi2 = QFileInfo(fi2.symLinkTarget());
987         // see note above why the extra check with fileName is needed.
988         return fi1 == fi2 && fi1.fileName() == fi2.fileName();
989 }
990
991
992 bool operator==(FileName const & lhs, FileName const & rhs)
993 {
994         return os::isFilesystemCaseSensitive()
995                 ? lhs.absFilename() == rhs.absFilename()
996                 : !QString::compare(toqstr(lhs.absFilename()),
997                                 toqstr(rhs.absFilename()), Qt::CaseInsensitive);
998 }
999
1000
1001 bool operator!=(FileName const & lhs, FileName const & rhs)
1002 {
1003         return !(operator==(lhs, rhs));
1004 }
1005
1006
1007 bool operator<(FileName const & lhs, FileName const & rhs)
1008 {
1009         return lhs.absFilename() < rhs.absFilename();
1010 }
1011
1012
1013 bool operator>(FileName const & lhs, FileName const & rhs)
1014 {
1015         return lhs.absFilename() > rhs.absFilename();
1016 }
1017
1018
1019 ostream & operator<<(ostream & os, FileName const & filename)
1020 {
1021         return os << filename.absFilename();
1022 }
1023
1024
1025 /////////////////////////////////////////////////////////////////////
1026 //
1027 // DocFileName
1028 //
1029 /////////////////////////////////////////////////////////////////////
1030
1031
1032 DocFileName::DocFileName()
1033         : save_abs_path_(true)
1034 {}
1035
1036
1037 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
1038         : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
1039 {}
1040
1041
1042 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
1043         : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
1044 {}
1045
1046
1047 void DocFileName::set(string const & name, string const & buffer_path)
1048 {
1049         save_abs_path_ = isAbsolute(name);
1050         if (save_abs_path_)
1051                 FileName::set(name);
1052         else
1053                 FileName::set(makeAbsPath(name, buffer_path).absFilename());
1054         zipped_valid_ = false;
1055 }
1056
1057
1058 void DocFileName::erase()
1059 {
1060         FileName::erase();
1061         zipped_valid_ = false;
1062 }
1063
1064
1065 string DocFileName::relFilename(string const & path) const
1066 {
1067         // FIXME UNICODE
1068         return to_utf8(relPath(path));
1069 }
1070
1071
1072 string DocFileName::outputFilename(string const & path) const
1073 {
1074         return save_abs_path_ ? absFilename() : relFilename(path);
1075 }
1076
1077
1078 string DocFileName::mangledFilename(string const & dir) const
1079 {
1080         // We need to make sure that every DocFileName instance for a given
1081         // filename returns the same mangled name.
1082         typedef map<string, string> MangledMap;
1083         static MangledMap mangledNames;
1084         MangledMap::const_iterator const it = mangledNames.find(absFilename());
1085         if (it != mangledNames.end())
1086                 return (*it).second;
1087
1088         string const name = absFilename();
1089         // Now the real work
1090         string mname = os::internal_path(name);
1091         // Remove the extension.
1092         mname = support::changeExtension(name, string());
1093         // The mangled name must be a valid LaTeX name.
1094         // The list of characters to keep is probably over-restrictive,
1095         // but it is not really a problem.
1096         // Apart from non-ASCII characters, at least the following characters
1097         // are forbidden: '/', '.', ' ', and ':'.
1098         // On windows it is not possible to create files with '<', '>' or '?'
1099         // in the name.
1100         static string const keep = "abcdefghijklmnopqrstuvwxyz"
1101                                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
1102                                    "+,-0123456789;=";
1103         string::size_type pos = 0;
1104         while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
1105                 mname[pos++] = '_';
1106         // Add the extension back on
1107         mname = support::changeExtension(mname, getExtension(name));
1108
1109         // Prepend a counter to the filename. This is necessary to make
1110         // the mangled name unique.
1111         static int counter = 0;
1112         ostringstream s;
1113         s << counter++ << mname;
1114         mname = s.str();
1115
1116         // MiKTeX's YAP (version 2.4.1803) crashes if the file name
1117         // is longer than about 160 characters. MiKTeX's pdflatex
1118         // is even pickier. A maximum length of 100 has been proven to work.
1119         // If dir.size() > max length, all bets are off for YAP. We truncate
1120         // the filename nevertheless, keeping a minimum of 10 chars.
1121
1122         string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
1123
1124         // If the mangled file name is too long, hack it to fit.
1125         // We know we're guaranteed to have a unique file name because
1126         // of the counter.
1127         if (mname.size() > max_length) {
1128                 int const half = (int(max_length) / 2) - 2;
1129                 if (half > 0) {
1130                         mname = mname.substr(0, half) + "___" +
1131                                 mname.substr(mname.size() - half);
1132                 }
1133         }
1134
1135         mangledNames[absFilename()] = mname;
1136         return mname;
1137 }
1138
1139
1140 bool DocFileName::isZipped() const
1141 {
1142         if (!zipped_valid_) {
1143                 zipped_ = isZippedFile();
1144                 zipped_valid_ = true;
1145         }
1146         return zipped_;
1147 }
1148
1149
1150 string DocFileName::unzippedFilename() const
1151 {
1152         return unzippedFileName(absFilename());
1153 }
1154
1155
1156 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
1157 {
1158         return static_cast<FileName const &>(lhs)
1159                 == static_cast<FileName const &>(rhs)
1160                 && lhs.saveAbsPath() == rhs.saveAbsPath();
1161 }
1162
1163
1164 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
1165 {
1166         return !(lhs == rhs);
1167 }
1168
1169 } // namespace support
1170 } // namespace lyx