]> git.lyx.org Git - lyx.git/blob - src/support/FileName.cpp
header cleanup.
[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/lstrings.h"
20 #include "support/os.h"
21 #include "support/Package.h"
22 #include "support/qstring_helpers.h"
23
24 #include <QDateTime>
25 #include <QDir>
26 #include <QFile>
27 #include <QFileInfo>
28 #include <QList>
29 #include <QTime>
30
31 #include <boost/assert.hpp>
32 #include <boost/scoped_array.hpp>
33
34 #include <map>
35 #include <sstream>
36 #include <fstream>
37 #include <algorithm>
38
39 #ifdef HAVE_SYS_TYPES_H
40 # include <sys/types.h>
41 #endif
42 #ifdef HAVE_SYS_STAT_H
43 # include <sys/stat.h>
44 #endif
45 #ifdef HAVE_UNISTD_H
46 # include <unistd.h>
47 #endif
48 #ifdef HAVE_DIRECT_H
49 # include <direct.h>
50 #endif
51 #ifdef _WIN32
52 # include <windows.h>
53 #endif
54
55 #include <cerrno>
56 #include <fcntl.h>
57
58
59 #ifdef HAVE_UNISTD_H
60 # include <unistd.h>
61 #endif
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 using namespace std;
77
78 namespace lyx {
79 namespace support {
80
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                 fi.setCaching(fi.exists() ? true : false);
95         }
96         ///
97         QFileInfo fi;
98 };
99
100 /////////////////////////////////////////////////////////////////////
101 //
102 // FileName
103 //
104 /////////////////////////////////////////////////////////////////////
105
106
107 FileName::FileName() : d(new Private)
108 {
109 }
110
111
112 FileName::FileName(string const & abs_filename)
113         : d(abs_filename.empty() ? new Private : new Private(abs_filename))
114 {
115 }
116
117
118 FileName::~FileName()
119 {
120         delete d;
121 }
122
123
124 FileName::FileName(FileName const & rhs) : d(new Private)
125 {
126         d->fi = rhs.d->fi;
127 }
128
129
130 FileName & FileName::operator=(FileName const & rhs)
131 {
132         d->fi = rhs.d->fi;
133         return *this;
134 }
135
136
137 bool FileName::empty() const
138 {
139         return d->fi.absoluteFilePath().isEmpty();
140 }
141
142
143 string FileName::absFilename() const
144 {
145         return fromqstr(d->fi.absoluteFilePath());
146 }
147
148
149 void FileName::set(string const & name)
150 {
151         d->fi.setFile(toqstr(name));
152         BOOST_ASSERT(d->fi.isAbsolute());
153 }
154
155
156 void FileName::erase()
157 {
158         d->fi = QFileInfo();
159 }
160
161
162 bool FileName::copyTo(FileName const & name) const
163 {
164         QFile::remove(name.d->fi.absoluteFilePath());
165         bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
166         if (!success)
167                 lyxerr << "FileName::copyTo(): Could not copy file "
168                         << *this << " to " << name << endl;
169         return success;
170 }
171
172
173 bool FileName::renameTo(FileName const & name) const
174 {
175         bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
176         if (!success)
177                 LYXERR0("Could not rename file " << *this << " to " << name);
178         return success;
179 }
180
181
182 bool FileName::moveTo(FileName const & name) const
183 {
184         QFile::remove(name.d->fi.absoluteFilePath());
185
186         bool success = QFile::rename(d->fi.absoluteFilePath(),
187                 name.d->fi.absoluteFilePath());
188         if (!success)
189                 LYXERR0("Could not move file " << *this << " to " << name);
190         return success;
191 }
192
193
194 bool FileName::changePermission(unsigned long int mode) const
195 {
196         if (!isWritable()) {
197                 LYXERR0("File " << *this << " is not writable!");
198                 return false;
199         }
200
201 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
202         if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
203                 LYXERR0("File " << *this << ": cannot change permission to "
204                         << mode << ".");
205                 return false;
206         }
207 #endif
208         return true;
209 }
210
211
212 string FileName::toFilesystemEncoding() const
213 {
214         QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
215         return string(encoded.begin(), encoded.end());
216 }
217
218
219 FileName FileName::fromFilesystemEncoding(string const & name)
220 {
221         QByteArray const encoded(name.c_str(), name.length());
222         return FileName(fromqstr(QFile::decodeName(encoded)));
223 }
224
225
226 bool FileName::exists() const
227 {
228         return d->fi.exists();
229 }
230
231
232 bool FileName::isSymLink() const
233 {
234         return d->fi.isSymLink();
235 }
236
237
238 bool FileName::isFileEmpty() const
239 {
240         return d->fi.size() == 0;
241 }
242
243
244 bool FileName::isDirectory() const
245 {
246         return d->fi.isDir();
247 }
248
249
250 bool FileName::isReadOnly() const
251 {
252         return d->fi.isReadable() && !d->fi.isWritable();
253 }
254
255
256 bool FileName::isReadableDirectory() const
257 {
258         return d->fi.isDir() && d->fi.isReadable();
259 }
260
261
262 string FileName::onlyFileName() const
263 {
264         return support::onlyFilename(absFilename());
265 }
266
267
268 FileName FileName::onlyPath() const
269 {
270         return FileName(support::onlyPath(absFilename()));
271 }
272
273
274 bool FileName::isReadableFile() const
275 {
276         return d->fi.isFile() && d->fi.isReadable();
277 }
278
279
280 bool FileName::isWritable() const
281 {
282         return d->fi.isWritable();
283 }
284
285
286 bool FileName::isDirWritable() const
287 {
288         LYXERR(Debug::FILES, "isDirWriteable: " << *this);
289
290         FileName const tmpfl = FileName::tempName(absFilename() + "/lyxwritetest");
291
292         if (tmpfl.empty())
293                 return false;
294
295         tmpfl.removeFile();
296         return true;
297 }
298
299
300 FileNameList FileName::dirList(string const & ext) const
301 {
302         FileNameList dirlist;
303         if (!isDirectory()) {
304                 LYXERR0("Directory '" << *this << "' does not exist!");
305                 return dirlist;
306         }
307
308         QDir dir = d->fi.absoluteDir();
309
310         if (!ext.empty()) {
311                 QString filter;
312                 switch (ext[0]) {
313                 case '.': filter = "*" + toqstr(ext); break;
314                 case '*': filter = toqstr(ext); break;
315                 default: filter = "*." + toqstr(ext);
316                 }
317                 dir.setNameFilters(QStringList(filter));
318                 LYXERR(Debug::FILES, "filtering on extension "
319                         << fromqstr(filter) << " is requested.");
320         }
321
322         QFileInfoList list = dir.entryInfoList();
323         for (int i = 0; i != list.size(); ++i) {
324                 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
325                 dirlist.push_back(fi);
326                 LYXERR(Debug::FILES, "found file " << fi);
327         }
328
329         return dirlist;
330 }
331
332
333 static int make_tempfile(char * templ)
334 {
335 #if defined(HAVE_MKSTEMP)
336         return ::mkstemp(templ);
337 #elif defined(HAVE_MKTEMP)
338         // This probably just barely works...
339         ::mktemp(templ);
340 # if defined (HAVE_OPEN)
341 # if (!defined S_IRUSR)
342 #   define S_IRUSR S_IREAD
343 #   define S_IWUSR S_IWRITE
344 # endif
345         return ::open(templ, O_RDWR | O_CREAT | O_EXCL, S_IRUSR | S_IWUSR);
346 # elif defined (HAVE__OPEN)
347         return ::_open(templ,
348                        _O_RDWR | _O_CREAT | _O_EXCL,
349                        _S_IREAD | _S_IWRITE);
350 # else
351 #  error No open() function.
352 # endif
353 #else
354 #error FIX FIX FIX
355 #endif
356 }
357
358
359 FileName FileName::tempName(string const & mask)
360 {
361         FileName tmp_name(mask);
362         string tmpfl;
363         if (tmp_name.d->fi.isAbsolute())
364                 tmpfl = mask;
365         else
366                 tmpfl = package().temp_dir().absFilename() + "/" + mask;
367
368 #if defined (HAVE_GETPID)
369         tmpfl += convert<string>(getpid());
370 #elif defined (HAVE__GETPID)
371         tmpfl += convert<string>(_getpid());
372 #else
373 # error No getpid() function
374 #endif
375         tmpfl += "XXXXXX";
376
377         // The supposedly safe mkstemp version
378         // FIXME: why not using std::string directly?
379         boost::scoped_array<char> tmpl(new char[tmpfl.length() + 1]); // + 1 for '\0'
380         tmpfl.copy(tmpl.get(), string::npos);
381         tmpl[tmpfl.length()] = '\0'; // terminator
382
383         int const tmpf = make_tempfile(tmpl.get());
384         if (tmpf != -1) {
385                 string const t(to_utf8(from_filesystem8bit(tmpl.get())));
386 #if defined (HAVE_CLOSE)
387                 ::close(tmpf);
388 #elif defined (HAVE__CLOSE)
389                 ::_close(tmpf);
390 #else
391 # error No x() function.
392 #endif
393                 LYXERR(Debug::FILES, "Temporary file `" << t << "' created.");
394                 return FileName(t);
395         }
396         LYXERR(Debug::FILES, "LyX Error: Unable to create temporary file.");
397         return FileName();
398 }
399
400
401 FileName FileName::getcwd()
402 {
403         return FileName(".");
404 }
405
406
407 time_t FileName::lastModified() const
408 {
409         return d->fi.lastModified().toTime_t();
410 }
411
412
413 bool FileName::chdir() const
414 {
415         return QDir::setCurrent(d->fi.absoluteFilePath());
416 }
417
418
419 extern unsigned long sum(char const * file);
420
421 unsigned long FileName::checksum() const
422 {
423         if (!exists()) {
424                 //LYXERR0("File \"" << absFilename() << "\" does not exist!");
425                 return 0;
426         }
427         // a directory may be passed here so we need to test it. (bug 3622)
428         if (isDirectory()) {
429                 LYXERR0('"' << absFilename() << "\" is a directory!");
430                 return 0;
431         }
432         if (!lyxerr.debugging(Debug::FILES))
433                 return sum(absFilename().c_str());
434
435         QTime t;
436         t.start();
437         unsigned long r = sum(absFilename().c_str());
438         lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
439                 << t.elapsed() << " ms." << endl;
440         return r;
441 }
442
443
444 bool FileName::removeFile() const
445 {
446         bool const success = QFile::remove(d->fi.absoluteFilePath());
447         if (!success && exists())
448                 LYXERR0("Could not delete file " << *this);
449         return success;
450 }
451
452
453 static bool rmdir(QFileInfo const & fi)
454 {
455         QDir dir(fi.absoluteFilePath());
456         QFileInfoList list = dir.entryInfoList();
457         bool success = true;
458         for (int i = 0; i != list.size(); ++i) {
459                 if (list.at(i).fileName() == ".")
460                         continue;
461                 if (list.at(i).fileName() == "..")
462                         continue;
463                 bool removed;
464                 if (list.at(i).isDir()) {
465                         LYXERR(Debug::FILES, "Removing dir " 
466                                 << fromqstr(list.at(i).absoluteFilePath()));
467                         removed = rmdir(list.at(i));
468                 }
469                 else {
470                         LYXERR(Debug::FILES, "Removing file " 
471                                 << fromqstr(list.at(i).absoluteFilePath()));
472                         removed = dir.remove(list.at(i).fileName());
473                 }
474                 if (!removed) {
475                         success = false;
476                         LYXERR0("Could not delete "
477                                 << fromqstr(list.at(i).absoluteFilePath()));
478                 }
479         } 
480         QDir parent = fi.absolutePath();
481         success &= parent.rmdir(fi.fileName());
482         return success;
483 }
484
485
486 bool FileName::destroyDirectory() const
487 {
488         bool const success = rmdir(d->fi);
489         if (!success)
490                 LYXERR0("Could not delete " << *this);
491
492         return success;
493 }
494
495
496 static int mymkdir(char const * pathname, unsigned long int mode)
497 {
498         // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
499 #if HAVE_MKDIR
500 # if MKDIR_TAKES_ONE_ARG
501         // MinGW32
502         return ::mkdir(pathname);
503         // FIXME: "Permissions of created directories are ignored on this system."
504 # else
505         // POSIX
506         return ::mkdir(pathname, mode_t(mode));
507 # endif
508 #elif defined(_WIN32)
509         // plain Windows 32
510         return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
511         // FIXME: "Permissions of created directories are ignored on this system."
512 #elif HAVE__MKDIR
513         return ::_mkdir(pathname);
514         // FIXME: "Permissions of created directories are ignored on this system."
515 #else
516 #   error "Don't know how to create a directory on this system."
517 #endif
518
519 }
520
521
522 bool FileName::createDirectory(int permission) const
523 {
524         BOOST_ASSERT(!empty());
525         return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
526 }
527
528
529 bool FileName::createPath() const
530 {
531         BOOST_ASSERT(!empty());
532         if (isDirectory())
533                 return true;
534
535         QDir dir;
536         bool success = dir.mkpath(d->fi.absoluteFilePath());
537         if (!success)
538                 LYXERR0("Cannot create path '" << *this << "'!");
539         return success;
540 }
541
542
543 docstring const FileName::absoluteFilePath() const
544 {
545         return qstring_to_ucs4(d->fi.absoluteFilePath());
546 }
547
548
549 docstring FileName::displayName(int threshold) const
550 {
551         return makeDisplayPath(absFilename(), threshold);
552 }
553
554
555 docstring FileName::fileContents(string const & encoding) const
556 {
557         if (!isReadableFile()) {
558                 LYXERR0("File '" << *this << "' is not redable!");
559                 return docstring();
560         }
561
562         QFile file(d->fi.absoluteFilePath());
563         if (!file.open(QIODevice::ReadOnly)) {
564                 LYXERR0("File '" << *this
565                         << "' could not be opened in read only mode!");
566                 return docstring();
567         }
568         QByteArray contents = file.readAll();
569         file.close();
570
571         if (contents.isEmpty()) {
572                 LYXERR(Debug::FILES, "File '" << *this
573                         << "' is either empty or some error happened while reading it.");
574                 return docstring();
575         }
576
577         QString s;
578         if (encoding.empty() || encoding == "UTF-8")
579                 s = QString::fromUtf8(contents.data());
580         else if (encoding == "ascii")
581                 s = QString::fromAscii(contents.data());
582         else if (encoding == "local8bit")
583                 s = QString::fromLocal8Bit(contents.data());
584         else if (encoding == "latin1")
585                 s = QString::fromLatin1(contents.data());
586
587         return qstring_to_ucs4(s);
588 }
589
590
591 void FileName::changeExtension(string const & extension)
592 {
593         // FIXME: use Qt native methods...
594         string const oldname = absFilename();
595         string::size_type const last_slash = oldname.rfind('/');
596         string::size_type last_dot = oldname.rfind('.');
597         if (last_dot < last_slash && last_slash != string::npos)
598                 last_dot = string::npos;
599
600         string ext;
601         // Make sure the extension starts with a dot
602         if (!extension.empty() && extension[0] != '.')
603                 ext= '.' + extension;
604         else
605                 ext = extension;
606
607         set(oldname.substr(0, last_dot) + ext);
608 }
609
610
611 string FileName::guessFormatFromContents() const
612 {
613         // the different filetypes and what they contain in one of the first lines
614         // (dots are any characters).           (Herbert 20020131)
615         // AGR  Grace...
616         // BMP  BM...
617         // EPS  %!PS-Adobe-3.0 EPSF...
618         // FIG  #FIG...
619         // FITS ...BITPIX...
620         // GIF  GIF...
621         // JPG  JFIF
622         // PDF  %PDF-...
623         // PNG  .PNG...
624         // PBM  P1... or P4     (B/W)
625         // PGM  P2... or P5     (Grayscale)
626         // PPM  P3... or P6     (color)
627         // PS   %!PS-Adobe-2.0 or 1.0,  no "EPSF"!
628         // SGI  \001\332...     (decimal 474)
629         // TGIF %TGIF...
630         // TIFF II... or MM...
631         // XBM  ..._bits[]...
632         // XPM  /* XPM */    sometimes missing (f.ex. tgif-export)
633         //      ...static char *...
634         // XWD  \000\000\000\151        (0x00006900) decimal 105
635         //
636         // GZIP \037\213        http://www.ietf.org/rfc/rfc1952.txt
637         // ZIP  PK...                   http://www.halyava.ru/document/ind_arch.htm
638         // Z    \037\235                UNIX compress
639
640         // paranoia check
641         if (empty() || !isReadableFile())
642                 return string();
643
644         ifstream ifs(toFilesystemEncoding().c_str());
645         if (!ifs)
646                 // Couldn't open file...
647                 return string();
648
649         // gnuzip
650         static string const gzipStamp = "\037\213";
651
652         // PKZIP
653         static string const zipStamp = "PK";
654
655         // compress
656         static string const compressStamp = "\037\235";
657
658         // Maximum strings to read
659         int const max_count = 50;
660         int count = 0;
661
662         string str;
663         string format;
664         bool firstLine = true;
665         while ((count++ < max_count) && format.empty()) {
666                 if (ifs.eof()) {
667                         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
668                                 << "\tFile type not recognised before EOF!");
669                         break;
670                 }
671
672                 getline(ifs, str);
673                 string const stamp = str.substr(0, 2);
674                 if (firstLine && str.size() >= 2) {
675                         // at first we check for a zipped file, because this
676                         // information is saved in the first bytes of the file!
677                         // also some graphic formats which save the information
678                         // in the first line, too.
679                         if (prefixIs(str, gzipStamp)) {
680                                 format =  "gzip";
681
682                         } else if (stamp == zipStamp) {
683                                 format =  "zip";
684
685                         } else if (stamp == compressStamp) {
686                                 format =  "compress";
687
688                         // the graphics part
689                         } else if (stamp == "BM") {
690                                 format =  "bmp";
691
692                         } else if (stamp == "\001\332") {
693                                 format =  "sgi";
694
695                         // PBM family
696                         // Don't need to use str.at(0), str.at(1) because
697                         // we already know that str.size() >= 2
698                         } else if (str[0] == 'P') {
699                                 switch (str[1]) {
700                                 case '1':
701                                 case '4':
702                                         format =  "pbm";
703                                     break;
704                                 case '2':
705                                 case '5':
706                                         format =  "pgm";
707                                     break;
708                                 case '3':
709                                 case '6':
710                                         format =  "ppm";
711                                 }
712                                 break;
713
714                         } else if ((stamp == "II") || (stamp == "MM")) {
715                                 format =  "tiff";
716
717                         } else if (prefixIs(str,"%TGIF")) {
718                                 format =  "tgif";
719
720                         } else if (prefixIs(str,"#FIG")) {
721                                 format =  "fig";
722
723                         } else if (prefixIs(str,"GIF")) {
724                                 format =  "gif";
725
726                         } else if (str.size() > 3) {
727                                 int const c = ((str[0] << 24) & (str[1] << 16) &
728                                                (str[2] << 8)  & str[3]);
729                                 if (c == 105) {
730                                         format =  "xwd";
731                                 }
732                         }
733
734                         firstLine = false;
735                 }
736
737                 if (!format.empty())
738                     break;
739                 else if (contains(str,"EPSF"))
740                         // dummy, if we have wrong file description like
741                         // %!PS-Adobe-2.0EPSF"
742                         format = "eps";
743
744                 else if (contains(str, "Grace"))
745                         format = "agr";
746
747                 else if (contains(str, "JFIF"))
748                         format = "jpg";
749
750                 else if (contains(str, "%PDF"))
751                         format = "pdf";
752
753                 else if (contains(str, "PNG"))
754                         format = "png";
755
756                 else if (contains(str, "%!PS-Adobe")) {
757                         // eps or ps
758                         ifs >> str;
759                         if (contains(str,"EPSF"))
760                                 format = "eps";
761                         else
762                             format = "ps";
763                 }
764
765                 else if (contains(str, "_bits[]"))
766                         format = "xbm";
767
768                 else if (contains(str, "XPM") || contains(str, "static char *"))
769                         format = "xpm";
770
771                 else if (contains(str, "BITPIX"))
772                         format = "fits";
773         }
774
775         if (!format.empty()) {
776                 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
777                 return format;
778         }
779
780         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
781                 << "\tCouldn't find a known format!");
782         return string();
783 }
784
785
786 bool FileName::isZippedFile() const
787 {
788         string const type = guessFormatFromContents();
789         return contains("gzip zip compress", type) && !type.empty();
790 }
791
792
793 docstring const FileName::relPath(string const & path) const
794 {
795         // FIXME UNICODE
796         return makeRelPath(absoluteFilePath(), from_utf8(path));
797 }
798
799
800 bool operator==(FileName const & lhs, FileName const & rhs)
801 {
802         return lhs.absFilename() == rhs.absFilename();
803 }
804
805
806 bool operator!=(FileName const & lhs, FileName const & rhs)
807 {
808         return lhs.absFilename() != rhs.absFilename();
809 }
810
811
812 bool operator<(FileName const & lhs, FileName const & rhs)
813 {
814         return lhs.absFilename() < rhs.absFilename();
815 }
816
817
818 bool operator>(FileName const & lhs, FileName const & rhs)
819 {
820         return lhs.absFilename() > rhs.absFilename();
821 }
822
823
824 ostream & operator<<(ostream & os, FileName const & filename)
825 {
826         return os << filename.absFilename();
827 }
828
829
830 /////////////////////////////////////////////////////////////////////
831 //
832 // DocFileName
833 //
834 /////////////////////////////////////////////////////////////////////
835
836
837 DocFileName::DocFileName()
838         : save_abs_path_(true)
839 {}
840
841
842 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
843         : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
844 {}
845
846
847 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
848         : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
849 {}
850
851
852 void DocFileName::set(string const & name, string const & buffer_path)
853 {
854         save_abs_path_ = absolutePath(name);
855         FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
856         zipped_valid_ = false;
857 }
858
859
860 void DocFileName::erase()
861 {
862         FileName::erase();
863         zipped_valid_ = false;
864 }
865
866
867 string DocFileName::relFilename(string const & path) const
868 {
869         // FIXME UNICODE
870         return to_utf8(relPath(path));
871 }
872
873
874 string DocFileName::outputFilename(string const & path) const
875 {
876         return save_abs_path_ ? absFilename() : relFilename(path);
877 }
878
879
880 string DocFileName::mangledFilename(string const & dir) const
881 {
882         // We need to make sure that every DocFileName instance for a given
883         // filename returns the same mangled name.
884         typedef map<string, string> MangledMap;
885         static MangledMap mangledNames;
886         MangledMap::const_iterator const it = mangledNames.find(absFilename());
887         if (it != mangledNames.end())
888                 return (*it).second;
889
890         string const name = absFilename();
891         // Now the real work
892         string mname = os::internal_path(name);
893         // Remove the extension.
894         mname = support::changeExtension(name, string());
895         // The mangled name must be a valid LaTeX name.
896         // The list of characters to keep is probably over-restrictive,
897         // but it is not really a problem.
898         // Apart from non-ASCII characters, at least the following characters
899         // are forbidden: '/', '.', ' ', and ':'.
900         // On windows it is not possible to create files with '<', '>' or '?'
901         // in the name.
902         static string const keep = "abcdefghijklmnopqrstuvwxyz"
903                                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
904                                    "+,-0123456789;=";
905         string::size_type pos = 0;
906         while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
907                 mname[pos++] = '_';
908         // Add the extension back on
909         mname = support::changeExtension(mname, getExtension(name));
910
911         // Prepend a counter to the filename. This is necessary to make
912         // the mangled name unique.
913         static int counter = 0;
914         ostringstream s;
915         s << counter++ << mname;
916         mname = s.str();
917
918         // MiKTeX's YAP (version 2.4.1803) crashes if the file name
919         // is longer than about 160 characters. MiKTeX's pdflatex
920         // is even pickier. A maximum length of 100 has been proven to work.
921         // If dir.size() > max length, all bets are off for YAP. We truncate
922         // the filename nevertheless, keeping a minimum of 10 chars.
923
924         string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
925
926         // If the mangled file name is too long, hack it to fit.
927         // We know we're guaranteed to have a unique file name because
928         // of the counter.
929         if (mname.size() > max_length) {
930                 int const half = (int(max_length) / 2) - 2;
931                 if (half > 0) {
932                         mname = mname.substr(0, half) + "___" +
933                                 mname.substr(mname.size() - half);
934                 }
935         }
936
937         mangledNames[absFilename()] = mname;
938         return mname;
939 }
940
941
942 bool DocFileName::isZipped() const
943 {
944         if (!zipped_valid_) {
945                 zipped_ = isZippedFile();
946                 zipped_valid_ = true;
947         }
948         return zipped_;
949 }
950
951
952 string DocFileName::unzippedFilename() const
953 {
954         return unzippedFileName(absFilename());
955 }
956
957
958 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
959 {
960         return lhs.absFilename() == rhs.absFilename()
961                 && lhs.saveAbsPath() == rhs.saveAbsPath();
962 }
963
964
965 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
966 {
967         return !(lhs == rhs);
968 }
969
970 } // namespace support
971 } // namespace lyx