]> git.lyx.org Git - lyx.git/blob - src/support/FileName.cpp
The rename() function removed in rev had in fact move() functionality. So we replace...
[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/FileNameList.h"
15
16 #include "support/debug.h"
17 #include "support/filetools.h"
18 #include "support/lstrings.h"
19 #include "support/lyxlib.h"
20 #include "support/os.h"
21 #include "support/qstring_helpers.h"
22
23 #include <QDateTime>
24 #include <QDir>
25 #include <QFile>
26 #include <QFileInfo>
27 #include <QList>
28 #include <QTime>
29
30 #include <boost/assert.hpp>
31
32 #include <map>
33 #include <sstream>
34 #include <fstream>
35 #include <algorithm>
36
37 #ifdef HAVE_SYS_TYPES_H
38 # include <sys/types.h>
39 #endif
40 #ifdef HAVE_SYS_STAT_H
41 # include <sys/stat.h>
42 #endif
43 #include <cerrno>
44 #include <fcntl.h>
45
46 using namespace std;
47
48 namespace lyx {
49 namespace support {
50
51
52 /////////////////////////////////////////////////////////////////////
53 //
54 // FileName::Private
55 //
56 /////////////////////////////////////////////////////////////////////
57
58 struct FileName::Private
59 {
60         Private() {}
61
62         Private(string const & abs_filename) : fi(toqstr(abs_filename))
63         {
64                 fi.setCaching(fi.exists() ? true : false);
65         }
66         ///
67         QFileInfo fi;
68 };
69
70 /////////////////////////////////////////////////////////////////////
71 //
72 // FileName
73 //
74 /////////////////////////////////////////////////////////////////////
75
76
77 FileName::FileName() : d(new Private)
78 {
79 }
80
81
82 FileName::FileName(string const & abs_filename)
83         : d(abs_filename.empty() ? new Private : new Private(abs_filename))
84 {
85 }
86
87
88 FileName::~FileName()
89 {
90         delete d;
91 }
92
93
94 FileName::FileName(FileName const & rhs) : d(new Private)
95 {
96         d->fi = rhs.d->fi;
97 }
98
99
100 FileName & FileName::operator=(FileName const & rhs)
101 {
102         d->fi = rhs.d->fi;
103         return *this;
104 }
105
106
107 bool FileName::empty() const
108 {
109         return d->fi.absoluteFilePath().isEmpty();
110 }
111
112
113 string FileName::absFilename() const
114 {
115         return fromqstr(d->fi.absoluteFilePath());
116 }
117
118
119 void FileName::set(string const & name)
120 {
121         d->fi.setFile(toqstr(name));
122         BOOST_ASSERT(d->fi.isAbsolute());
123 }
124
125
126 void FileName::erase()
127 {
128         d->fi = QFileInfo();
129 }
130
131
132 bool FileName::copyTo(FileName const & name, bool overwrite) const
133 {
134         if (overwrite)
135                 QFile::remove(name.d->fi.absoluteFilePath());
136         bool success = QFile::copy(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
137         if (!success)
138                 lyxerr << "FileName::copyTo(): Could not copy file "
139                         << *this << " to " << name << endl;
140         return success;
141 }
142
143
144 bool FileName::renameTo(FileName const & name) const
145 {
146         bool success = QFile::rename(d->fi.absoluteFilePath(), name.d->fi.absoluteFilePath());
147         if (!success)
148                 LYXERR0("Could not rename file " << *this << " to " << name);
149         return success;
150 }
151
152
153 bool FileName::moveTo(FileName const & name) const
154 {
155         if (name.exists() && !name.removeFile())
156                 return false;
157
158         bool success = QFile::rename(d->fi.absoluteFilePath(),
159                 name.d->fi.absoluteFilePath());
160         if (!success)
161                 LYXERR0("Could not move file " << *this << " to " << name);
162         return success;
163 }
164
165
166 bool FileName::changePermission(unsigned long int mode) const
167 {
168         if (!isWritable()) {
169                 LYXERR0("File " << *this << " is not writable!");
170                 return false;
171         }
172
173 #if defined (HAVE_CHMOD) && defined (HAVE_MODE_T)
174         if (::chmod(toFilesystemEncoding().c_str(), mode_t(mode)) != 0) {
175                 LYXERR0("File " << *this << ": cannot change permission to "
176                         << mode << ".");
177                 return false;
178         }
179 #endif
180         return true;
181 }
182
183
184 string FileName::toFilesystemEncoding() const
185 {
186         QByteArray const encoded = QFile::encodeName(d->fi.absoluteFilePath());
187         return string(encoded.begin(), encoded.end());
188 }
189
190
191 FileName FileName::fromFilesystemEncoding(string const & name)
192 {
193         QByteArray const encoded(name.c_str(), name.length());
194         return FileName(fromqstr(QFile::decodeName(encoded)));
195 }
196
197
198 bool FileName::exists() const
199 {
200         return d->fi.exists();
201 }
202
203
204 bool FileName::isSymLink() const
205 {
206         return d->fi.isSymLink();
207 }
208
209
210 bool FileName::isFileEmpty() const
211 {
212         return d->fi.size() == 0;
213 }
214
215
216 bool FileName::isDirectory() const
217 {
218         return d->fi.isDir();
219 }
220
221
222 bool FileName::isReadOnly() const
223 {
224         return d->fi.isReadable() && !d->fi.isWritable();
225 }
226
227
228 bool FileName::isReadableDirectory() const
229 {
230         return d->fi.isDir() && d->fi.isReadable();
231 }
232
233
234 string FileName::onlyFileName() const
235 {
236         return support::onlyFilename(absFilename());
237 }
238
239
240 FileName FileName::onlyPath() const
241 {
242         return FileName(support::onlyPath(absFilename()));
243 }
244
245
246 bool FileName::isReadableFile() const
247 {
248         return d->fi.isFile() && d->fi.isReadable();
249 }
250
251
252 bool FileName::isWritable() const
253 {
254         return d->fi.isWritable();
255 }
256
257
258 bool FileName::isDirWritable() const
259 {
260         LYXERR(Debug::FILES, "isDirWriteable: " << *this);
261
262         FileName const tmpfl(tempName(*this, "lyxwritetest"));
263
264         if (tmpfl.empty())
265                 return false;
266
267         tmpfl.removeFile();
268         return true;
269 }
270
271
272 FileNameList FileName::dirList(string const & ext) const
273 {
274         FileNameList dirlist;
275         if (!isDirectory()) {
276                 LYXERR0("Directory '" << *this << "' does not exist!");
277                 return dirlist;
278         }
279
280         QDir dir = d->fi.absoluteDir();
281
282         if (!ext.empty()) {
283                 QString filter;
284                 switch (ext[0]) {
285                 case '.': filter = "*" + toqstr(ext); break;
286                 case '*': filter = toqstr(ext); break;
287                 default: filter = "*." + toqstr(ext);
288                 }
289                 dir.setNameFilters(QStringList(filter));
290                 LYXERR(Debug::FILES, "filtering on extension "
291                         << fromqstr(filter) << " is requested.");
292         }
293
294         QFileInfoList list = dir.entryInfoList();
295         for (int i = 0; i != list.size(); ++i) {
296                 FileName fi(fromqstr(list.at(i).absoluteFilePath()));
297                 dirlist.push_back(fi);
298                 LYXERR(Debug::FILES, "found file " << fi);
299         }
300
301         return dirlist;
302 }
303
304
305 FileName FileName::tempName(FileName const & dir, string const & mask)
306 {
307         return support::tempName(dir, mask);
308 }
309
310
311 time_t FileName::lastModified() const
312 {
313         return d->fi.lastModified().toTime_t();
314 }
315
316
317 bool FileName::chdir() const
318 {
319         return QDir::setCurrent(d->fi.absoluteFilePath());
320 }
321
322
323 extern unsigned long sum(char const * file);
324
325 unsigned long FileName::checksum() const
326 {
327         if (!exists()) {
328                 LYXERR0("File \"" << absFilename() << "\" does not exist!");
329                 return 0;
330         }
331         // a directory may be passed here so we need to test it. (bug 3622)
332         if (isDirectory()) {
333                 LYXERR0('"' << absFilename() << "\" is a directory!");
334                 return 0;
335         }
336         if (!lyxerr.debugging(Debug::FILES))
337                 return sum(absFilename().c_str());
338
339         QTime t;
340         t.start();
341         unsigned long r = sum(absFilename().c_str());
342         lyxerr << "Checksumming \"" << absFilename() << "\" lasted "
343                 << t.elapsed() << " ms." << endl;
344         return r;
345 }
346
347
348 bool FileName::removeFile() const
349 {
350         bool const success = QFile::remove(d->fi.absoluteFilePath());
351         if (!success && exists())
352                 LYXERR0("Could not delete file " << *this);
353         return success;
354 }
355
356
357 static bool rmdir(QFileInfo const & fi)
358 {
359         QDir dir(fi.absoluteFilePath());
360         QFileInfoList list = dir.entryInfoList();
361         bool success = true;
362         for (int i = 0; i != list.size(); ++i) {
363                 if (list.at(i).fileName() == ".")
364                         continue;
365                 if (list.at(i).fileName() == "..")
366                         continue;
367                 bool removed;
368                 if (list.at(i).isDir()) {
369                         LYXERR(Debug::FILES, "Removing dir " 
370                                 << fromqstr(list.at(i).absoluteFilePath()));
371                         removed = rmdir(list.at(i));
372                 }
373                 else {
374                         LYXERR(Debug::FILES, "Removing file " 
375                                 << fromqstr(list.at(i).absoluteFilePath()));
376                         removed = dir.remove(list.at(i).fileName());
377                 }
378                 if (!removed) {
379                         success = false;
380                         LYXERR0("Could not delete "
381                                 << fromqstr(list.at(i).absoluteFilePath()));
382                 }
383         } 
384         QDir parent = fi.absolutePath();
385         success &= parent.rmdir(fi.fileName());
386         return success;
387 }
388
389
390 bool FileName::destroyDirectory() const
391 {
392         bool const success = rmdir(d->fi);
393         if (!success)
394                 LYXERR0("Could not delete " << *this);
395
396         return success;
397 }
398
399
400 bool FileName::createDirectory(int permission) const
401 {
402         BOOST_ASSERT(!empty());
403         return mkdir(*this, permission) == 0;
404 }
405
406
407 docstring const FileName::absoluteFilePath() const
408 {
409         return qstring_to_ucs4(d->fi.absoluteFilePath());
410 }
411
412
413 docstring FileName::displayName(int threshold) const
414 {
415         return makeDisplayPath(absFilename(), threshold);
416 }
417
418
419 docstring FileName::fileContents(string const & encoding) const
420 {
421         if (!isReadableFile()) {
422                 LYXERR0("File '" << *this << "' is not redable!");
423                 return docstring();
424         }
425
426         QFile file(d->fi.absoluteFilePath());
427         if (!file.open(QIODevice::ReadOnly)) {
428                 LYXERR0("File '" << *this
429                         << "' could not be opened in read only mode!");
430                 return docstring();
431         }
432         QByteArray contents = file.readAll();
433         file.close();
434
435         if (contents.isEmpty()) {
436                 LYXERR(Debug::FILES, "File '" << *this
437                         << "' is either empty or some error happened while reading it.");
438                 return docstring();
439         }
440
441         QString s;
442         if (encoding.empty() || encoding == "UTF-8")
443                 s = QString::fromUtf8(contents.data());
444         else if (encoding == "ascii")
445                 s = QString::fromAscii(contents.data());
446         else if (encoding == "local8bit")
447                 s = QString::fromLocal8Bit(contents.data());
448         else if (encoding == "latin1")
449                 s = QString::fromLatin1(contents.data());
450
451         return qstring_to_ucs4(s);
452 }
453
454
455 void FileName::changeExtension(string const & extension)
456 {
457         // FIXME: use Qt native methods...
458         string const oldname = absFilename();
459         string::size_type const last_slash = oldname.rfind('/');
460         string::size_type last_dot = oldname.rfind('.');
461         if (last_dot < last_slash && last_slash != string::npos)
462                 last_dot = string::npos;
463
464         string ext;
465         // Make sure the extension starts with a dot
466         if (!extension.empty() && extension[0] != '.')
467                 ext= '.' + extension;
468         else
469                 ext = extension;
470
471         set(oldname.substr(0, last_dot) + ext);
472 }
473
474
475 string FileName::guessFormatFromContents() const
476 {
477         // the different filetypes and what they contain in one of the first lines
478         // (dots are any characters).           (Herbert 20020131)
479         // AGR  Grace...
480         // BMP  BM...
481         // EPS  %!PS-Adobe-3.0 EPSF...
482         // FIG  #FIG...
483         // FITS ...BITPIX...
484         // GIF  GIF...
485         // JPG  JFIF
486         // PDF  %PDF-...
487         // PNG  .PNG...
488         // PBM  P1... or P4     (B/W)
489         // PGM  P2... or P5     (Grayscale)
490         // PPM  P3... or P6     (color)
491         // PS   %!PS-Adobe-2.0 or 1.0,  no "EPSF"!
492         // SGI  \001\332...     (decimal 474)
493         // TGIF %TGIF...
494         // TIFF II... or MM...
495         // XBM  ..._bits[]...
496         // XPM  /* XPM */    sometimes missing (f.ex. tgif-export)
497         //      ...static char *...
498         // XWD  \000\000\000\151        (0x00006900) decimal 105
499         //
500         // GZIP \037\213        http://www.ietf.org/rfc/rfc1952.txt
501         // ZIP  PK...                   http://www.halyava.ru/document/ind_arch.htm
502         // Z    \037\235                UNIX compress
503
504         // paranoia check
505         if (empty() || !isReadableFile())
506                 return string();
507
508         ifstream ifs(toFilesystemEncoding().c_str());
509         if (!ifs)
510                 // Couldn't open file...
511                 return string();
512
513         // gnuzip
514         static string const gzipStamp = "\037\213";
515
516         // PKZIP
517         static string const zipStamp = "PK";
518
519         // compress
520         static string const compressStamp = "\037\235";
521
522         // Maximum strings to read
523         int const max_count = 50;
524         int count = 0;
525
526         string str;
527         string format;
528         bool firstLine = true;
529         while ((count++ < max_count) && format.empty()) {
530                 if (ifs.eof()) {
531                         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
532                                 << "\tFile type not recognised before EOF!");
533                         break;
534                 }
535
536                 getline(ifs, str);
537                 string const stamp = str.substr(0, 2);
538                 if (firstLine && str.size() >= 2) {
539                         // at first we check for a zipped file, because this
540                         // information is saved in the first bytes of the file!
541                         // also some graphic formats which save the information
542                         // in the first line, too.
543                         if (prefixIs(str, gzipStamp)) {
544                                 format =  "gzip";
545
546                         } else if (stamp == zipStamp) {
547                                 format =  "zip";
548
549                         } else if (stamp == compressStamp) {
550                                 format =  "compress";
551
552                         // the graphics part
553                         } else if (stamp == "BM") {
554                                 format =  "bmp";
555
556                         } else if (stamp == "\001\332") {
557                                 format =  "sgi";
558
559                         // PBM family
560                         // Don't need to use str.at(0), str.at(1) because
561                         // we already know that str.size() >= 2
562                         } else if (str[0] == 'P') {
563                                 switch (str[1]) {
564                                 case '1':
565                                 case '4':
566                                         format =  "pbm";
567                                     break;
568                                 case '2':
569                                 case '5':
570                                         format =  "pgm";
571                                     break;
572                                 case '3':
573                                 case '6':
574                                         format =  "ppm";
575                                 }
576                                 break;
577
578                         } else if ((stamp == "II") || (stamp == "MM")) {
579                                 format =  "tiff";
580
581                         } else if (prefixIs(str,"%TGIF")) {
582                                 format =  "tgif";
583
584                         } else if (prefixIs(str,"#FIG")) {
585                                 format =  "fig";
586
587                         } else if (prefixIs(str,"GIF")) {
588                                 format =  "gif";
589
590                         } else if (str.size() > 3) {
591                                 int const c = ((str[0] << 24) & (str[1] << 16) &
592                                                (str[2] << 8)  & str[3]);
593                                 if (c == 105) {
594                                         format =  "xwd";
595                                 }
596                         }
597
598                         firstLine = false;
599                 }
600
601                 if (!format.empty())
602                     break;
603                 else if (contains(str,"EPSF"))
604                         // dummy, if we have wrong file description like
605                         // %!PS-Adobe-2.0EPSF"
606                         format = "eps";
607
608                 else if (contains(str, "Grace"))
609                         format = "agr";
610
611                 else if (contains(str, "JFIF"))
612                         format = "jpg";
613
614                 else if (contains(str, "%PDF"))
615                         format = "pdf";
616
617                 else if (contains(str, "PNG"))
618                         format = "png";
619
620                 else if (contains(str, "%!PS-Adobe")) {
621                         // eps or ps
622                         ifs >> str;
623                         if (contains(str,"EPSF"))
624                                 format = "eps";
625                         else
626                             format = "ps";
627                 }
628
629                 else if (contains(str, "_bits[]"))
630                         format = "xbm";
631
632                 else if (contains(str, "XPM") || contains(str, "static char *"))
633                         format = "xpm";
634
635                 else if (contains(str, "BITPIX"))
636                         format = "fits";
637         }
638
639         if (!format.empty()) {
640                 LYXERR(Debug::GRAPHICS, "Recognised Fileformat: " << format);
641                 return format;
642         }
643
644         LYXERR(Debug::GRAPHICS, "filetools(getFormatFromContents)\n"
645                 << "\tCouldn't find a known format!");
646         return string();
647 }
648
649
650 bool FileName::isZippedFile() const
651 {
652         string const type = guessFormatFromContents();
653         return contains("gzip zip compress", type) && !type.empty();
654 }
655
656
657 docstring const FileName::relPath(string const & path) const
658 {
659         // FIXME UNICODE
660         return makeRelPath(absoluteFilePath(), from_utf8(path));
661 }
662
663
664 bool operator==(FileName const & lhs, FileName const & rhs)
665 {
666         return lhs.absFilename() == rhs.absFilename();
667 }
668
669
670 bool operator!=(FileName const & lhs, FileName const & rhs)
671 {
672         return lhs.absFilename() != rhs.absFilename();
673 }
674
675
676 bool operator<(FileName const & lhs, FileName const & rhs)
677 {
678         return lhs.absFilename() < rhs.absFilename();
679 }
680
681
682 bool operator>(FileName const & lhs, FileName const & rhs)
683 {
684         return lhs.absFilename() > rhs.absFilename();
685 }
686
687
688 ostream & operator<<(ostream & os, FileName const & filename)
689 {
690         return os << filename.absFilename();
691 }
692
693
694 /////////////////////////////////////////////////////////////////////
695 //
696 // DocFileName
697 //
698 /////////////////////////////////////////////////////////////////////
699
700
701 DocFileName::DocFileName()
702         : save_abs_path_(true)
703 {}
704
705
706 DocFileName::DocFileName(string const & abs_filename, bool save_abs)
707         : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
708 {}
709
710
711 DocFileName::DocFileName(FileName const & abs_filename, bool save_abs)
712         : FileName(abs_filename), save_abs_path_(save_abs), zipped_valid_(false)
713 {}
714
715
716 void DocFileName::set(string const & name, string const & buffer_path)
717 {
718         save_abs_path_ = absolutePath(name);
719         FileName::set(save_abs_path_ ? name : makeAbsPath(name, buffer_path).absFilename());
720         zipped_valid_ = false;
721 }
722
723
724 void DocFileName::erase()
725 {
726         FileName::erase();
727         zipped_valid_ = false;
728 }
729
730
731 string DocFileName::relFilename(string const & path) const
732 {
733         // FIXME UNICODE
734         return to_utf8(relPath(path));
735 }
736
737
738 string DocFileName::outputFilename(string const & path) const
739 {
740         return save_abs_path_ ? absFilename() : relFilename(path);
741 }
742
743
744 string DocFileName::mangledFilename(string const & dir) const
745 {
746         // We need to make sure that every DocFileName instance for a given
747         // filename returns the same mangled name.
748         typedef map<string, string> MangledMap;
749         static MangledMap mangledNames;
750         MangledMap::const_iterator const it = mangledNames.find(absFilename());
751         if (it != mangledNames.end())
752                 return (*it).second;
753
754         string const name = absFilename();
755         // Now the real work
756         string mname = os::internal_path(name);
757         // Remove the extension.
758         mname = support::changeExtension(name, string());
759         // The mangled name must be a valid LaTeX name.
760         // The list of characters to keep is probably over-restrictive,
761         // but it is not really a problem.
762         // Apart from non-ASCII characters, at least the following characters
763         // are forbidden: '/', '.', ' ', and ':'.
764         // On windows it is not possible to create files with '<', '>' or '?'
765         // in the name.
766         static string const keep = "abcdefghijklmnopqrstuvwxyz"
767                                    "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
768                                    "+,-0123456789;=";
769         string::size_type pos = 0;
770         while ((pos = mname.find_first_not_of(keep, pos)) != string::npos)
771                 mname[pos++] = '_';
772         // Add the extension back on
773         mname = support::changeExtension(mname, getExtension(name));
774
775         // Prepend a counter to the filename. This is necessary to make
776         // the mangled name unique.
777         static int counter = 0;
778         ostringstream s;
779         s << counter++ << mname;
780         mname = s.str();
781
782         // MiKTeX's YAP (version 2.4.1803) crashes if the file name
783         // is longer than about 160 characters. MiKTeX's pdflatex
784         // is even pickier. A maximum length of 100 has been proven to work.
785         // If dir.size() > max length, all bets are off for YAP. We truncate
786         // the filename nevertheless, keeping a minimum of 10 chars.
787
788         string::size_type max_length = max(100 - ((int)dir.size() + 1), 10);
789
790         // If the mangled file name is too long, hack it to fit.
791         // We know we're guaranteed to have a unique file name because
792         // of the counter.
793         if (mname.size() > max_length) {
794                 int const half = (int(max_length) / 2) - 2;
795                 if (half > 0) {
796                         mname = mname.substr(0, half) + "___" +
797                                 mname.substr(mname.size() - half);
798                 }
799         }
800
801         mangledNames[absFilename()] = mname;
802         return mname;
803 }
804
805
806 bool DocFileName::isZipped() const
807 {
808         if (!zipped_valid_) {
809                 zipped_ = isZippedFile();
810                 zipped_valid_ = true;
811         }
812         return zipped_;
813 }
814
815
816 string DocFileName::unzippedFilename() const
817 {
818         return unzippedFileName(absFilename());
819 }
820
821
822 bool operator==(DocFileName const & lhs, DocFileName const & rhs)
823 {
824         return lhs.absFilename() == rhs.absFilename()
825                 && lhs.saveAbsPath() == rhs.saveAbsPath();
826 }
827
828
829 bool operator!=(DocFileName const & lhs, DocFileName const & rhs)
830 {
831         return !(lhs == rhs);
832 }
833
834 } // namespace support
835 } // namespace lyx