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