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