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