]> git.lyx.org Git - lyx.git/blob - src/support/filetools.C
forward port latex_path quoting fix from 1.3
[lyx.git] / src / support / filetools.C
1 /**
2  * \file filetools.C
3  * This file is part of LyX, the document processor.
4  * Licence details can be found in the file COPYING.
5  *
6  * parts Copyright 1985, 1990, 1993 Free Software Foundation, Inc.
7  *
8  * \author Ivan Schreter
9  * \author Dirk Niggemann
10  * \author Asger Alstrup
11  * \author Lars Gullik Bjønnes
12  * \author Jean-Marc Lasgouttes
13  * \author Angus Leeming
14  * \author John Levon
15  * \author Herbert Voß
16  *
17  * Full author contact details are available in file CREDITS.
18  *
19  * General path-mangling functions
20  */
21
22 #include <config.h>
23
24 #include "support/convert.h"
25 #include "support/environment.h"
26 #include "support/filetools.h"
27 #include "support/fs_extras.h"
28 #include "support/lstrings.h"
29 #include "support/lyxlib.h"
30 #include "support/os.h"
31 #include "support/package.h"
32 #include "support/path.h"
33 #include "support/systemcall.h"
34
35 // FIXME Interface violation
36 #include "gettext.h"
37 #include "debug.h"
38
39 #include <boost/assert.hpp>
40 #include <boost/filesystem/operations.hpp>
41 #include <boost/regex.hpp>
42
43 #include <fcntl.h>
44
45 #include <cctype>
46 #include <cerrno>
47 #include <cstdlib>
48 #include <cstdio>
49
50 #include <utility>
51 #include <fstream>
52 #include <sstream>
53
54 #ifndef CXX_GLOBAL_CSTD
55 using std::fgetc;
56 using std::isalnum;
57 using std::isalpha;
58 #endif
59
60 using std::endl;
61 using std::getline;
62 using std::make_pair;
63 using std::string;
64 using std::ifstream;
65 using std::ostringstream;
66 using std::vector;
67
68 namespace fs = boost::filesystem;
69
70 namespace lyx {
71 namespace support {
72
73 bool IsLyXFilename(string const & filename)
74 {
75         return suffixIs(ascii_lowercase(filename), ".lyx");
76 }
77
78
79 bool IsSGMLFilename(string const & filename)
80 {
81         return suffixIs(ascii_lowercase(filename), ".sgml");
82 }
83
84
85 string const latex_path(string const & original_path, bool exclude_extension)
86 {
87         string path = subst(original_path, "\\", "/");
88         path = subst(path, "~", "\\string~");
89         if (path.find(' ') != string::npos)
90                 // We can't use '"' because " is sometimes active (e.g. if
91                 // babel is loaded with the "german" option)
92                 if (exclude_extension) {
93                         string const base = ChangeExtension(path, string());
94                         string const ext = GetExtension(path);
95                         // ChangeExtension calls os::internal_path internally
96                         // so don't use it to re-add the extension.
97                         path = "\\string\"" + base + "\\string\"." + ext;
98                 } else
99                         path = "\\string\"" + path + "\\string\"";
100         return path;
101 }
102
103
104 // Substitutes spaces with underscores in filename (and path)
105 string const MakeLatexName(string const & file)
106 {
107         string name = OnlyFilename(file);
108         string const path = OnlyPath(file);
109
110         for (string::size_type i = 0; i < name.length(); ++i) {
111                 name[i] &= 0x7f; // set 8th bit to 0
112         };
113
114         // ok so we scan through the string twice, but who cares.
115         string const keep("abcdefghijklmnopqrstuvwxyz"
116                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
117                 "@!\"'()*+,-./0123456789:;<=>?[]`|");
118
119         string::size_type pos = 0;
120         while ((pos = name.find_first_not_of(keep, pos)) != string::npos) {
121                 name[pos++] = '_';
122         }
123         return AddName(path, name);
124 }
125
126
127 string const QuoteName(string const & name)
128 {
129         return (os::shell() == os::UNIX) ?
130                 '\'' + name + '\'':
131                 '"' + name + '"';
132 }
133
134
135 // Is a file readable ?
136 bool IsFileReadable(string const & path)
137 {
138         return fs::exists(path) && !fs::is_directory(path) && fs::is_readable(path);
139 }
140
141
142 //returns true: dir writeable
143 //        false: not writeable
144 bool IsDirWriteable(string const & path)
145 {
146         lyxerr[Debug::FILES] << "IsDirWriteable: " << path << endl;
147
148         string const tmpfl(tempName(path, "lyxwritetest"));
149
150         if (tmpfl.empty())
151                 return false;
152
153         unlink(tmpfl);
154         return true;
155 }
156
157
158 // Uses a string of paths separated by ";"s to find a file to open.
159 // Can't cope with pathnames with a ';' in them. Returns full path to file.
160 // If path entry begins with $$LyX/, use system_lyxdir
161 // If path entry begins with $$User/, use user_lyxdir
162 // Example: "$$User/doc;$$LyX/doc"
163 string const FileOpenSearch(string const & path, string const & name,
164                              string const & ext)
165 {
166         string real_file;
167         string path_element;
168         bool notfound = true;
169         string tmppath = split(path, path_element, ';');
170
171         while (notfound && !path_element.empty()) {
172                 path_element = os::internal_path(path_element);
173                 if (!suffixIs(path_element, '/'))
174                         path_element+= '/';
175                 path_element = subst(path_element, "$$LyX",
176                                      package().system_support());
177                 path_element = subst(path_element, "$$User",
178                                      package().user_support());
179
180                 real_file = FileSearch(path_element, name, ext);
181
182                 if (real_file.empty()) {
183                         do {
184                                 tmppath = split(tmppath, path_element, ';');
185                         } while (!tmppath.empty() && path_element.empty());
186                 } else {
187                         notfound = false;
188                 }
189         }
190 #ifdef __EMX__
191         if (ext.empty() && notfound) {
192                 real_file = FileOpenSearch(path, name, "exe");
193                 if (notfound) real_file = FileOpenSearch(path, name, "cmd");
194         }
195 #endif
196         return real_file;
197 }
198
199
200 /// Returns a vector of all files in directory dir having extension ext.
201 vector<string> const DirList(string const & dir, string const & ext)
202 {
203         // EXCEPTIONS FIXME. Rewrite needed when we turn on exceptions. (Lgb)
204         vector<string> dirlist;
205
206         if (!(fs::exists(dir) && fs::is_directory(dir))) {
207                 lyxerr[Debug::FILES]
208                         << "Directory \"" << dir
209                         << "\" does not exist to DirList." << endl;
210                 return dirlist;
211         }
212
213         string extension;
214         if (!ext.empty() && ext[0] != '.')
215                 extension += '.';
216         extension += ext;
217
218         fs::directory_iterator dit(dir);
219         fs::directory_iterator end;
220         for (; dit != end; ++dit) {
221                 string const & fil = dit->leaf();
222                 if (suffixIs(fil, extension)) {
223                         dirlist.push_back(fil);
224                 }
225         }
226         return dirlist;
227 }
228
229
230 // Returns the real name of file name in directory path, with optional
231 // extension ext.
232 string const FileSearch(string const & path, string const & name,
233                         string const & ext)
234 {
235         // if `name' is an absolute path, we ignore the setting of `path'
236         // Expand Environmentvariables in 'name'
237         string const tmpname = ReplaceEnvironmentPath(name);
238         string fullname = MakeAbsPath(tmpname, path);
239         // search first without extension, then with it.
240         if (IsFileReadable(fullname))
241                 return fullname;
242         else if (ext.empty())
243                 return string();
244         else { // Is it not more reasonable to use ChangeExtension()? (SMiyata)
245                 fullname += '.';
246                 fullname += ext;
247                 if (IsFileReadable(fullname))
248                         return fullname;
249                 else
250                         return string();
251         }
252 }
253
254
255 // Search the file name.ext in the subdirectory dir of
256 //   1) user_lyxdir
257 //   2) build_lyxdir (if not empty)
258 //   3) system_lyxdir
259 string const LibFileSearch(string const & dir, string const & name,
260                            string const & ext)
261 {
262         string fullname = FileSearch(AddPath(package().user_support(), dir),
263                                      name, ext);
264         if (!fullname.empty())
265                 return fullname;
266
267         if (!package().build_support().empty())
268                 fullname = FileSearch(AddPath(package().build_support(), dir),
269                                       name, ext);
270         if (!fullname.empty())
271                 return fullname;
272
273         return FileSearch(AddPath(package().system_support(), dir), name, ext);
274 }
275
276
277 string const
278 i18nLibFileSearch(string const & dir, string const & name,
279                   string const & ext)
280 {
281         // the following comments are from intl/dcigettext.c. We try
282         // to mimick this behaviour here.
283         /* The highest priority value is the `LANGUAGE' environment
284            variable. But we don't use the value if the currently
285            selected locale is the C locale. This is a GNU extension. */
286         /* [Otherwise] We have to proceed with the POSIX methods of
287            looking to `LC_ALL', `LC_xxx', and `LANG'. */
288
289         string lang = getEnv("LC_ALL");
290         if (lang.empty()) {
291                 lang = getEnv("LC_MESSAGES");
292                 if (lang.empty()) {
293                         lang = getEnv("LANG");
294                         if (lang.empty())
295                                 lang = "C";
296                 }
297         }
298
299         string const language = getEnv("LANGUAGE");
300         if (lang != "C" && lang != "POSIX" && !language.empty())
301                 lang = language;
302
303         string l;
304         lang = split(lang, l, ':');
305         while (!l.empty() && l != "C" && l != "POSIX") {
306                 string const tmp = LibFileSearch(dir,
307                                                  token(l, '_', 0) + '_' + name,
308                                                  ext);
309                 if (!tmp.empty())
310                         return tmp;
311                 lang = split(lang, l, ':');
312         }
313
314         return LibFileSearch(dir, name, ext);
315 }
316
317
318 string const LibScriptSearch(string const & command_in)
319 {
320         string const token_scriptpath("$$s/");
321
322         string command = command_in;
323         // Find the starting position of "$$s/"
324         string::size_type const pos1 = command.find(token_scriptpath);
325         if (pos1 == string::npos)
326                 return command;
327         // Find the end of the "$$s/some_subdir/some_script" word within
328         // command. Assumes that the script name does not contain spaces.
329         string::size_type const start_script = pos1 + 4;
330         string::size_type const pos2 = command.find(' ', start_script);
331         string::size_type const size_script = pos2 == string::npos?
332                 (command.size() - start_script) : pos2 - start_script;
333
334         // Does this script file exist?
335         string const script =
336                 LibFileSearch(".", command.substr(start_script, size_script));
337
338         if (script.empty()) {
339                 // Replace "$$s/" with ""
340                 command.erase(pos1, 4);
341         } else {
342                 // Replace "$$s/foo/some_script" with "<path to>/some_script".
343                 string::size_type const size_replace = size_script + 4;
344                 command.replace(pos1, size_replace, QuoteName(script));
345         }
346
347         return command;
348 }
349
350
351 namespace {
352
353 string const createTmpDir(string const & tempdir, string const & mask)
354 {
355         lyxerr[Debug::FILES]
356                 << "createTmpDir: tempdir=`" << tempdir << "'\n"
357                 << "createTmpDir:    mask=`" << mask << '\'' << endl;
358
359         string const tmpfl(tempName(tempdir, mask));
360         // lyx::tempName actually creates a file to make sure that it
361         // stays unique. So we have to delete it before we can create
362         // a dir with the same name. Note also that we are not thread
363         // safe because of the gap between unlink and mkdir. (Lgb)
364         unlink(tmpfl);
365
366         if (tmpfl.empty() || mkdir(tmpfl, 0700)) {
367                 lyxerr << "LyX could not create the temporary directory '"
368                        << tmpfl << "'" << endl;
369                 return string();
370         }
371
372         return MakeAbsPath(tmpfl);
373 }
374
375 } // namespace anon
376
377
378 bool destroyDir(string const & tmpdir)
379 {
380
381 #ifdef __EMX__
382         Path p(user_lyxdir());
383 #endif
384         return fs::remove_all(tmpdir) > 0;
385 }
386
387
388 string const createBufferTmpDir()
389 {
390         static int count;
391         // We are in our own directory.  Why bother to mangle name?
392         // In fact I wrote this code to circumvent a problematic behaviour
393         // (bug?) of EMX mkstemp().
394         string const tmpfl =
395                 package().temp_dir() + "/lyx_tmpbuf" +
396                 convert<string>(count++);
397
398         if (mkdir(tmpfl, 0777)) {
399                 lyxerr << "LyX could not create the temporary directory '"
400                        << tmpfl << "'" << endl;
401                 return string();
402         }
403         return tmpfl;
404 }
405
406
407 string const createLyXTmpDir(string const & deflt)
408 {
409         if (!deflt.empty() && deflt != "/tmp") {
410                 if (mkdir(deflt, 0777)) {
411 #ifdef __EMX__
412                         Path p(package().user_support());
413 #endif
414                         if (IsDirWriteable(deflt)) {
415                                 // deflt could not be created because it
416                                 // did exist already, so let's create our own
417                                 // dir inside deflt.
418                                 return createTmpDir(deflt, "lyx_tmpdir");
419                         } else {
420                                 // some other error occured.
421                                 return createTmpDir("/tmp", "lyx_tmpdir");
422                         }
423                 } else
424                         return deflt;
425         } else {
426 #ifdef __EMX__
427                 Path p(package().user_support());
428 #endif
429                 return createTmpDir("/tmp", "lyx_tmpdir");
430         }
431 }
432
433
434 bool createDirectory(string const & path, int permission)
435 {
436         string temp(rtrim(os::internal_path(path), "/"));
437
438         BOOST_ASSERT(!temp.empty());
439
440         if (mkdir(temp, permission))
441                 return false;
442
443         return true;
444 }
445
446
447 // Strip filename from path name
448 string const OnlyPath(string const & Filename)
449 {
450         // If empty filename, return empty
451         if (Filename.empty()) return Filename;
452
453         // Find last / or start of filename
454         string::size_type j = Filename.rfind('/');
455         if (j == string::npos)
456                 return "./";
457         return Filename.substr(0, j + 1);
458 }
459
460
461 // Convert relative path into absolute path based on a basepath.
462 // If relpath is absolute, just use that.
463 // If basepath is empty, use CWD as base.
464 string const MakeAbsPath(string const & RelPath, string const & BasePath)
465 {
466         // checks for already absolute path
467         if (os::is_absolute_path(RelPath))
468                 return RelPath;
469
470         // Copies given paths
471         string TempRel(os::internal_path(RelPath));
472         // Since TempRel is NOT absolute, we can safely replace "//" with "/"
473         TempRel = subst(TempRel, "//", "/");
474
475         string TempBase;
476
477         if (os::is_absolute_path(BasePath))
478                 TempBase = BasePath;
479         else
480                 TempBase = AddPath(getcwd(), BasePath);
481
482         // Handle /./ at the end of the path
483         while (suffixIs(TempBase, "/./"))
484                 TempBase.erase(TempBase.length() - 2);
485
486         // processes relative path
487         string RTemp(TempRel);
488         string Temp;
489
490         while (!RTemp.empty()) {
491                 // Split by next /
492                 RTemp = split(RTemp, Temp, '/');
493
494                 if (Temp == ".") continue;
495                 if (Temp == "..") {
496                         // Remove one level of TempBase
497                         string::difference_type i = TempBase.length() - 2;
498 #ifndef __EMX__
499                         if (i < 0) i = 0;
500                         while (i > 0 && TempBase[i] != '/') --i;
501                         if (i > 0)
502 #else
503                         if (i < 2) i = 2;
504                         while (i > 2 && TempBase[i] != '/') --i;
505                         if (i > 2)
506 #endif
507                                 TempBase.erase(i, string::npos);
508                         else
509                                 TempBase += '/';
510                 } else if (Temp.empty() && !RTemp.empty()) {
511                                 TempBase = os::current_root() + RTemp;
512                                 RTemp.erase();
513                 } else {
514                         // Add this piece to TempBase
515                         if (!suffixIs(TempBase, '/'))
516                                 TempBase += '/';
517                         TempBase += Temp;
518                 }
519         }
520
521         // returns absolute path
522         return os::internal_path(TempBase);
523 }
524
525
526 // Correctly append filename to the pathname.
527 // If pathname is '.', then don't use pathname.
528 // Chops any path of filename.
529 string const AddName(string const & path, string const & fname)
530 {
531         // Get basename
532         string const basename(OnlyFilename(fname));
533
534         string buf;
535
536         if (path != "." && path != "./" && !path.empty()) {
537                 buf = os::internal_path(path);
538                 if (!suffixIs(path, '/'))
539                         buf += '/';
540         }
541
542         return buf + basename;
543 }
544
545
546 // Strips path from filename
547 string const OnlyFilename(string const & fname)
548 {
549         if (fname.empty())
550                 return fname;
551
552         string::size_type j = fname.rfind('/');
553         if (j == string::npos) // no '/' in fname
554                 return fname;
555
556         // Strip to basename
557         return fname.substr(j + 1);
558 }
559
560
561 /// Returns true is path is absolute
562 bool AbsolutePath(string const & path)
563 {
564         return os::is_absolute_path(path);
565 }
566
567
568
569 // Create absolute path. If impossible, don't do anything
570 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
571 string const ExpandPath(string const & path)
572 {
573         // checks for already absolute path
574         string RTemp(ReplaceEnvironmentPath(path));
575         if (os::is_absolute_path(RTemp))
576                 return RTemp;
577
578         string Temp;
579         string const copy(RTemp);
580
581         // Split by next /
582         RTemp = split(RTemp, Temp, '/');
583
584         if (Temp == ".") {
585                 return getcwd() + '/' + RTemp;
586         }
587         if (Temp == "~") {
588                 return package().home_dir() + '/' + RTemp;
589         }
590         if (Temp == "..") {
591                 return MakeAbsPath(copy);
592         }
593         // Don't know how to handle this
594         return copy;
595 }
596
597
598 // Normalize a path
599 // Constracts path/../path
600 // Can't handle "../../" or "/../" (Asger)
601 // Also converts paths like /foo//bar ==> /foo/bar
602 string const NormalizePath(string const & path)
603 {
604         string TempBase;
605         string RTemp;
606         string Temp;
607
608         if (os::is_absolute_path(path))
609                 RTemp = path;
610         else
611                 // Make implicit current directory explicit
612                 RTemp = "./" +path;
613
614         // Normalise paths like /foo//bar ==> /foo/bar
615         boost::RegEx regex("/{2,}");
616         RTemp = regex.Merge(RTemp, "/");
617
618         while (!RTemp.empty()) {
619                 // Split by next /
620                 RTemp = split(RTemp, Temp, '/');
621
622                 if (Temp == ".") {
623                         TempBase = "./";
624                 } else if (Temp == "..") {
625                         // Remove one level of TempBase
626                         string::difference_type i = TempBase.length() - 2;
627                         while (i > 0 && TempBase[i] != '/')
628                                 --i;
629                         if (i >= 0 && TempBase[i] == '/')
630                                 TempBase.erase(i + 1, string::npos);
631                         else
632                                 TempBase = "../";
633                 } else {
634                         TempBase += Temp + '/';
635                 }
636         }
637
638         // returns absolute path
639         return TempBase;
640 }
641
642
643 string const GetFileContents(string const & fname)
644 {
645         if (fs::exists(fname)) {
646                 ifstream ifs(fname.c_str());
647                 ostringstream ofs;
648                 if (ifs && ofs) {
649                         ofs << ifs.rdbuf();
650                         ifs.close();
651                         return ofs.str();
652                 }
653         }
654         lyxerr << "LyX was not able to read file '" << fname << '\'' << endl;
655         return string();
656 }
657
658
659 // Search the string for ${VAR} and $VAR and replace VAR using getenv.
660 string const ReplaceEnvironmentPath(string const & path)
661 {
662         // ${VAR} is defined as
663         // $\{[A-Za-z_][A-Za-z_0-9]*\}
664         static string const envvar_br = "[$]\\{([A-Za-z_][A-Za-z_0-9]*)\\}";
665
666         // $VAR is defined as:
667         // $\{[A-Za-z_][A-Za-z_0-9]*\}
668         static string const envvar = "[$]([A-Za-z_][A-Za-z_0-9]*)";
669
670         static boost::regex envvar_br_re("(.*)" + envvar_br + "(.*)");
671         static boost::regex envvar_re("(.*)" + envvar + "(.*)");
672         boost::smatch what;
673
674         string result = path;
675         while (1) {
676                 regex_match(result, what, envvar_br_re);
677                 if (!what[0].matched) {
678                         regex_match(result, what, envvar_re);
679                         if (!what[0].matched)
680                                 break;
681                 }
682                 result = what.str(1) + getEnv(what.str(2)) + what.str(3);
683         }
684         return result;
685 }
686
687
688 // Make relative path out of two absolute paths
689 string const MakeRelPath(string const & abspath, string const & basepath)
690 // Makes relative path out of absolute path. If it is deeper than basepath,
691 // it's easy. If basepath and abspath share something (they are all deeper
692 // than some directory), it'll be rendered using ..'s. If they are completely
693 // different, then the absolute path will be used as relative path.
694 {
695         string::size_type const abslen = abspath.length();
696         string::size_type const baselen = basepath.length();
697
698         string::size_type i = os::common_path(abspath, basepath);
699
700         if (i == 0) {
701                 // actually no match - cannot make it relative
702                 return abspath;
703         }
704
705         // Count how many dirs there are in basepath above match
706         // and append as many '..''s into relpath
707         string buf;
708         string::size_type j = i;
709         while (j < baselen) {
710                 if (basepath[j] == '/') {
711                         if (j + 1 == baselen)
712                                 break;
713                         buf += "../";
714                 }
715                 ++j;
716         }
717
718         // Append relative stuff from common directory to abspath
719         if (abspath[i] == '/')
720                 ++i;
721         for (; i < abslen; ++i)
722                 buf += abspath[i];
723         // Remove trailing /
724         if (suffixIs(buf, '/'))
725                 buf.erase(buf.length() - 1);
726         // Substitute empty with .
727         if (buf.empty())
728                 buf = '.';
729         return buf;
730 }
731
732
733 // Append sub-directory(ies) to a path in an intelligent way
734 string const AddPath(string const & path, string const & path_2)
735 {
736         string buf;
737         string const path2 = os::internal_path(path_2);
738
739         if (!path.empty() && path != "." && path != "./") {
740                 buf = os::internal_path(path);
741                 if (path[path.length() - 1] != '/')
742                         buf += '/';
743         }
744
745         if (!path2.empty()) {
746                 string::size_type const p2start = path2.find_first_not_of('/');
747                 string::size_type const p2end = path2.find_last_not_of('/');
748                 string const tmp = path2.substr(p2start, p2end - p2start + 1);
749                 buf += tmp + '/';
750         }
751         return buf;
752 }
753
754
755 /*
756  Change extension of oldname to extension.
757  Strips path off if no_path == true.
758  If no extension on oldname, just appends.
759  */
760 string const ChangeExtension(string const & oldname, string const & extension)
761 {
762         string::size_type const last_slash = oldname.rfind('/');
763         string::size_type last_dot = oldname.rfind('.');
764         if (last_dot < last_slash && last_slash != string::npos)
765                 last_dot = string::npos;
766
767         string ext;
768         // Make sure the extension starts with a dot
769         if (!extension.empty() && extension[0] != '.')
770                 ext= '.' + extension;
771         else
772                 ext = extension;
773
774         return os::internal_path(oldname.substr(0, last_dot) + ext);
775 }
776
777
778 /// Return the extension of the file (not including the .)
779 string const GetExtension(string const & name)
780 {
781         string::size_type const last_slash = name.rfind('/');
782         string::size_type const last_dot = name.rfind('.');
783         if (last_dot != string::npos &&
784             (last_slash == string::npos || last_dot > last_slash))
785                 return name.substr(last_dot + 1,
786                                    name.length() - (last_dot + 1));
787         else
788                 return string();
789 }
790
791
792 // the different filetypes and what they contain in one of the first lines
793 // (dots are any characters).           (Herbert 20020131)
794 // AGR  Grace...
795 // BMP  BM...
796 // EPS  %!PS-Adobe-3.0 EPSF...
797 // FIG  #FIG...
798 // FITS ...BITPIX...
799 // GIF  GIF...
800 // JPG  JFIF
801 // PDF  %PDF-...
802 // PNG  .PNG...
803 // PBM  P1... or P4     (B/W)
804 // PGM  P2... or P5     (Grayscale)
805 // PPM  P3... or P6     (color)
806 // PS   %!PS-Adobe-2.0 or 1.0,  no "EPSF"!
807 // SGI  \001\332...     (decimal 474)
808 // TGIF %TGIF...
809 // TIFF II... or MM...
810 // XBM  ..._bits[]...
811 // XPM  /* XPM */    sometimes missing (f.ex. tgif-export)
812 //      ...static char *...
813 // XWD  \000\000\000\151        (0x00006900) decimal 105
814 //
815 // GZIP \037\213        http://www.ietf.org/rfc/rfc1952.txt
816 // ZIP  PK...                   http://www.halyava.ru/document/ind_arch.htm
817 // Z    \037\235                UNIX compress
818
819 string const getFormatFromContents(string const & filename)
820 {
821         // paranoia check
822         if (filename.empty() || !IsFileReadable(filename))
823                 return string();
824
825         ifstream ifs(filename.c_str());
826         if (!ifs)
827                 // Couldn't open file...
828                 return string();
829
830         // gnuzip
831         string const gzipStamp = "\037\213";
832
833         // PKZIP
834         string const zipStamp = "PK";
835
836         // compress
837         string const compressStamp = "\037\235";
838
839         // Maximum strings to read
840         int const max_count = 50;
841         int count = 0;
842
843         string str;
844         string format;
845         bool firstLine = true;
846         while ((count++ < max_count) && format.empty()) {
847                 if (ifs.eof()) {
848                         lyxerr[Debug::GRAPHICS]
849                                 << "filetools(getFormatFromContents)\n"
850                                 << "\tFile type not recognised before EOF!"
851                                 << endl;
852                         break;
853                 }
854
855                 getline(ifs, str);
856                 string const stamp = str.substr(0,2);
857                 if (firstLine && str.size() >= 2) {
858                         // at first we check for a zipped file, because this
859                         // information is saved in the first bytes of the file!
860                         // also some graphic formats which save the information
861                         // in the first line, too.
862                         if (prefixIs(str, gzipStamp)) {
863                                 format =  "gzip";
864
865                         } else if (stamp == zipStamp) {
866                                 format =  "zip";
867
868                         } else if (stamp == compressStamp) {
869                                 format =  "compress";
870
871                         // the graphics part
872                         } else if (stamp == "BM") {
873                                 format =  "bmp";
874
875                         } else if (stamp == "\001\332") {
876                                 format =  "sgi";
877
878                         // PBM family
879                         // Don't need to use str.at(0), str.at(1) because
880                         // we already know that str.size() >= 2
881                         } else if (str[0] == 'P') {
882                                 switch (str[1]) {
883                                 case '1':
884                                 case '4':
885                                         format =  "pbm";
886                                     break;
887                                 case '2':
888                                 case '5':
889                                         format =  "pgm";
890                                     break;
891                                 case '3':
892                                 case '6':
893                                         format =  "ppm";
894                                 }
895                                 break;
896
897                         } else if ((stamp == "II") || (stamp == "MM")) {
898                                 format =  "tiff";
899
900                         } else if (prefixIs(str,"%TGIF")) {
901                                 format =  "tgif";
902
903                         } else if (prefixIs(str,"#FIG")) {
904                                 format =  "fig";
905
906                         } else if (prefixIs(str,"GIF")) {
907                                 format =  "gif";
908
909                         } else if (str.size() > 3) {
910                                 int const c = ((str[0] << 24) & (str[1] << 16) &
911                                                (str[2] << 8)  & str[3]);
912                                 if (c == 105) {
913                                         format =  "xwd";
914                                 }
915                         }
916
917                         firstLine = false;
918                 }
919
920                 if (!format.empty())
921                     break;
922                 else if (contains(str,"EPSF"))
923                         // dummy, if we have wrong file description like
924                         // %!PS-Adobe-2.0EPSF"
925                         format =  "eps";
926
927                 else if (contains(str,"Grace"))
928                         format =  "agr";
929
930                 else if (contains(str,"JFIF"))
931                         format =  "jpg";
932
933                 else if (contains(str,"%PDF"))
934                         format =  "pdf";
935
936                 else if (contains(str,"PNG"))
937                         format =  "png";
938
939                 else if (contains(str,"%!PS-Adobe")) {
940                         // eps or ps
941                         ifs >> str;
942                         if (contains(str,"EPSF"))
943                                 format = "eps";
944                         else
945                             format = "ps";
946                 }
947
948                 else if (contains(str,"_bits[]"))
949                         format = "xbm";
950
951                 else if (contains(str,"XPM") || contains(str, "static char *"))
952                         format = "xpm";
953
954                 else if (contains(str,"BITPIX"))
955                         format = "fits";
956         }
957
958         if (!format.empty()) {
959                 lyxerr[Debug::GRAPHICS]
960                         << "Recognised Fileformat: " << format << endl;
961                 return format;
962         }
963
964         lyxerr[Debug::GRAPHICS]
965                 << "filetools(getFormatFromContents)\n"
966                 << "\tCouldn't find a known format!\n";
967         return string();
968 }
969
970
971 /// check for zipped file
972 bool zippedFile(string const & name)
973 {
974         string const type = getFormatFromContents(name);
975         if (contains("gzip zip compress", type) && !type.empty())
976                 return true;
977         return false;
978 }
979
980
981 string const unzippedFileName(string const & zipped_file)
982 {
983         string const ext = GetExtension(zipped_file);
984         if (ext == "gz" || ext == "z" || ext == "Z")
985                 return ChangeExtension(zipped_file, string());
986         return "unzipped_" + zipped_file;
987 }
988
989
990 string const unzipFile(string const & zipped_file, string const & unzipped_file)
991 {
992         string const tempfile = unzipped_file.empty() ?
993                 unzippedFileName(zipped_file) : unzipped_file;
994         // Run gunzip
995         string const command = "gunzip -c " + zipped_file + " > " + tempfile;
996         Systemcall one;
997         one.startscript(Systemcall::Wait, command);
998         // test that command was executed successfully (anon)
999         // yes, please do. (Lgb)
1000         return tempfile;
1001 }
1002
1003
1004 string const MakeDisplayPath(string const & path, unsigned int threshold)
1005 {
1006         string str = path;
1007
1008         string const home(package().home_dir());
1009
1010         // replace /home/blah with ~/
1011         if (prefixIs(str, home))
1012                 str = subst(str, home, "~");
1013
1014         if (str.length() <= threshold)
1015                 return os::external_path(str);
1016
1017         string const prefix = ".../";
1018         string temp;
1019
1020         while (str.length() > threshold)
1021                 str = split(str, temp, '/');
1022
1023         // Did we shorten everything away?
1024         if (str.empty()) {
1025                 // Yes, filename itself is too long.
1026                 // Pick the start and the end of the filename.
1027                 str = OnlyFilename(path);
1028                 string const head = str.substr(0, threshold / 2 - 3);
1029
1030                 string::size_type len = str.length();
1031                 string const tail =
1032                         str.substr(len - threshold / 2 - 2, len - 1);
1033                 str = head + "..." + tail;
1034         }
1035
1036         return os::external_path(prefix + str);
1037 }
1038
1039
1040 bool LyXReadLink(string const & file, string & link, bool resolve)
1041 {
1042 #ifdef HAVE_READLINK
1043         char linkbuffer[512];
1044         // Should be PATH_MAX but that needs autconf support
1045         int const nRead = ::readlink(file.c_str(),
1046                                      linkbuffer, sizeof(linkbuffer) - 1);
1047         if (nRead <= 0)
1048                 return false;
1049         linkbuffer[nRead] = '\0'; // terminator
1050         if (resolve)
1051                 link = MakeAbsPath(linkbuffer, OnlyPath(file));
1052         else
1053                 link = linkbuffer;
1054         return true;
1055 #else
1056         return false;
1057 #endif
1058 }
1059
1060
1061 cmd_ret const RunCommand(string const & cmd)
1062 {
1063         // FIXME: replace all calls to RunCommand with ForkedCall
1064         // (if the output is not needed) or the code in ispell.C
1065         // (if the output is needed).
1066
1067         // One question is if we should use popen or
1068         // create our own popen based on fork, exec, pipe
1069         // of course the best would be to have a
1070         // pstream (process stream), with the
1071         // variants ipstream, opstream
1072
1073 #if defined (HAVE_POPEN)
1074         FILE * inf = ::popen(cmd.c_str(), os::popen_read_mode());
1075 #elif defined (HAVE__POPEN)
1076         FILE * inf = ::_popen(cmd.c_str(), os::popen_read_mode());
1077 #else
1078 #error No popen() function.
1079 #endif
1080
1081         // (Claus Hentschel) Check if popen was succesful ;-)
1082         if (!inf) {
1083                 return make_pair(-1, string());
1084                 lyxerr << "RunCommand:: could not start child process" << endl;
1085                 }
1086
1087         string ret;
1088         int c = fgetc(inf);
1089         while (c != EOF) {
1090                 ret += static_cast<char>(c);
1091                 c = fgetc(inf);
1092         }
1093
1094 #if defined (HAVE_PCLOSE)
1095         int const pret = pclose(inf);
1096 #elif defined (HAVE__PCLOSE)
1097         int const pret = _pclose(inf);
1098 #else
1099 #error No pclose() function.
1100 #endif
1101
1102         if (pret == -1)
1103                 perror("RunCommand:: could not terminate child process");
1104
1105         return make_pair(pret, ret);
1106 }
1107
1108
1109 string const findtexfile(string const & fil, string const & /*format*/)
1110 {
1111         /* There is no problem to extend this function too use other
1112            methods to look for files. It could be setup to look
1113            in environment paths and also if wanted as a last resort
1114            to a recursive find. One of the easier extensions would
1115            perhaps be to use the LyX file lookup methods. But! I am
1116            going to implement this until I see some demand for it.
1117            Lgb
1118         */
1119
1120         // If the file can be found directly, we just return a
1121         // absolute path version of it.
1122         if (fs::exists(fil))
1123                 return MakeAbsPath(fil);
1124
1125         // No we try to find it using kpsewhich.
1126         // It seems from the kpsewhich manual page that it is safe to use
1127         // kpsewhich without --format: "When the --format option is not
1128         // given, the search path used when looking for a file is inferred
1129         // from the name given, by looking for a known extension. If no
1130         // known extension is found, the search path for TeX source files
1131         // is used."
1132         // However, we want to take advantage of the format sine almost all
1133         // the different formats has environment variables that can be used
1134         // to controll which paths to search. f.ex. bib looks in
1135         // BIBINPUTS and TEXBIB. Small list follows:
1136         // bib - BIBINPUTS, TEXBIB
1137         // bst - BSTINPUTS
1138         // graphic/figure - TEXPICTS, TEXINPUTS
1139         // ist - TEXINDEXSTYLE, INDEXSTYLE
1140         // pk - PROGRAMFONTS, PKFONTS, TEXPKS, GLYPHFONTS, TEXFONTS
1141         // tex - TEXINPUTS
1142         // tfm - TFMFONTS, TEXFONTS
1143         // This means that to use kpsewhich in the best possible way we
1144         // should help it by setting additional path in the approp. envir.var.
1145         string const kpsecmd = "kpsewhich " + fil;
1146
1147         cmd_ret const c = RunCommand(kpsecmd);
1148
1149         lyxerr[Debug::LATEX] << "kpse status = " << c.first << '\n'
1150                  << "kpse result = `" << rtrim(c.second, "\n")
1151                  << '\'' << endl;
1152         if (c.first != -1)
1153                 return os::internal_path(rtrim(c.second, "\n\r"));
1154         else
1155                 return string();
1156 }
1157
1158
1159 void removeAutosaveFile(string const & filename)
1160 {
1161         string a = OnlyPath(filename);
1162         a += '#';
1163         a += OnlyFilename(filename);
1164         a += '#';
1165         if (fs::exists(a))
1166                 unlink(a);
1167 }
1168
1169
1170 void readBB_lyxerrMessage(string const & file, bool & zipped,
1171         string const & message)
1172 {
1173         lyxerr[Debug::GRAPHICS] << "[readBB_from_PSFile] "
1174                 << message << std::endl;
1175 #ifdef WITH_WARNINGS
1176 #warning Why is this func deleting a file? (Lgb)
1177 #endif
1178         if (zipped)
1179                 unlink(file);
1180 }
1181
1182
1183 string const readBB_from_PSFile(string const & file)
1184 {
1185         // in a (e)ps-file it's an entry like %%BoundingBox:23 45 321 345
1186         // It seems that every command in the header has an own line,
1187         // getline() should work for all files.
1188         // On the other hand some plot programs write the bb at the
1189         // end of the file. Than we have in the header:
1190         // %%BoundingBox: (atend)
1191         // In this case we must check the end.
1192         bool zipped = zippedFile(file);
1193         string const file_ = zipped ?
1194                 string(unzipFile(file)) : string(file);
1195         string const format = getFormatFromContents(file_);
1196
1197         if (format != "eps" && format != "ps") {
1198                 readBB_lyxerrMessage(file_, zipped,"no(e)ps-format");
1199                 return string();
1200         }
1201
1202         std::ifstream is(file_.c_str());
1203         while (is) {
1204                 string s;
1205                 getline(is,s);
1206                 if (contains(s,"%%BoundingBox:") && !contains(s,"atend")) {
1207                         string const bb = ltrim(s.substr(14));
1208                         readBB_lyxerrMessage(file_, zipped, bb);
1209                         return bb;
1210                 }
1211         }
1212         readBB_lyxerrMessage(file_, zipped, "no bb found");
1213         return string();
1214 }
1215
1216
1217 int compare_timestamps(string const & file1, string const & file2)
1218 {
1219         BOOST_ASSERT(AbsolutePath(file1) && AbsolutePath(file2));
1220
1221         // If the original is newer than the copy, then copy the original
1222         // to the new directory.
1223
1224         int cmp = 0;
1225         if (fs::exists(file1) && fs::exists(file2)) {
1226                 double const tmp = difftime(fs::last_write_time(file1),
1227                                             fs::last_write_time(file2));
1228                 if (tmp != 0)
1229                         cmp = tmp > 0 ? 1 : -1;
1230
1231         } else if (fs::exists(file1)) {
1232                 cmp = 1;
1233         } else if (fs::exists(file2)) {
1234                 cmp = -1;
1235         }
1236
1237         return cmp;
1238 }
1239
1240 } //namespace support
1241 } // namespace lyx