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