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