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