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