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
24 #include "support/convert.h"
25 #include "support/systemcall.h"
26 #include "support/filetools.h"
27 #include "support/lstrings.h"
28 #include "support/forkedcontr.h"
29 #include "support/fs_extras.h"
30 #include "support/package.h"
31 #include "support/path.h"
32 #include "support/lyxlib.h"
33 #include "support/os.h"
35 // FIXME Interface violation
39 #include <boost/assert.hpp>
40 #include <boost/filesystem/operations.hpp>
41 #include <boost/regex.hpp>
42 #include <boost/tokenizer.hpp>
55 #ifndef CXX_GLOBAL_CSTD
66 using std::ostringstream;
69 namespace fs = boost::filesystem;
74 bool IsLyXFilename(string const & filename)
76 return suffixIs(ascii_lowercase(filename), ".lyx");
80 bool IsSGMLFilename(string const & filename)
82 return suffixIs(ascii_lowercase(filename), ".sgml");
86 // Substitutes spaces with underscores in filename (and path)
87 string const MakeLatexName(string const & file)
89 string name = OnlyFilename(file);
90 string const path = OnlyPath(file);
92 for (string::size_type i = 0; i < name.length(); ++i) {
93 name[i] &= 0x7f; // set 8th bit to 0
96 // ok so we scan through the string twice, but who cares.
97 string const keep("abcdefghijklmnopqrstuvwxyz"
98 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
99 "@!\"'()*+,-./0123456789:;<=>?[]`|");
101 string::size_type pos = 0;
102 while ((pos = name.find_first_not_of(keep, pos)) != string::npos) {
105 return AddName(path, name);
109 string const QuoteName(string const & name)
111 return (os::shell() == os::UNIX) ?
117 // Is a file readable ?
118 bool IsFileReadable(string const & path)
120 return fs::exists(path) && !fs::is_directory(path) && fs::is_readable(path);
124 //returns true: dir writeable
125 // false: not writeable
126 bool IsDirWriteable(string const & path)
128 lyxerr[Debug::FILES] << "IsDirWriteable: " << path << endl;
130 string const tmpfl(tempName(path, "lyxwritetest"));
140 // Uses a string of paths separated by ";"s to find a file to open.
141 // Can't cope with pathnames with a ';' in them. Returns full path to file.
142 // If path entry begins with $$LyX/, use system_lyxdir
143 // If path entry begins with $$User/, use user_lyxdir
144 // Example: "$$User/doc;$$LyX/doc"
145 string const FileOpenSearch(string const & path, string const & name,
150 bool notfound = true;
151 string tmppath = split(path, path_element, ';');
153 while (notfound && !path_element.empty()) {
154 path_element = os::internal_path(path_element);
155 if (!suffixIs(path_element, '/'))
157 path_element = subst(path_element, "$$LyX",
158 package().system_support());
159 path_element = subst(path_element, "$$User",
160 package().user_support());
162 real_file = FileSearch(path_element, name, ext);
164 if (real_file.empty()) {
166 tmppath = split(tmppath, path_element, ';');
167 } while (!tmppath.empty() && path_element.empty());
173 if (ext.empty() && notfound) {
174 real_file = FileOpenSearch(path, name, "exe");
175 if (notfound) real_file = FileOpenSearch(path, name, "cmd");
182 /// Returns a vector of all files in directory dir having extension ext.
183 vector<string> const DirList(string const & dir, string const & ext)
185 // EXCEPTIONS FIXME. Rewrite needed when we turn on exceptions. (Lgb)
186 vector<string> dirlist;
188 if (!(fs::exists(dir) && fs::is_directory(dir))) {
190 << "Directory \"" << dir
191 << "\" does not exist to DirList." << endl;
196 if (!ext.empty() && ext[0] != '.')
200 fs::directory_iterator dit(dir);
201 fs::directory_iterator end;
202 for (; dit != end; ++dit) {
203 string const & fil = dit->leaf();
204 if (suffixIs(fil, extension)) {
205 dirlist.push_back(fil);
212 // Returns the real name of file name in directory path, with optional
214 string const FileSearch(string const & path, string const & name,
217 // if `name' is an absolute path, we ignore the setting of `path'
218 // Expand Environmentvariables in 'name'
219 string const tmpname = ReplaceEnvironmentPath(name);
220 string fullname = MakeAbsPath(tmpname, path);
221 // search first without extension, then with it.
222 if (IsFileReadable(fullname))
224 else if (ext.empty())
226 else { // Is it not more reasonable to use ChangeExtension()? (SMiyata)
229 if (IsFileReadable(fullname))
237 // Search the file name.ext in the subdirectory dir of
239 // 2) build_lyxdir (if not empty)
241 string const LibFileSearch(string const & dir, string const & name,
244 string fullname = FileSearch(AddPath(package().user_support(), dir),
246 if (!fullname.empty())
249 if (!package().build_support().empty())
250 fullname = FileSearch(AddPath(package().build_support(), dir),
252 if (!fullname.empty())
255 return FileSearch(AddPath(package().system_support(), dir), name, ext);
260 i18nLibFileSearch(string const & dir, string const & name,
263 // the following comments are from intl/dcigettext.c. We try
264 // to mimick this behaviour here.
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. */
268 /* [Otherwise] We have to proceed with the POSIX methods of
269 looking to `LC_ALL', `LC_xxx', and `LANG'. */
271 string lang = GetEnv("LC_ALL");
273 lang = GetEnv("LC_MESSAGES");
275 lang = GetEnv("LANG");
281 string const language = GetEnv("LANGUAGE");
282 if (lang != "C" && lang != "POSIX" && !language.empty())
286 lang = split(lang, l, ':');
287 while (!l.empty() && l != "C" && l != "POSIX") {
288 string const tmp = LibFileSearch(dir,
289 token(l, '_', 0) + '_' + name,
293 lang = split(lang, l, ':');
296 return LibFileSearch(dir, name, ext);
300 string const LibScriptSearch(string const & command_in)
302 string const token_scriptpath("$$s/");
304 string command = command_in;
305 // Find the starting position of "$$s/"
306 string::size_type const pos1 = command.find(token_scriptpath);
307 if (pos1 == string::npos)
309 // Find the end of the "$$s/some_subdir/some_script" word within
310 // command. Assumes that the script name does not contain spaces.
311 string::size_type const start_script = pos1 + 4;
312 string::size_type const pos2 = command.find(' ', start_script);
313 string::size_type const size_script = pos2 == string::npos?
314 (command.size() - start_script) : pos2 - start_script;
316 // Does this script file exist?
317 string const script =
318 LibFileSearch(".", command.substr(start_script, size_script));
320 if (script.empty()) {
321 // Replace "$$s/" with ""
322 command.erase(pos1, 4);
324 // Replace "$$s/foo/some_script" with "<path to>/some_script".
325 string::size_type const size_replace = size_script + 4;
326 command.replace(pos1, size_replace, QuoteName(script));
333 string const GetEnv(string const & envname)
335 // f.ex. what about error checking?
336 char const * const ch = getenv(envname.c_str());
337 string const envstr = !ch ? "" : ch;
342 vector<string> const getEnvPath(string const & name)
344 typedef boost::char_separator<char> Separator;
345 typedef boost::tokenizer<Separator> Tokenizer;
347 string const env_var = GetEnv(name);
348 Separator const separator(string(1, os::path_separator()).c_str());
349 Tokenizer const tokens(env_var, separator);
350 Tokenizer::const_iterator it = tokens.begin();
351 Tokenizer::const_iterator const end = tokens.end();
353 std::vector<string> vars;
354 for (; it != end; ++it)
355 vars.push_back(os::internal_path(*it));
361 void setEnvPath(string const & name, vector<string> const & env)
363 char const separator(os::path_separator());
364 std::ostringstream ss;
365 vector<string>::const_iterator it = env.begin();
366 vector<string>::const_iterator const end = env.end();
367 for (; it != end; ++it) {
370 ss << os::external_path(*it);
372 putEnv(name + "=" + ss.str());
376 void prependEnvPath(string const & name, string const & prefix)
378 vector<string> env_var = getEnvPath(name);
380 typedef boost::char_separator<char> Separator;
381 typedef boost::tokenizer<Separator> Tokenizer;
383 Separator const separator(string(1, os::path_separator()).c_str());
385 // Prepend each new element to the list, removing identical elements
386 // that occur later in the list.
387 Tokenizer const tokens(prefix, separator);
388 vector<string> reversed_tokens(tokens.begin(), tokens.end());
390 typedef vector<string>::const_reverse_iterator token_iterator;
391 token_iterator it = reversed_tokens.rbegin();
392 token_iterator const end = reversed_tokens.rend();
393 for (; it != end; ++it) {
394 vector<string>::iterator remove_it =
395 std::remove(env_var.begin(), env_var.end(), *it);
396 env_var.erase(remove_it, env_var.end());
397 env_var.insert(env_var.begin(), *it);
400 setEnvPath(name, env_var);
404 bool putEnv(string const & envstr)
406 // CHECK Look at and fix this.
407 // f.ex. what about error checking?
409 #if defined (HAVE_SETENV)
411 string const value = split(envstr, name, '=');
412 int const retval = ::setenv(name.c_str(), value.c_str(), true);
413 #elif defined (HAVE_PUTENV)
414 // this leaks, but what can we do about it?
415 // Is doing a getenv() and a free() of the older value
416 // a good idea? (JMarc)
417 // Actually we don't have to leak...calling putenv like this
418 // should be enough: ... and this is obviously not enough if putenv
419 // does not make a copy of the string. It is also not very wise to
420 // put a string on the free store. If we have to leak we should do it
422 char * leaker = new char[envstr.length() + 1];
423 envstr.copy(leaker, envstr.length());
424 leaker[envstr.length()] = '\0';
425 int const retval = ::putenv(leaker);
427 // If putenv does not make a copy of the char const * this
428 // is very dangerous. OTOH if it does take a copy this is the
430 // The only implementation of putenv that I have seen does not
431 // allocate memory. _And_ after testing the putenv in glibc it
432 // seems that we need to make a copy of the string contents.
433 // I will enable the above.
434 //int retval = lyx::putenv(envstr.c_str());
436 // No environment setting function. Can this happen?
437 int const retval = 1; //return an error condition.
445 string const createTmpDir(string const & tempdir, string const & mask)
448 << "createTmpDir: tempdir=`" << tempdir << "'\n"
449 << "createTmpDir: mask=`" << mask << '\'' << endl;
451 string const tmpfl(tempName(tempdir, mask));
452 // lyx::tempName actually creates a file to make sure that it
453 // stays unique. So we have to delete it before we can create
454 // a dir with the same name. Note also that we are not thread
455 // safe because of the gap between unlink and mkdir. (Lgb)
458 if (tmpfl.empty() || mkdir(tmpfl, 0700)) {
459 lyxerr << "LyX could not create the temporary directory '"
460 << tmpfl << "'" << endl;
464 return MakeAbsPath(tmpfl);
470 bool destroyDir(string const & tmpdir)
474 Path p(user_lyxdir());
476 return fs::remove_all(tmpdir) > 0;
480 string const createBufferTmpDir()
483 // We are in our own directory. Why bother to mangle name?
484 // In fact I wrote this code to circumvent a problematic behaviour
485 // (bug?) of EMX mkstemp().
487 package().temp_dir() + "/lyx_tmpbuf" +
488 convert<string>(count++);
490 if (mkdir(tmpfl, 0777)) {
491 lyxerr << "LyX could not create the temporary directory '"
492 << tmpfl << "'" << endl;
499 string const createLyXTmpDir(string const & deflt)
501 if (!deflt.empty() && deflt != "/tmp") {
502 if (mkdir(deflt, 0777)) {
504 Path p(package().user_support());
506 if (IsDirWriteable(deflt)) {
507 // deflt could not be created because it
508 // did exist already, so let's create our own
510 return createTmpDir(deflt, "lyx_tmpdir");
512 // some other error occured.
513 return createTmpDir("/tmp", "lyx_tmpdir");
519 Path p(package().user_support());
521 return createTmpDir("/tmp", "lyx_tmpdir");
526 bool createDirectory(string const & path, int permission)
528 string temp(rtrim(os::internal_path(path), "/"));
530 BOOST_ASSERT(!temp.empty());
532 if (mkdir(temp, permission))
539 // Strip filename from path name
540 string const OnlyPath(string const & Filename)
542 // If empty filename, return empty
543 if (Filename.empty()) return Filename;
545 // Find last / or start of filename
546 string::size_type j = Filename.rfind('/');
547 if (j == string::npos)
549 return Filename.substr(0, j + 1);
553 // Convert relative path into absolute path based on a basepath.
554 // If relpath is absolute, just use that.
555 // If basepath is empty, use CWD as base.
556 string const MakeAbsPath(string const & RelPath, string const & BasePath)
558 // checks for already absolute path
559 if (os::is_absolute_path(RelPath))
562 // Copies given paths
563 string TempRel(os::internal_path(RelPath));
564 // Since TempRel is NOT absolute, we can safely replace "//" with "/"
565 TempRel = subst(TempRel, "//", "/");
569 if (os::is_absolute_path(BasePath))
572 TempBase = AddPath(getcwd(), BasePath);
574 // Handle /./ at the end of the path
575 while (suffixIs(TempBase, "/./"))
576 TempBase.erase(TempBase.length() - 2);
578 // processes relative path
579 string RTemp(TempRel);
582 while (!RTemp.empty()) {
584 RTemp = split(RTemp, Temp, '/');
586 if (Temp == ".") continue;
588 // Remove one level of TempBase
589 string::difference_type i = TempBase.length() - 2;
592 while (i > 0 && TempBase[i] != '/') --i;
596 while (i > 2 && TempBase[i] != '/') --i;
599 TempBase.erase(i, string::npos);
602 } else if (Temp.empty() && !RTemp.empty()) {
603 TempBase = os::current_root() + RTemp;
606 // Add this piece to TempBase
607 if (!suffixIs(TempBase, '/'))
613 // returns absolute path
614 return os::internal_path(TempBase);
618 // Correctly append filename to the pathname.
619 // If pathname is '.', then don't use pathname.
620 // Chops any path of filename.
621 string const AddName(string const & path, string const & fname)
624 string const basename(OnlyFilename(fname));
628 if (path != "." && path != "./" && !path.empty()) {
629 buf = os::internal_path(path);
630 if (!suffixIs(path, '/'))
634 return buf + basename;
638 // Strips path from filename
639 string const OnlyFilename(string const & fname)
644 string::size_type j = fname.rfind('/');
645 if (j == string::npos) // no '/' in fname
649 return fname.substr(j + 1);
653 /// Returns true is path is absolute
654 bool AbsolutePath(string const & path)
656 return os::is_absolute_path(path);
661 // Create absolute path. If impossible, don't do anything
662 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
663 string const ExpandPath(string const & path)
665 // checks for already absolute path
666 string RTemp(ReplaceEnvironmentPath(path));
667 if (os::is_absolute_path(RTemp))
671 string const copy(RTemp);
674 RTemp = split(RTemp, Temp, '/');
677 return getcwd() + '/' + RTemp;
680 return package().home_dir() + '/' + RTemp;
683 return MakeAbsPath(copy);
685 // Don't know how to handle this
691 // Constracts path/../path
692 // Can't handle "../../" or "/../" (Asger)
693 // Also converts paths like /foo//bar ==> /foo/bar
694 string const NormalizePath(string const & path)
700 if (os::is_absolute_path(path))
703 // Make implicit current directory explicit
706 // Normalise paths like /foo//bar ==> /foo/bar
707 boost::RegEx regex("/{2,}");
708 RTemp = regex.Merge(RTemp, "/");
710 while (!RTemp.empty()) {
712 RTemp = split(RTemp, Temp, '/');
716 } else if (Temp == "..") {
717 // Remove one level of TempBase
718 string::difference_type i = TempBase.length() - 2;
719 while (i > 0 && TempBase[i] != '/')
721 if (i >= 0 && TempBase[i] == '/')
722 TempBase.erase(i + 1, string::npos);
726 TempBase += Temp + '/';
730 // returns absolute path
735 string const GetFileContents(string const & fname)
737 if (fs::exists(fname)) {
738 ifstream ifs(fname.c_str());
746 lyxerr << "LyX was not able to read file '" << fname << '\'' << endl;
751 // Search the string for ${VAR} and $VAR and replace VAR using getenv.
752 string const ReplaceEnvironmentPath(string const & path)
754 // ${VAR} is defined as
755 // $\{[A-Za-z_][A-Za-z_0-9]*\}
756 static string const envvar_br = "[$]\\{([A-Za-z_][A-Za-z_0-9]*)\\}";
758 // $VAR is defined as:
759 // $\{[A-Za-z_][A-Za-z_0-9]*\}
760 static string const envvar = "[$]([A-Za-z_][A-Za-z_0-9]*)";
762 static boost::regex envvar_br_re("(.*)" + envvar_br + "(.*)");
763 static boost::regex envvar_re("(.*)" + envvar + "(.*)");
766 string result = path;
768 regex_match(result, what, envvar_br_re);
769 if (!what[0].matched) {
770 regex_match(result, what, envvar_re);
771 if (!what[0].matched)
774 result = what.str(1) + GetEnv(what.str(2)) + what.str(3);
780 // Make relative path out of two absolute paths
781 string const MakeRelPath(string const & abspath, string const & basepath)
782 // Makes relative path out of absolute path. If it is deeper than basepath,
783 // it's easy. If basepath and abspath share something (they are all deeper
784 // than some directory), it'll be rendered using ..'s. If they are completely
785 // different, then the absolute path will be used as relative path.
787 string::size_type const abslen = abspath.length();
788 string::size_type const baselen = basepath.length();
790 string::size_type i = os::common_path(abspath, basepath);
793 // actually no match - cannot make it relative
797 // Count how many dirs there are in basepath above match
798 // and append as many '..''s into relpath
800 string::size_type j = i;
801 while (j < baselen) {
802 if (basepath[j] == '/') {
803 if (j + 1 == baselen)
810 // Append relative stuff from common directory to abspath
811 if (abspath[i] == '/')
813 for (; i < abslen; ++i)
816 if (suffixIs(buf, '/'))
817 buf.erase(buf.length() - 1);
818 // Substitute empty with .
825 // Append sub-directory(ies) to a path in an intelligent way
826 string const AddPath(string const & path, string const & path_2)
829 string const path2 = os::internal_path(path_2);
831 if (!path.empty() && path != "." && path != "./") {
832 buf = os::internal_path(path);
833 if (path[path.length() - 1] != '/')
837 if (!path2.empty()) {
838 string::size_type const p2start = path2.find_first_not_of('/');
839 string::size_type const p2end = path2.find_last_not_of('/');
840 string const tmp = path2.substr(p2start, p2end - p2start + 1);
848 Change extension of oldname to extension.
849 Strips path off if no_path == true.
850 If no extension on oldname, just appends.
852 string const ChangeExtension(string const & oldname, string const & extension)
854 string::size_type const last_slash = oldname.rfind('/');
855 string::size_type last_dot = oldname.rfind('.');
856 if (last_dot < last_slash && last_slash != string::npos)
857 last_dot = string::npos;
860 // Make sure the extension starts with a dot
861 if (!extension.empty() && extension[0] != '.')
862 ext= '.' + extension;
866 return os::internal_path(oldname.substr(0, last_dot) + ext);
870 /// Return the extension of the file (not including the .)
871 string const GetExtension(string const & name)
873 string::size_type const last_slash = name.rfind('/');
874 string::size_type const last_dot = name.rfind('.');
875 if (last_dot != string::npos &&
876 (last_slash == string::npos || last_dot > last_slash))
877 return name.substr(last_dot + 1,
878 name.length() - (last_dot + 1));
884 // the different filetypes and what they contain in one of the first lines
885 // (dots are any characters). (Herbert 20020131)
888 // EPS %!PS-Adobe-3.0 EPSF...
895 // PBM P1... or P4 (B/W)
896 // PGM P2... or P5 (Grayscale)
897 // PPM P3... or P6 (color)
898 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
899 // SGI \001\332... (decimal 474)
901 // TIFF II... or MM...
903 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
904 // ...static char *...
905 // XWD \000\000\000\151 (0x00006900) decimal 105
907 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
908 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
909 // Z \037\235 UNIX compress
911 string const getFormatFromContents(string const & filename)
914 if (filename.empty() || !IsFileReadable(filename))
917 ifstream ifs(filename.c_str());
919 // Couldn't open file...
923 string const gzipStamp = "\037\213";
926 string const zipStamp = "PK";
929 string const compressStamp = "\037\235";
931 // Maximum strings to read
932 int const max_count = 50;
937 bool firstLine = true;
938 while ((count++ < max_count) && format.empty()) {
940 lyxerr[Debug::GRAPHICS]
941 << "filetools(getFormatFromContents)\n"
942 << "\tFile type not recognised before EOF!"
948 string const stamp = str.substr(0,2);
949 if (firstLine && str.size() >= 2) {
950 // at first we check for a zipped file, because this
951 // information is saved in the first bytes of the file!
952 // also some graphic formats which save the information
953 // in the first line, too.
954 if (prefixIs(str, gzipStamp)) {
957 } else if (stamp == zipStamp) {
960 } else if (stamp == compressStamp) {
964 } else if (stamp == "BM") {
967 } else if (stamp == "\001\332") {
971 // Don't need to use str.at(0), str.at(1) because
972 // we already know that str.size() >= 2
973 } else if (str[0] == 'P') {
989 } else if ((stamp == "II") || (stamp == "MM")) {
992 } else if (prefixIs(str,"%TGIF")) {
995 } else if (prefixIs(str,"#FIG")) {
998 } else if (prefixIs(str,"GIF")) {
1001 } else if (str.size() > 3) {
1002 int const c = ((str[0] << 24) & (str[1] << 16) &
1003 (str[2] << 8) & str[3]);
1012 if (!format.empty())
1014 else if (contains(str,"EPSF"))
1015 // dummy, if we have wrong file description like
1016 // %!PS-Adobe-2.0EPSF"
1019 else if (contains(str,"Grace"))
1022 else if (contains(str,"JFIF"))
1025 else if (contains(str,"%PDF"))
1028 else if (contains(str,"PNG"))
1031 else if (contains(str,"%!PS-Adobe")) {
1034 if (contains(str,"EPSF"))
1040 else if (contains(str,"_bits[]"))
1043 else if (contains(str,"XPM") || contains(str, "static char *"))
1046 else if (contains(str,"BITPIX"))
1050 if (!format.empty()) {
1051 lyxerr[Debug::GRAPHICS]
1052 << "Recognised Fileformat: " << format << endl;
1056 lyxerr[Debug::GRAPHICS]
1057 << "filetools(getFormatFromContents)\n"
1058 << "\tCouldn't find a known format!\n";
1063 /// check for zipped file
1064 bool zippedFile(string const & name)
1066 string const type = getFormatFromContents(name);
1067 if (contains("gzip zip compress", type) && !type.empty())
1073 string const unzippedFileName(string const & zipped_file)
1075 string const ext = GetExtension(zipped_file);
1076 if (ext == "gz" || ext == "z" || ext == "Z")
1077 return ChangeExtension(zipped_file, string());
1078 return "unzipped_" + zipped_file;
1082 string const unzipFile(string const & zipped_file, string const & unzipped_file)
1084 string const tempfile = unzipped_file.empty() ?
1085 unzippedFileName(zipped_file) : unzipped_file;
1087 string const command = "gunzip -c " + zipped_file + " > " + tempfile;
1089 one.startscript(Systemcall::Wait, command);
1090 // test that command was executed successfully (anon)
1091 // yes, please do. (Lgb)
1096 string const MakeDisplayPath(string const & path, unsigned int threshold)
1100 string const home(package().home_dir());
1102 // replace /home/blah with ~/
1103 if (prefixIs(str, home))
1104 str = subst(str, home, "~");
1106 if (str.length() <= threshold)
1109 string const prefix = ".../";
1112 while (str.length() > threshold)
1113 str = split(str, temp, '/');
1115 // Did we shorten everything away?
1117 // Yes, filename itself is too long.
1118 // Pick the start and the end of the filename.
1119 str = OnlyFilename(path);
1120 string const head = str.substr(0, threshold / 2 - 3);
1122 string::size_type len = str.length();
1124 str.substr(len - threshold / 2 - 2, len - 1);
1125 str = head + "..." + tail;
1128 return prefix + str;
1132 bool LyXReadLink(string const & file, string & link, bool resolve)
1134 #ifdef HAVE_READLINK
1135 char linkbuffer[512];
1136 // Should be PATH_MAX but that needs autconf support
1137 int const nRead = ::readlink(file.c_str(),
1138 linkbuffer, sizeof(linkbuffer) - 1);
1141 linkbuffer[nRead] = '\0'; // terminator
1143 link = MakeAbsPath(linkbuffer, OnlyPath(file));
1153 cmd_ret const RunCommand(string const & cmd)
1155 // FIXME: replace all calls to RunCommand with ForkedCall
1156 // (if the output is not needed) or the code in ispell.C
1157 // (if the output is needed).
1159 // One question is if we should use popen or
1160 // create our own popen based on fork, exec, pipe
1161 // of course the best would be to have a
1162 // pstream (process stream), with the
1163 // variants ipstream, opstream
1165 sigset_t newMask, oldMask;
1166 sigemptyset(&oldMask);
1167 sigemptyset(&newMask);
1168 sigaddset(&newMask, SIGCHLD);
1170 // Block the SIGCHLD signal.
1171 sigprocmask(SIG_BLOCK, &newMask, &oldMask);
1173 FILE * inf = ::popen(cmd.c_str(), os::popen_read_mode());
1175 // (Claus Hentschel) Check if popen was succesful ;-)
1177 return make_pair(-1, string());
1178 lyxerr << "RunCommand:: could not start child process" << endl;
1184 ret += static_cast<char>(c);
1187 int const pret = pclose(inf);
1189 perror("RunCommand:: could not terminate child process");
1191 // Unblock the SIGCHLD signal and restore the old mask.
1192 sigprocmask(SIG_SETMASK, &oldMask, 0);
1194 return make_pair(pret, ret);
1198 string const findtexfile(string const & fil, string const & /*format*/)
1200 /* There is no problem to extend this function too use other
1201 methods to look for files. It could be setup to look
1202 in environment paths and also if wanted as a last resort
1203 to a recursive find. One of the easier extensions would
1204 perhaps be to use the LyX file lookup methods. But! I am
1205 going to implement this until I see some demand for it.
1209 // If the file can be found directly, we just return a
1210 // absolute path version of it.
1211 if (fs::exists(fil))
1212 return MakeAbsPath(fil);
1214 // No we try to find it using kpsewhich.
1215 // It seems from the kpsewhich manual page that it is safe to use
1216 // kpsewhich without --format: "When the --format option is not
1217 // given, the search path used when looking for a file is inferred
1218 // from the name given, by looking for a known extension. If no
1219 // known extension is found, the search path for TeX source files
1221 // However, we want to take advantage of the format sine almost all
1222 // the different formats has environment variables that can be used
1223 // to controll which paths to search. f.ex. bib looks in
1224 // BIBINPUTS and TEXBIB. Small list follows:
1225 // bib - BIBINPUTS, TEXBIB
1227 // graphic/figure - TEXPICTS, TEXINPUTS
1228 // ist - TEXINDEXSTYLE, INDEXSTYLE
1229 // pk - PROGRAMFONTS, PKFONTS, TEXPKS, GLYPHFONTS, TEXFONTS
1231 // tfm - TFMFONTS, TEXFONTS
1232 // This means that to use kpsewhich in the best possible way we
1233 // should help it by setting additional path in the approp. envir.var.
1234 string const kpsecmd = "kpsewhich " + fil;
1236 cmd_ret const c = RunCommand(kpsecmd);
1238 lyxerr[Debug::LATEX] << "kpse status = " << c.first << '\n'
1239 << "kpse result = `" << rtrim(c.second, "\n")
1242 return os::internal_path(rtrim(c.second, "\n\r"));
1248 void removeAutosaveFile(string const & filename)
1250 string a = OnlyPath(filename);
1252 a += OnlyFilename(filename);
1259 void readBB_lyxerrMessage(string const & file, bool & zipped,
1260 string const & message)
1262 lyxerr[Debug::GRAPHICS] << "[readBB_from_PSFile] "
1263 << message << std::endl;
1264 #ifdef WITH_WARNINGS
1265 #warning Why is this func deleting a file? (Lgb)
1272 string const readBB_from_PSFile(string const & file)
1274 // in a (e)ps-file it's an entry like %%BoundingBox:23 45 321 345
1275 // It seems that every command in the header has an own line,
1276 // getline() should work for all files.
1277 // On the other hand some plot programs write the bb at the
1278 // end of the file. Than we have in the header:
1279 // %%BoundingBox: (atend)
1280 // In this case we must check the end.
1281 bool zipped = zippedFile(file);
1282 string const file_ = zipped ?
1283 string(unzipFile(file)) : string(file);
1284 string const format = getFormatFromContents(file_);
1286 if (format != "eps" && format != "ps") {
1287 readBB_lyxerrMessage(file_, zipped,"no(e)ps-format");
1291 std::ifstream is(file_.c_str());
1295 if (contains(s,"%%BoundingBox:") && !contains(s,"atend")) {
1296 string const bb = ltrim(s.substr(14));
1297 readBB_lyxerrMessage(file_, zipped, bb);
1301 readBB_lyxerrMessage(file_, zipped, "no bb found");
1306 int compare_timestamps(string const & file1, string const & file2)
1308 BOOST_ASSERT(AbsolutePath(file1) && AbsolutePath(file2));
1310 // If the original is newer than the copy, then copy the original
1311 // to the new directory.
1314 if (fs::exists(file1) && fs::exists(file2)) {
1315 double const tmp = difftime(fs::last_write_time(file1),
1316 fs::last_write_time(file2));
1318 cmp = tmp > 0 ? 1 : -1;
1320 } else if (fs::exists(file1)) {
1322 } else if (fs::exists(file2)) {
1329 } //namespace support