]> git.lyx.org Git - lyx.git/blobdiff - src/support/filetools.C
some new (not extensive) changes, some fixes, will probably reverto to .la libs later...
[lyx.git] / src / support / filetools.C
index 28268b7258adc472e6b3d8d00bbd04199cb2cf65..5f3e939d2045c38d9c371d5ba3a8dcaad0a59151 100644 (file)
 #include <config.h>
 
 #include <cctype>
+#include <fstream>
+using std::fstream;
+using std::ios;
+
 #include <utility>
 using std::make_pair;
 using std::pair;
@@ -31,7 +35,6 @@ using std::pair;
 #include "FileInfo.h"
 #include "support/path.h"        // I know it's OS/2 specific (SMiyata)
 #include "gettext.h"
-#include "LAssert.h"
 #include "lyxlib.h"
 
 // Which part of this is still necessary? (JMarc).
@@ -98,10 +101,11 @@ string QuoteName(string const & name)
 #ifdef WITH_WARNINGS
 #warning Add proper emx support here!
 #endif
-       string qname = name;
-       while (qname.find("'") != string::npos) 
-         LSubstring(qname,"'") = "\\'";
-       return '\'' + qname + '\'';
+#ifndef __EMX__
+       return '\'' + name + '\'';
+#else
+       return name; 
+#endif
 }
 
 
@@ -121,9 +125,9 @@ string TmpFileName(string const & dir, string const & mask)
        // a short string...
        string ret;
        FileInfo fnfo;
-       for (int a= 'a'; a<= 'z'; ++a)
-               for (int b= 'a'; b<= 'z'; ++b)
-                       for (int c= 'a'; c<= 'z'; ++c) {
+       for (int a = 'a'; a <= 'z'; ++a)
+               for (int b = 'a'; b <= 'z'; ++b)
+                       for (int c = 'a'; c <= 'z'; ++c) {
                                // if this is not enough I have no idea what
                                // to do.
                                ret = tmpfl + char(a) + char(b) + char(c);
@@ -153,15 +157,13 @@ bool IsFileReadable (string const & path)
 //      -1 error (doesn't exist, no access, anything else) 
 int IsFileWriteable (string const & path)
 {
-       FilePtr fp(path, FilePtr::update);
-       if (!fp()) {
-               if ((errno == EACCES) || (errno == EROFS)) {
-                       fp.reopen(path, FilePtr::read);
-                       if (fp()) {
-                               return 0;
-                       }
-               }
-               return -1;
+       fstream fs(path.c_str(), ios::out|ios::ate);
+       if (!fs) {
+               fs.open(path.c_str(), ios::in|ios::ate);
+               if (fs)
+                       return 0;
+               else
+                       return -1;
        }
        return 1;
 }
@@ -179,23 +181,10 @@ int IsDirWriteable (string const & path)
                             _("Could not test if directory is writeable"));
                return -1;
        } else {
-       FilePtr fp(tmpfl, FilePtr::truncate);
-       if (!fp()) {
-               if (errno == EACCES) {
-                       return 0;
-               } else { 
-                       WriteFSAlert(_("LyX Internal Error!"), 
-                                    _("Cannot open directory test file"));
-                       return -1;
-               }
-               }
-       }
-               if (remove (tmpfl.c_str())) {
-                       WriteFSAlert(_("LyX Internal Error!"), 
-                                   _("Created test file but cannot remove it?"));
-                       return -1;
+               FileInfo fi(path);
+               if (fi.writable()) return 1;
+               return 0;
        }
-       return 1;
 }
 
 
