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