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