]> git.lyx.org Git - lyx.git/blob - src/support/FileName.cpp
f3e73a8bc4dbec8184084be7d9825ae526f058df
[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 time_t FileName::lastModified() const
403 {
404         return d->fi.lastModified().toTime_t();
405 }
406
407
408 bool FileName::chdir() const
409 {
410         return QDir::setCurrent(d->fi.absoluteFilePath());
411 }
412
413
414 extern unsigned long sum(char const * file);
415
416 unsigned long FileName::checksum() const
417 {
418         if (!exists()) {
419                 LYXERR0("File \"" << absFilename() << "\" does not exist!");
420                 return 0;
421         }
422         // a directory may be passed here so we need to test it. (bug 3622)
423         if (isDirectory()) {
424                 LYXERR0('"' << absFilename() << "\" is a directory!");
425                 return 0;
426         }
427         if (!lyxerr.debugging(Debug::FILES))
428                 return sum(absFilename().c_str());
429
430         QTime t;
431         t.start();
432         unsigned long r = sum(absFilename().c_str());
433         lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
434                 << t.elapsed() << " ms." << endl;
435         return r;
436 }
437
438
439 bool FileName::removeFile() const
440 {
441         bool const success = QFile::remove(d->fi.absoluteFilePath());
442         if (!success && exists())
443                 LYXERR0("Could not delete file " << *this);
444         return success;
445 }
446
447
448 static bool rmdir(QFileInfo const & fi)
449 {
450         QDir dir(fi.absoluteFilePath());
451         QFileInfoList list = dir.entryInfoList();
452         bool success = true;
453         for (int i = 0; i != list.size(); ++i) {
454                 if (list.at(i).fileName() == ".")
455                         continue;
456                 if (list.at(i).fileName() == "..")
457                         continue;
458                 bool removed;
459                 if (list.at(i).isDir()) {
460                         LYXERR(Debug::FILES, "Removing dir " 
461                                 << fromqstr(list.at(i).absoluteFilePath()));
462                         removed = rmdir(list.at(i));
463                 }
464                 else {
465                         LYXERR(Debug::FILES, "Removing file " 
466                                 << fromqstr(list.at(i).absoluteFilePath()));
467                         removed = dir.remove(list.at(i).fileName());
468                 }
469                 if (!removed) {
470                         success = false;
471                         LYXERR0("Could not delete "
472                                 << fromqstr(list.at(i).absoluteFilePath()));
473                 }
474         } 
475         QDir parent = fi.absolutePath();
476         success &= parent.rmdir(fi.fileName());
477         return success;
478 }
479
480
481 bool FileName::destroyDirectory() const
482 {
483         bool const success = rmdir(d->fi);
484         if (!success)
485                 LYXERR0("Could not delete " << *this);
486
487         return success;
488 }
489
490
491 static int mymkdir(char const * pathname, unsigned long int mode)
492 {
493         // FIXME: why don't we have mode_t in lyx::mkdir prototype ??
494 #if HAVE_MKDIR
495 # if MKDIR_TAKES_ONE_ARG
496         // MinGW32
497         return ::mkdir(pathname);
498         // FIXME: "Permissions of created directories are ignored on this system."
499 # else
500         // POSIX
501         return ::mkdir(pathname, mode_t(mode));
502 # endif
503 #elif defined(_WIN32)
504         // plain Windows 32
505         return CreateDirectory(pathname, 0) != 0 ? 0 : -1;
506         // FIXME: "Permissions of created directories are ignored on this system."
507 #elif HAVE__MKDIR
508         return ::_mkdir(pathname);
509         // FIXME: "Permissions of created directories are ignored on this system."
510 #else
511 #   error "Don't know how to create a directory on this system."
512 #endif
513
514 }
515
516
517 bool FileName::createDirectory(int permission) const
518 {
519         BOOST_ASSERT(!empty());
520         return mymkdir(toFilesystemEncoding().c_str(), permission) == 0;
521 }
522
523
524 bool FileName::createPath() const
525 {
526         BOOST_ASSERT(!empty());
527         if (isDirectory())
528                 return true;
529
530         QDir dir;
531         bool success = dir.mkpath(d->fi.absoluteFilePath());
532         if (!success)
533                 LYXERR0("Cannot create path '" << *this << "'!");
534         return success;
535 }
536
537
538 docstring const FileName::absoluteFilePath() const
539 {
540         return qstring_to_ucs4(d->fi.absoluteFilePath());
541 }
542
543
544 docstring FileName::displayName(int threshold) const
545 {
546         return makeDisplayPath(absFilename(), threshold);
547 }
548
549
550 docstring FileName::fileContents(string const & encoding) const
551 {
552         if (!isReadableFile()) {
553                 LYXERR0("File '" << *this << "' is not redable!");
554                 return docstring();
555         }
556
557         QFile file(d->fi.absoluteFilePath());
558         if (!file.open(QIODevice::ReadOnly)) {
559                 LYXERR0("File '" << *this
560                         << "' could not be opened in read only mode!");
561                 return docstring();
562         }
563         QByteArray contents = file.readAll();
564         file.close();
565
566         if (contents.isEmpty()) {
567                 LYXERR(Debug::FILES, "File '" << *this
568                         << "' is either empty or some error happened while reading it.");
569                 return docstring();
570         }
571
572         QString s;
573         if (encoding.empty() || encoding == "UTF-8")
574                 s = QString::fromUtf8(contents.data());
575         else if (encoding == "ascii")
576                 s = QString::fromAscii(contents.data());
577         else if (encoding == "local8bit")
578                 s = QString::fromLocal8Bit(contents.data());
579         else if (encoding == "latin1")
580                 s = QString::fromLatin1(contents.data());
581
582         return qstring_to_ucs4(s);
583 }
584
585
586 void FileName::changeExtension(string const & extension)
587 {
588         // FIXME: use Qt native methods...
589         string const oldname = absFilename();
590         string::size_type const last_slash = oldname.rfind('/');
591         string::size_type last_dot = oldname.rfind('.');
592         if (last_dot < last_slash && last_slash != string::npos)
593                 last_dot = string::npos;
594
595         string ext;
596         // Make sure the extension starts with a dot
597         if (!extension.empty() && extension[0] != '.')
598                 ext= '.' + extension;
599         else
600                 ext = extension;
601
602         set(oldname.substr(0, last_dot) + ext);
603 }
604
605
606 string FileName::guessFormatFromContents() const
607 {
608         // the different filetypes and what they contain in one of the first lines
609         // (dots are any characters).           (Herbert 20020131)
610         // AGR  Grace...
611         // BMP  BM...
612         // EPS  %!PS-Adobe-3.0 EPSF...
613         // FIG  #FIG...
614         // FITS ...BITPIX...
615         // GIF  GIF...
616         // JPG  JFIF
617         // PDF  %PDF-...
618         // PNG  .PNG...
619         // PBM  P1... or P4     (B/W)
620         // PGM  P2... or P5     (Grayscale)
621         // PPM  P3... or P6     (color)
622         // PS   %!PS-Adobe-2.0 or 1.0,  no "EPSF"!
623         // SGI  \001\332...     (decimal 474)
624         // TGIF %TGIF...
625         // TIFF II... or MM...
626         // XBM  ..._bits[]...
627         // XPM  /* XPM */    sometimes missing (f.ex. tgif-export)
628         //      ...static char *...
629         // XWD  \000\000\000\151        (0x00006900) decimal 105
630         //
631         // GZIP \037\213        http://www.ietf.org/rfc/rfc1952.txt
632         // ZIP  PK...                   http://www.halyava.ru/document/ind_arch.htm
633         // Z    \037\235                UNIX compress
634
635         // paranoia check
636         if (empty() || !isReadableFile())
637                 return string();
638
639         ifstream ifs(toFilesystemEncoding().c_str());
640         if (!ifs)
641                 // Couldn't open file...
642                 return string();
643
644         // gnuzip
645         static string const gzipStamp = "\037\213";
646
647         // PKZIP
648         static string const zipStamp = "PK";
649
650         // compress
651         static string const compressStamp = "\037\235";
652
653         // Maximum strings to read
654         int const max_count = 50;
655         int count = 0;
656
657         string str;
658         string format;
659         bool firstLine = true;
660         while ((count++ < max_count) && format.empty()) {
661                 if (ifs.eof()) {
662                         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
663                                 << "\tFile type not recognised before EOF!");
664                         break;
665                 }
666
667                 getline(ifs, str);
668                 string const stamp = str.substr(0, 2);
669                 if (firstLine && str.size() >= 2) {
670                         // at first we check for a zipped file, because this
671                         // information is saved in the first bytes of the file!
672                         // also some graphic formats which save the information
673                         // in the first line, too.
674                         if (prefixIs(str, gzipStamp)) {
675                                 format =  "gzip";
676
677                         } else if (stamp == zipStamp) {
678                                 format =  "zip";
679
680                         } else if (stamp == compressStamp) {
681                                 format =  "compress";
682
683                         // the graphics part
684                         } else if (stamp == "BM") {
685                                 format =  "bmp";
686
687                         } else if (stamp == "\001\332") {
688                                 format =  "sgi";
689
690                         // PBM family
691                         // Don't need to use str.at(0), str.at(1) because
692                         // we already know that str.size() >= 2
693                         } else if (str[0] == 'P') {
694                                 switch (str[1]) {
695                                 case '1':
696                                 case '4':
697                                         format =  "pbm";
698                                     break;
699                                 case '2':
700                                 case '5':
701                                         format =  "pgm";
702                                     break;
703                                 case '3':
704                                 case '6':
705                                         format =  "ppm";
706                                 }
707                                 break;
708
709                         } else if ((stamp == "II") || (stamp == "MM")) {
710                                 format =  "tiff";
711
712                         } else if (prefixIs(str,"%TGIF")) {
713                                 format =  "tgif";
714
715                         } else if (prefixIs(str,"#FIG")) {
716                                 format =  "fig";
717
718                         } else if (prefixIs(str,"GIF")) {
719                                 format =  "gif";
720
721                         } else if (str.size() > 3) {
722                                 int const c = ((str[0] << 24) & (str[1] << 16) &
723                                                (str[2] << 8)  & str[3]);
724                                 if (c == 105) {
725                                         format =  "xwd";
726                                 }
727                         }
728
729                         firstLine = false;
730                 }
731
732                 if (!format.empty())
733                     break;
734                 else if (contains(str,"EPSF"))
735                         // dummy, if we have wrong file description like
736                         // %!PS-Adobe-2.0EPSF"
737                         format = "eps";
738
739                 else if (contains(str, "Grace"))
740                         format = "agr";
741
742                 else if (contains(str, "JFIF"))
743                         format = "jpg";
744
745                 else if (contains(str, "%PDF"))
746                         format = "pdf";
747
748                 else if (contains(str, "PNG"))
749                         format = "png";
750
751                 else if (contains(str, "%!PS-Adobe")) {
752                         // eps or ps
753                         ifs >> str;
754                         if (contains(str,"EPSF"))
755                                 format = "eps";
756                         else
757                             format = "ps";
758                 }
759
760                 else if (contains(str, "_bits[]"))
761                         format = "xbm";
762
763                 else if (contains(str, "XPM") || contains(str, "static char *"))
764                         format = "xpm";
765
766                 else if (contains(str, "BITPIX"))
767                         format = "fits";
768         }
769
770         if (!format.empty()) {
771                 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
772                 return format;
773         }
774
775         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
776                 << "\tCouldn't find a known format!");
777         return string();
778 }
779
780
781 bool FileName::isZippedFile() const
782 {
783         string const type = guessFormatFromContents();
784         return contains("gzip zip compress", type) && !type.empty();
785 }
786
787
788 docstring const FileName::relPath(string const & path) const
789 {
790         // FIXME UNICODE
791         return makeRelPath(absoluteFilePath(), from_utf8(path));
792 }
793
794
795 bool operator==(FileName const & lhs, FileName const & rhs)
796 {
797         return lhs.absFilename() == rhs.absFilename();
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 ostream & operator<<(ostream & os, FileName const & filename)
820 {
821         return os << filename.absFilename();
822 }
823
824
825 /////////////////////////////////////////////////////////////////////
826 //
827 // DocFileName
828 //
829 /////////////////////////////////////////////////////////////////////
830
831
832 DocFileName::DocFileName()
833         : save_abs_path_(true)
834 {}
835
836
837 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
838         : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
839 {}
840
841
842 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
843         : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
844 {}
845
846
847 void DocFileName::set(string const & name, string const & buffer_path)
848 {
849         save_abs_path_ = absolutePath(name);
850         FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
851         zipped_valid_ = false;
852 }
853
854
855 void DocFileName::erase()
856 {
857         FileName::erase();
858         zipped_valid_ = false;
859 }
860
861
862 string DocFileName::relFilename(string const & path) const
863 {
864         // FIXME UNICODE
865         return to_utf8(relPath(path));
866 }
867
868
869 string DocFileName::outputFilename(string const & path) const
870 {
871         return save_abs_path_ ? absFilename() : relFilename(path);
872 }
873
874
875 string DocFileName::mangledFilename(string const & dir) const
876 {
877         // We need to make sure that every DocFileName instance for a given
878         // filename returns the same mangled name.
879         typedef map<string, string> MangledMap;
880         static MangledMap mangledNames;
881         MangledMap::const_iterator const it = mangledNames.find(absFilename());
882         if (it != mangledNames.end())
883                 return (*it).second;
884
885         string const name = absFilename();
886         // Now the real work
887         string mname = os::internal_path(name);
888         // Remove the extension.
889         mname = support::changeExtension(name, string());
890         // The mangled name must be a valid LaTeX name.
891         // The list of characters to keep is probably over-restrictive,
892         // but it is not really a problem.
893         // Apart from non-ASCII characters, at least the following characters
894         // are forbidden: '/', '.', ' ', and ':'.
895         // On windows it is not possible to create files with '<', '>' or '?'
896         // in the name.
897         static string const keep = "abcdefghijklmnopqrstuvwxyz"
898                                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
899                                    "+,-0123456789;=";
900         string::size_type pos = 0;
901         while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
902                 mname[pos++] = '_';
903         // Add the extension back on
904         mname = support::changeExtension(mname, getExtension(name));
905
906         // Prepend a counter to the filename. This is necessary to make
907         // the mangled name unique.
908         static int counter = 0;
909         ostringstream s;
910         s << counter++ << mname;
911         mname = s.str();
912
913         // MiKTeX's YAP (version 2.4.1803) crashes if the file name
914         // is longer than about 160 characters. MiKTeX's pdflatex
915         // is even pickier. A maximum length of 100 has been proven to work.
916         // If dir.size() > max length, all bets are off for YAP. We truncate
917         // the filename nevertheless, keeping a minimum of 10 chars.
918
919         string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
920
921         // If the mangled file name is too long, hack it to fit.
922         // We know we're guaranteed to have a unique file name because
923         // of the counter.
924         if (mname.size() > max_length) {
925                 int const half = (int(max_length) / 2) - 2;
926                 if (half > 0) {
927                         mname = mname.substr(0, half) + "___" +
928                                 mname.substr(mname.size() - half);
929                 }
930         }
931
932         mangledNames[absFilename()] = mname;
933         return mname;
934 }
935
936
937 bool DocFileName::isZipped() const
938 {
939         if (!zipped_valid_) {
940                 zipped_ = isZippedFile();
941                 zipped_valid_ = true;
942         }
943         return zipped_;
944 }
945
946
947 string DocFileName::unzippedFilename() const
948 {
949         return unzippedFileName(absFilename());
950 }
951
952
953 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
954 {
955         return lhs.absFilename() == rhs.absFilename()
956                 && lhs.saveAbsPath() == rhs.saveAbsPath();
957 }
958
959
960 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
961 {
962         return !(lhs == rhs);
963 }
964
965 } // namespace support
966 } // namespace lyx