]> git.lyx.org Git - lyx.git/blob - src/support/FileName.cpp
Revert qprocess code. Revisions reverted: 22026, 22030, 22044, 22048,
[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/FileNameList.h"
15
16 #include "support/debug.h"
17 #include "support/filetools.h"
18 #include "support/lstrings.h"
19 #include "support/lyxlib.h"
20 #include "support/os.h"
21 #include "support/qstring_helpers.h"
22
23 #include <QDateTime>
24 #include <QDir>
25 #include <QFile>
26 #include <QFileInfo>
27 #include <QList>
28 #include <QTime>
29
30 #include <boost/assert.hpp>
31
32 #include <map>
33 #include <sstream>
34 #include <fstream>
35 #include <algorithm>
36
37 #ifdef HAVE_SYS_TYPES_H
38 # include <sys/types.h>
39 #endif
40 #ifdef HAVE_SYS_STAT_H
41 # include <sys/stat.h>
42 #endif
43 #include <cerrno>
44 #include <fcntl.h>
45
46 using namespace std;
47
48 namespace lyx {
49 namespace support {
50
51
52 /////////////////////////////////////////////////////////////////////
53 //
54 // FileName::Private
55 //
56 /////////////////////////////////////////////////////////////////////
57
58 struct FileName::Private
59 {
60         Private() {}
61
62         Private(string const & abs_filename) : fi(toqstr(abs_filename))
63         {}
64         ///
65         QFileInfo fi;
66 };
67
68 /////////////////////////////////////////////////////////////////////
69 //
70 // FileName
71 //
72 /////////////////////////////////////////////////////////////////////
73
74
75 FileName::FileName() : d(new Private)
76 {
77 }
78
79
80 FileName::FileName(string const & abs_filename)
81         : d(abs_filename.empty() ? new Private : new Private(abs_filename))
82 {
83 }
84
85
86 FileName::~FileName()
87 {
88         delete d;
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 }
122
123
124 void FileName::erase()
125 {
126         d->fi = QFileInfo();
127 }
128
129
130 bool FileName::copyTo(FileName const & name, bool overwrite) const
131 {
132         if (overwrite)
133                 QFile::remove(name.d->fi.absoluteFilePath());
134         bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
135         if (!success)
136                 lyxerr << "FileName::copyTo(): Could not copy file "
137                         << *this << " to " << name << endl;
138         return success;
139 }
140
141
142 string FileName::toFilesystemEncoding() const
143 {
144         QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
145         return string(encoded.begin(), encoded.end());
146 }
147
148
149 FileName FileName::fromFilesystemEncoding(string const & name)
150 {
151         QByteArray const encoded(name.c_str(), name.length());
152         return FileName(fromqstr(QFile::decodeName(encoded)));
153 }
154
155
156 bool FileName::exists() const
157 {
158         return d->fi.exists();
159 }
160
161
162 bool FileName::isSymLink() const
163 {
164         return d->fi.isSymLink();
165 }
166
167
168 bool FileName::isFileEmpty() const
169 {
170         return d->fi.size() == 0;
171 }
172
173
174 bool FileName::isDirectory() const
175 {
176         return d->fi.isDir();
177 }
178
179
180 bool FileName::isReadOnly() const
181 {
182         return d->fi.isReadable() && !d->fi.isWritable();
183 }
184
185
186 bool FileName::isReadableDirectory() const
187 {
188         return d->fi.isDir() && d->fi.isReadable();
189 }
190
191
192 std::string FileName::onlyFileName() const
193 {
194         return support::onlyFilename(absFilename());
195 }
196
197
198 FileName FileName::onlyPath() const
199 {
200         return FileName(support::onlyPath(absFilename()));
201 }
202
203
204 bool FileName::isReadableFile() const
205 {
206         return d->fi.isFile() && d->fi.isReadable();
207 }
208
209
210 bool FileName::isWritable() const
211 {
212         return d->fi.isWritable();
213 }
214
215
216 bool FileName::isDirWritable() const
217 {
218         LYXERR(Debug::FILES, "isDirWriteable: " << *this);
219
220         FileName const tmpfl(tempName(*this, "lyxwritetest"));
221
222         if (tmpfl.empty())
223                 return false;
224
225         tmpfl.removeFile();
226         return true;
227 }
228
229
230 FileNameList FileName::dirList(std::string const & ext) const
231 {
232         FileNameList dirlist;
233         if (!isDirectory()) {
234                 LYXERR0("Directory '" << *this << "' does not exist!");
235                 return dirlist;
236         }
237
238         QDir dir = d->fi.absoluteDir();
239
240         if (!ext.empty()) {
241                 QString filter;
242                 switch (ext[0]) {
243                 case '.': filter = "*" + toqstr(ext); break;
244                 case '*': filter = toqstr(ext); break;
245                 default: filter = "*." + toqstr(ext);
246                 }
247                 dir.setNameFilters(QStringList(filter));
248                 LYXERR(Debug::FILES, "filtering on extension "
249                         << fromqstr(filter) << " is requested.");
250         }
251
252         QFileInfoList list = dir.entryInfoList();
253         for (int i = 0; i != list.size(); ++i) {
254                 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
255                 dirlist.push_back(fi);
256                 LYXERR(Debug::FILES, "found file " << fi);
257         }
258
259         return dirlist;
260 }
261
262
263 FileName FileName::tempName(FileName const & dir, std::string const & mask)
264 {
265         return support::tempName(dir, mask);
266 }
267
268
269 std::time_t FileName::lastModified() const
270 {
271         return d->fi.lastModified().toTime_t();
272 }
273
274
275 bool FileName::chdir() const
276 {
277         return QDir::setCurrent(d->fi.absoluteFilePath());
278 }
279
280
281 extern unsigned long sum(char const * file);
282
283 unsigned long FileName::checksum() const
284 {
285         if (!exists()) {
286                 LYXERR0("File \"" << absFilename() << "\" does not exist!");
287                 return 0;
288         }
289         // a directory may be passed here so we need to test it. (bug 3622)
290         if (isDirectory()) {
291                 LYXERR0('"' << absFilename() << "\" is a directory!");
292                 return 0;
293         }
294         if (!lyxerr.debugging(Debug::FILES))
295                 return sum(absFilename().c_str());
296
297         QTime t;
298         t.start();
299         unsigned long r = sum(absFilename().c_str());
300         lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
301                 << t.elapsed() << " ms." << endl;
302         return r;
303 }
304
305
306 bool FileName::removeFile() const
307 {
308         bool const success = QFile::remove(d->fi.absoluteFilePath());
309         if (!success && exists())
310                 LYXERR0("Could not delete file " << *this);
311         return success;
312 }
313
314
315 static bool rmdir(QFileInfo const & fi)
316 {
317         QDir dir(fi.absoluteFilePath());
318         QFileInfoList list = dir.entryInfoList();
319         bool success = true;
320         for (int i = 0; i != list.size(); ++i) {
321                 if (list.at(i).fileName() == ".")
322                         continue;
323                 if (list.at(i).fileName() == "..")
324                         continue;
325                 bool removed;
326                 if (list.at(i).isDir()) {
327                         LYXERR(Debug::FILES, "Removing dir " 
328                                 << fromqstr(list.at(i).absoluteFilePath()));
329                         removed = rmdir(list.at(i));
330                 }
331                 else {
332                         LYXERR(Debug::FILES, "Removing file " 
333                                 << fromqstr(list.at(i).absoluteFilePath()));
334                         removed = dir.remove(list.at(i).fileName());
335                 }
336                 if (!removed) {
337                         success = false;
338                         LYXERR0("Could not delete "
339                                 << fromqstr(list.at(i).absoluteFilePath()));
340                 }
341         } 
342         QDir parent = fi.absolutePath();
343         success &= parent.rmdir(fi.fileName());
344         return success;
345 }
346
347
348 bool FileName::destroyDirectory() const
349 {
350         bool const success = rmdir(d->fi);
351         if (!success)
352                 LYXERR0("Could not delete " << *this);
353
354         return success;
355 }
356
357
358 bool FileName::createDirectory(int permission) const
359 {
360         BOOST_ASSERT(!empty());
361         return mkdir(*this, permission) == 0;
362 }
363
364
365 docstring const FileName::absoluteFilePath() const
366 {
367         return qstring_to_ucs4(d->fi.absoluteFilePath());
368 }
369
370
371 docstring FileName::displayName(int threshold) const
372 {
373         return makeDisplayPath(absFilename(), threshold);
374 }
375
376
377 docstring FileName::fileContents(string const & encoding) const
378 {
379         if (!isReadableFile()) {
380                 LYXERR0("File '" << *this << "' is not redable!");
381                 return docstring();
382         }
383
384         QFile file(d->fi.absoluteFilePath());
385         if (!file.open(QIODevice::ReadOnly)) {
386                 LYXERR0("File '" << *this
387                         << "' could not be opened in read only mode!");
388                 return docstring();
389         }
390         QByteArray contents = file.readAll();
391         file.close();
392
393         if (contents.isEmpty()) {
394                 LYXERR(Debug::FILES, "File '" << *this
395                         << "' is either empty or some error happened while reading it.");
396                 return docstring();
397         }
398
399         QString s;
400         if (encoding.empty() || encoding == "UTF-8")
401                 s = QString::fromUtf8(contents.data());
402         else if (encoding == "ascii")
403                 s = QString::fromAscii(contents.data());
404         else if (encoding == "local8bit")
405                 s = QString::fromLocal8Bit(contents.data());
406         else if (encoding == "latin1")
407                 s = QString::fromLatin1(contents.data());
408
409         return qstring_to_ucs4(s);
410 }
411
412
413 void FileName::changeExtension(std::string const & extension)
414 {
415         // FIXME: use Qt native methods...
416         string const oldname = absFilename();
417         string::size_type const last_slash = oldname.rfind('/');
418         string::size_type last_dot = oldname.rfind('.');
419         if (last_dot < last_slash && last_slash != string::npos)
420                 last_dot = string::npos;
421
422         string ext;
423         // Make sure the extension starts with a dot
424         if (!extension.empty() && extension[0] != '.')
425                 ext= '.' + extension;
426         else
427                 ext = extension;
428
429         set(oldname.substr(0, last_dot) + ext);
430 }
431
432
433 string FileName::guessFormatFromContents() const
434 {
435         // the different filetypes and what they contain in one of the first lines
436         // (dots are any characters).           (Herbert 20020131)
437         // AGR  Grace...
438         // BMP  BM...
439         // EPS  %!PS-Adobe-3.0 EPSF...
440         // FIG  #FIG...
441         // FITS ...BITPIX...
442         // GIF  GIF...
443         // JPG  JFIF
444         // PDF  %PDF-...
445         // PNG  .PNG...
446         // PBM  P1... or P4     (B/W)
447         // PGM  P2... or P5     (Grayscale)
448         // PPM  P3... or P6     (color)
449         // PS   %!PS-Adobe-2.0 or 1.0,  no "EPSF"!
450         // SGI  \001\332...     (decimal 474)
451         // TGIF %TGIF...
452         // TIFF II... or MM...
453         // XBM  ..._bits[]...
454         // XPM  /* XPM */    sometimes missing (f.ex. tgif-export)
455         //      ...static char *...
456         // XWD  \000\000\000\151        (0x00006900) decimal 105
457         //
458         // GZIP \037\213        http://www.ietf.org/rfc/rfc1952.txt
459         // ZIP  PK...                   http://www.halyava.ru/document/ind_arch.htm
460         // Z    \037\235                UNIX compress
461
462         // paranoia check
463         if (empty() || !isReadableFile())
464                 return string();
465
466         ifstream ifs(toFilesystemEncoding().c_str());
467         if (!ifs)
468                 // Couldn't open file...
469                 return string();
470
471         // gnuzip
472         static string const gzipStamp = "\037\213";
473
474         // PKZIP
475         static string const zipStamp = "PK";
476
477         // compress
478         static string const compressStamp = "\037\235";
479
480         // Maximum strings to read
481         int const max_count = 50;
482         int count = 0;
483
484         string str;
485         string format;
486         bool firstLine = true;
487         while ((count++ < max_count) && format.empty()) {
488                 if (ifs.eof()) {
489                         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
490                                 << "\tFile type not recognised before EOF!");
491                         break;
492                 }
493
494                 getline(ifs, str);
495                 string const stamp = str.substr(0, 2);
496                 if (firstLine && str.size() >= 2) {
497                         // at first we check for a zipped file, because this
498                         // information is saved in the first bytes of the file!
499                         // also some graphic formats which save the information
500                         // in the first line, too.
501                         if (prefixIs(str, gzipStamp)) {
502                                 format =  "gzip";
503
504                         } else if (stamp == zipStamp) {
505                                 format =  "zip";
506
507                         } else if (stamp == compressStamp) {
508                                 format =  "compress";
509
510                         // the graphics part
511                         } else if (stamp == "BM") {
512                                 format =  "bmp";
513
514                         } else if (stamp == "\001\332") {
515                                 format =  "sgi";
516
517                         // PBM family
518                         // Don't need to use str.at(0), str.at(1) because
519                         // we already know that str.size() >= 2
520                         } else if (str[0] == 'P') {
521                                 switch (str[1]) {
522                                 case '1':
523                                 case '4':
524                                         format =  "pbm";
525                                     break;
526                                 case '2':
527                                 case '5':
528                                         format =  "pgm";
529                                     break;
530                                 case '3':
531                                 case '6':
532                                         format =  "ppm";
533                                 }
534                                 break;
535
536                         } else if ((stamp == "II") || (stamp == "MM")) {
537                                 format =  "tiff";
538
539                         } else if (prefixIs(str,"%TGIF")) {
540                                 format =  "tgif";
541
542                         } else if (prefixIs(str,"#FIG")) {
543                                 format =  "fig";
544
545                         } else if (prefixIs(str,"GIF")) {
546                                 format =  "gif";
547
548                         } else if (str.size() > 3) {
549                                 int const c = ((str[0] << 24) & (str[1] << 16) &
550                                                (str[2] << 8)  & str[3]);
551                                 if (c == 105) {
552                                         format =  "xwd";
553                                 }
554                         }
555
556                         firstLine = false;
557                 }
558
559                 if (!format.empty())
560                     break;
561                 else if (contains(str,"EPSF"))
562                         // dummy, if we have wrong file description like
563                         // %!PS-Adobe-2.0EPSF"
564                         format = "eps";
565
566                 else if (contains(str, "Grace"))
567                         format = "agr";
568
569                 else if (contains(str, "JFIF"))
570                         format = "jpg";
571
572                 else if (contains(str, "%PDF"))
573                         format = "pdf";
574
575                 else if (contains(str, "PNG"))
576                         format = "png";
577
578                 else if (contains(str, "%!PS-Adobe")) {
579                         // eps or ps
580                         ifs >> str;
581                         if (contains(str,"EPSF"))
582                                 format = "eps";
583                         else
584                             format = "ps";
585                 }
586
587                 else if (contains(str, "_bits[]"))
588                         format = "xbm";
589
590                 else if (contains(str, "XPM") || contains(str, "static char *"))
591                         format = "xpm";
592
593                 else if (contains(str, "BITPIX"))
594                         format = "fits";
595         }
596
597         if (!format.empty()) {
598                 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
599                 return format;
600         }
601
602         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
603                 << "\tCouldn't find a known format!");
604         return string();
605 }
606
607
608 bool FileName::isZippedFile() const
609 {
610         string const type = guessFormatFromContents();
611         return contains("gzip zip compress", type) && !type.empty();
612 }
613
614
615 docstring const FileName::relPath(string const & path) const
616 {
617         // FIXME UNICODE
618         return makeRelPath(absoluteFilePath(), from_utf8(path));
619 }
620
621
622 bool operator==(FileName const & lhs, FileName const & rhs)
623 {
624         return lhs.absFilename() == rhs.absFilename();
625 }
626
627
628 bool operator!=(FileName const & lhs, FileName const & rhs)
629 {
630         return lhs.absFilename() != rhs.absFilename();
631 }
632
633
634 bool operator<(FileName const & lhs, FileName const & rhs)
635 {
636         return lhs.absFilename() < rhs.absFilename();
637 }
638
639
640 bool operator>(FileName const & lhs, FileName const & rhs)
641 {
642         return lhs.absFilename() > rhs.absFilename();
643 }
644
645
646 std::ostream & operator<<(std::ostream & os, FileName const & filename)
647 {
648         return os << filename.absFilename();
649 }
650
651
652 /////////////////////////////////////////////////////////////////////
653 //
654 // DocFileName
655 //
656 /////////////////////////////////////////////////////////////////////
657
658
659 DocFileName::DocFileName()
660         : save_abs_path_(true)
661 {}
662
663
664 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
665         : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
666 {}
667
668
669 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
670         : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
671 {}
672
673
674 void DocFileName::set(string const & name, string const & buffer_path)
675 {
676         save_abs_path_ = absolutePath(name);
677         FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
678         zipped_valid_ = false;
679 }
680
681
682 void DocFileName::erase()
683 {
684         FileName::erase();
685         zipped_valid_ = false;
686 }
687
688
689 string DocFileName::relFilename(string const & path) const
690 {
691         // FIXME UNICODE
692         return to_utf8(relPath(path));
693 }
694
695
696 string DocFileName::outputFilename(string const & path) const
697 {
698         return save_abs_path_ ? absFilename() : relFilename(path);
699 }
700
701
702 string DocFileName::mangledFilename(std::string const & dir) const
703 {
704         // We need to make sure that every DocFileName instance for a given
705         // filename returns the same mangled name.
706         typedef map<string, string> MangledMap;
707         static MangledMap mangledNames;
708         MangledMap::const_iterator const it = mangledNames.find(absFilename());
709         if (it != mangledNames.end())
710                 return (*it).second;
711
712         string const name = absFilename();
713         // Now the real work
714         string mname = os::internal_path(name);
715         // Remove the extension.
716         mname = support::changeExtension(name, string());
717         // The mangled name must be a valid LaTeX name.
718         // The list of characters to keep is probably over-restrictive,
719         // but it is not really a problem.
720         // Apart from non-ASCII characters, at least the following characters
721         // are forbidden: '/', '.', ' ', and ':'.
722         // On windows it is not possible to create files with '<', '>' or '?'
723         // in the name.
724         static string const keep = "abcdefghijklmnopqrstuvwxyz"
725                                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
726                                    "+,-0123456789;=";
727         string::size_type pos = 0;
728         while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
729                 mname[pos++] = '_';
730         // Add the extension back on
731         mname = support::changeExtension(mname, getExtension(name));
732
733         // Prepend a counter to the filename. This is necessary to make
734         // the mangled name unique.
735         static int counter = 0;
736         std::ostringstream s;
737         s << counter++ << mname;
738         mname = s.str();
739
740         // MiKTeX's YAP (version 2.4.1803) crashes if the file name
741         // is longer than about 160 characters. MiKTeX's pdflatex
742         // is even pickier. A maximum length of 100 has been proven to work.
743         // If dir.size() > max length, all bets are off for YAP. We truncate
744         // the filename nevertheless, keeping a minimum of 10 chars.
745
746         string::size_type max_length = std::max(100 - ((int)dir.size() + 1), 10);
747
748         // If the mangled file name is too long, hack it to fit.
749         // We know we're guaranteed to have a unique file name because
750         // of the counter.
751         if (mname.size() > max_length) {
752                 int const half = (int(max_length) / 2) - 2;
753                 if (half > 0) {
754                         mname = mname.substr(0, half) + "___" +
755                                 mname.substr(mname.size() - half);
756                 }
757         }
758
759         mangledNames[absFilename()] = mname;
760         return mname;
761 }
762
763
764 bool DocFileName::isZipped() const
765 {
766         if (!zipped_valid_) {
767                 zipped_ = isZippedFile();
768                 zipped_valid_ = true;
769         }
770         return zipped_;
771 }
772
773
774 string DocFileName::unzippedFilename() const
775 {
776         return unzippedFileName(absFilename());
777 }
778
779
780 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
781 {
782         return lhs.absFilename() == rhs.absFilename()
783                 && lhs.saveAbsPath() == rhs.saveAbsPath();
784 }
785
786
787 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
788 {
789         return !(lhs == rhs);
790 }
791
792 } // namespace support
793 } // namespace lyx