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