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