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