]> git.lyx.org Git - lyx.git/blob - src/support/filetools.cpp
Fix samba related crashes
[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(_(languageTestString()));
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         string result = path;
550         while (1) {
551                 smatch what;
552                 if (!regex_match(result, what, envvar_br_re)) {
553                         if (!regex_match(result, what, envvar_re))
554                                 break;
555                 }
556                 string env_var = getEnv(what.str(2));
557                 result = what.str(1) + env_var + what.str(3);
558         }
559         return result;
560 }
561
562
563 // Make relative path out of two absolute paths
564 docstring const makeRelPath(docstring const & abspath, docstring const & basepath)
565 // Makes relative path out of absolute path. If it is deeper than basepath,
566 // it's easy. If basepath and abspath share something (they are all deeper
567 // than some directory), it'll be rendered using ..'s. If they are completely
568 // different, then the absolute path will be used as relative path.
569 {
570         docstring::size_type const abslen = abspath.length();
571         docstring::size_type const baselen = basepath.length();
572
573         docstring::size_type i = os::common_path(abspath, basepath);
574
575         if (i == 0) {
576                 // actually no match - cannot make it relative
577                 return abspath;
578         }
579
580         // Count how many dirs there are in basepath above match
581         // and append as many '..''s into relpath
582         docstring buf;
583         docstring::size_type j = i;
584         while (j < baselen) {
585                 if (basepath[j] == '/') {
586                         if (j + 1 == baselen)
587                                 break;
588                         buf += "../";
589                 }
590                 ++j;
591         }
592
593         // Append relative stuff from common directory to abspath
594         if (abspath[i] == '/')
595                 ++i;
596         for (; i < abslen; ++i)
597                 buf += abspath[i];
598         // Remove trailing /
599         if (suffixIs(buf, '/'))
600                 buf.erase(buf.length() - 1);
601         // Substitute empty with .
602         if (buf.empty())
603                 buf = '.';
604         return buf;
605 }
606
607
608 // Append sub-directory(ies) to a path in an intelligent way
609 string const addPath(string const & path, string const & path_2)
610 {
611         string buf;
612         string const path2 = os::internal_path(path_2);
613
614         if (!path.empty() && path != "." && path != "./") {
615                 buf = os::internal_path(path);
616                 if (path[path.length() - 1] != '/')
617                         buf += '/';
618         }
619
620         if (!path2.empty()) {
621                 string::size_type const p2start = path2.find_first_not_of('/');
622                 string::size_type const p2end = path2.find_last_not_of('/');
623                 string const tmp = path2.substr(p2start, p2end - p2start + 1);
624                 buf += tmp + '/';
625         }
626         return buf;
627 }
628
629
630 string const changeExtension(string const & oldname, string const & extension)
631 {
632         string::size_type const last_slash = oldname.rfind('/');
633         string::size_type last_dot = oldname.rfind('.');
634         if (last_dot < last_slash && last_slash != string::npos)
635                 last_dot = string::npos;
636
637         string ext;
638         // Make sure the extension starts with a dot
639         if (!extension.empty() && extension[0] != '.')
640                 ext= '.' + extension;
641         else
642                 ext = extension;
643
644         return os::internal_path(oldname.substr(0, last_dot) + ext);
645 }
646
647
648 string const removeExtension(string const & name)
649 {
650         return changeExtension(name, string());
651 }
652
653
654 string const addExtension(string const & name, string const & extension)
655 {
656         if (!extension.empty() && extension[0] != '.')
657                 return name + '.' + extension;
658         return name + extension;
659 }
660
661
662 /// Return the extension of the file (not including the .)
663 string const getExtension(string const & name)
664 {
665         string::size_type const last_slash = name.rfind('/');
666         string::size_type const last_dot = name.rfind('.');
667         if (last_dot != string::npos &&
668             (last_slash == string::npos || last_dot > last_slash))
669                 return name.substr(last_dot + 1,
670                                    name.length() - (last_dot + 1));
671         else
672                 return string();
673 }
674
675
676 string const unzippedFileName(string const & zipped_file)
677 {
678         string const ext = getExtension(zipped_file);
679         if (ext == "gz" || ext == "z" || ext == "Z")
680                 return changeExtension(zipped_file, string());
681         return onlyPath(zipped_file) + "unzipped_" + onlyFileName(zipped_file);
682 }
683
684
685 FileName const unzipFile(FileName const & zipped_file, string const & unzipped_file)
686 {
687         FileName const tempfile = FileName(unzipped_file.empty() ?
688                 unzippedFileName(zipped_file.toFilesystemEncoding()) :
689                 unzipped_file);
690         // Run gunzip
691         string const command = "gunzip -c " +
692                 zipped_file.toFilesystemEncoding() + " > " +
693                 tempfile.toFilesystemEncoding();
694         Systemcall one;
695         one.startscript(Systemcall::Wait, command);
696         // test that command was executed successfully (anon)
697         // yes, please do. (Lgb)
698         return tempfile;
699 }
700
701
702 docstring const makeDisplayPath(string const & path, unsigned int threshold)
703 {
704         string str = path;
705
706         // If file is from LyXDir, display it as if it were relative.
707         string const system = package().system_support().absFileName();
708         if (prefixIs(str, system) && str != system)
709                 return from_utf8("[" + str.erase(0, system.length()) + "]");
710
711         // replace /home/blah with ~/
712         string const home = package().home_dir().absFileName();
713         if (!home.empty() && prefixIs(str, home))
714                 str = subst(str, home, "~");
715
716         if (str.length() <= threshold)
717                 return from_utf8(os::external_path(str));
718
719         string const prefix = ".../";
720         string temp;
721
722         while (str.length() > threshold)
723                 str = split(str, temp, '/');
724
725         // Did we shorten everything away?
726         if (str.empty()) {
727                 // Yes, filename itself is too long.
728                 // Pick the start and the end of the filename.
729                 str = onlyFileName(path);
730                 string const head = str.substr(0, threshold / 2 - 3);
731
732                 string::size_type len = str.length();
733                 string const tail =
734                         str.substr(len - threshold / 2 - 2, len - 1);
735                 str = head + "..." + tail;
736         }
737
738         return from_utf8(os::external_path(prefix + str));
739 }
740
741
742 #ifdef HAVE_READLINK
743 bool readLink(FileName const & file, FileName & link)
744 {
745         char linkbuffer[PATH_MAX + 1];
746         string const encoded = file.toFilesystemEncoding();
747         int const nRead = ::readlink(encoded.c_str(),
748                                      linkbuffer, sizeof(linkbuffer) - 1);
749         if (nRead <= 0)
750                 return false;
751         linkbuffer[nRead] = '\0'; // terminator
752         link = makeAbsPath(linkbuffer, onlyPath(file.absFileName()));
753         return true;
754 }
755 #else
756 bool readLink(FileName const &, FileName &)
757 {
758         return false;
759 }
760 #endif
761
762
763 cmd_ret const runCommand(string const & cmd)
764 {
765         // FIXME: replace all calls to RunCommand with ForkedCall
766         // (if the output is not needed) or the code in ISpell.cpp
767         // (if the output is needed).
768
769         // One question is if we should use popen or
770         // create our own popen based on fork, exec, pipe
771         // of course the best would be to have a
772         // pstream (process stream), with the
773         // variants ipstream, opstream
774
775 #if defined (_WIN32)
776         int fno;
777         STARTUPINFO startup;
778         PROCESS_INFORMATION process;
779         SECURITY_ATTRIBUTES security;
780         HANDLE in, out;
781         FILE * inf = 0;
782
783         security.nLength = sizeof(SECURITY_ATTRIBUTES);
784         security.bInheritHandle = TRUE;
785         security.lpSecurityDescriptor = NULL;
786
787         if (CreatePipe(&in, &out, &security, 0)) {
788                 memset(&startup, 0, sizeof(STARTUPINFO));
789                 memset(&process, 0, sizeof(PROCESS_INFORMATION));
790
791                 startup.cb = sizeof(STARTUPINFO);
792                 startup.dwFlags = STARTF_USESTDHANDLES;
793
794                 startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);
795                 startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
796                 startup.hStdOutput = out;
797
798                 if (CreateProcess(0, (LPTSTR)cmd.c_str(), &security, &security,
799                         TRUE, CREATE_NO_WINDOW, 0, 0, &startup, &process)) {
800
801                         CloseHandle(process.hThread);
802                         fno = _open_osfhandle((long)in, _O_RDONLY);
803                         CloseHandle(out);
804                         inf = _fdopen(fno, "r");
805                 }
806         }
807 #elif defined (HAVE_POPEN)
808         FILE * inf = ::popen(cmd.c_str(), os::popen_read_mode());
809 #elif defined (HAVE__POPEN)
810         FILE * inf = ::_popen(cmd.c_str(), os::popen_read_mode());
811 #else
812 #error No popen() function.
813 #endif
814
815         // (Claus Hentschel) Check if popen was successful ;-)
816         if (!inf) {
817                 lyxerr << "RunCommand:: could not start child process" << endl;
818                 return make_pair(-1, string());
819         }
820
821         string ret;
822         int c = fgetc(inf);
823         while (c != EOF) {
824                 ret += static_cast<char>(c);
825                 c = fgetc(inf);
826         }
827
828 #if defined (_WIN32)
829         WaitForSingleObject(process.hProcess, INFINITE);
830         CloseHandle(process.hProcess);
831         int const pret = fclose(inf);
832 #elif defined (HAVE_PCLOSE)
833         int const pret = pclose(inf);
834 #elif defined (HAVE__PCLOSE)
835         int const pret = _pclose(inf);
836 #else
837 #error No pclose() function.
838 #endif
839
840         if (pret == -1)
841                 perror("RunCommand:: could not terminate child process");
842
843         return make_pair(pret, ret);
844 }
845
846
847 FileName const findtexfile(string const & fil, string const & /*format*/)
848 {
849         /* There is no problem to extend this function too use other
850            methods to look for files. It could be setup to look
851            in environment paths and also if wanted as a last resort
852            to a recursive find. One of the easier extensions would
853            perhaps be to use the LyX file lookup methods. But! I am
854            going to implement this until I see some demand for it.
855            Lgb
856         */
857
858         // If the file can be found directly, we just return a
859         // absolute path version of it.
860         FileName const absfile(makeAbsPath(fil));
861         if (absfile.exists())
862                 return absfile;
863
864         // Now we try to find it using kpsewhich.
865         // It seems from the kpsewhich manual page that it is safe to use
866         // kpsewhich without --format: "When the --format option is not
867         // given, the search path used when looking for a file is inferred
868         // from the name given, by looking for a known extension. If no
869         // known extension is found, the search path for TeX source files
870         // is used."
871         // However, we want to take advantage of the format sine almost all
872         // the different formats has environment variables that can be used
873         // to controll which paths to search. f.ex. bib looks in
874         // BIBINPUTS and TEXBIB. Small list follows:
875         // bib - BIBINPUTS, TEXBIB
876         // bst - BSTINPUTS
877         // graphic/figure - TEXPICTS, TEXINPUTS
878         // ist - TEXINDEXSTYLE, INDEXSTYLE
879         // pk - PROGRAMFONTS, PKFONTS, TEXPKS, GLYPHFONTS, TEXFONTS
880         // tex - TEXINPUTS
881         // tfm - TFMFONTS, TEXFONTS
882         // This means that to use kpsewhich in the best possible way we
883         // should help it by setting additional path in the approp. envir.var.
884         string const kpsecmd = "kpsewhich " + fil;
885
886         cmd_ret const c = runCommand(kpsecmd);
887
888         LYXERR(Debug::LATEX, "kpse status = " << c.first << '\n'
889                  << "kpse result = `" << rtrim(c.second, "\n\r") << '\'');
890         if (c.first != -1)
891                 return FileName(rtrim(to_utf8(from_filesystem8bit(c.second)), "\n\r"));
892         else
893                 return FileName();
894 }
895
896
897 void readBB_lyxerrMessage(FileName const & file, bool & zipped,
898         string const & message)
899 {
900         LYXERR(Debug::GRAPHICS, "[readBB_from_PSFile] " << message);
901         // FIXME: Why is this func deleting a file? (Lgb)
902         if (zipped)
903                 file.removeFile();
904 }
905
906
907 string const readBB_from_PSFile(FileName const & file)
908 {
909         // in a (e)ps-file it's an entry like %%BoundingBox:23 45 321 345
910         // It seems that every command in the header has an own line,
911         // getline() should work for all files.
912         // On the other hand some plot programs write the bb at the
913         // end of the file. Than we have in the header:
914         // %%BoundingBox: (atend)
915         // In this case we must check the end.
916         bool zipped = file.isZippedFile();
917         FileName const file_ = zipped ? unzipFile(file) : file;
918         string const format = file_.guessFormatFromContents();
919
920         if (format != "eps" && format != "ps") {
921                 readBB_lyxerrMessage(file_, zipped,"no(e)ps-format");
922                 return string();
923         }
924
925         static lyx::regex bbox_re(
926                 "^%%BoundingBox:\\s*([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)");
927         ifstream is(file_.toFilesystemEncoding().c_str());
928         while (is) {
929                 string s;
930                 getline(is,s);
931                 lyx::smatch what;
932                 if (regex_match(s, what, bbox_re)) {
933                         // Our callers expect the tokens in the string
934                         // separated by single spaces.
935                         // FIXME: change return type from string to something
936                         // sensible
937                         ostringstream os;
938                         os << what.str(1) << ' ' << what.str(2) << ' '
939                            << what.str(3) << ' ' << what.str(4);
940                         string const bb = os.str();
941                         readBB_lyxerrMessage(file_, zipped, bb);
942                         return bb;
943                 }
944         }
945         readBB_lyxerrMessage(file_, zipped, "no bb found");
946         return string();
947 }
948
949
950 int compare_timestamps(FileName const & file1, FileName const & file2)
951 {
952         // If the original is newer than the copy, then copy the original
953         // to the new directory.
954
955         int cmp = 0;
956         if (file1.exists() && file2.exists()) {
957                 double const tmp = difftime(file1.lastModified(), file2.lastModified());
958                 if (tmp != 0)
959                         cmp = tmp > 0 ? 1 : -1;
960
961         } else if (file1.exists()) {
962                 cmp = 1;
963         } else if (file2.exists()) {
964                 cmp = -1;
965         }
966
967         return cmp;
968 }
969
970
971 bool prefs2prefs(FileName const & filename, FileName const & tempfile, bool lfuns)
972 {
973         FileName const script = libFileSearch("scripts", "prefs2prefs.py");
974         if (script.empty()) {
975                 LYXERR0("Could not find bind file conversion "
976                                 "script prefs2prefs.py.");
977                 return false;
978         }
979
980         ostringstream command;
981         command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
982           << ' ' << (lfuns ? "-l" : "-p") << ' '
983                 << quoteName(filename.toFilesystemEncoding())
984                 << ' ' << quoteName(tempfile.toFilesystemEncoding());
985         string const command_str = command.str();
986
987         LYXERR(Debug::FILES, "Running `" << command_str << '\'');
988
989         cmd_ret const ret = runCommand(command_str);
990         if (ret.first != 0) {
991                 LYXERR0("Could not run file conversion script prefs2prefs.py.");
992                 return false;
993         }
994         return true;
995 }
996
997
998 } //namespace support
999 } // namespace lyx