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