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