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