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 // Substitutes spaces with underscores in filename (and path)
110 string const QuoteName(string const & name)
112 return (os::shell() == os::UNIX) ?
118 // Is a file readable ?
119 bool IsFileReadable(string const & path)
121 return fs::exists(path) && !fs::is_directory(path) && fs::is_readable(path);
125 //returns true: dir writeable
126 // false: not writeable
127 bool IsDirWriteable(string const & path)
129 lyxerr[Debug::FILES] << "IsDirWriteable: " << path << endl;
131 string const tmpfl(tempName(path, "lyxwritetest"));
141 // Uses a string of paths separated by ";"s to find a file to open.
142 // Can't cope with pathnames with a ';' in them. Returns full path to file.
143 // If path entry begins with $$LyX/, use system_lyxdir
144 // If path entry begins with $$User/, use user_lyxdir
145 // Example: "$$User/doc;$$LyX/doc"
146 string const FileOpenSearch(string const & path, string const & name,
151 bool notfound = true;
152 string tmppath = split(path, path_element, ';');
154 while (notfound && !path_element.empty()) {
155 path_element = os::internal_path(path_element);
156 if (!suffixIs(path_element, '/'))
158 path_element = subst(path_element, "$$LyX",
159 package().system_support());
160 path_element = subst(path_element, "$$User",
161 package().user_support());
163 real_file = FileSearch(path_element, name, ext);
165 if (real_file.empty()) {
167 tmppath = split(tmppath, path_element, ';');
168 } while (!tmppath.empty() && path_element.empty());
174 if (ext.empty() && notfound) {
175 real_file = FileOpenSearch(path, name, "exe");
176 if (notfound) real_file = FileOpenSearch(path, name, "cmd");
183 /// Returns a vector of all files in directory dir having extension ext.
184 vector<string> const DirList(string const & dir, string const & ext)
186 // EXCEPTIONS FIXME. Rewrite needed when we turn on exceptions. (Lgb)
187 vector<string> dirlist;
189 if (!(fs::exists(dir) && fs::is_directory(dir))) {
191 << "Directory \"" << dir
192 << "\" does not exist to DirList." << endl;
197 if (!ext.empty() && ext[0] != '.')
201 fs::directory_iterator dit(dir);
202 fs::directory_iterator end;
203 for (; dit != end; ++dit) {
204 string const & fil = dit->leaf();
205 if (suffixIs(fil, extension)) {
206 dirlist.push_back(fil);
213 // Returns the real name of file name in directory path, with optional
215 string const FileSearch(string const & path, string const & name,
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 string fullname = MakeAbsPath(tmpname, path);
222 // search first without extension, then with it.
223 if (IsFileReadable(fullname))
225 else if (ext.empty())
227 else { // Is it not more reasonable to use ChangeExtension()? (SMiyata)
230 if (IsFileReadable(fullname))
238 // Search the file name.ext in the subdirectory dir of
240 // 2) build_lyxdir (if not empty)
242 string const LibFileSearch(string const & dir, string const & name,
245 string fullname = FileSearch(AddPath(package().user_support(), dir),
247 if (!fullname.empty())
250 if (!package().build_support().empty())
251 fullname = FileSearch(AddPath(package().build_support(), dir),
253 if (!fullname.empty())
256 return FileSearch(AddPath(package().system_support(), dir), name, ext);
261 i18nLibFileSearch(string const & dir, string const & name,
264 // the following comments are from intl/dcigettext.c. We try
265 // to mimick this behaviour here.
266 /* The highest priority value is the `LANGUAGE' environment
267 variable. But we don't use the value if the currently
268 selected locale is the C locale. This is a GNU extension. */
269 /* [Otherwise] We have to proceed with the POSIX methods of
270 looking to `LC_ALL', `LC_xxx', and `LANG'. */
272 string lang = GetEnv("LC_ALL");
274 lang = GetEnv("LC_MESSAGES");
276 lang = GetEnv("LANG");
282 string const language = GetEnv("LANGUAGE");
283 if (lang != "C" && lang != "POSIX" && !language.empty())
287 lang = split(lang, l, ':');
288 while (!l.empty() && l != "C" && l != "POSIX") {
289 string const tmp = LibFileSearch(dir,
290 token(l, '_', 0) + '_' + name,
294 lang = split(lang, l, ':');
297 return LibFileSearch(dir, name, ext);
301 string const LibScriptSearch(string const & command_in)
303 string const token_scriptpath("$$s/");
305 string command = command_in;
306 // Find the starting position of "$$s/"
307 string::size_type const pos1 = command.find(token_scriptpath);
308 if (pos1 == string::npos)
310 // Find the end of the "$$s/some_script" word within command.
311 // Assumes that the script name does not contain spaces.
312 string::size_type const start_script = pos1 + 4;
313 string::size_type const pos2 = command.find(' ', start_script);
314 string::size_type const size_script = pos2 == string::npos?
315 (command.size() - start_script) : pos2 - start_script;
317 // Does this script file exist?
318 string const script =
319 LibFileSearch(".", command.substr(start_script, size_script));
321 if (script.empty()) {
322 // Replace "$$s/" with ""
323 command.erase(pos1, 4);
325 // Replace "$$s/foo/some_script" with "<path to>/some_script".
326 string::size_type const size_replace = size_script + 4;
327 command.replace(pos1, size_replace, QuoteName(script));
334 string const GetEnv(string const & envname)
336 // f.ex. what about error checking?
337 char const * const ch = getenv(envname.c_str());
338 string const envstr = !ch ? "" : ch;
343 vector<string> const getEnvPath(string const & name)
345 typedef boost::char_separator<char> Separator;
346 typedef boost::tokenizer<Separator> Tokenizer;
348 string const env_var = GetEnv(name);
349 Separator const separator(string(1, os::path_separator()).c_str());
350 Tokenizer const tokens(env_var, separator);
351 Tokenizer::const_iterator it = tokens.begin();
352 Tokenizer::const_iterator const end = tokens.end();
354 std::vector<string> vars;
355 for (; it != end; ++it)
356 vars.push_back(os::internal_path(*it));
362 void setEnvPath(string const & name, vector<string> const & env)
364 char const separator(os::path_separator());
365 std::ostringstream ss;
366 vector<string>::const_iterator it = env.begin();
367 vector<string>::const_iterator const end = env.end();
368 for (; it != end; ++it) {
371 ss << os::external_path(*it);
373 putEnv(name + "=" + ss.str());
377 void prependEnvPath(string const & name, string const & prefix)
379 vector<string> env_var = getEnvPath(name);
381 typedef boost::char_separator<char> Separator;
382 typedef boost::tokenizer<Separator> Tokenizer;
384 Separator const separator(string(1, os::path_separator()).c_str());
386 // Prepend each new element to the list, removing identical elements
387 // that occur later in the list.
388 Tokenizer const tokens(prefix, separator);
389 vector<string> reversed_tokens(tokens.begin(), tokens.end());
391 typedef vector<string>::const_reverse_iterator token_iterator;
392 token_iterator it = reversed_tokens.rbegin();
393 token_iterator const end = reversed_tokens.rend();
394 for (; it != end; ++it) {
395 vector<string>::iterator remove_it =
396 std::remove(env_var.begin(), env_var.end(), *it);
397 env_var.erase(remove_it, env_var.end());
398 env_var.insert(env_var.begin(), *it);
401 setEnvPath(name, env_var);
405 bool putEnv(string const & envstr)
407 // CHECK Look at and fix this.
408 // f.ex. what about error checking?
410 #if defined (HAVE_SETENV)
412 string const value = split(envstr, name, '=');
413 int const retval = ::setenv(name.c_str(), value.c_str(), true);
414 #elif defined (HAVE_PUTENV)
415 // this leaks, but what can we do about it?
416 // Is doing a getenv() and a free() of the older value
417 // a good idea? (JMarc)
418 // Actually we don't have to leak...calling putenv like this
419 // should be enough: ... and this is obviously not enough if putenv
420 // does not make a copy of the string. It is also not very wise to
421 // put a string on the free store. If we have to leak we should do it
423 char * leaker = new char[envstr.length() + 1];
424 envstr.copy(leaker, envstr.length());
425 leaker[envstr.length()] = '\0';
426 int const retval = ::putenv(leaker);
428 // If putenv does not make a copy of the char const * this
429 // is very dangerous. OTOH if it does take a copy this is the
431 // The only implementation of putenv that I have seen does not
432 // allocate memory. _And_ after testing the putenv in glibc it
433 // seems that we need to make a copy of the string contents.
434 // I will enable the above.
435 //int retval = lyx::putenv(envstr.c_str());
437 // No environment setting function. Can this happen?
438 int const retval = 1; //return an error condition.
446 string const createTmpDir(string const & tempdir, string const & mask)
449 << "createTmpDir: tempdir=`" << tempdir << "'\n"
450 << "createTmpDir: mask=`" << mask << '\'' << endl;
452 string const tmpfl(tempName(tempdir, mask));
453 // lyx::tempName actually creates a file to make sure that it
454 // stays unique. So we have to delete it before we can create
455 // a dir with the same name. Note also that we are not thread
456 // safe because of the gap between unlink and mkdir. (Lgb)
459 if (tmpfl.empty() || mkdir(tmpfl, 0700)) {
460 lyxerr << "LyX could not create the temporary directory '"
461 << tmpfl << "'" << endl;
465 return MakeAbsPath(tmpfl);
471 bool destroyDir(string const & tmpdir)
475 Path p(user_lyxdir());
477 return fs::remove_all(tmpdir) > 0;
481 string const createBufferTmpDir()
484 // We are in our own directory. Why bother to mangle name?
485 // In fact I wrote this code to circumvent a problematic behaviour
486 // (bug?) of EMX mkstemp().
488 package().temp_dir() + "/lyx_tmpbuf" +
489 convert<string>(count++);
491 if (mkdir(tmpfl, 0777)) {
492 lyxerr << "LyX could not create the temporary directory '"
493 << tmpfl << "'" << endl;
500 string const createLyXTmpDir(string const & deflt)
502 if (!deflt.empty() && deflt != "/tmp") {
503 if (mkdir(deflt, 0777)) {
505 Path p(package().user_support());
507 if (IsDirWriteable(deflt)) {
508 // deflt could not be created because it
509 // did exist already, so let's create our own
511 return createTmpDir(deflt, "lyx_tmpdir");
513 // some other error occured.
514 return createTmpDir("/tmp", "lyx_tmpdir");
520 Path p(package().user_support());
522 return createTmpDir("/tmp", "lyx_tmpdir");
527 bool createDirectory(string const & path, int permission)
529 string temp(rtrim(os::internal_path(path), "/"));
531 BOOST_ASSERT(!temp.empty());
533 if (mkdir(temp, permission))
540 // Strip filename from path name
541 string const OnlyPath(string const & Filename)
543 // If empty filename, return empty
544 if (Filename.empty()) return Filename;
546 // Find last / or start of filename
547 string::size_type j = Filename.rfind('/');
548 if (j == string::npos)
550 return Filename.substr(0, j + 1);
554 // Convert relative path into absolute path based on a basepath.
555 // If relpath is absolute, just use that.
556 // If basepath is empty, use CWD as base.
557 string const MakeAbsPath(string const & RelPath, string const & BasePath)
559 // checks for already absolute path
560 if (os::is_absolute_path(RelPath))
563 // Copies given paths
564 string TempRel(os::internal_path(RelPath));
565 // Since TempRel is NOT absolute, we can safely replace "//" with "/"
566 TempRel = subst(TempRel, "//", "/");
570 if (os::is_absolute_path(BasePath))
573 TempBase = AddPath(getcwd(), BasePath);
575 // Handle /./ at the end of the path
576 while (suffixIs(TempBase, "/./"))
577 TempBase.erase(TempBase.length() - 2);
579 // processes relative path
580 string RTemp(TempRel);
583 while (!RTemp.empty()) {
585 RTemp = split(RTemp, Temp, '/');
587 if (Temp == ".") continue;
589 // Remove one level of TempBase
590 string::difference_type i = TempBase.length() - 2;
593 while (i > 0 && TempBase[i] != '/') --i;
597 while (i > 2 && TempBase[i] != '/') --i;
600 TempBase.erase(i, string::npos);
603 } else if (Temp.empty() && !RTemp.empty()) {
604 TempBase = os::current_root() + RTemp;
607 // Add this piece to TempBase
608 if (!suffixIs(TempBase, '/'))
614 // returns absolute path
615 return os::internal_path(TempBase);
619 // Correctly append filename to the pathname.
620 // If pathname is '.', then don't use pathname.
621 // Chops any path of filename.
622 string const AddName(string const & path, string const & fname)
625 string const basename(OnlyFilename(fname));
629 if (path != "." && path != "./" && !path.empty()) {
630 buf = os::internal_path(path);
631 if (!suffixIs(path, '/'))
635 return buf + basename;
639 // Strips path from filename
640 string const OnlyFilename(string const & fname)
645 string::size_type j = fname.rfind('/');
646 if (j == string::npos) // no '/' in fname
650 return fname.substr(j + 1);
654 /// Returns true is path is absolute
655 bool AbsolutePath(string const & path)
657 return os::is_absolute_path(path);
662 // Create absolute path. If impossible, don't do anything
663 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
664 string const ExpandPath(string const & path)
666 // checks for already absolute path
667 string RTemp(ReplaceEnvironmentPath(path));
668 if (os::is_absolute_path(RTemp))
672 string const copy(RTemp);
675 RTemp = split(RTemp, Temp, '/');
678 return getcwd() + '/' + RTemp;
681 return package().home_dir() + '/' + RTemp;
684 return MakeAbsPath(copy);
686 // Don't know how to handle this
692 // Constracts path/../path
693 // Can't handle "../../" or "/../" (Asger)
694 // Also converts paths like /foo//bar ==> /foo/bar
695 string const NormalizePath(string const & path)
701 if (os::is_absolute_path(path))
704 // Make implicit current directory explicit
707 // Normalise paths like /foo//bar ==> /foo/bar
708 boost::RegEx regex("/{2,}");
709 RTemp = regex.Merge(RTemp, "/");
711 while (!RTemp.empty()) {
713 RTemp = split(RTemp, Temp, '/');
717 } else if (Temp == "..") {
718 // Remove one level of TempBase
719 string::difference_type i = TempBase.length() - 2;
720 while (i > 0 && TempBase[i] != '/')
722 if (i >= 0 && TempBase[i] == '/')
723 TempBase.erase(i + 1, string::npos);
727 TempBase += Temp + '/';
731 // returns absolute path
736 string const GetFileContents(string const & fname)
738 if (fs::exists(fname)) {
739 ifstream ifs(fname.c_str());
747 lyxerr << "LyX was not able to read file '" << fname << '\'' << endl;
752 // Search the string for ${VAR} and $VAR and replace VAR using getenv.
753 string const ReplaceEnvironmentPath(string const & path)
755 // ${VAR} is defined as
756 // $\{[A-Za-z_][A-Za-z_0-9]*\}
757 static string const envvar_br = "[$]\\{([A-Za-z_][A-Za-z_0-9]*)\\}";
759 // $VAR is defined as:
760 // $\{[A-Za-z_][A-Za-z_0-9]*\}
761 static string const envvar = "[$]([A-Za-z_][A-Za-z_0-9]*)";
763 static boost::regex envvar_br_re("(.*)" + envvar_br + "(.*)");
764 static boost::regex envvar_re("(.*)" + envvar + "(.*)");
767 string result = path;
769 regex_match(result, what, envvar_br_re);
770 if (!what[0].matched) {
771 regex_match(result, what, envvar_re);
772 if (!what[0].matched)
775 result = what.str(1) + GetEnv(what.str(2)) + what.str(3);
781 // Make relative path out of two absolute paths
782 string const MakeRelPath(string const & abspath, string const & basepath)
783 // Makes relative path out of absolute path. If it is deeper than basepath,
784 // it's easy. If basepath and abspath share something (they are all deeper
785 // than some directory), it'll be rendered using ..'s. If they are completely
786 // different, then the absolute path will be used as relative path.
788 string::size_type const abslen = abspath.length();
789 string::size_type const baselen = basepath.length();
791 string::size_type i = os::common_path(abspath, basepath);
794 // actually no match - cannot make it relative
798 // Count how many dirs there are in basepath above match
799 // and append as many '..''s into relpath
801 string::size_type j = i;
802 while (j < baselen) {
803 if (basepath[j] == '/') {
804 if (j + 1 == baselen)
811 // Append relative stuff from common directory to abspath
812 if (abspath[i] == '/')
814 for (; i < abslen; ++i)
817 if (suffixIs(buf, '/'))
818 buf.erase(buf.length() - 1);
819 // Substitute empty with .
826 // Append sub-directory(ies) to a path in an intelligent way
827 string const AddPath(string const & path, string const & path_2)
830 string const path2 = os::internal_path(path_2);
832 if (!path.empty() && path != "." && path != "./") {
833 buf = os::internal_path(path);
834 if (path[path.length() - 1] != '/')
838 if (!path2.empty()) {
839 string::size_type const p2start = path2.find_first_not_of('/');
840 string::size_type const p2end = path2.find_last_not_of('/');
841 string const tmp = path2.substr(p2start, p2end - p2start + 1);
849 Change extension of oldname to extension.
850 Strips path off if no_path == true.
851 If no extension on oldname, just appends.
853 string const ChangeExtension(string const & oldname, string const & extension)
855 string::size_type const last_slash = oldname.rfind('/');
856 string::size_type last_dot = oldname.rfind('.');
857 if (last_dot < last_slash && last_slash != string::npos)
858 last_dot = string::npos;
861 // Make sure the extension starts with a dot
862 if (!extension.empty() && extension[0] != '.')
863 ext= '.' + extension;
867 return os::internal_path(oldname.substr(0, last_dot) + ext);
871 /// Return the extension of the file (not including the .)
872 string const GetExtension(string const & name)
874 string::size_type const last_slash = name.rfind('/');
875 string::size_type const last_dot = name.rfind('.');
876 if (last_dot != string::npos &&
877 (last_slash == string::npos || last_dot > last_slash))
878 return name.substr(last_dot + 1,
879 name.length() - (last_dot + 1));
885 // the different filetypes and what they contain in one of the first lines
886 // (dots are any characters). (Herbert 20020131)
889 // EPS %!PS-Adobe-3.0 EPSF...
896 // PBM P1... or P4 (B/W)
897 // PGM P2... or P5 (Grayscale)
898 // PPM P3... or P6 (color)
899 // PS %!PS-Adobe-2.0 or 1.0, no "EPSF"!
900 // SGI \001\332... (decimal 474)
902 // TIFF II... or MM...
904 // XPM /* XPM */ sometimes missing (f.ex. tgif-export)
905 // ...static char *...
906 // XWD \000\000\000\151 (0x00006900) decimal 105
908 // GZIP \037\213 http://www.ietf.org/rfc/rfc1952.txt
909 // ZIP PK... http://www.halyava.ru/document/ind_arch.htm
910 // Z \037\235 UNIX compress
912 string const getFormatFromContents(string const & filename)
915 if (filename.empty() || !IsFileReadable(filename))
918 ifstream ifs(filename.c_str());
920 // Couldn't open file...
924 string const gzipStamp = "\037\213";
927 string const zipStamp = "PK";
930 string const compressStamp = "\037\235";
932 // Maximum strings to read
933 int const max_count = 50;
938 bool firstLine = true;
939 while ((count++ < max_count) && format.empty()) {
941 lyxerr[Debug::GRAPHICS]
942 << "filetools(getFormatFromContents)\n"
943 << "\tFile type not recognised before EOF!"
949 string const stamp = str.substr(0,2);
950 if (firstLine && str.size() >= 2) {
951 // at first we check for a zipped file, because this
952 // information is saved in the first bytes of the file!
953 // also some graphic formats which save the information
954 // in the first line, too.
955 if (prefixIs(str, gzipStamp)) {
958 } else if (stamp == zipStamp) {
961 } else if (stamp == compressStamp) {
965 } else if (stamp == "BM") {
968 } else if (stamp == "\001\332") {
972 // Don't need to use str.at(0), str.at(1) because
973 // we already know that str.size() >= 2
974 } else if (str[0] == 'P') {
990 } else if ((stamp == "II") || (stamp == "MM")) {
993 } else if (prefixIs(str,"%TGIF")) {
996 } else if (prefixIs(str,"#FIG")) {
999 } else if (prefixIs(str,"GIF")) {
1002 } else if (str.size() > 3) {
1003 int const c = ((str[0] << 24) & (str[1] << 16) &
1004 (str[2] << 8) & str[3]);
1013 if (!format.empty())
1015 else if (contains(str,"EPSF"))
1016 // dummy, if we have wrong file description like
1017 // %!PS-Adobe-2.0EPSF"
1020 else if (contains(str,"Grace"))
1023 else if (contains(str,"JFIF"))
1026 else if (contains(str,"%PDF"))
1029 else if (contains(str,"PNG"))
1032 else if (contains(str,"%!PS-Adobe")) {
1035 if (contains(str,"EPSF"))
1041 else if (contains(str,"_bits[]"))
1044 else if (contains(str,"XPM") || contains(str, "static char *"))
1047 else if (contains(str,"BITPIX"))
1051 if (!format.empty()) {
1052 lyxerr[Debug::GRAPHICS]
1053 << "Recognised Fileformat: " << format << endl;
1057 lyxerr[Debug::GRAPHICS]
1058 << "filetools(getFormatFromContents)\n"
1059 << "\tCouldn't find a known format!\n";
1064 /// check for zipped file
1065 bool zippedFile(string const & name)
1067 string const type = getFormatFromContents(name);
1068 if (contains("gzip zip compress", type) && !type.empty())
1074 string const unzippedFileName(string const & zipped_file)
1076 string const ext = GetExtension(zipped_file);
1077 if (ext == "gz" || ext == "z" || ext == "Z")
1078 return ChangeExtension(zipped_file, string());
1079 return "unzipped_" + zipped_file;
1083 string const unzipFile(string const & zipped_file, string const & unzipped_file)
1085 string const tempfile = unzipped_file.empty() ?
1086 unzippedFileName(zipped_file) : unzipped_file;
1088 string const command = "gunzip -c " + zipped_file + " > " + tempfile;
1090 one.startscript(Systemcall::Wait, command);
1091 // test that command was executed successfully (anon)
1092 // yes, please do. (Lgb)
1097 string const MakeDisplayPath(string const & path, unsigned int threshold)
1101 string const home(package().home_dir());
1103 // replace /home/blah with ~/
1104 if (prefixIs(str, home))
1105 str = subst(str, home, "~");
1107 if (str.length() <= threshold)
1110 string const prefix = ".../";
1113 while (str.length() > threshold)
1114 str = split(str, temp, '/');
1116 // Did we shorten everything away?
1118 // Yes, filename itself is too long.
1119 // Pick the start and the end of the filename.
1120 str = OnlyFilename(path);
1121 string const head = str.substr(0, threshold / 2 - 3);
1123 string::size_type len = str.length();
1125 str.substr(len - threshold / 2 - 2, len - 1);
1126 str = head + "..." + tail;
1129 return prefix + str;
1133 bool LyXReadLink(string const & file, string & link, bool resolve)
1135 #ifdef HAVE_READLINK
1136 char linkbuffer[512];
1137 // Should be PATH_MAX but that needs autconf support
1138 int const nRead = ::readlink(file.c_str(),
1139 linkbuffer, sizeof(linkbuffer) - 1);
1142 linkbuffer[nRead] = '\0'; // terminator
1144 link = MakeAbsPath(linkbuffer, OnlyPath(file));
1154 cmd_ret const RunCommand(string const & cmd)
1156 // FIXME: replace all calls to RunCommand with ForkedCall
1157 // (if the output is not needed) or the code in ispell.C
1158 // (if the output is needed).
1160 // One question is if we should use popen or
1161 // create our own popen based on fork, exec, pipe
1162 // of course the best would be to have a
1163 // pstream (process stream), with the
1164 // variants ipstream, opstream
1166 sigset_t newMask, oldMask;
1167 sigemptyset(&oldMask);
1168 sigemptyset(&newMask);
1169 sigaddset(&newMask, SIGCHLD);
1171 // Block the SIGCHLD signal.
1172 sigprocmask(SIG_BLOCK, &newMask, &oldMask);
1174 FILE * inf = ::popen(cmd.c_str(), os::popen_read_mode());
1176 // (Claus Hentschel) Check if popen was succesful ;-)
1178 return make_pair(-1, string());
1179 lyxerr << "RunCommand:: could not start child process" << endl;
1185 ret += static_cast<char>(c);
1188 int const pret = pclose(inf);
1190 perror("RunCommand:: could not terminate child process");
1192 // Unblock the SIGCHLD signal and restore the old mask.
1193 sigprocmask(SIG_SETMASK, &oldMask, 0);
1195 return make_pair(pret, ret);
1199 string const findtexfile(string const & fil, string const & /*format*/)
1201 /* There is no problem to extend this function too use other
1202 methods to look for files. It could be setup to look
1203 in environment paths and also if wanted as a last resort
1204 to a recursive find. One of the easier extensions would
1205 perhaps be to use the LyX file lookup methods. But! I am
1206 going to implement this until I see some demand for it.
1210 // If the file can be found directly, we just return a
1211 // absolute path version of it.
1212 if (fs::exists(fil))
1213 return MakeAbsPath(fil);
1215 // No we try to find it using kpsewhich.
1216 // It seems from the kpsewhich manual page that it is safe to use
1217 // kpsewhich without --format: "When the --format option is not
1218 // given, the search path used when looking for a file is inferred
1219 // from the name given, by looking for a known extension. If no
1220 // known extension is found, the search path for TeX source files
1222 // However, we want to take advantage of the format sine almost all
1223 // the different formats has environment variables that can be used
1224 // to controll which paths to search. f.ex. bib looks in
1225 // BIBINPUTS and TEXBIB. Small list follows:
1226 // bib - BIBINPUTS, TEXBIB
1228 // graphic/figure - TEXPICTS, TEXINPUTS
1229 // ist - TEXINDEXSTYLE, INDEXSTYLE
1230 // pk - PROGRAMFONTS, PKFONTS, TEXPKS, GLYPHFONTS, TEXFONTS
1232 // tfm - TFMFONTS, TEXFONTS
1233 // This means that to use kpsewhich in the best possible way we
1234 // should help it by setting additional path in the approp. envir.var.
1235 string const kpsecmd = "kpsewhich " + fil;
1237 cmd_ret const c = RunCommand(kpsecmd);
1239 lyxerr[Debug::LATEX] << "kpse status = " << c.first << '\n'
1240 << "kpse result = `" << rtrim(c.second, "\n")
1243 return os::internal_path(rtrim(c.second, "\n\r"));
1249 void removeAutosaveFile(string const & filename)
1251 string a = OnlyPath(filename);
1253 a += OnlyFilename(filename);
1260 void readBB_lyxerrMessage(string const & file, bool & zipped,
1261 string const & message)
1263 lyxerr[Debug::GRAPHICS] << "[readBB_from_PSFile] "
1264 << message << std::endl;
1265 #ifdef WITH_WARNINGS
1266 #warning Why is this func deleting a file? (Lgb)
1273 string const readBB_from_PSFile(string const & file)
1275 // in a (e)ps-file it's an entry like %%BoundingBox:23 45 321 345
1276 // It seems that every command in the header has an own line,
1277 // getline() should work for all files.
1278 // On the other hand some plot programs write the bb at the
1279 // end of the file. Than we have in the header:
1280 // %%BoundingBox: (atend)
1281 // In this case we must check the end.
1282 bool zipped = zippedFile(file);
1283 string const file_ = zipped ?
1284 string(unzipFile(file)) : string(file);
1285 string const format = getFormatFromContents(file_);
1287 if (format != "eps" && format != "ps") {
1288 readBB_lyxerrMessage(file_, zipped,"no(e)ps-format");
1292 std::ifstream is(file_.c_str());
1296 if (contains(s,"%%BoundingBox:") && !contains(s,"atend")) {
1297 string const bb = ltrim(s.substr(14));
1298 readBB_lyxerrMessage(file_, zipped, bb);
1302 readBB_lyxerrMessage(file_, zipped, "no bb found");
1307 int compare_timestamps(string const & file1, string const & file2)
1309 BOOST_ASSERT(AbsolutePath(file1) && AbsolutePath(file2));
1311 // If the original is newer than the copy, then copy the original
1312 // to the new directory.
1315 if (fs::exists(file1) && fs::exists(file2)) {
1316 double const tmp = difftime(fs::last_write_time(file1),
1317 fs::last_write_time(file2));
1319 cmp = tmp > 0 ? 1 : -1;
1321 } else if (fs::exists(file1)) {
1323 } else if (fs::exists(file2)) {
1330 } //namespace support