3 * This file is part of LyX, the document processor.
4 * Licence details can be found in the file COPYING.
6 * parts Copyright 1985, 1990, 1993 Free Software Foundation, Inc.
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
17 * Full author contact details are available in file CREDITS.
19 * General path-mangling functions
26 #include "support/filetools.h"
28 #include "support/debug.h"
29 #include "support/environment.h"
30 #include "support/gettext.h"
31 #include "support/lstrings.h"
32 #include "support/os.h"
33 #include "support/Package.h"
34 #include "support/Path.h"
35 #include "support/Systemcall.h"
36 #include "support/qstring_helpers.h"
40 #include "support/lassert.h"
41 #include "support/regex.h"
65 bool isLyXFileName(string const & filename)
67 return suffixIs(ascii_lowercase(filename), ".lyx");
71 bool isSGMLFileName(string const & filename)
73 return suffixIs(ascii_lowercase(filename), ".sgml");
77 bool isValidLaTeXFileName(string const & filename)
79 string const invalid_chars("#%\"");
80 return filename.find_first_of(invalid_chars) == string::npos;
84 bool isValidDVIFileName(string const & filename)
86 string const invalid_chars("${}()[]^");
87 return filename.find_first_of(invalid_chars) == string::npos;
91 string const latex_path(string const & original_path,
92 latex_path_extension extension,
95 // On cygwin, we may need windows or posix style paths.
96 string path = os::latex_path(original_path);
97 path = subst(path, "~", "\\string~");
98 if (path.find(' ') != string::npos) {
99 // We can't use '"' because " is sometimes active (e.g. if
100 // babel is loaded with the "german" option)
101 if (extension == EXCLUDE_EXTENSION) {
102 // ChangeExtension calls os::internal_path internally
103 // so don't use it to remove the extension.
104 string const ext = getExtension(path);
105 string const base = ext.empty() ?
107 path.substr(0, path.length() - ext.length() - 1);
108 // ChangeExtension calls os::internal_path internally
109 // so don't use it to re-add the extension.
110 path = "\\string\"" + base + "\\string\"." + ext;
112 path = "\\string\"" + path + "\\string\"";
116 return dots == ESCAPE_DOTS ? subst(path, ".", "\\lyxdot ") : path;
120 // Substitutes spaces with underscores in filename (and path)
121 FileName const makeLatexName(FileName const & file)
123 string name = file.onlyFileName();
124 string const path = file.onlyPath().absFileName() + "/";
126 // ok so we scan through the string twice, but who cares.
127 // FIXME: in Unicode time this will break for sure! There is
128 // a non-latin world out there...
129 string const keep = "abcdefghijklmnopqrstuvwxyz"
130 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
131 "@!'()*+,-./0123456789:;<=>?[]`|";
133 string::size_type pos = 0;
134 while ((pos = name.find_first_not_of(keep, pos)) != string::npos)
137 FileName latex_name(path + name);
138 latex_name.changeExtension(".tex");
143 string const quoteName(string const & name, quote_style style)
147 // This does not work on native Windows for filenames
148 // containing the following characters < > : " / \ | ? *
149 // Moreover, it can't be made to work, as, according to
150 // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx
151 // those are reserved characters, and thus are forbidden.
152 // Please, also note that the command-line parser in
153 // ForkedCall::generateChild cannot deal with filenames
154 // containing " or ', therefore we don't pass user filenames
155 // to child processes if possible. We store them in a python
156 // script instead, where we don't have these limitations.
158 return (os::shell() == os::UNIX) ?
159 '\'' + subst(name, "'", "\'\\\'\'") + '\'' :
162 // According to the QProcess parser, a single double
163 // quote is represented by three consecutive ones.
164 // Here we simply escape the double quote and let our
165 // simple parser in Systemcall.cpp do the substitution.
166 return '"' + subst(name, "\"", "\\\"") + '"';
169 return "\"" + subst(subst(name, "\\", "\\\\"), "\"", "\\\"")
172 // shut up stupid compiler
178 // Uses a string of paths separated by ";"s to find a file to open.
179 // Can't cope with pathnames with a ';' in them. Returns full path to file.
180 // If path entry begins with $$LyX/, use system_lyxdir
181 // If path entry begins with $$User/, use user_lyxdir
182 // Example: "$$User/doc;$$LyX/doc"
183 FileName const fileOpenSearch(string const & path, string const & name,
188 bool notfound = true;
189 string tmppath = split(path, path_element, ';');
191 while (notfound && !path_element.empty()) {
192 path_element = os::internal_path(path_element);
193 if (!suffixIs(path_element, '/'))
195 path_element = subst(path_element, "$$LyX",
196 package().system_support().absFileName());
197 path_element = subst(path_element, "$$User",
198 package().user_support().absFileName());
200 real_file = fileSearch(path_element, name, ext);
202 if (real_file.empty()) {
204 tmppath = split(tmppath, path_element, ';');
205 } while (!tmppath.empty() && path_element.empty());
215 // Returns the real name of file name in directory path, with optional
217 FileName const fileSearch(string const & path, string const & name,
218 string const & ext, search_mode mode)
220 // if `name' is an absolute path, we ignore the setting of `path'
221 // Expand Environmentvariables in 'name'
222 string const tmpname = replaceEnvironmentPath(name);
223 FileName fullname(makeAbsPath(tmpname, path));
224 // search first without extension, then with it.
225 if (fullname.isReadableFile())
229 return mode == may_not_exist ? fullname : FileName();
230 // Only add the extension if it is not already the extension of
232 if (getExtension(fullname.absFileName()) != ext)
233 fullname = FileName(addExtension(fullname.absFileName(), ext));
234 if (fullname.isReadableFile() || mode == may_not_exist)
240 // Search the file name.ext in the subdirectory dir of
242 // 2) build_lyxdir (if not empty)
244 FileName const libFileSearch(string const & dir, string const & name,
247 FileName fullname = fileSearch(addPath(package().user_support().absFileName(), dir),
249 if (!fullname.empty())
252 if (!package().build_support().empty())
253 fullname = fileSearch(addPath(package().build_support().absFileName(), dir),
255 if (!fullname.empty())
258 return fileSearch(addPath(package().system_support().absFileName(), dir), name, ext);
262 FileName const i18nLibFileSearch(string const & dir, string const & name,
265 /* The highest priority value is the `LANGUAGE' environment
266 variable. But we don't use the value if the currently
267 selected locale is the C locale. This is a GNU extension.
269 Otherwise, w use a trick to guess what support/gettext.has done:
270 each po file is able to tell us its name. (JMarc)
273 string lang = to_ascii(_(languageTestString()));
274 string const language = getEnv("LANGUAGE");
275 if (!lang.empty() && !language.empty())
279 lang = split(lang, l, ':');
282 // First try with the full name
283 tmp = libFileSearch(addPath(dir, l), name, ext);
287 // Then the name without country code
288 string const shortl = token(l, '_', 0);
290 tmp = libFileSearch(addPath(dir, shortl), name, ext);
296 // For compatibility, to be removed later (JMarc)
297 tmp = libFileSearch(dir, token(l, '_', 0) + '_' + name,
300 lyxerr << "i18nLibFileSearch: File `" << tmp
301 << "' has been found by the old method" <<endl;
305 lang = split(lang, l, ':');
308 return libFileSearch(dir, name, ext);
312 FileName const imageLibFileSearch(string & dir, string const & name,
315 if (!lyx::lyxrc.icon_set.empty()) {
316 string const imagedir = addPath(dir, lyx::lyxrc.icon_set);
317 FileName const fn = libFileSearch(imagedir, name, ext);
323 return libFileSearch(dir, name, ext);
327 string const libScriptSearch(string const & command_in, quote_style style)
329 static string const token_scriptpath = "$$s/";
331 string command = command_in;
332 // Find the starting position of "$$s/"
333 string::size_type const pos1 = command.find(token_scriptpath);
334 if (pos1 == string::npos)
336 // Find the end of the "$$s/some_subdir/some_script" word within
337 // command. Assumes that the script name does not contain spaces.
338 string::size_type const start_script = pos1 + 4;
339 string::size_type const pos2 = command.find(' ', start_script);
340 string::size_type const size_script = pos2 == string::npos?
341 (command.size() - start_script) : pos2 - start_script;
343 // Does this script file exist?
344 string const script =
345 libFileSearch(".", command.substr(start_script, size_script)).absFileName();
347 if (script.empty()) {
348 // Replace "$$s/" with ""
349 command.erase(pos1, 4);
351 // Replace "$$s/foo/some_script" with "<path to>/some_script".
352 string::size_type const size_replace = size_script + 4;
353 command.replace(pos1, size_replace, quoteName(script, style));
360 static FileName createTmpDir(FileName const & tempdir, string const & mask)
362 LYXERR(Debug::FILES, "createTmpDir: tempdir=`" << tempdir << "'\n"
363 << "createTmpDir: mask=`" << mask << '\'');
365 FileName const tmpfl = FileName::tempName(tempdir, mask);
367 if (tmpfl.empty() || !tmpfl.createDirectory(0700)) {
368 LYXERR0("LyX could not create temporary directory in " << tempdir
377 FileName const createLyXTmpDir(FileName const & deflt)
379 if (deflt.empty() || deflt == package().system_temp_dir())
380 return createTmpDir(package().system_temp_dir(), "lyx_tmpdir");
382 if (deflt.createDirectory(0777))
385 if (deflt.isDirWritable()) {
386 // deflt could not be created because it
387 // did exist already, so let's create our own
389 return createTmpDir(deflt, "lyx_tmpdir");
391 // some other error occured.
392 return createTmpDir(package().system_temp_dir(), "lyx_tmpdir");
397 // Strip filename from path name
398 string const onlyPath(string const & filename)
400 // If empty filename, return empty
401 if (filename.empty())
404 // Find last / or start of filename
405 size_t j = filename.rfind('/');
406 return j == string::npos ? "./" : filename.substr(0, j + 1);
410 // Convert relative path into absolute path based on a basepath.
411 // If relpath is absolute, just use that.
412 // If basepath is empty, use CWD as base.
413 // Note that basePath can be a relative path, in the sense that it may
414 // not begin with "/" (e.g.), but it should NOT contain such constructs
416 // FIXME It might be nice if the code didn't simply assume that.
417 FileName const makeAbsPath(string const & relPath, string const & basePath)
419 // checks for already absolute path
420 if (FileName::isAbsolute(relPath))
421 return FileName(relPath);
423 // Copies given paths
424 string tempRel = os::internal_path(relPath);
425 // Since TempRel is NOT absolute, we can safely replace "//" with "/"
426 tempRel = subst(tempRel, "//", "/");
430 if (FileName::isAbsolute(basePath))
433 tempBase = addPath(FileName::getcwd().absFileName(), basePath);
435 // Handle /./ at the end of the path
436 while (suffixIs(tempBase, "/./"))
437 tempBase.erase(tempBase.length() - 2);
439 // processes relative path
440 string rTemp = tempRel;
443 // Check for a leading "~"
445 rTemp = split(rTemp, temp, '/');
447 tempBase = Package::get_home_dir().absFileName();
452 while (!rTemp.empty()) {
454 rTemp = split(rTemp, temp, '/');
456 if (temp == ".") continue;
458 // Remove one level of TempBase
459 if (tempBase.length() <= 1) {
460 //this is supposed to be an absolute path, so...
464 //erase a trailing slash if there is one
465 if (suffixIs(tempBase, "/"))
466 tempBase.erase(tempBase.length() - 1, string::npos);
468 string::size_type i = tempBase.length() - 1;
469 while (i > 0 && tempBase[i] != '/')
472 tempBase.erase(i, string::npos);
475 } else if (temp.empty() && !rTemp.empty()) {
476 tempBase = os::current_root() + rTemp;
479 // Add this piece to TempBase
480 if (!suffixIs(tempBase, '/'))
486 // returns absolute path
487 return FileName(tempBase);
491 // Correctly append filename to the pathname.
492 // If pathname is '.', then don't use pathname.
493 // Chops any path of filename.
494 string const addName(string const & path, string const & fname)
496 string const basename = onlyFileName(fname);
499 if (path != "." && path != "./" && !path.empty()) {
500 buf = os::internal_path(path);
501 if (!suffixIs(path, '/'))
505 return buf + basename;
509 // Strips path from filename
510 string const onlyFileName(string const & fname)
515 string::size_type j = fname.rfind('/');
516 if (j == string::npos) // no '/' in fname
520 return fname.substr(j + 1);
524 // Create absolute path. If impossible, don't do anything
525 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
526 string const expandPath(string const & path)
528 // checks for already absolute path
529 string rTemp = replaceEnvironmentPath(path);
530 if (FileName::isAbsolute(rTemp))
534 string const copy = rTemp;
537 rTemp = split(rTemp, temp, '/');
540 return FileName::getcwd().absFileName() + '/' + rTemp;
543 return Package::get_home_dir().absFileName() + '/' + rTemp;
546 return makeAbsPath(copy).absFileName();
548 // Don't know how to handle this
553 // Search the string for ${VAR} and $VAR and replace VAR using getenv.
554 string const replaceEnvironmentPath(string const & path)
556 // ${VAR} is defined as
557 // $\{[A-Za-z_][A-Za-z_0-9]*\}
558 static string const envvar_br = "[$]\\{([A-Za-z_][A-Za-z_0-9]*)\\}";
560 // $VAR is defined as:
561 // $[A-Za-z_][A-Za-z_0-9]*
562 static string const envvar = "[$]([A-Za-z_][A-Za-z_0-9]*)";
564 static regex envvar_br_re("(.*)" + envvar_br + "(.*)");
565 static regex envvar_re("(.*)" + envvar + "(.*)");
566 string result = path;
569 if (!regex_match(result, what, envvar_br_re)) {
570 if (!regex_match(result, what, envvar_re))
573 string env_var = getEnv(what.str(2));
574 result = what.str(1) + env_var + what.str(3);
580 // Replace current directory in all elements of a path list with a given path.
581 string const replaceCurdirPath(string const & path, string const & pathlist)
583 string const oldpathlist = replaceEnvironmentPath(pathlist);
584 char const sep = os::path_separator();
587 for (size_t i = 0, k = 0; i != string::npos; k = i) {
588 i = oldpathlist.find(sep, i);
589 string p = oldpathlist.substr(k, i - k);
590 if (FileName::isAbsolute(p)) {
596 } else if (prefixIs(p, "./")) {
598 while (p[offset] == '/')
601 newpathlist += addPath(path, p.substr(offset));
602 if (suffixIs(p, "//"))
605 if (i != string::npos) {
607 // Stop here if the last element is empty
608 if (++i == oldpathlist.length())
616 // Make relative path out of two absolute paths
617 docstring const makeRelPath(docstring const & abspath, docstring const & basepath)
618 // Makes relative path out of absolute path. If it is deeper than basepath,
619 // it's easy. If basepath and abspath share something (they are all deeper
620 // than some directory), it'll be rendered using ..'s. If they are completely
621 // different, then the absolute path will be used as relative path.
623 docstring::size_type const abslen = abspath.length();
624 docstring::size_type const baselen = basepath.length();
626 docstring::size_type i = os::common_path(abspath, basepath);
629 // actually no match - cannot make it relative
633 // Count how many dirs there are in basepath above match
634 // and append as many '..''s into relpath
636 docstring::size_type j = i;
637 while (j < baselen) {
638 if (basepath[j] == '/') {
639 if (j + 1 == baselen)
646 // Append relative stuff from common directory to abspath
647 if (abspath[i] == '/')
649 for (; i < abslen; ++i)
652 if (suffixIs(buf, '/'))
653 buf.erase(buf.length() - 1);
654 // Substitute empty with .
661 // Append sub-directory(ies) to a path in an intelligent way
662 string const addPath(string const & path, string const & path_2)
665 string const path2 = os::internal_path(path_2);
667 if (!path.empty() && path != "." && path != "./") {
668 buf = os::internal_path(path);
669 if (path[path.length() - 1] != '/')
673 if (!path2.empty()) {
674 string::size_type const p2start = path2.find_first_not_of('/');
675 string::size_type const p2end = path2.find_last_not_of('/');
676 string const tmp = path2.substr(p2start, p2end - p2start + 1);
683 string const changeExtension(string const & oldname, string const & extension)
685 string::size_type const last_slash = oldname.rfind('/');
686 string::size_type last_dot = oldname.rfind('.');
687 if (last_dot < last_slash && last_slash != string::npos)
688 last_dot = string::npos;
691 // Make sure the extension starts with a dot
692 if (!extension.empty() && extension[0] != '.')
693 ext= '.' + extension;
697 return os::internal_path(oldname.substr(0, last_dot) + ext);
701 string const removeExtension(string const & name)
703 return changeExtension(name, string());
707 string const addExtension(string const & name, string const & extension)
709 if (!extension.empty() && extension[0] != '.')
710 return name + '.' + extension;
711 return name + extension;
715 /// Return the extension of the file (not including the .)
716 string const getExtension(string const & name)
718 string::size_type const last_slash = name.rfind('/');
719 string::size_type const last_dot = name.rfind('.');
720 if (last_dot != string::npos &&
721 (last_slash == string::npos || last_dot > last_slash))
722 return name.substr(last_dot + 1,
723 name.length() - (last_dot + 1));
729 string const unzippedFileName(string const & zipped_file)
731 string const ext = getExtension(zipped_file);
732 if (ext == "gz" || ext == "z" || ext == "Z")
733 return changeExtension(zipped_file, string());
734 return onlyPath(zipped_file) + "unzipped_" + onlyFileName(zipped_file);
738 FileName const unzipFile(FileName const & zipped_file, string const & unzipped_file)
740 FileName const tempfile = FileName(unzipped_file.empty() ?
741 unzippedFileName(zipped_file.toFilesystemEncoding()) :
744 string const command = "gunzip -c " +
745 zipped_file.toFilesystemEncoding() + " > " +
746 tempfile.toFilesystemEncoding();
748 one.startscript(Systemcall::Wait, command);
749 // test that command was executed successfully (anon)
750 // yes, please do. (Lgb)
755 docstring const makeDisplayPath(string const & path, unsigned int threshold)
759 // If file is from LyXDir, display it as if it were relative.
760 string const system = package().system_support().absFileName();
761 if (prefixIs(str, system) && str != system)
762 return from_utf8("[" + str.erase(0, system.length()) + "]");
764 // replace /home/blah with ~/
765 string const home = Package::get_home_dir().absFileName();
766 if (!home.empty() && prefixIs(str, home))
767 str = subst(str, home, "~");
769 if (str.length() <= threshold)
770 return from_utf8(os::external_path(str));
772 string const prefix = ".../";
775 while (str.length() > threshold)
776 str = split(str, temp, '/');
778 // Did we shorten everything away?
780 // Yes, filename itself is too long.
781 // Pick the start and the end of the filename.
782 str = onlyFileName(path);
783 string const head = str.substr(0, threshold / 2 - 3);
785 string::size_type len = str.length();
787 str.substr(len - threshold / 2 - 2, len - 1);
788 str = head + "..." + tail;
791 return from_utf8(os::external_path(prefix + str));
796 bool readLink(FileName const & file, FileName & link)
798 char linkbuffer[PATH_MAX + 1];
799 string const encoded = file.toFilesystemEncoding();
800 int const nRead = ::readlink(encoded.c_str(),
801 linkbuffer, sizeof(linkbuffer) - 1);
804 linkbuffer[nRead] = '\0'; // terminator
805 link = makeAbsPath(linkbuffer, onlyPath(file.absFileName()));
809 bool readLink(FileName const &, FileName &)
816 cmd_ret const runCommand(string const & cmd)
818 // FIXME: replace all calls to RunCommand with ForkedCall
819 // (if the output is not needed) or the code in ISpell.cpp
820 // (if the output is needed).
822 // One question is if we should use popen or
823 // create our own popen based on fork, exec, pipe
824 // of course the best would be to have a
825 // pstream (process stream), with the
826 // variants ipstream, opstream
831 PROCESS_INFORMATION process;
832 SECURITY_ATTRIBUTES security;
836 security.nLength = sizeof(SECURITY_ATTRIBUTES);
837 security.bInheritHandle = TRUE;
838 security.lpSecurityDescriptor = NULL;
840 if (CreatePipe(&in, &out, &security, 0)) {
841 memset(&startup, 0, sizeof(STARTUPINFO));
842 memset(&process, 0, sizeof(PROCESS_INFORMATION));
844 startup.cb = sizeof(STARTUPINFO);
845 startup.dwFlags = STARTF_USESTDHANDLES;
847 startup.hStdError = GetStdHandle(STD_ERROR_HANDLE);
848 startup.hStdInput = GetStdHandle(STD_INPUT_HANDLE);
849 startup.hStdOutput = out;
851 if (CreateProcess(0, (LPTSTR)cmd.c_str(), &security, &security,
852 TRUE, CREATE_NO_WINDOW, 0, 0, &startup, &process)) {
854 CloseHandle(process.hThread);
855 fno = _open_osfhandle((long)in, _O_RDONLY);
857 inf = _fdopen(fno, "r");
860 #elif defined (HAVE_POPEN)
861 FILE * inf = ::popen(cmd.c_str(), os::popen_read_mode());
862 #elif defined (HAVE__POPEN)
863 FILE * inf = ::_popen(cmd.c_str(), os::popen_read_mode());
865 #error No popen() function.
868 // (Claus Hentschel) Check if popen was successful ;-)
870 lyxerr << "RunCommand:: could not start child process" << endl;
871 return make_pair(-1, string());
877 ret += static_cast<char>(c);
882 WaitForSingleObject(process.hProcess, INFINITE);
883 CloseHandle(process.hProcess);
884 int const pret = fclose(inf);
885 #elif defined (HAVE_PCLOSE)
886 int const pret = pclose(inf);
887 #elif defined (HAVE__PCLOSE)
888 int const pret = _pclose(inf);
890 #error No pclose() function.
894 perror("RunCommand:: could not terminate child process");
896 return make_pair(pret, ret);
900 FileName const findtexfile(string const & fil, string const & /*format*/)
902 /* There is no problem to extend this function too use other
903 methods to look for files. It could be setup to look
904 in environment paths and also if wanted as a last resort
905 to a recursive find. One of the easier extensions would
906 perhaps be to use the LyX file lookup methods. But! I am
907 going to implement this until I see some demand for it.
911 // If the file can be found directly, we just return a
912 // absolute path version of it.
913 FileName const absfile(makeAbsPath(fil));
914 if (absfile.exists())
917 // Now we try to find it using kpsewhich.
918 // It seems from the kpsewhich manual page that it is safe to use
919 // kpsewhich without --format: "When the --format option is not
920 // given, the search path used when looking for a file is inferred
921 // from the name given, by looking for a known extension. If no
922 // known extension is found, the search path for TeX source files
924 // However, we want to take advantage of the format sine almost all
925 // the different formats has environment variables that can be used
926 // to controll which paths to search. f.ex. bib looks in
927 // BIBINPUTS and TEXBIB. Small list follows:
928 // bib - BIBINPUTS, TEXBIB
930 // graphic/figure - TEXPICTS, TEXINPUTS
931 // ist - TEXINDEXSTYLE, INDEXSTYLE
932 // pk - PROGRAMFONTS, PKFONTS, TEXPKS, GLYPHFONTS, TEXFONTS
934 // tfm - TFMFONTS, TEXFONTS
935 // This means that to use kpsewhich in the best possible way we
936 // should help it by setting additional path in the approp. envir.var.
937 string const kpsecmd = "kpsewhich " + fil;
939 cmd_ret const c = runCommand(kpsecmd);
941 LYXERR(Debug::LATEX, "kpse status = " << c.first << '\n'
942 << "kpse result = `" << rtrim(c.second, "\n\r") << '\'');
944 return FileName(rtrim(to_utf8(from_filesystem8bit(c.second)), "\n\r"));
950 void readBB_lyxerrMessage(FileName const & file, bool & zipped,
951 string const & message)
953 LYXERR(Debug::GRAPHICS, "[readBB_from_PSFile] " << message);
954 // FIXME: Why is this func deleting a file? (Lgb)
960 string const readBB_from_PSFile(FileName const & file)
962 // in a (e)ps-file it's an entry like %%BoundingBox:23 45 321 345
963 // It seems that every command in the header has an own line,
964 // getline() should work for all files.
965 // On the other hand some plot programs write the bb at the
966 // end of the file. Than we have in the header:
967 // %%BoundingBox: (atend)
968 // In this case we must check the end.
969 bool zipped = file.isZippedFile();
970 FileName const file_ = zipped ? unzipFile(file) : file;
971 string const format = file_.guessFormatFromContents();
973 if (format != "eps" && format != "ps") {
974 readBB_lyxerrMessage(file_, zipped,"no(e)ps-format");
978 static lyx::regex bbox_re(
979 "^%%BoundingBox:\\s*([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)\\s+([[:digit:]]+)");
980 ifstream is(file_.toFilesystemEncoding().c_str());
985 if (regex_match(s, what, bbox_re)) {
986 // Our callers expect the tokens in the string
987 // separated by single spaces.
988 // FIXME: change return type from string to something
991 os << what.str(1) << ' ' << what.str(2) << ' '
992 << what.str(3) << ' ' << what.str(4);
993 string const bb = os.str();
994 readBB_lyxerrMessage(file_, zipped, bb);
998 readBB_lyxerrMessage(file_, zipped, "no bb found");
1003 int compare_timestamps(FileName const & file1, FileName const & file2)
1005 // If the original is newer than the copy, then copy the original
1006 // to the new directory.
1009 if (file1.exists() && file2.exists()) {
1010 double const tmp = difftime(file1.lastModified(), file2.lastModified());
1012 cmp = tmp > 0 ? 1 : -1;
1014 } else if (file1.exists()) {
1016 } else if (file2.exists()) {
1024 bool prefs2prefs(FileName const & filename, FileName const & tempfile, bool lfuns)
1026 FileName const script = libFileSearch("scripts", "prefs2prefs.py");
1027 if (script.empty()) {
1028 LYXERR0("Could not find bind file conversion "
1029 "script prefs2prefs.py.");
1033 ostringstream command;
1034 command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
1035 << ' ' << (lfuns ? "-l" : "-p") << ' '
1036 << quoteName(filename.toFilesystemEncoding())
1037 << ' ' << quoteName(tempfile.toFilesystemEncoding());
1038 string const command_str = command.str();
1040 LYXERR(Debug::FILES, "Running `" << command_str << '\'');
1042 cmd_ret const ret = runCommand(command_str);
1043 if (ret.first != 0) {
1044 LYXERR0("Could not run file conversion script prefs2prefs.py.");
1051 } //namespace support