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