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