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