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