@@ -269,10 +258,10 @@ string FileSearch(string const & path, string const & name,
 //   2) build_lyxdir (if not empty)
 //   3) system_lyxdir
 string LibFileSearch(string const & dir, string const & name, 
-                     string const & ext)
+                    string const & ext)
 {
-        string fullname = FileSearch(AddPath(user_lyxdir, dir), name,
-                                     ext); 
+        string fullname = FileSearch(AddPath(user_lyxdir, dir),
+                                    name, ext); 
        if (!fullname.empty())
                return fullname;
 
@@ -287,7 +276,7 @@ string LibFileSearch(string const & dir, string const & name,
 
 
 string i18nLibFileSearch(string const & dir, string const & name, 
-                         string const & ext)
+                        string const & ext)
 {
        string lang = token(string(GetEnv("LANG")), '_', 0);
 
@@ -330,17 +319,31 @@ bool PutEnv(string const & envstr)
 #warning Look at and fix this.
 #endif
         // f.ex. what about error checking?
-        int retval = 0;
 #if HAVE_PUTENV
         // this leaks, but what can we do about it?
         //   Is doing a getenv() and a free() of the older value 
         //   a good idea? (JMarc)
-        retval = putenv((new string(envstr))->c_str());
+       // Actually we don't have to leak...calling putenv like this
+       // should be enough: ... and this is obviously not enough if putenv
+       // does not make a copy of the string. It is also not very wise to
+       // put a string on the free store. If we have to leak we should do it
+       // like this:
+       /*
+       char * leaker = new char[envstr.length() + 1];
+       envstr.copy(leaker, envstr.length());
+       leaker[envstr.length()] = '\0';
+       int retval = putenv(const_cast<PUTENV_TYPE_ARG>(leaker));
+       */
+
+       // If putenv does not make a copy of the char const * this
+       // is very dangerous. OTOH if it does take a copy this is the
+       // best solution.
+       int retval = putenv(const_cast<PUTENV_TYPE_ARG>(envstr.c_str()));
 #else
 #ifdef HAVE_SETENV 
         string varname;
         string str = envstr.split(varname,'=');
-        retval = setenv(varname.c_str(), str.c_str(), true);
+        int retval = setenv(varname.c_str(), str.c_str(), true);
 #endif
 #endif
         return retval == 0;
@@ -356,12 +359,12 @@ bool PutEnvPath(string const & envstr)
 static
 int DeleteAllFilesInDir (string const & path)
 {
-       struct dirent * de;
        DIR * dir = opendir(path.c_str());
        if (!dir) {
                WriteFSAlert (_("Error! Cannot open directory:"), path);
                return -1;
        }
+       struct dirent * de;
        while ((de = readdir(dir))) {
                string temp = de->d_name;
                if (temp == "." || temp == "..") 
@@ -370,11 +373,11 @@ int DeleteAllFilesInDir (string const & path)
 
                lyxerr.debug() << "Deleting file: " << unlinkpath << endl;
 
-               if (remove (unlinkpath.c_str()))
+               if (remove(unlinkpath.c_str()))
                        WriteFSAlert (_("Error! Could not remove file:"), 
                                      unlinkpath);
         }
-       closedir (dir);
+       closedir(dir);
        return 0;
 }
 
@@ -411,26 +414,24 @@ int DestroyTmpDir (string const & tmpdir, bool Allfiles)
 
 string CreateBufferTmpDir (string const & pathfor)
 {
-       return CreateTmpDir (pathfor, "lyx_bufrtmp");
+       return CreateTmpDir(pathfor, "lyx_bufrtmp");
 }
 
 
 int DestroyBufferTmpDir (string const & tmpdir)
 {
-       return DestroyTmpDir (tmpdir, true);
+       return DestroyTmpDir(tmpdir, true);
 }
 
 
 string CreateLyXTmpDir (string const & deflt)
 {
-       string t;        
-
        if ((!deflt.empty()) && (deflt  != "/tmp")) {
-               if (mkdir (deflt.c_str(), 0777)) {
+               if (mkdir(deflt.c_str(), 0777)) {
 #ifdef __EMX__
                         Path p(user_lyxdir);
 #endif
-                       t = CreateTmpDir (deflt.c_str(), "lyx_tmp");
+                       string t = CreateTmpDir (deflt.c_str(), "lyx_tmp");
                         return t;
                } else
                         return deflt;
@@ -438,7 +439,7 @@ string CreateLyXTmpDir (string const & deflt)
 #ifdef __EMX__
                Path p(user_lyxdir);
 #endif
-               t = CreateTmpDir ("/tmp", "lyx_tmp");
+               string t = CreateTmpDir ("/tmp", "lyx_tmp");
                return t;
        }
 }
@@ -475,7 +476,6 @@ string GetCWD ()
        int n = 256;    // Assume path is less than 256 chars
        char * err;
        char * tbuf = new char[n];
-       string result;
        
        // Safe. Hopefully all getcwds behave this way!
        while (((err = lyx::getcwd (tbuf, n)) == 0) && (errno == ERANGE)) {
@@ -485,6 +485,7 @@ string GetCWD ()
                tbuf = new char[n];
        }
 
+       string result;
        if (err) result = tbuf;
        delete[] tbuf;
        return result;
@@ -553,7 +554,7 @@ string MakeAbsPath(string const & RelPath, string const & BasePath)
                if (Temp == ".") continue;
                if (Temp == "..") {
                        // Remove one level of TempBase
-                       int i = TempBase.length()-2;
+                       int i = TempBase.length() - 2;
 #ifndef __EMX__
                        if (i < 0) i = 0;
                        while (i > 0 && TempBase[i] != '/') --i;
@@ -575,7 +576,7 @@ string MakeAbsPath(string const & RelPath, string const & BasePath)
        }
 
        // returns absolute path
-       return TempBase;        
+       return TempBase;
 }
 
 
@@ -675,11 +676,11 @@ string NormalizePath(string const & path)
                        TempBase = "./";
                } else if (Temp == "..") {
                        // Remove one level of TempBase
-                       int i = TempBase.length()-2;
-                       while (i>0 && TempBase[i] != '/')
+                       int i = TempBase.length() - 2;
+                       while (i > 0 && TempBase[i] != '/')
                                --i;
-                       if (i>= 0 && TempBase[i] == '/')
-                               TempBase.erase(i+1, string::npos);
+                       if (i >= 0 && TempBase[i] == '/')
+                               TempBase.erase(i + 1, string::npos);
                        else
                                TempBase = "../";
                } else {
@@ -759,12 +760,12 @@ string ReplaceEnvironmentPath(string const & path)
                if (*res1_contents != FirstChar) {
                        // Again No Environmentvariable
                        result1 += CompareString;
-                       result0  = res0;
+                       result0 = res0;
                }
 
                // Check for variable names
                // Situation ${} is detected as "No Environmentvariable"
-               char const * cp1 = res1_contents+1;
+               char const * cp1 = res1_contents + 1;
                bool result = isalpha(*cp1) || (*cp1 == UnderscoreChar);
                ++cp1;
                while (*cp1 && result) {
@@ -844,7 +845,7 @@ string MakeRelPath(string const & abspath0, string const & basepath0)
 
        // Append relative stuff from common directory to abspath
        if (abspath[i] == '/') ++i;
-       for (; i<abslen; ++i)
+       for (; i < abslen; ++i)
                buf += abspath[i];
        // Remove trailing /
        if (suffixIs(buf, '/'))
@@ -865,7 +866,6 @@ string AddPath(string const & path, string const & path_2)
        if (!path.empty() && path != "." && path != "./") {
                buf = CleanupPath(path);
                if (path[path.length() - 1] != '/')
-                                                          
                        buf += '/';
        }
 
@@ -913,7 +913,6 @@ string ChangeExtension(string const & oldname, string const & extension,
 }
 
 
-
 // Creates a nice compact path for displaying
 string MakeDisplayPath (string const & path, unsigned int threshold)
 {
@@ -967,9 +966,8 @@ string MakeDisplayPath (string const & path, unsigned int threshold)
 bool LyXReadLink(string const & File, string & Link)
 {
        char LinkBuffer[512];
-                // Should be PATH_MAX but that needs autconf support
-       int nRead;
-       nRead = readlink(File.c_str(), LinkBuffer, sizeof(LinkBuffer)-1);
+       // Should be PATH_MAX but that needs autconf support
+       int nRead = readlink(File.c_str(), LinkBuffer, sizeof(LinkBuffer)-1);
        if (nRead <= 0)
                return false;
        LinkBuffer[nRead] = 0;
@@ -985,7 +983,7 @@ static cmdret do_popen(string const & cmd)
        // create our own popen based on fork, exec, pipe
        // of course the best would be to have a
        // pstream (process stream), with the
-       // variants ipstream, opstream and
+       // variants ipstream, opstream
        FILE * inf = popen(cmd.c_str(), "r");
        string ret;
        int c = fgetc(inf);
@@ -1020,7 +1018,8 @@ string findtexfile(string const & fil, string const & format)
         string kpsecmd = "kpsewhich --format= " + format + " " + OnlyFilename(fil);
         cmdret c = do_popen(kpsecmd);
        
-        lyxerr << "kpse status = " << c.first << "\n"
-               << "kpse result = `" << strip(c.second, '\n') << "'" << endl;
+        lyxerr[Debug::LATEX] << "kpse status = " << c.first << "\n"
+                            << "kpse result = `" << strip(c.second, '\n') 
+                            << "'" << endl;
         return c.first != -1 ? strip(c.second, '\n') : string();
 }