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