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