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