]> git.lyx.org Git - lyx.git/blob - src/support/filetools.cpp
ae9437f5296bb5abf578a468cb996d1b885f904b
[lyx.git] / src / support / filetools.cpp
1 /**
2  * \file filetools.cpp
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/filetools.h"
25
26 #include "support/debug.h"
27 #include "support/environment.h"
28 #include "support/gettext.h"
29 #include "support/lstrings.h"
30 #include "support/os.h"
31 #include "support/Package.h"
32 #include "support/Path.h"
33 #include "support/Systemcall.h"
34 #include "support/qstring_helpers.h"
35
36 #include <QDir>
37
38 #include "support/lassert.h"
39 #include <boost/regex.hpp>
40
41 #include <fcntl.h>
42
43 #include <cerrno>
44 #include <cstdlib>
45 #include <cstdio>
46
47 #include <utility>
48 #include <fstream>
49 #include <sstream>
50
51 using namespace std;
52
53 #define USE_QPROCESS
54
55 namespace lyx {
56 namespace support {
57
58 bool isLyXFilename(string const & filename)
59 {
60         return suffixIs(ascii_lowercase(filename), ".lyx");
61 }
62
63
64 bool isSGMLFilename(string const & filename)
65 {
66         return suffixIs(ascii_lowercase(filename), ".sgml");
67 }
68
69
70 bool isValidLaTeXFilename(string const & filename)
71 {
72         string const invalid_chars("#$%{}()[]\"^");
73         return filename.find_first_of(invalid_chars) == string::npos;
74 }
75
76
77 string const latex_path(string const & original_path,
78                 latex_path_extension extension,
79                 latex_path_dots dots)
80 {
81         // On cygwin, we may need windows or posix style paths.
82         string path = os::latex_path(original_path);
83         path = subst(path, "~", "\\string~");
84         if (path.find(' ') != string::npos) {
85                 // We can't use '"' because " is sometimes active (e.g. if
86                 // babel is loaded with the "german" option)
87                 if (extension == EXCLUDE_EXTENSION) {
88                         // ChangeExtension calls os::internal_path internally
89                         // so don't use it to remove the extension.
90                         string const ext = getExtension(path);
91                         string const base = ext.empty() ?
92                                 path :
93                                 path.substr(0, path.length() - ext.length() - 1);
94                         // ChangeExtension calls os::internal_path internally
95                         // so don't use it to re-add the extension.
96                         path = "\\string\"" + base + "\\string\"." + ext;
97                 } else {
98                         path = "\\string\"" + path + "\\string\"";
99                 }
100         }
101
102         return dots == ESCAPE_DOTS ? subst(path, ".", "\\lyxdot ") : path;
103 }
104
105
106 // Substitutes spaces with underscores in filename (and path)
107 FileName const makeLatexName(FileName const & file)
108 {
109         string name = file.onlyFileName();
110         string const path = file.onlyPath().absFilename() + "/";
111
112         // ok so we scan through the string twice, but who cares.
113         // FIXME: in Unicode time this will break for sure! There is
114         // a non-latin world out there...
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         FileName latex_name(path + name);
124         latex_name.changeExtension(".tex");
125         return latex_name;
126 }
127
128
129 string const quoteName(string const & name, quote_style style)
130 {
131         switch(style) {
132         case quote_shell:
133                 // This does not work for filenames containing " (windows)
134                 // or ' (all other OSes). This can't be changed easily, since
135                 // we would need to adapt the command line parser in
136                 // Forkedcall::generateChild. Therefore we don't pass user
137                 // filenames to child processes if possible. We store them in
138                 // a python script instead, where we don't have these
139                 // limitations.
140 #ifndef USE_QPROCESS
141                 return (os::shell() == os::UNIX) ?
142                         '\'' + name + '\'':
143                         '"' + name + '"';
144 #else
145                 // According to the QProcess parser, a single double
146                 // quote is represented by three consecutive ones.
147                 return '"' + subst(name, "\"", "\"\"\"") + '"';
148 #endif
149         case quote_python:
150                 return "\"" + subst(subst(name, "\\", "\\\\"), "\"", "\\\"")
151                      + "\"";
152         }
153         // shut up stupid compiler
154         return string();
155 }
156
157
158 #if 0
159 // Uses a string of paths separated by ";"s to find a file to open.
160 // Can't cope with pathnames with a ';' in them. Returns full path to file.
161 // If path entry begins with $$LyX/, use system_lyxdir
162 // If path entry begins with $$User/, use user_lyxdir
163 // Example: "$$User/doc;$$LyX/doc"
164 FileName const fileOpenSearch(string const & path, string const & name,
165                              string const & ext)
166 {
167         FileName real_file;
168         string path_element;
169         bool notfound = true;
170         string tmppath = split(path, path_element, ';');
171
172         while (notfound && !path_element.empty()) {
173                 path_element = os::internal_path(path_element);
174                 if (!suffixIs(path_element, '/'))
175                         path_element += '/';
176                 path_element = subst(path_element, "$$LyX",
177                                      package().system_support().absFilename());
178                 path_element = subst(path_element, "$$User",
179                                      package().user_support().absFilename());
180
181                 real_file = fileSearch(path_element, name, ext);
182
183                 if (real_file.empty()) {
184                         do {
185                                 tmppath = split(tmppath, path_element, ';');
186                         } while (!tmppath.empty() && path_element.empty());
187                 } else {
188                         notfound = false;
189                 }
190         }
191         return real_file;
192 }
193 #endif
194
195
196 // Returns the real name of file name in directory path, with optional
197 // extension ext.
198 FileName const fileSearch(string const & path, string const & name,
199                           string const & ext, search_mode mode)
200 {
201         // if `name' is an absolute path, we ignore the setting of `path'
202         // Expand Environmentvariables in 'name'
203         string const tmpname = replaceEnvironmentPath(name);
204         FileName fullname(makeAbsPath(tmpname, path));
205         // search first without extension, then with it.
206         if (fullname.isReadableFile())
207                 return fullname;
208         if (ext.empty())
209                 // We are done.
210                 return mode == may_not_exist ? fullname : FileName();
211         // Only add the extension if it is not already the extension of
212         // fullname.
213         if (getExtension(fullname.absFilename()) != ext)
214                 fullname = FileName(addExtension(fullname.absFilename(), ext));
215         if (fullname.isReadableFile() || mode == may_not_exist)
216                 return fullname;
217         return FileName();
218 }
219
220
221 // Search the file name.ext in the subdirectory dir of
222 //   1) user_lyxdir
223 //   2) build_lyxdir (if not empty)
224 //   3) system_lyxdir
225 FileName const libFileSearch(string const & dir, string const & name,
226                            string const & ext)
227 {
228         FileName fullname = fileSearch(addPath(package().user_support().absFilename(), dir),
229                                      name, ext);
230         if (!fullname.empty())
231                 return fullname;
232
233         if (!package().build_support().empty())
234                 fullname = fileSearch(addPath(package().build_support().absFilename(), dir),
235                                       name, ext);
236         if (!fullname.empty())
237                 return fullname;
238
239         return fileSearch(addPath(package().system_support().absFilename(), dir), name, ext);
240 }
241
242
243 FileName const i18nLibFileSearch(string const & dir, string const & name,
244                   string const & ext)
245 {
246         /* The highest priority value is the `LANGUAGE' environment
247            variable. But we don't use the value if the currently
248            selected locale is the C locale. This is a GNU extension.
249
250            Otherwise, w use a trick to guess what support/gettext.has done:
251            each po file is able to tell us its name. (JMarc)
252         */
253
254         string lang = to_ascii(_("[[Replace with the code of your language]]"));
255         string const language = getEnv("LANGUAGE");
256         if (!lang.empty() && !language.empty())
257                 lang = language;
258
259         string l;
260         lang = split(lang, l, ':');
261         while (!l.empty()) {
262                 FileName tmp;
263                 // First try with the full name
264                 tmp = libFileSearch(addPath(dir, l), name, ext);
265                 if (!tmp.empty())
266                         return tmp;
267
268                 // Then the name without country code
269                 string const shortl = token(l, '_', 0);
270                 if (shortl != l) {
271                         tmp = libFileSearch(addPath(dir, shortl), name, ext);
272                         if (!tmp.empty())
273                                 return tmp;
274                 }
275
276 #if 1
277                 // For compatibility, to be removed later (JMarc)
278                 tmp = libFileSearch(dir, token(l, '_', 0) + '_' + name,
279                                     ext);
280                 if (!tmp.empty()) {
281                         lyxerr << "i18nLibFileSearch: File `" << tmp
282                                << "' has been found by the old method" <<endl;
283                         return tmp;
284                 }
285 #endif
286                 lang = split(lang, l, ':');
287         }
288
289         return libFileSearch(dir, name, ext);
290 }
291
292
293 string const libScriptSearch(string const & command_in, quote_style style)
294 {
295         static string const token_scriptpath = "$$s/";
296
297         string command = command_in;
298         // Find the starting position of "$$s/"
299         string::size_type const pos1 = command.find(token_scriptpath);
300         if (pos1 == string::npos)
301                 return command;
302         // Find the end of the "$$s/some_subdir/some_script" word within
303         // command. Assumes that the script name does not contain spaces.
304         string::size_type const start_script = pos1 + 4;
305         string::size_type const pos2 = command.find(' ', start_script);
306         string::size_type const size_script = pos2 == string::npos?
307                 (command.size() - start_script) : pos2 - start_script;
308
309         // Does this script file exist?
310         string const script =
311                 libFileSearch(".", command.substr(start_script, size_script)).absFilename();
312
313         if (script.empty()) {
314                 // Replace "$$s/" with ""
315                 command.erase(pos1, 4);
316         } else {
317                 // Replace "$$s/foo/some_script" with "<path to>/some_script".
318                 string::size_type const size_replace = size_script + 4;
319                 command.replace(pos1, size_replace, quoteName(script, style));
320         }
321
322         return command;
323 }
324
325
326 static FileName createTmpDir(FileName const & tempdir, string const & mask)
327 {
328         LYXERR(Debug::FILES, "createTmpDir: tempdir=`" << tempdir << "'\n"
329                 << "createTmpDir:    mask=`" << mask << '\'');
330
331         FileName const tmpfl = FileName::tempName(tempdir, mask);
332
333         if (tmpfl.empty() || !tmpfl.createDirectory(0700)) {
334                 LYXERR0("LyX could not create temporary directory in " << tempdir
335                         << "'");
336                 return FileName();
337         }
338
339         return tmpfl;
340 }
341
342
343 FileName const createLyXTmpDir(FileName const & deflt)
344 {
345         if (deflt.empty() || deflt == package().system_temp_dir())
346                 return createTmpDir(package().system_temp_dir(), "lyx_tmpdir");
347
348         if (deflt.createDirectory(0777)) 
349                 return deflt;
350
351         if (deflt.isDirWritable()) {
352                 // deflt could not be created because it
353                 // did exist already, so let's create our own
354                 // dir inside deflt.
355                 return createTmpDir(deflt, "lyx_tmpdir");
356         } else {
357                 // some other error occured.
358                 return createTmpDir(package().system_temp_dir(), "lyx_tmpdir");
359         }
360 }
361
362
363 // Strip filename from path name
364 string const onlyPath(string const & filename)
365 {
366         // If empty filename, return empty
367         if (filename.empty())
368                 return filename;
369
370         // Find last / or start of filename
371         size_t j = filename.rfind('/');
372         return j == string::npos ? "./" : filename.substr(0, j + 1);
373 }
374
375
376 // Convert relative path into absolute path based on a basepath.
377 // If relpath is absolute, just use that.
378 // If basepath is empty, use CWD as base.
379 // Note that basePath can be a relative path, in the sense that it may
380 // not begin with "/" (e.g.), but it should NOT contain such constructs
381 // as "/../".
382 // FIXME It might be nice if the code didn't simply assume that.
383 FileName const makeAbsPath(string const & relPath, string const & basePath)
384 {
385         // checks for already absolute path
386         if (FileName::isAbsolute(relPath))
387                 return FileName(relPath);
388
389         // Copies given paths
390         string tempRel = os::internal_path(relPath);
391         // Since TempRel is NOT absolute, we can safely replace "//" with "/"
392         tempRel = subst(tempRel, "//", "/");
393
394         string tempBase;
395
396         if (FileName::isAbsolute(basePath))
397                 tempBase = basePath;
398         else
399                 tempBase = addPath(FileName::getcwd().absFilename(), basePath);
400
401         // Handle /./ at the end of the path
402         while (suffixIs(tempBase, "/./"))
403                 tempBase.erase(tempBase.length() - 2);
404
405         // processes relative path
406         string rTemp = tempRel;
407         string temp;
408
409         // Check for a leading "~"
410         // Split by first /
411         rTemp = split(rTemp, temp, '/');
412         if (temp == "~") {
413                 tempBase = package().home_dir().absFilename();
414                 tempRel = rTemp;
415         }
416
417         rTemp = tempRel;
418         while (!rTemp.empty()) {
419                 // Split by next /
420                 rTemp = split(rTemp, temp, '/');
421
422                 if (temp == ".") continue;
423                 if (temp == "..") {
424                         // Remove one level of TempBase
425                         if (tempBase.length() <= 1) {
426                                 //this is supposed to be an absolute path, so...
427                                 tempBase = "/";
428                                 continue;
429                         }
430                         //erase a trailing slash if there is one
431                         if (suffixIs(tempBase, "/"))
432                                 tempBase.erase(tempBase.length() - 1, string::npos);
433
434                         string::size_type i = tempBase.length() - 1;
435                         while (i > 0 && tempBase[i] != '/')
436                                 --i;
437                         if (i > 0)
438                                 tempBase.erase(i, string::npos);
439                         else
440                                 tempBase = '/';
441                 } else if (temp.empty() && !rTemp.empty()) {
442                                 tempBase = os::current_root() + rTemp;
443                                 rTemp.erase();
444                 } else {
445                         // Add this piece to TempBase
446                         if (!suffixIs(tempBase, '/'))
447                                 tempBase += '/';
448                         tempBase += temp;
449                 }
450         }
451
452         // returns absolute path
453         return FileName(tempBase);
454 }
455
456
457 // Correctly append filename to the pathname.
458 // If pathname is '.', then don't use pathname.
459 // Chops any path of filename.
460 string const addName(string const & path, string const & fname)
461 {
462         string const basename = onlyFilename(fname);
463         string buf;
464
465         if (path != "." && path != "./" && !path.empty()) {
466                 buf = os::internal_path(path);
467                 if (!suffixIs(path, '/'))
468                         buf += '/';
469         }
470
471         return buf + basename;
472 }
473
474
475 // Strips path from filename
476 string const onlyFilename(string const & fname)
477 {
478         if (fname.empty())
479                 return fname;
480
481         string::size_type j = fname.rfind('/');
482         if (j == string::npos) // no '/' in fname
483                 return fname;
484
485         // Strip to basename
486         return fname.substr(j + 1);
487 }
488
489
490 // Create absolute path. If impossible, don't do anything
491 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
492 string const expandPath(string const & path)
493 {
494         // checks for already absolute path
495         string rTemp = replaceEnvironmentPath(path);
496         if (FileName::isAbsolute(rTemp))
497                 return rTemp;
498
499         string temp;
500         string const copy = rTemp;
501
502         // Split by next /
503         rTemp = split(rTemp, temp, '/');
504
505         if (temp == ".")
506                 return FileName::getcwd().absFilename() + '/' + rTemp;
507
508         if (temp == "~")
509                 return package().home_dir().absFilename() + '/' + rTemp;
510
511         if (temp == "..")
512                 return makeAbsPath(copy).absFilename();
513
514         // Don't know how to handle this
515         return copy;
516 }
517
518
519 // Search the string for ${VAR} and $VAR and replace VAR using getenv.
520 string const replaceEnvironmentPath(string const & path)
521 {
522         // ${VAR} is defined as
523         // $\{[A-Za-z_][A-Za-z_0-9]*\}
524         static string const envvar_br = "[$]\\{([A-Za-z_][A-Za-z_0-9]*)\\}";
525
526         // $VAR is defined as:
527         // $\{[A-Za-z_][A-Za-z_0-9]*\}
528         static string const envvar = "[$]([A-Za-z_][A-Za-z_0-9]*)";
529
530         static boost::regex envvar_br_re("(.*)" + envvar_br + "(.*)");
531         static boost::regex envvar_re("(.*)" + envvar + "(.*)");
532         boost::smatch what;
533         string result;
534         string remaining = path;
535         while (1) {
536                 regex_match(remaining, what, envvar_br_re);
537                 if (!what[0].matched) {
538                         regex_match(remaining, what, envvar_re);
539                         if (!what[0].matched) {
540                                 result += remaining;
541                                 break;
542                         }
543                 }
544                 string env_var = getEnv(what.str(2));
545                 if (!env_var.empty())
546                         result += what.str(1) + env_var;
547                 else
548                         result += what.str(1) + "$" + what.str(2);
549                 remaining = what.str(3);
550         }
551         return result;
552 }
553
554
555 // Make relative path out of two absolute paths
556 docstring const makeRelPath(docstring const & abspath, docstring const & basepath)
557 // Makes relative path out of absolute path. If it is deeper than basepath,
558 // it's easy. If basepath and abspath share something (they are all deeper
559 // than some directory), it'll be rendered using ..'s. If they are completely
560 // different, then the absolute path will be used as relative path.
561 {
562         docstring::size_type const abslen = abspath.length();
563         docstring::size_type const baselen = basepath.length();
564
565         docstring::size_type i = os::common_path(abspath, basepath);
566
567         if (i == 0) {
568                 // actually no match - cannot make it relative
569                 return abspath;
570         }
571
572         // Count how many dirs there are in basepath above match
573         // and append as many '..''s into relpath
574         docstring buf;
575         docstring::size_type j = i;
576         while (j < baselen) {
577                 if (basepath[j] == '/') {
578                         if (j + 1 == baselen)
579                                 break;
580                         buf += "../";
581                 }
582                 ++j;
583         }
584
585         // Append relative stuff from common directory to abspath
586         if (abspath[i] == '/')
587                 ++i;
588         for (; i < abslen; ++i)
589                 buf += abspath[i];
590         // Remove trailing /
591         if (suffixIs(buf, '/'))
592                 buf.erase(buf.length() - 1);
593         // Substitute empty with .
594         if (buf.empty())
595                 buf = '.';
596         return buf;
597 }
598
599
600 // Append sub-directory(ies) to a path in an intelligent way
601 string const addPath(string const & path, string const & path_2)
602 {
603         string buf;
604         string const path2 = os::internal_path(path_2);
605
606         if (!path.empty() && path != "." && path != "./") {
607                 buf = os::internal_path(path);
608                 if (path[path.length() - 1] != '/')
609                         buf += '/';
610         }
611
612         if (!path2.empty()) {
613                 string::size_type const p2start = path2.find_first_not_of('/');
614                 string::size_type const p2end = path2.find_last_not_of('/');
615                 string const tmp = path2.substr(p2start, p2end - p2start + 1);
616                 buf += tmp + '/';
617         }
618         return buf;
619 }
620
621
622 string const changeExtension(string const & oldname, string const & extension)
623 {
624         string::size_type const last_slash = oldname.rfind('/');
625         string::size_type last_dot = oldname.rfind('.');
626         if (last_dot < last_slash && last_slash != string::npos)
627                 last_dot = string::npos;
628
629         string ext;
630         // Make sure the extension starts with a dot
631         if (!extension.empty() && extension[0] != '.')
632                 ext= '.' + extension;
633         else
634                 ext = extension;
635
636         return os::internal_path(oldname.substr(0, last_dot) + ext);
637 }
638
639
640 string const removeExtension(string const & name)
641 {
642         return changeExtension(name, string());
643 }
644
645
646 string const addExtension(string const & name, string const & extension)
647 {
648         if (!extension.empty() && extension[0] != '.')
649                 return name + '.' + extension;
650         return name + extension;
651 }
652
653
654 /// Return the extension of the file (not including the .)
655 string const getExtension(string const & name)
656 {
657         string::size_type const last_slash = name.rfind('/');
658         string::size_type const last_dot = name.rfind('.');
659         if (last_dot != string::npos &&
660             (last_slash == string::npos || last_dot > last_slash))
661                 return name.substr(last_dot + 1,
662                                    name.length() - (last_dot + 1));
663         else
664                 return string();
665 }
666
667
668 string const unzippedFileName(string const & zipped_file)
669 {
670         string const ext = getExtension(zipped_file);
671         if (ext == "gz" || ext == "z" || ext == "Z")
672                 return changeExtension(zipped_file, string());
673         return onlyPath(zipped_file) + "unzipped_" + onlyFilename(zipped_file);
674 }
675
676
677 FileName const unzipFile(FileName const & zipped_file, string const & unzipped_file)
678 {
679         FileName const tempfile = FileName(unzipped_file.empty() ?
680                 unzippedFileName(zipped_file.toFilesystemEncoding()) :
681                 unzipped_file);
682         // Run gunzip
683         string const command = "gunzip -c " +
684                 zipped_file.toFilesystemEncoding() + " > " +
685                 tempfile.toFilesystemEncoding();
686         Systemcall one;
687         one.startscript(Systemcall::Wait, command);
688         // test that command was executed successfully (anon)
689         // yes, please do. (Lgb)
690         return tempfile;
691 }
692
693
694 docstring const makeDisplayPath(string const & path, unsigned int threshold)
695 {
696         string str = path;
697
698         // If file is from LyXDir, display it as if it were relative.
699         string const system = package().system_support().absFilename();
700         if (prefixIs(str, system) && str != system)
701                 return from_utf8("[" + str.erase(0, system.length()) + "]");
702
703         // replace /home/blah with ~/
704         string const home = package().home_dir().absFilename();
705         if (!home.empty() && prefixIs(str, home))
706                 str = subst(str, home, "~");
707
708         if (str.length() <= threshold)
709                 return from_utf8(os::external_path(str));
710
711         string const prefix = ".../";
712         string temp;
713
714         while (str.length() > threshold)
715                 str = split(str, temp, '/');
716
717         // Did we shorten everything away?
718         if (str.empty()) {
719                 // Yes, filename itself is too long.
720                 // Pick the start and the end of the filename.
721                 str = onlyFilename(path);
722                 string const head = str.substr(0, threshold / 2 - 3);
723
724                 string::size_type len = str.length();
725                 string const tail =
726                         str.substr(len - threshold / 2 - 2, len - 1);
727                 str = head + "..." + tail;
728         }
729
730         return from_utf8(os::external_path(prefix + str));
731 }
732
733
734 bool readLink(FileName const & file, FileName & link)
735 {
736 #ifdef HAVE_READLINK
737         char linkbuffer[512];
738         // Should be PATH_MAX but that needs autconf support
739         string const encoded = file.toFilesystemEncoding();
740         int const nRead = ::readlink(encoded.c_str(),
741                                      linkbuffer, sizeof(linkbuffer) - 1);
742         if (nRead <= 0)
743                 return false;
744         linkbuffer[nRead] = '\0'; // terminator
745         link = makeAbsPath(linkbuffer, onlyPath(file.absFilename()));
746         return true;
747 #else
748         return false;
749 #endif
750 }
751
752
753 cmd_ret const runCommand(string const & cmd)
754 {
755         // FIXME: replace all calls to RunCommand with ForkedCall
756         // (if the output is not needed) or the code in ISpell.cpp
757         // (if the output is needed).
758
759         // One question is if we should use popen or
760         // create our own popen based on fork, exec, pipe
761         // of course the best would be to have a
762         // pstream (process stream), with the
763         // variants ipstream, opstream
764
765 #if defined (HAVE_POPEN)
766         FILE * inf = ::popen(cmd.c_str(), os::popen_read_mode());
767 #elif defined (HAVE__POPEN)
768         FILE * inf = ::_popen(cmd.c_str(), os::popen_read_mode());
769 #else
770 #error No popen() function.
771 #endif
772
773         // (Claus Hentschel) Check if popen was succesful ;-)
774         if (!inf) {
775                 lyxerr << "RunCommand:: could not start child process" << endl;
776                 return make_pair(-1, string());
777         }
778
779         string ret;
780         int c = fgetc(inf);
781         while (c != EOF) {
782                 ret += static_cast<char>(c);
783                 c = fgetc(inf);
784         }
785
786 #if defined (HAVE_PCLOSE)
787         int const pret = pclose(inf);
788 #elif defined (HAVE__PCLOSE)
789         int const pret = _pclose(inf);
790 #else
791 #error No pclose() function.
792 #endif
793
794         if (pret == -1)
795                 perror("RunCommand:: could not terminate child process");
796
797         return make_pair(pret, ret);
798 }
799
800
801 FileName const findtexfile(string const & fil, string const & /*format*/)
802 {
803         /* There is no problem to extend this function too use other
804            methods to look for files. It could be setup to look
805            in environment paths and also if wanted as a last resort
806            to a recursive find. One of the easier extensions would
807            perhaps be to use the LyX file lookup methods. But! I am
808            going to implement this until I see some demand for it.
809            Lgb
810         */
811
812         // If the file can be found directly, we just return a
813         // absolute path version of it.
814         FileName const absfile(makeAbsPath(fil));
815         if (absfile.exists())
816                 return absfile;
817
818         // Now we try to find it using kpsewhich.
819         // It seems from the kpsewhich manual page that it is safe to use
820         // kpsewhich without --format: "When the --format option is not
821         // given, the search path used when looking for a file is inferred
822         // from the name given, by looking for a known extension. If no
823         // known extension is found, the search path for TeX source files
824         // is used."
825         // However, we want to take advantage of the format sine almost all
826         // the different formats has environment variables that can be used
827         // to controll which paths to search. f.ex. bib looks in
828         // BIBINPUTS and TEXBIB. Small list follows:
829         // bib - BIBINPUTS, TEXBIB
830         // bst - BSTINPUTS
831         // graphic/figure - TEXPICTS, TEXINPUTS
832         // ist - TEXINDEXSTYLE, INDEXSTYLE
833         // pk - PROGRAMFONTS, PKFONTS, TEXPKS, GLYPHFONTS, TEXFONTS
834         // tex - TEXINPUTS
835         // tfm - TFMFONTS, TEXFONTS
836         // This means that to use kpsewhich in the best possible way we
837         // should help it by setting additional path in the approp. envir.var.
838         string const kpsecmd = "kpsewhich " + fil;
839
840         cmd_ret const c = runCommand(kpsecmd);
841
842         LYXERR(Debug::LATEX, "kpse status = " << c.first << '\n'
843                  << "kpse result = `" << rtrim(c.second, "\n\r") << '\'');
844         if (c.first != -1)
845                 return FileName(rtrim(to_utf8(from_filesystem8bit(c.second)), "\n\r"));
846         else
847                 return FileName();
848 }
849
850
851 void readBB_lyxerrMessage(FileName const & file, bool & zipped,
852         string const & message)
853 {
854         LYXERR(Debug::GRAPHICS, "[readBB_from_PSFile] " << message);
855         // FIXME: Why is this func deleting a file? (Lgb)
856         if (zipped)
857                 file.removeFile();
858 }
859
860
861 string const readBB_from_PSFile(FileName const & file)
862 {
863         // in a (e)ps-file it's an entry like %%BoundingBox:23 45 321 345
864         // It seems that every command in the header has an own line,
865         // getline() should work for all files.
866         // On the other hand some plot programs write the bb at the
867         // end of the file. Than we have in the header:
868         // %%BoundingBox: (atend)
869         // In this case we must check the end.
870         bool zipped = file.isZippedFile();
871         FileName const file_ = zipped ? unzipFile(file) : file;
872         string const format = file_.guessFormatFromContents();
873
874         if (format != "eps" && format != "ps") {
875                 readBB_lyxerrMessage(file_, zipped,"no(e)ps-format");
876                 return string();
877         }
878
879         static boost::regex bbox_re(
880                 "^%%BoundingBox:\\s*([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)");
881         ifstream is(file_.toFilesystemEncoding().c_str());
882         while (is) {
883                 string s;
884                 getline(is,s);
885                 boost::smatch what;
886                 if (regex_match(s, what, bbox_re)) {
887                         // Our callers expect the tokens in the string
888                         // separated by single spaces.
889                         // FIXME: change return type from string to something
890                         // sensible
891                         ostringstream os;
892                         os << what.str(1) << ' ' << what.str(2) << ' '
893                            << what.str(3) << ' ' << what.str(4);
894                         string const bb = os.str();
895                         readBB_lyxerrMessage(file_, zipped, bb);
896                         return bb;
897                 }
898         }
899         readBB_lyxerrMessage(file_, zipped, "no bb found");
900         return string();
901 }
902
903
904 int compare_timestamps(FileName const & file1, FileName const & file2)
905 {
906         // If the original is newer than the copy, then copy the original
907         // to the new directory.
908
909         int cmp = 0;
910         if (file1.exists() && file2.exists()) {
911                 double const tmp = difftime(file1.lastModified(), file2.lastModified());
912                 if (tmp != 0)
913                         cmp = tmp > 0 ? 1 : -1;
914
915         } else if (file1.exists()) {
916                 cmp = 1;
917         } else if (file2.exists()) {
918                 cmp = -1;
919         }
920
921         return cmp;
922 }
923
924
925 } //namespace support
926 } // namespace lyx