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