]> git.lyx.org Git - lyx.git/blob - src/support/FileName.cpp
Comment out unneeded debug output and add some in 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 bool FileName::chdir() const
240 {
241         return QDir::setCurrent(d->fi.absoluteFilePath());
242 }
243
244
245 extern unsigned long sum(char const * file);
246
247 unsigned long FileName::checksum() const
248 {
249         if (!exists()) {
250                 LYXERR0("File \"" << absFilename() << "\" does not exist!");
251                 return 0;
252         }
253         // a directory may be passed here so we need to test it. (bug 3622)
254         if (isDirectory()) {
255                 LYXERR0('\\' << absFilename() << "\" is a directory!");
256                 return 0;
257         }
258         LYXERR0("Checksumming \"" << absFilename() << "\".");
259         return sum(absFilename().c_str());
260 }
261
262
263 bool FileName::removeFile() const
264 {
265         bool const success = QFile::remove(d->fi.absoluteFilePath());
266         if (!success && exists())
267                 lyxerr << "FileName::removeFile(): Could not delete file "
268                         << *this << "." << endl;
269         return success;
270 }
271
272
273 static bool rmdir(QFileInfo const & fi)
274 {
275         QDir dir(fi.absoluteFilePath());
276         QFileInfoList list = dir.entryInfoList();
277         bool global_success = true;
278         for (int i = 0; i != list.size(); ++i) {
279                 if (list.at(i).fileName() == ".")
280                         continue;
281                 if (list.at(i).fileName() == "..")
282                         continue;
283                 bool success;
284                 if (list.at(i).isDir()) {
285                         LYXERR(Debug::FILES, "Erasing dir " 
286                                 << fromqstr(list.at(i).absoluteFilePath()));
287                         success = rmdir(list.at(i));
288                 }
289                 else {
290                         LYXERR(Debug::FILES, "Erasing file " 
291                                 << fromqstr(list.at(i).absoluteFilePath()));
292                         success = dir.remove(list.at(i).fileName());
293                 }
294                 if (!success) {
295                         global_success = false;
296                         lyxerr << "Could not delete "
297                                 << fromqstr(list.at(i).absoluteFilePath()) << "." << endl;
298                 }
299         } 
300         QDir parent = fi.absolutePath();
301         global_success |= parent.rmdir(fi.fileName());
302         return global_success;
303 }
304
305
306 bool FileName::destroyDirectory() const
307 {
308         bool const success = rmdir(d->fi);
309         if (!success)
310                 lyxerr << "Could not delete " << *this << "." << endl;
311
312         return success;
313 }
314
315
316 bool FileName::createDirectory(int permission) const
317 {
318         BOOST_ASSERT(!empty());
319         return mkdir(*this, permission) == 0;
320 }
321
322
323 std::vector<FileName> dirList(FileName const & dirname, std::string const & ext)
324 {
325         std::vector<FileName> dirlist;
326         if (!dirname.isDirectory()) {
327                 LYXERR0("Directory '" << dirname << "' does not exist!");
328                 return dirlist;
329         }
330
331         QDir dir(dirname.d->fi.absoluteFilePath());
332
333         if (!ext.empty()) {
334                 QString filter;
335                 switch (ext[0]) {
336                 case '.': filter = "*" + toqstr(ext); break;
337                 case '*': filter = toqstr(ext); break;
338                 default: filter = "*." + toqstr(ext);
339                 }
340                 dir.setNameFilters(QStringList(filter));
341                 LYXERR(Debug::FILES, "filtering on extension "
342                         << fromqstr(filter) << " is requested.");
343         }
344
345         QFileInfoList list = dir.entryInfoList();
346         for (int i = 0; i != list.size(); ++i) {
347                 FileName fi;
348                 fi.d->fi = list.at(i);
349                 dirlist.push_back(fi);
350                 LYXERR(Debug::FILES, "found file " << fi);
351         }
352
353         return dirlist;
354 }
355
356
357 docstring FileName::displayName(int threshold) const
358 {
359         return makeDisplayPath(absFilename(), threshold);
360 }
361
362
363 string FileName::fileContents() const
364 {
365         if (exists()) {
366                 string const encodedname = toFilesystemEncoding();
367                 ifstream ifs(encodedname.c_str());
368                 ostringstream ofs;
369                 if (ifs && ofs) {
370                         ofs << ifs.rdbuf();
371                         ifs.close();
372                         return ofs.str();
373                 }
374         }
375         lyxerr << "LyX was not able to read file '" << *this << '\'' << std::endl;
376         return string();
377 }
378
379
380 void FileName::changeExtension(std::string const & extension)
381 {
382         // FIXME: use Qt native methods...
383         string const oldname = absFilename();
384         string::size_type const last_slash = oldname.rfind('/');
385         string::size_type last_dot = oldname.rfind('.');
386         if (last_dot < last_slash && last_slash != string::npos)
387                 last_dot = string::npos;
388
389         string ext;
390         // Make sure the extension starts with a dot
391         if (!extension.empty() && extension[0] != '.')
392                 ext= '.' + extension;
393         else
394                 ext = extension;
395
396         set(oldname.substr(0, last_dot) + ext);
397 }
398
399
400 string FileName::guessFormatFromContents() const
401 {
402         // the different filetypes and what they contain in one of the first lines
403         // (dots are any characters).           (Herbert 20020131)
404         // AGR  Grace...
405         // BMP  BM...
406         // EPS  %!PS-Adobe-3.0 EPSF...
407         // FIG  #FIG...
408         // FITS ...BITPIX...
409         // GIF  GIF...
410         // JPG  JFIF
411         // PDF  %PDF-...
412         // PNG  .PNG...
413         // PBM  P1... or P4     (B/W)
414         // PGM  P2... or P5     (Grayscale)
415         // PPM  P3... or P6     (color)
416         // PS   %!PS-Adobe-2.0 or 1.0,  no "EPSF"!
417         // SGI  \001\332...     (decimal 474)
418         // TGIF %TGIF...
419         // TIFF II... or MM...
420         // XBM  ..._bits[]...
421         // XPM  /* XPM */    sometimes missing (f.ex. tgif-export)
422         //      ...static char *...
423         // XWD  \000\000\000\151        (0x00006900) decimal 105
424         //
425         // GZIP \037\213        http://www.ietf.org/rfc/rfc1952.txt
426         // ZIP  PK...                   http://www.halyava.ru/document/ind_arch.htm
427         // Z    \037\235                UNIX compress
428         // paranoia check
429
430         if (empty() || !isReadableFile())
431                 return string();
432
433         ifstream ifs(toFilesystemEncoding().c_str());
434         if (!ifs)
435                 // Couldn't open file...
436                 return string();
437
438         // gnuzip
439         static string const gzipStamp = "\037\213";
440
441         // PKZIP
442         static string const zipStamp = "PK";
443
444         // compress
445         static string const compressStamp = "\037\235";
446
447         // Maximum strings to read
448         int const max_count = 50;
449         int count = 0;
450
451         string str;
452         string format;
453         bool firstLine = true;
454         while ((count++ < max_count) && format.empty()) {
455                 if (ifs.eof()) {
456                         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
457                                 << "\tFile type not recognised before EOF!");
458                         break;
459                 }
460
461                 getline(ifs, str);
462                 string const stamp = str.substr(0, 2);
463                 if (firstLine && str.size() >= 2) {
464                         // at first we check for a zipped file, because this
465                         // information is saved in the first bytes of the file!
466                         // also some graphic formats which save the information
467                         // in the first line, too.
468                         if (prefixIs(str, gzipStamp)) {
469                                 format =  "gzip";
470
471                         } else if (stamp == zipStamp) {
472                                 format =  "zip";
473
474                         } else if (stamp == compressStamp) {
475                                 format =  "compress";
476
477                         // the graphics part
478                         } else if (stamp == "BM") {
479                                 format =  "bmp";
480
481                         } else if (stamp == "\001\332") {
482                                 format =  "sgi";
483
484                         // PBM family
485                         // Don't need to use str.at(0), str.at(1) because
486                         // we already know that str.size() >= 2
487                         } else if (str[0] == 'P') {
488                                 switch (str[1]) {
489                                 case '1':
490                                 case '4':
491                                         format =  "pbm";
492                                     break;
493                                 case '2':
494                                 case '5':
495                                         format =  "pgm";
496                                     break;
497                                 case '3':
498                                 case '6':
499                                         format =  "ppm";
500                                 }
501                                 break;
502
503                         } else if ((stamp == "II") || (stamp == "MM")) {
504                                 format =  "tiff";
505
506                         } else if (prefixIs(str,"%TGIF")) {
507                                 format =  "tgif";
508
509                         } else if (prefixIs(str,"#FIG")) {
510                                 format =  "fig";
511
512                         } else if (prefixIs(str,"GIF")) {
513                                 format =  "gif";
514
515                         } else if (str.size() > 3) {
516                                 int const c = ((str[0] << 24) & (str[1] << 16) &
517                                                (str[2] << 8)  & str[3]);
518                                 if (c == 105) {
519                                         format =  "xwd";
520                                 }
521                         }
522
523                         firstLine = false;
524                 }
525
526                 if (!format.empty())
527                     break;
528                 else if (contains(str,"EPSF"))
529                         // dummy, if we have wrong file description like
530                         // %!PS-Adobe-2.0EPSF"
531                         format = "eps";
532
533                 else if (contains(str, "Grace"))
534                         format = "agr";
535
536                 else if (contains(str, "JFIF"))
537                         format = "jpg";
538
539                 else if (contains(str, "%PDF"))
540                         format = "pdf";
541
542                 else if (contains(str, "PNG"))
543                         format = "png";
544
545                 else if (contains(str, "%!PS-Adobe")) {
546                         // eps or ps
547                         ifs >> str;
548                         if (contains(str,"EPSF"))
549                                 format = "eps";
550                         else
551                             format = "ps";
552                 }
553
554                 else if (contains(str, "_bits[]"))
555                         format = "xbm";
556
557                 else if (contains(str, "XPM") || contains(str, "static char *"))
558                         format = "xpm";
559
560                 else if (contains(str, "BITPIX"))
561                         format = "fits";
562         }
563
564         if (!format.empty()) {
565                 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
566                 return format;
567         }
568
569         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
570                 << "\tCouldn't find a known format!");
571         return string();
572 }
573
574
575 bool FileName::isZippedFile() const
576 {
577         string const type = guessFormatFromContents();
578         return contains("gzip zip compress", type) && !type.empty();
579 }
580
581
582 bool operator==(FileName const & lhs, FileName const & rhs)
583 {
584         return lhs.absFilename() == rhs.absFilename();
585 }
586
587
588 bool operator!=(FileName const & lhs, FileName const & rhs)
589 {
590         return lhs.absFilename() != rhs.absFilename();
591 }
592
593
594 bool operator<(FileName const & lhs, FileName const & rhs)
595 {
596         return lhs.absFilename() < rhs.absFilename();
597 }
598
599
600 bool operator>(FileName const & lhs, FileName const & rhs)
601 {
602         return lhs.absFilename() > rhs.absFilename();
603 }
604
605
606 std::ostream & operator<<(std::ostream & os, FileName const & filename)
607 {
608         return os << filename.absFilename();
609 }
610
611
612 /////////////////////////////////////////////////////////////////////
613 //
614 // DocFileName
615 //
616 /////////////////////////////////////////////////////////////////////
617
618
619 DocFileName::DocFileName()
620         : save_abs_path_(true)
621 {}
622
623
624 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
625         : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
626 {}
627
628
629 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
630         : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
631 {}
632
633
634 void DocFileName::set(string const & name, string const & buffer_path)
635 {
636         save_abs_path_ = absolutePath(name);
637         FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
638         zipped_valid_ = false;
639 }
640
641
642 void DocFileName::erase()
643 {
644         FileName::erase();
645         zipped_valid_ = false;
646 }
647
648
649 string DocFileName::relFilename(string const & path) const
650 {
651         // FIXME UNICODE
652         return to_utf8(makeRelPath(qstring_to_ucs4(d->fi.absoluteFilePath()), from_utf8(path)));
653 }
654
655
656 string DocFileName::outputFilename(string const & path) const
657 {
658         return save_abs_path_ ? absFilename() : relFilename(path);
659 }
660
661
662 string DocFileName::mangledFilename(std::string const & dir) const
663 {
664         // We need to make sure that every DocFileName instance for a given
665         // filename returns the same mangled name.
666         typedef map<string, string> MangledMap;
667         static MangledMap mangledNames;
668         MangledMap::const_iterator const it = mangledNames.find(absFilename());
669         if (it != mangledNames.end())
670                 return (*it).second;
671
672         string const name = absFilename();
673         // Now the real work
674         string mname = os::internal_path(name);
675         // Remove the extension.
676         mname = support::changeExtension(name, string());
677         // The mangled name must be a valid LaTeX name.
678         // The list of characters to keep is probably over-restrictive,
679         // but it is not really a problem.
680         // Apart from non-ASCII characters, at least the following characters
681         // are forbidden: '/', '.', ' ', and ':'.
682         // On windows it is not possible to create files with '<', '>' or '?'
683         // in the name.
684         static string const keep = "abcdefghijklmnopqrstuvwxyz"
685                                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
686                                    "+,-0123456789;=";
687         string::size_type pos = 0;
688         while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
689                 mname[pos++] = '_';
690         // Add the extension back on
691         mname = support::changeExtension(mname, getExtension(name));
692
693         // Prepend a counter to the filename. This is necessary to make
694         // the mangled name unique.
695         static int counter = 0;
696         std::ostringstream s;
697         s << counter++ << mname;
698         mname = s.str();
699
700         // MiKTeX's YAP (version 2.4.1803) crashes if the file name
701         // is longer than about 160 characters. MiKTeX's pdflatex
702         // is even pickier. A maximum length of 100 has been proven to work.
703         // If dir.size() > max length, all bets are off for YAP. We truncate
704         // the filename nevertheless, keeping a minimum of 10 chars.
705
706         string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
707
708         // If the mangled file name is too long, hack it to fit.
709         // We know we're guaranteed to have a unique file name because
710         // of the counter.
711         if (mname.size() > max_length) {
712                 int const half = (int(max_length) / 2) - 2;
713                 if (half > 0) {
714                         mname = mname.substr(0, half) + "___" +
715                                 mname.substr(mname.size() - half);
716                 }
717         }
718
719         mangledNames[absFilename()] = mname;
720         return mname;
721 }
722
723
724 bool DocFileName::isZipped() const
725 {
726         if (!zipped_valid_) {
727                 zipped_ = isZippedFile();
728                 zipped_valid_ = true;
729         }
730         return zipped_;
731 }
732
733
734 string DocFileName::unzippedFilename() const
735 {
736         return unzippedFileName(absFilename());
737 }
738
739
740 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
741 {
742         return lhs.absFilename() == rhs.absFilename()
743                 && lhs.saveAbsPath() == rhs.saveAbsPath();
744 }
745
746
747 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
748 {
749         return !(lhs == rhs);
750 }
751
752 } // namespace support
753 } // namespace lyx