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