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