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