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