]> git.lyx.org Git - lyx.git/blob - src/support/filetools.h
72752f1a15ac00bb8d970b10395eaefcac19b2c2
[lyx.git] / src / support / filetools.h
1 // -*- C++-*-
2 /* lyx-filetool.h : tools functions for file/path handling
3    this file is part of LyX, the High Level Word Processor
4    Copyright 1995-1999, Matthias Ettrich and the LyX Team
5 */
6
7 #ifndef LYX_FILETOOL_H
8 #define LYX_FILETOOL_H
9
10 #ifdef __GNUG__
11 #pragma interface
12 #endif
13
14 #include <cstdio>
15 #include <cstdlib>
16 #include <fcntl.h>
17 #include <cerrno>
18 #include "debug.h"
19 #include "LString.h"
20 #include "support/lstrings.h"
21
22 /** A file class.
23   Use this instead of FILE *, it gives a much better structure.
24   It should prehaps do a bit more error checking than it does now.
25   Currently it is a verbatim copy from p309 of Bjarne Stroupstrups
26   The C++ Programming Language. + some additions.
27  */
28 class FilePtr {
29 public:
30         ///
31         enum file_mode {
32                 read,
33                 write,
34                 update,
35                 truncate
36         };
37         ///
38         FilePtr(string const & name, file_mode mode) {
39                 init();
40                 do_open(name, mode);
41         }
42         ///
43         FilePtr(FILE * pp) { init(); p = pp; }
44         ///
45         ~FilePtr() { close(); }
46
47         /** Use this if you want to rebind the FilePtr to another file.
48          */
49         FilePtr & reopen(string const & name, file_mode mode) {
50                 // close the file it it is already open
51                 close();
52                 // Now open the file.
53                 do_open(name, mode);
54
55                 return *this;
56         }
57         /** Close the file.
58             Use this with some carefullness. After it has been used
59             the FilePtr is unusable. Only use it if it is important
60             that the file is closed before the FilePtr goes out
61             of scope. */
62         int close() { 
63                 if (p) {
64                         int result = fclose(p); 
65                         p = 0; 
66                         return result;
67                 } else 
68                         return 0;
69         }
70         /// automatic converson to FILE* if that is needed.
71         operator FILE*() { return p; }
72         ///
73         FilePtr & operator=(FILE * f) { p= f; return *this;}
74         ///
75         FILE * operator()() { return p; }
76 private:
77         ///
78         void do_open(string const & name, file_mode mode) {
79                 string modestr;
80                 
81                 switch(mode) {
82                         // do appropiate #ifdef here so support EMX
83 #ifndef __EMX__
84                 case read: modestr = "r"; break;
85                 case write: modestr = "w"; break;
86 #else
87                 case read: modestr = "rt"; break; // Can read both DOS & UNIX text files.
88                 case write: modestr = "w"; break; // Write UNIX text files.
89 #endif
90                         
91                 case update: modestr = "r+"; break;
92                 case truncate: modestr = "w+"; break;
93                 }
94                 // Should probably be rewritten to use open(2)
95                 if((p = fopen(name.c_str(), modestr.c_str()))) {
96                         // file succesfully opened.
97                         if (fcntl(fileno(p), F_SETFD, FD_CLOEXEC) == -1) {
98                                 p = 0;
99                         }
100                 } else {
101                         // we have an error let's check what it is.
102                         switch(errno) {
103                         case EINVAL:
104                                 // Internal LyX error.
105                                 lyxerr << "FilePtr: Wrong parameter given to fopen." << endl;
106                                 break;
107                         default:
108                                 // unknown error
109                                 break;
110                         }
111                 }
112         }
113         ///
114         void init() { p = 0; }
115         ///
116         FILE * p;
117 };
118
119
120 ///
121 string CreateBufferTmpDir (string const & pathfor = string());
122
123 /// Creates directory. Returns true on succes.
124 bool createDirectory(string const & name, int permissions);
125
126 ///
127 string CreateLyXTmpDir (string const & deflt);
128
129 ///
130 int DestroyBufferTmpDir (string const & tmpdir);
131
132 ///
133 int DestroyLyXTmpDir (string const & tmpdir);
134
135 /** Find file by searching several directories.
136   Uses a string of paths separated by ";"s to find a file to open.
137     Can't cope with pathnames with a ';' in them. Returns full path to file.
138     If path entry begins with $$LyX/, use system_lyxdir.
139     If path entry begins with $$User/, use user_lyxdir.
140     Example: "$$User/doc;$$LyX/doc".
141 */
142 string FileOpenSearch (string const & path, string const & name, 
143                        string const & ext = string());
144
145 /** Returns the real name of file name in directory path, with optional
146   extension ext.
147   The file is searched in the given path (unless it is an absolute
148   file name), first directly, and then with extension .ext (if given).
149   */
150 string FileSearch(string const & path, string const & name, 
151                   string const & ext = string());
152
153 /** Is directory read only?
154   returns 
155     1: dir writeable
156     0: not writeable
157    -1: error- couldn't find out, or unsure
158   */
159 int IsDirWriteable (string const & path);
160
161 /** Is a file readable ?
162   Returns true if the file `path' is readable.
163  */
164 bool IsFileReadable (string const & path);
165
166 /** Is file read only?
167   returns
168     1: read-write
169     0: read_only
170    -1: error (doesn't exist, no access, anything else)
171   */
172 int IsFileWriteable (string const & path);
173
174 ///
175 bool IsLyXFilename(string const & filename);
176
177 ///
178 bool IsSGMLFilename(string const & filename);
179
180 /** Returns the path of a library data file.
181   Search the file name.ext in the subdirectory dir of
182   \begin{enumerate}
183     \item user_lyxdir
184     \item build_lyxdir (if not empty)
185     \item system_lyxdir
186   \end{enumerate}
187     The third parameter `ext' is optional.
188 */
189 string LibFileSearch(string const & dir, string const & name, 
190                      string const & ext = string());
191
192 /** Same as LibFileSearch(), but tries first to find an
193   internationalized version of the file by prepending $LANG_ to the
194   name 
195   */
196 string i18nLibFileSearch(string const & dir, string const & name, 
197                          string const & ext = string());
198
199 ///
200 string GetEnv(string const & envname);
201
202 /// A helper function.
203 string GetEnvPath(string const & name);
204
205 ///
206 bool PutEnv(string const & envstr);
207
208 ///
209 bool PutEnvPath(string const & envstr);
210
211 /// Substitutes active latex characters with underscores in filename
212 string MakeLatexName(string const & file);
213
214 /// Put the name in quotes suitable for the current shell
215 string QuoteName(string const & file);
216
217 /** Returns an unique name to be used as a temporary file. If given,
218   'mask' should the prefix to the temporary file, the rest of the
219   temporary filename will be made from the pid and three letters.
220   */
221 string TmpFileName(string const & dir = string(), 
222                    string const & mask = "lyx_tmp");
223
224 /// Is a filename/path absolute?
225 bool AbsolutePath(string const & path);
226
227 /// Add a filename to a path. Any path from filename is stripped first.
228 string AddName(string const & path, string const & fname);
229
230 /// Append sub-directory(ies) to path in an intelligent way
231 string AddPath(string const & path, string const & path2);
232
233 /** Change extension of oldname to extension.
234  If no_path is true, the path is stripped from the filename.
235  If oldname does not have an extension, it is appended.
236  If the extension is empty, any extension is removed from the name.
237  */
238 string ChangeExtension(string const & oldname, string const & extension, 
239                        bool no_path);
240
241 /// Create absolute path. If impossible, don't do anything
242 string ExpandPath(string const & path);
243
244 /// gets current working directory
245 string GetCWD();
246
247
248 /** Convert relative path into absolute path based on a basepath.
249   If relpath is absolute, just use that.
250   If basepath doesn't exist use CWD.
251   */
252 string MakeAbsPath(string const & RelPath = string(), 
253                    string const & BasePath = string());
254
255 /** Creates a nice compact path for displaying. The parameter
256   threshold, if given, specifies the maximal length of the path.
257   */
258 string MakeDisplayPath(string const & path, unsigned int threshold= 1000);
259
260 /** Makes relative path out of absolute path.
261   If it is deeper than basepath,
262   it's easy. If basepath and abspath share something (they are all deeper
263   than some directory), it'll be rendered using ..'s. If they are completely
264   different, then the absolute path will be used as relative path
265   WARNING: the absolute path and base path must really be absolute paths!!!
266   */
267 string MakeRelPath(string const & abspath, string const & basepath);
268
269 /// Strip filename from path name
270 string OnlyPath(string const & fname);
271
272 /// Normalize a path. Constracts path/../path
273 string NormalizePath(string const & path);
274
275 /// Strips path from filename
276 string OnlyFilename(string const & fname);
277
278 /// Cleanup a path if necessary. Currently only useful with OS/2
279 string CleanupPath(string const & path) ;
280
281 /** Check and Replace Environmentvariables ${NAME} in Path.
282     Replaces all occurences of these, if they are found in the
283     environment.
284     Variables are defined by Var := '${' [a-zA-Z_][a-zA-Z_0-9]* '}'
285 */
286 string ReplaceEnvironmentPath(string const & path);
287
288 /* Set Link to the path File Points to as a symbolic link.
289    Return True if succesfull, False other wise */
290 bool LyXReadLink(string const & file, string & Link);
291
292 /* Uses kpsewhich to find tex files */
293 string findtexfile(string const & fil, string const & format);
294
295 #endif