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