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