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