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