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