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