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