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