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