]> git.lyx.org Git - lyx.git/blob - src/support/filetools.cpp
Fix some display glitches
[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 "LyXRC.h"
25
26 #include "support/filetools.h"
27
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/Messages.h"
34 #include "support/Package.h"
35 #include "support/PathChanger.h"
36 #include "support/Systemcall.h"
37 #include "support/qstring_helpers.h"
38
39 #include <QDir>
40 #include <QTemporaryFile>
41
42 #include "support/lassert.h"
43 #include "support/regex.h"
44
45 #include <fcntl.h>
46 #ifdef HAVE_MAGIC_H
47 #include <magic.h>
48 #endif
49
50 #include <cerrno>
51 #include <cstdlib>
52 #include <cstdio>
53
54 #include <utility>
55 #include <fstream>
56 #include <sstream>
57 #include <vector>
58
59 #if defined (_WIN32)
60 #include <io.h>
61 #include <windows.h>
62 #endif
63
64 using namespace std;
65
66 #define USE_QPROCESS
67
68 namespace lyx {
69 namespace support {
70
71 bool isLyXFileName(string const & filename)
72 {
73         return suffixIs(ascii_lowercase(filename), ".lyx");
74 }
75
76
77 bool isSGMLFileName(string const & filename)
78 {
79         return suffixIs(ascii_lowercase(filename), ".sgml");
80 }
81
82
83 bool isValidLaTeXFileName(string const & filename)
84 {
85         string const invalid_chars("#%\"");
86         return filename.find_first_of(invalid_chars) == string::npos;
87 }
88
89
90 bool isValidDVIFileName(string const & filename)
91 {
92         string const invalid_chars("${}()[]^");
93         return filename.find_first_of(invalid_chars) == string::npos;
94 }
95
96
97 bool isBinaryFile(FileName const & filename)
98 {
99         bool isbinary = false;
100         if (filename.empty() || !filename.exists())
101                 return isbinary;
102
103 #ifdef HAVE_MAGIC_H
104         magic_t magic_cookie = magic_open(MAGIC_MIME_ENCODING);
105         if (magic_cookie) {
106                 bool detected = true;
107                 if (magic_load(magic_cookie, NULL) != 0) {
108                         LYXERR(Debug::FILES, "isBinaryFile: "
109                                 "Could not load magic database - "
110                                 << magic_error(magic_cookie));
111                         detected = false;
112                 } else {
113                         char const *charset = magic_file(magic_cookie,
114                                         filename.toFilesystemEncoding().c_str());
115                         isbinary = contains(charset, "binary");
116                 }
117                 magic_close(magic_cookie);
118                 if (detected)
119                         return isbinary;
120         }
121 #endif
122         // Try by looking for binary chars at the beginning of the file.
123         // Note that this is formally not correct, since count_bin_chars
124         // expects utf8, and the passed string can be anything: plain text
125         // in any encoding, or really binary data. In practice it works,
126         // since QString::fromUtf8() drops invalid utf8 sequences, and
127         // while the exact number may not be correct, we still get a high
128         // number for truly binary files.
129
130         ifstream ifs(filename.toFilesystemEncoding().c_str());
131         if (!ifs)
132                 return isbinary;
133
134         // Maximum strings to read
135         int const max_count = 50;
136
137         // Maximum number of binary chars allowed
138         int const max_bin = 5;
139
140         int count = 0;
141         int binchars = 0;
142         string str;
143         while (count++ < max_count && !ifs.eof()) {
144                 getline(ifs, str);
145                 binchars += count_bin_chars(str);
146         }
147         return binchars > max_bin;
148 }
149
150
151 string const latex_path(string const & original_path,
152                 latex_path_extension extension,
153                 latex_path_dots dots)
154 {
155         // On cygwin, we may need windows or posix style paths.
156         string path = os::latex_path(original_path);
157         path = subst(path, "~", "\\string~");
158         if (path.find(' ') != string::npos) {
159                 // We can't use '"' because " is sometimes active (e.g. if
160                 // babel is loaded with the "german" option)
161                 if (extension == EXCLUDE_EXTENSION) {
162                         // changeExtension calls os::internal_path internally
163                         // so don't use it to remove the extension.
164                         string const ext = getExtension(path);
165                         string const base = ext.empty() ?
166                                 path :
167                                 path.substr(0, path.length() - ext.length() - 1);
168                         // changeExtension calls os::internal_path internally
169                         // so don't use it to re-add the extension.
170                         path = "\\string\"" + base + "\\string\"." + ext;
171                 } else {
172                         path = "\\string\"" + path + "\\string\"";
173                 }
174         }
175
176         if (dots != ESCAPE_DOTS)
177                 return path;
178
179         // Replace dots with the lyxdot macro, but only in the file name,
180         // not the directory part.
181         // addName etc call os::internal_path internally
182         // so don't use them for path manipulation
183         // The directory separator is always '/' for LaTeX.
184         string::size_type pos = path.rfind('/');
185         if (pos == string::npos)
186                 return subst(path, ".", "\\lyxdot ");
187         return path.substr(0, pos) + subst(path.substr(pos), ".", "\\lyxdot ");
188 }
189
190
191 // Substitutes spaces with underscores in filename (and path)
192 FileName const makeLatexName(FileName const & file)
193 {
194         string name = file.onlyFileName();
195         string const path = file.onlyPath().absFileName() + "/";
196
197         // ok so we scan through the string twice, but who cares.
198         // FIXME: in Unicode time this will break for sure! There is
199         // a non-latin world out there...
200         string const keep = "abcdefghijklmnopqrstuvwxyz"
201                 "ABCDEFGHIJKLMNOPQRSTUVWXYZ"
202                 "@!'()*+,-./0123456789:;<=>?[]`|";
203
204         string::size_type pos = 0;
205         while ((pos = name.find_first_not_of(keep, pos)) != string::npos)
206                 name[pos++] = '_';
207
208         FileName latex_name(path + name);
209         latex_name.changeExtension(".tex");
210         return latex_name;
211 }
212
213
214 string const quoteName(string const & name, quote_style style)
215 {
216         switch(style) {
217         case quote_shell:
218                 // This does not work on native Windows for filenames
219                 // containing the following characters < > : " / \ | ? *
220                 // Moreover, it can't be made to work, as, according to
221                 // http://msdn.microsoft.com/en-us/library/aa365247(VS.85).aspx
222                 // those are reserved characters, and thus are forbidden.
223                 // Please, also note that the command-line parser in
224                 // ForkedCall::generateChild cannot deal with filenames
225                 // containing " or ', therefore we don't pass user filenames
226                 // to child processes if possible. We store them in a python
227                 // script instead, where we don't have these limitations.
228 #ifndef USE_QPROCESS
229                 return (os::shell() == os::UNIX) ?
230                         '\'' + subst(name, "'", "\'\\\'\'") + '\'' :
231                         '"' + name + '"';
232 #else
233                 // According to the QProcess parser, a single double
234                 // quote is represented by three consecutive ones.
235                 // Here we simply escape the double quote and let our
236                 // simple parser in Systemcall.cpp do the substitution.
237                 return '"' + subst(name, "\"", "\\\"") + '"';
238 #endif
239         case quote_python:
240                 return "\"" + subst(subst(name, "\\", "\\\\"), "\"", "\\\"")
241                      + "\"";
242         }
243         // shut up stupid compiler
244         return string();
245 }
246
247
248 #if 0
249 // Uses a string of paths separated by ";"s to find a file to open.
250 // Can't cope with pathnames with a ';' in them. Returns full path to file.
251 // If path entry begins with $$LyX/, use system_lyxdir
252 // If path entry begins with $$User/, use user_lyxdir
253 // Example: "$$User/doc;$$LyX/doc"
254 FileName const fileOpenSearch(string const & path, string const & name,
255                              string const & ext)
256 {
257         FileName real_file;
258         string path_element;
259         bool notfound = true;
260         string tmppath = split(path, path_element, ';');
261
262         while (notfound && !path_element.empty()) {
263                 path_element = os::internal_path(path_element);
264                 if (!suffixIs(path_element, '/'))
265                         path_element += '/';
266                 path_element = subst(path_element, "$$LyX",
267                                      package().system_support().absFileName());
268                 path_element = subst(path_element, "$$User",
269                                      package().user_support().absFileName());
270
271                 real_file = fileSearch(path_element, name, ext);
272
273                 if (real_file.empty()) {
274                         do {
275                                 tmppath = split(tmppath, path_element, ';');
276                         } while (!tmppath.empty() && path_element.empty());
277                 } else {
278                         notfound = false;
279                 }
280         }
281         return real_file;
282 }
283 #endif
284
285
286 // Returns the real name of file name in directory path, with optional
287 // extension ext.
288 FileName const fileSearch(string const & path, string const & name,
289                           string const & ext, search_mode mode)
290 {
291         // if `name' is an absolute path, we ignore the setting of `path'
292         // Expand Environmentvariables in 'name'
293         string const tmpname = replaceEnvironmentPath(name);
294         FileName fullname(makeAbsPath(tmpname, path));
295         // search first without extension, then with it.
296         if (fullname.isReadableFile())
297                 return fullname;
298         if (ext.empty())
299                 // We are done.
300                 return mode == may_not_exist ? fullname : FileName();
301         // Only add the extension if it is not already the extension of
302         // fullname.
303         if (getExtension(fullname.absFileName()) != ext)
304                 fullname = FileName(addExtension(fullname.absFileName(), ext));
305         if (fullname.isReadableFile() || mode == may_not_exist)
306                 return fullname;
307         return FileName();
308 }
309
310
311 // Search the file name.ext in the subdirectory dir of
312 //   1) user_lyxdir
313 //   2) build_lyxdir (if not empty)
314 //   3) system_lyxdir
315 FileName const libFileSearch(string const & dir, string const & name,
316                            string const & ext)
317 {
318         FileName fullname = fileSearch(addPath(package().user_support().absFileName(), dir),
319                                      name, ext);
320         if (!fullname.empty())
321                 return fullname;
322
323         if (!package().build_support().empty())
324                 fullname = fileSearch(addPath(package().build_support().absFileName(), dir),
325                                       name, ext);
326         if (!fullname.empty())
327                 return fullname;
328
329         return fileSearch(addPath(package().system_support().absFileName(), dir), name, ext);
330 }
331
332
333 FileName const i18nLibFileSearch(string const & dir, string const & name,
334                   string const & ext)
335 {
336         /* The highest priority value is the `LANGUAGE' environment
337            variable. But we don't use the value if the currently
338            selected locale is the C locale. This is a GNU extension.
339
340            Otherwise, w use a trick to guess what support/gettext.has done:
341            each po file is able to tell us its name. (JMarc)
342         */
343
344         string lang = getGuiMessages().language();
345         string const language = getEnv("LANGUAGE");
346         if (!lang.empty() && !language.empty())
347                 lang = language;
348
349         string l;
350         lang = split(lang, l, ':');
351         while (!l.empty()) {
352                 FileName tmp;
353                 // First try with the full name
354                 tmp = libFileSearch(addPath(dir, l), name, ext);
355                 if (!tmp.empty())
356                         return tmp;
357
358                 // Then the name without country code
359                 string const shortl = token(l, '_', 0);
360                 if (shortl != l) {
361                         tmp = libFileSearch(addPath(dir, shortl), name, ext);
362                         if (!tmp.empty())
363                                 return tmp;
364                 }
365
366 #if 1
367                 // For compatibility, to be removed later (JMarc)
368                 tmp = libFileSearch(dir, token(l, '_', 0) + '_' + name,
369                                     ext);
370                 if (!tmp.empty()) {
371                         lyxerr << "i18nLibFileSearch: File `" << tmp
372                                << "' has been found by the old method" <<endl;
373                         return tmp;
374                 }
375 #endif
376                 lang = split(lang, l, ':');
377         }
378
379         return libFileSearch(dir, name, ext);
380 }
381
382
383 FileName const imageLibFileSearch(string & dir, string const & name,
384                   string const & ext)
385 {
386         if (!lyx::lyxrc.icon_set.empty()) {
387                 string const imagedir = addPath(dir, lyx::lyxrc.icon_set);
388                 FileName const fn = libFileSearch(imagedir, name, ext);
389                 if (fn.exists()) {
390                         dir = imagedir;
391                         return fn;
392                 }
393         }
394         return libFileSearch(dir, name, ext);
395 }
396
397
398 string const commandPrep(string const & command_in)
399 {
400         static string const token_scriptpath = "$$s/";
401         string const python_call = "python -tt";
402
403         string command = command_in;
404         if (prefixIs(command_in, python_call))
405                 command = os::python() + command_in.substr(python_call.length());
406
407         // Find the starting position of "$$s/"
408         string::size_type const pos1 = command.find(token_scriptpath);
409         if (pos1 == string::npos)
410                 return command;
411         // Find the end of the "$$s/some_subdir/some_script" word within
412         // command. Assumes that the script name does not contain spaces.
413         string::size_type const start_script = pos1 + 4;
414         string::size_type const pos2 = command.find(' ', start_script);
415         string::size_type const size_script = pos2 == string::npos?
416                 (command.size() - start_script) : pos2 - start_script;
417
418         // Does this script file exist?
419         string const script =
420                 libFileSearch(".", command.substr(start_script, size_script)).absFileName();
421
422         if (script.empty()) {
423                 // Replace "$$s/" with ""
424                 command.erase(pos1, 4);
425         } else {
426                 quote_style style = quote_shell;
427                 if (prefixIs(command, os::python()))
428                         style = quote_python;
429
430                 // Replace "$$s/foo/some_script" with "<path to>/some_script".
431                 string::size_type const size_replace = size_script + 4;
432                 command.replace(pos1, size_replace, quoteName(script, style));
433         }
434
435         return command;
436 }
437
438
439 static string createTempFile(QString const & mask)
440 {
441         // FIXME: This is not safe. QTemporaryFile creates a file in open(),
442         //        but the file is deleted when qt_tmp goes out of scope.
443         //        Therefore the next call to createTempFile() may create the
444         //        same file again. To make this safe the QTemporaryFile object
445         //        needs to be kept for the whole life time of the temp file name.
446         //        This could be achieved by creating a class TempDir (like
447         //        TempFile, but using a currentlky non-existing
448         //        QTemporaryDirectory object).
449         QTemporaryFile qt_tmp(mask + ".XXXXXXXXXXXX");
450         if (qt_tmp.open()) {
451                 string const temp_file = fromqstr(qt_tmp.fileName());
452                 LYXERR(Debug::FILES, "Temporary file `" << temp_file << "' created.");
453                 return temp_file;
454         }
455         LYXERR(Debug::FILES, "Unable to create temporary file with following template: "
456                         << qt_tmp.fileTemplate());
457         return string();
458 }
459
460
461 static FileName createTmpDir(FileName const & tempdir, string const & mask)
462 {
463         LYXERR(Debug::FILES, "createTmpDir: tempdir=`" << tempdir << "'\n"
464                 << "createTmpDir:    mask=`" << mask << '\'');
465
466         QFileInfo tmp_fi(QDir(toqstr(tempdir.absFileName())), toqstr(mask));
467         FileName const tmpfl(createTempFile(tmp_fi.absoluteFilePath()));
468
469         if (tmpfl.empty() || !tmpfl.createDirectory(0700)) {
470                 LYXERR0("LyX could not create temporary directory in " << tempdir
471                         << "'");
472                 return FileName();
473         }
474
475         return tmpfl;
476 }
477
478
479 FileName const createLyXTmpDir(FileName const & deflt)
480 {
481         if (deflt.empty() || deflt == package().system_temp_dir())
482                 return createTmpDir(package().system_temp_dir(), "lyx_tmpdir");
483
484         if (deflt.createDirectory(0777))
485                 return deflt;
486
487         if (deflt.isDirWritable()) {
488                 // deflt could not be created because it
489                 // did exist already, so let's create our own
490                 // dir inside deflt.
491                 return createTmpDir(deflt, "lyx_tmpdir");
492         } else {
493                 // some other error occured.
494                 return createTmpDir(package().system_temp_dir(), "lyx_tmpdir");
495         }
496 }
497
498
499 // Strip filename from path name
500 string const onlyPath(string const & filename)
501 {
502         // If empty filename, return empty
503         if (filename.empty())
504                 return filename;
505
506         // Find last / or start of filename
507         size_t j = filename.rfind('/');
508         return j == string::npos ? "./" : filename.substr(0, j + 1);
509 }
510
511
512 // Convert relative path into absolute path based on a basepath.
513 // If relpath is absolute, just use that.
514 // If basepath is empty, use CWD as base.
515 // Note that basePath can be a relative path, in the sense that it may
516 // not begin with "/" (e.g.), but it should NOT contain such constructs
517 // as "/../".
518 // FIXME It might be nice if the code didn't simply assume that.
519 FileName const makeAbsPath(string const & relPath, string const & basePath)
520 {
521         // checks for already absolute path
522         if (FileName::isAbsolute(relPath))
523                 return FileName(relPath);
524
525         // Copies given paths
526         string tempRel = os::internal_path(relPath);
527         // Since TempRel is NOT absolute, we can safely replace "//" with "/"
528         tempRel = subst(tempRel, "//", "/");
529
530         string tempBase;
531
532         if (FileName::isAbsolute(basePath))
533                 tempBase = basePath;
534         else
535                 tempBase = addPath(FileName::getcwd().absFileName(), basePath);
536
537         // Handle /./ at the end of the path
538         while (suffixIs(tempBase, "/./"))
539                 tempBase.erase(tempBase.length() - 2);
540
541         // processes relative path
542         string rTemp = tempRel;
543         string temp;
544
545         // Check for a leading "~"
546         // Split by first /
547         rTemp = split(rTemp, temp, '/');
548         if (temp == "~") {
549                 tempBase = Package::get_home_dir().absFileName();
550                 tempRel = rTemp;
551         }
552
553         rTemp = tempRel;
554         while (!rTemp.empty()) {
555                 // Split by next /
556                 rTemp = split(rTemp, temp, '/');
557
558                 if (temp == ".") continue;
559                 if (temp == "..") {
560                         // Remove one level of TempBase
561                         if (tempBase.length() <= 1) {
562                                 //this is supposed to be an absolute path, so...
563                                 tempBase = "/";
564                                 continue;
565                         }
566                         //erase a trailing slash if there is one
567                         if (suffixIs(tempBase, "/"))
568                                 tempBase.erase(tempBase.length() - 1, string::npos);
569
570                         string::size_type i = tempBase.length() - 1;
571                         while (i > 0 && tempBase[i] != '/')
572                                 --i;
573                         if (i > 0)
574                                 tempBase.erase(i, string::npos);
575                         else
576                                 tempBase = '/';
577                 } else if (temp.empty() && !rTemp.empty()) {
578                                 tempBase = os::current_root() + rTemp;
579                                 rTemp.erase();
580                 } else {
581                         // Add this piece to TempBase
582                         if (!suffixIs(tempBase, '/'))
583                                 tempBase += '/';
584                         tempBase += temp;
585                 }
586         }
587
588         // returns absolute path
589         return FileName(tempBase);
590 }
591
592
593 // Correctly append filename to the pathname.
594 // If pathname is '.', then don't use pathname.
595 // Chops any path of filename.
596 string const addName(string const & path, string const & fname)
597 {
598         string const basename = onlyFileName(fname);
599         string buf;
600
601         if (path != "." && path != "./" && !path.empty()) {
602                 buf = os::internal_path(path);
603                 if (!suffixIs(path, '/'))
604                         buf += '/';
605         }
606
607         return buf + basename;
608 }
609
610
611 // Strips path from filename
612 string const onlyFileName(string const & fname)
613 {
614         if (fname.empty())
615                 return fname;
616
617         string::size_type j = fname.rfind('/');
618         if (j == string::npos) // no '/' in fname
619                 return fname;
620
621         // Strip to basename
622         return fname.substr(j + 1);
623 }
624
625
626 // Create absolute path. If impossible, don't do anything
627 // Supports ./ and ~/. Later we can add support for ~logname/. (Asger)
628 string const expandPath(string const & path)
629 {
630         // checks for already absolute path
631         string rTemp = replaceEnvironmentPath(path);
632         if (FileName::isAbsolute(rTemp))
633                 return rTemp;
634
635         string temp;
636         string const copy = rTemp;
637
638         // Split by next /
639         rTemp = split(rTemp, temp, '/');
640
641         if (temp == ".")
642                 return FileName::getcwd().absFileName() + '/' + rTemp;
643
644         if (temp == "~")
645                 return Package::get_home_dir().absFileName() + '/' + rTemp;
646
647         if (temp == "..")
648                 return makeAbsPath(copy).absFileName();
649
650         // Don't know how to handle this
651         return copy;
652 }
653
654
655 // Search the string for ${VAR} and $VAR and replace VAR using getenv.
656 string const replaceEnvironmentPath(string const & path)
657 {
658         // ${VAR} is defined as
659         // $\{[A-Za-z_][A-Za-z_0-9]*\}
660         static string const envvar_br = "[$]\\{([A-Za-z_][A-Za-z_0-9]*)\\}";
661
662         // $VAR is defined as:
663         // $[A-Za-z_][A-Za-z_0-9]*
664         static string const envvar = "[$]([A-Za-z_][A-Za-z_0-9]*)";
665
666         static regex const envvar_br_re("(.*)" + envvar_br + "(.*)");
667         static regex const envvar_re("(.*)" + envvar + "(.*)");
668         string result = path;
669         while (1) {
670                 smatch what;
671                 if (!regex_match(result, what, envvar_br_re)) {
672                         if (!regex_match(result, what, envvar_re))
673                                 break;
674                 }
675                 string env_var = getEnv(what.str(2));
676                 result = what.str(1) + env_var + what.str(3);
677         }
678         return result;
679 }
680
681
682 // Return a command prefix for setting the environment of the TeX engine.
683 string latexEnvCmdPrefix(string const & path)
684 {
685         if (path.empty() || lyxrc.texinputs_prefix.empty())
686                 return string();
687
688         string const texinputs_prefix = os::latex_path_list(
689                         replaceCurdirPath(path, lyxrc.texinputs_prefix));
690         string const sep = string(1, os::path_separator(os::TEXENGINE));
691         string const texinputs = getEnv("TEXINPUTS");
692
693         if (os::shell() == os::UNIX)
694                 return "env TEXINPUTS=\"." + sep + texinputs_prefix
695                                           + sep + texinputs + "\" ";
696         else
697                 return "cmd /d /c set TEXINPUTS=." + sep + texinputs_prefix
698                                                    + sep + texinputs + "&";
699 }
700
701
702 // Replace current directory in all elements of a path list with a given path.
703 string const replaceCurdirPath(string const & path, string const & pathlist)
704 {
705         string const oldpathlist = replaceEnvironmentPath(pathlist);
706         char const sep = os::path_separator();
707         string newpathlist;
708
709         for (size_t i = 0, k = 0; i != string::npos; k = i) {
710                 i = oldpathlist.find(sep, i);
711                 string p = oldpathlist.substr(k, i - k);
712                 if (FileName::isAbsolute(p)) {
713                         newpathlist += p;
714                 } else if (i > k) {
715                         size_t offset = 0;
716                         if (p == ".") {
717                                 offset = 1;
718                         } else if (prefixIs(p, "./")) {
719                                 offset = 2;
720                                 while (p[offset] == '/')
721                                         ++offset;
722                         }
723                         newpathlist += addPath(path, p.substr(offset));
724                         if (suffixIs(p, "//"))
725                                 newpathlist += '/';
726                 }
727                 if (i != string::npos) {
728                         newpathlist += sep;
729                         // Stop here if the last element is empty 
730                         if (++i == oldpathlist.length())
731                                 break;
732                 }
733         }
734         return newpathlist;
735 }
736
737
738 // Make relative path out of two absolute paths
739 docstring const makeRelPath(docstring const & abspath, docstring const & basepath)
740 // Makes relative path out of absolute path. If it is deeper than basepath,
741 // it's easy. If basepath and abspath share something (they are all deeper
742 // than some directory), it'll be rendered using ..'s. If they are completely
743 // different, then the absolute path will be used as relative path.
744 {
745         docstring::size_type const abslen = abspath.length();
746         docstring::size_type const baselen = basepath.length();
747
748         docstring::size_type i = os::common_path(abspath, basepath);
749
750         if (i == 0) {
751                 // actually no match - cannot make it relative
752                 return abspath;
753         }
754
755         // Count how many dirs there are in basepath above match
756         // and append as many '..''s into relpath
757         docstring buf;
758         docstring::size_type j = i;
759         while (j < baselen) {
760                 if (basepath[j] == '/') {
761                         if (j + 1 == baselen)
762                                 break;
763                         buf += "../";
764                 }
765                 ++j;
766         }
767
768         // Append relative stuff from common directory to abspath
769         if (abspath[i] == '/')
770                 ++i;
771         for (; i < abslen; ++i)
772                 buf += abspath[i];
773         // Remove trailing /
774         if (suffixIs(buf, '/'))
775                 buf.erase(buf.length() - 1);
776         // Substitute empty with .
777         if (buf.empty())
778                 buf = '.';
779         return buf;
780 }
781
782
783 // Append sub-directory(ies) to a path in an intelligent way
784 string const addPath(string const & path, string const & path_2)
785 {
786         string buf;
787         string const path2 = os::internal_path(path_2);
788
789         if (!path.empty() && path != "." && path != "./") {
790                 buf = os::internal_path(path);
791                 if (path[path.length() - 1] != '/')
792                         buf += '/';
793         }
794
795         if (!path2.empty()) {
796                 string::size_type const p2start = path2.find_first_not_of('/');
797                 string::size_type const p2end = path2.find_last_not_of('/');
798                 string const tmp = path2.substr(p2start, p2end - p2start + 1);
799                 buf += tmp + '/';
800         }
801         return buf;
802 }
803
804
805 string const changeExtension(string const & oldname, string const & extension)
806 {
807         string::size_type const last_slash = oldname.rfind('/');
808         string::size_type last_dot = oldname.rfind('.');
809         if (last_dot < last_slash && last_slash != string::npos)
810                 last_dot = string::npos;
811
812         string ext;
813         // Make sure the extension starts with a dot
814         if (!extension.empty() && extension[0] != '.')
815                 ext= '.' + extension;
816         else
817                 ext = extension;
818
819         return os::internal_path(oldname.substr(0, last_dot) + ext);
820 }
821
822
823 string const removeExtension(string const & name)
824 {
825         return changeExtension(name, string());
826 }
827
828
829 string const addExtension(string const & name, string const & extension)
830 {
831         if (!extension.empty() && extension[0] != '.')
832                 return name + '.' + extension;
833         return name + extension;
834 }
835
836
837 /// Return the extension of the file (not including the .)
838 string const getExtension(string const & name)
839 {
840         string::size_type const last_slash = name.rfind('/');
841         string::size_type const last_dot = name.rfind('.');
842         if (last_dot != string::npos &&
843             (last_slash == string::npos || last_dot > last_slash))
844                 return name.substr(last_dot + 1,
845                                    name.length() - (last_dot + 1));
846         else
847                 return string();
848 }
849
850
851 string const unzippedFileName(string const & zipped_file)
852 {
853         string const ext = getExtension(zipped_file);
854         if (ext == "gz" || ext == "z" || ext == "Z")
855                 return changeExtension(zipped_file, string());
856         return onlyPath(zipped_file) + "unzipped_" + onlyFileName(zipped_file);
857 }
858
859
860 FileName const unzipFile(FileName const & zipped_file, string const & unzipped_file)
861 {
862         FileName const tempfile = FileName(unzipped_file.empty() ?
863                 unzippedFileName(zipped_file.toFilesystemEncoding()) :
864                 unzipped_file);
865         // Run gunzip
866         string const command = "gunzip -c " +
867                 zipped_file.toFilesystemEncoding() + " > " +
868                 tempfile.toFilesystemEncoding();
869         Systemcall one;
870         one.startscript(Systemcall::Wait, command);
871         // test that command was executed successfully (anon)
872         // yes, please do. (Lgb)
873         return tempfile;
874 }
875
876
877 docstring const makeDisplayPath(string const & path, unsigned int threshold)
878 {
879         string str = path;
880
881         // If file is from LyXDir, display it as if it were relative.
882         string const system = package().system_support().absFileName();
883         if (prefixIs(str, system) && str != system)
884                 return from_utf8("[" + str.erase(0, system.length()) + "]");
885
886         // replace /home/blah with ~/
887         string const home = Package::get_home_dir().absFileName();
888         if (!home.empty() && prefixIs(str, home))
889                 str = subst(str, home, "~");
890
891         if (str.length() <= threshold)
892                 return from_utf8(os::external_path(str));
893
894         string const prefix = ".../";
895         docstring dstr = from_utf8(str);
896         docstring temp;
897
898         while (dstr.length() > threshold)
899                 dstr = split(dstr, temp, '/');
900
901         // Did we shorten everything away?
902         if (dstr.empty()) {
903                 // Yes, filename itself is too long.
904                 // Pick the start and the end of the filename.
905                 dstr = from_utf8(onlyFileName(path));
906                 docstring const head = dstr.substr(0, threshold / 2 - 3);
907
908                 docstring::size_type len = dstr.length();
909                 docstring const tail =
910                         dstr.substr(len - threshold / 2 - 2, len - 1);
911                 dstr = head + from_ascii("...") + tail;
912         }
913
914         return from_utf8(os::external_path(prefix + to_utf8(dstr)));
915 }
916
917
918 #ifdef HAVE_READLINK
919 bool readLink(FileName const & file, FileName & link)
920 {
921         string const encoded = file.toFilesystemEncoding();
922 #ifdef HAVE_DEF_PATH_MAX
923         char linkbuffer[PATH_MAX + 1];
924         ssize_t const nRead = ::readlink(encoded.c_str(),
925                                      linkbuffer, sizeof(linkbuffer) - 1);
926         if (nRead <= 0)
927                 return false;
928         linkbuffer[nRead] = '\0'; // terminator
929 #else
930         vector<char> buf(1024);
931         int nRead = -1;
932
933         while (true) {
934                 nRead = ::readlink(encoded.c_str(), &buf[0], buf.size() - 1);
935                 if (nRead < 0) {
936                         return false;
937                 }
938                 if (static_cast<size_t>(nRead) < buf.size() - 1) {
939                         break;
940                 }
941                 buf.resize(buf.size() * 2);
942         }
943         buf[nRead] = '\0'; // terminator
944         const char * linkbuffer = &buf[0];
945 #endif
946         link = makeAbsPath(linkbuffer, onlyPath(file.absFileName()));
947         return true;
948 }
949 #else
950 bool readLink(FileName const &, FileName &)
951 {
952         return false;
953 }
954 #endif
955
956
957 cmd_ret const runCommand(string const & cmd)
958 {
959         // FIXME: replace all calls to RunCommand with ForkedCall
960         // (if the output is not needed) or the code in ISpell.cpp
961         // (if the output is needed).
962
963         // One question is if we should use popen or
964         // create our own popen based on fork, exec, pipe
965         // of course the best would be to have a
966         // pstream (process stream), with the
967         // variants ipstream, opstream
968
969 #if defined (_WIN32)
970         int fno;
971         STARTUPINFO startup;
972         PROCESS_INFORMATION process;
973         SECURITY_ATTRIBUTES security;
974         HANDLE in, out;
975         FILE * inf = 0;
976         bool err2out = false;
977         string command;
978         string const infile = trim(split(cmd, command, '<'), " \"");
979         command = rtrim(command);
980         if (suffixIs(command, "2>&1")) {
981                 command = rtrim(command, "2>&1");
982                 err2out = true;
983         }
984         string const cmdarg = "/d /c " + command;
985         string const comspec = getEnv("COMSPEC");
986
987         security.nLength = sizeof(SECURITY_ATTRIBUTES);
988         security.bInheritHandle = TRUE;
989         security.lpSecurityDescriptor = NULL;
990
991         if (CreatePipe(&in, &out, &security, 0)) {
992                 memset(&startup, 0, sizeof(STARTUPINFO));
993                 memset(&process, 0, sizeof(PROCESS_INFORMATION));
994
995                 startup.cb = sizeof(STARTUPINFO);
996                 startup.dwFlags = STARTF_USESTDHANDLES;
997
998                 startup.hStdError = err2out ? out : GetStdHandle(STD_ERROR_HANDLE);
999                 startup.hStdInput = infile.empty()
1000                         ? GetStdHandle(STD_INPUT_HANDLE)
1001                         : CreateFile(infile.c_str(), GENERIC_READ,
1002                                 FILE_SHARE_READ, &security, OPEN_EXISTING,
1003                                 FILE_ATTRIBUTE_NORMAL, NULL);
1004                 startup.hStdOutput = out;
1005
1006                 if (startup.hStdInput != INVALID_HANDLE_VALUE &&
1007                         CreateProcess(comspec.c_str(), (LPTSTR)cmdarg.c_str(),
1008                                 &security, &security, TRUE, CREATE_NO_WINDOW,
1009                                 0, 0, &startup, &process)) {
1010
1011                         CloseHandle(process.hThread);
1012                         fno = _open_osfhandle((long)in, _O_RDONLY);
1013                         CloseHandle(out);
1014                         inf = _fdopen(fno, "r");
1015                 }
1016         }
1017 #elif defined (HAVE_POPEN)
1018         FILE * inf = ::popen(cmd.c_str(), os::popen_read_mode());
1019 #elif defined (HAVE__POPEN)
1020         FILE * inf = ::_popen(cmd.c_str(), os::popen_read_mode());
1021 #else
1022 #error No popen() function.
1023 #endif
1024
1025         // (Claus Hentschel) Check if popen was successful ;-)
1026         if (!inf) {
1027                 lyxerr << "RunCommand:: could not start child process" << endl;
1028                 return make_pair(-1, string());
1029         }
1030
1031         string ret;
1032         int c = fgetc(inf);
1033         while (c != EOF) {
1034                 ret += static_cast<char>(c);
1035                 c = fgetc(inf);
1036         }
1037
1038 #if defined (_WIN32)
1039         WaitForSingleObject(process.hProcess, INFINITE);
1040         if (!infile.empty())
1041                 CloseHandle(startup.hStdInput);
1042         CloseHandle(process.hProcess);
1043         int const pret = fclose(inf);
1044 #elif defined (HAVE_PCLOSE)
1045         int const pret = pclose(inf);
1046 #elif defined (HAVE__PCLOSE)
1047         int const pret = _pclose(inf);
1048 #else
1049 #error No pclose() function.
1050 #endif
1051
1052         if (pret == -1)
1053                 perror("RunCommand:: could not terminate child process");
1054
1055         return make_pair(pret, ret);
1056 }
1057
1058
1059 FileName const findtexfile(string const & fil, string const & /*format*/)
1060 {
1061         /* There is no problem to extend this function too use other
1062            methods to look for files. It could be setup to look
1063            in environment paths and also if wanted as a last resort
1064            to a recursive find. One of the easier extensions would
1065            perhaps be to use the LyX file lookup methods. But! I am
1066            going to implement this until I see some demand for it.
1067            Lgb
1068         */
1069
1070         // If the file can be found directly, we just return a
1071         // absolute path version of it.
1072         FileName const absfile(makeAbsPath(fil));
1073         if (absfile.exists())
1074                 return absfile;
1075
1076         // Now we try to find it using kpsewhich.
1077         // It seems from the kpsewhich manual page that it is safe to use
1078         // kpsewhich without --format: "When the --format option is not
1079         // given, the search path used when looking for a file is inferred
1080         // from the name given, by looking for a known extension. If no
1081         // known extension is found, the search path for TeX source files
1082         // is used."
1083         // However, we want to take advantage of the format sine almost all
1084         // the different formats has environment variables that can be used
1085         // to controll which paths to search. f.ex. bib looks in
1086         // BIBINPUTS and TEXBIB. Small list follows:
1087         // bib - BIBINPUTS, TEXBIB
1088         // bst - BSTINPUTS
1089         // graphic/figure - TEXPICTS, TEXINPUTS
1090         // ist - TEXINDEXSTYLE, INDEXSTYLE
1091         // pk - PROGRAMFONTS, PKFONTS, TEXPKS, GLYPHFONTS, TEXFONTS
1092         // tex - TEXINPUTS
1093         // tfm - TFMFONTS, TEXFONTS
1094         // This means that to use kpsewhich in the best possible way we
1095         // should help it by setting additional path in the approp. envir.var.
1096         string const kpsecmd = "kpsewhich " + fil;
1097
1098         cmd_ret const c = runCommand(kpsecmd);
1099
1100         LYXERR(Debug::LATEX, "kpse status = " << c.first << '\n'
1101                  << "kpse result = `" << rtrim(c.second, "\n\r") << '\'');
1102         if (c.first != -1)
1103                 return FileName(rtrim(to_utf8(from_filesystem8bit(c.second)), "\n\r"));
1104         else
1105                 return FileName();
1106 }
1107
1108
1109 int compare_timestamps(FileName const & file1, FileName const & file2)
1110 {
1111         // If the original is newer than the copy, then copy the original
1112         // to the new directory.
1113
1114         int cmp = 0;
1115         if (file1.exists() && file2.exists()) {
1116                 double const tmp = difftime(file1.lastModified(), file2.lastModified());
1117                 if (tmp != 0)
1118                         cmp = tmp > 0 ? 1 : -1;
1119
1120         } else if (file1.exists()) {
1121                 cmp = 1;
1122         } else if (file2.exists()) {
1123                 cmp = -1;
1124         }
1125
1126         return cmp;
1127 }
1128
1129
1130 bool prefs2prefs(FileName const & filename, FileName const & tempfile, bool lfuns)
1131 {
1132         FileName const script = libFileSearch("scripts", "prefs2prefs.py");
1133         if (script.empty()) {
1134                 LYXERR0("Could not find bind file conversion "
1135                                 "script prefs2prefs.py.");
1136                 return false;
1137         }
1138
1139         ostringstream command;
1140         command << os::python() << ' ' << quoteName(script.toFilesystemEncoding())
1141           << ' ' << (lfuns ? "-l" : "-p") << ' '
1142                 << quoteName(filename.toFilesystemEncoding())
1143                 << ' ' << quoteName(tempfile.toFilesystemEncoding());
1144         string const command_str = command.str();
1145
1146         LYXERR(Debug::FILES, "Running `" << command_str << '\'');
1147
1148         cmd_ret const ret = runCommand(command_str);
1149         if (ret.first != 0) {
1150                 LYXERR0("Could not run file conversion script prefs2prefs.py.");
1151                 return false;
1152         }
1153         return true;
1154 }
1155
1156 int fileLock(const char * lock_file)
1157 {
1158         int fd = -1;
1159 #if defined(HAVE_LOCKF)
1160         fd = open(lock_file, O_CREAT|O_APPEND|O_SYNC|O_RDWR, 0666);
1161         if (lockf(fd, F_LOCK, 0) != 0) {
1162                 close(fd);
1163                 return(-1);
1164         }
1165 #endif
1166         return(fd);
1167 }
1168
1169 void fileUnlock(int fd, const char * /* lock_file*/)
1170 {
1171 #if defined(HAVE_LOCKF)
1172         if (fd >= 0) {
1173                 if (lockf(fd, F_ULOCK, 0))
1174                         LYXERR0("Can't unlock the file.");
1175                 close(fd);
1176         }
1177 #endif
1178 }
1179
1180 } //namespace support
1181 } // namespace lyx