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