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