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