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