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