]> git.lyx.org Git - features.git/blob - src/filetools.h
last updates from 1.0.4, no more updates expected from that branch now
[features.git] / src / 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 (C) 1995-1997, 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 <stdio.h>
15 #include <stdlib.h>
16 #include <fcntl.h>
17 #include <errno.h>
18 #include "error.h"
19 #include "LString.h"
20
21 /** A file class.
22   Use this instead of FILE *, it gives a much better structure.
23   It should prehaps do a bit more error checking than it does now.
24   Currently it is a verbatim copy from p309 of Bjarne Stroupstrups
25   The C++ Programming Language. + some additions.
26  */
27 class FilePtr {
28 public:
29         ///
30         enum file_mode {
31                 read,
32                 write,
33                 update,
34                 truncate
35         };
36         ///
37         FilePtr(LString const &name, file_mode mode)
38         {
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(LString 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(LString const &name, file_mode mode) {
79                 char modestr[3];
80                 
81                 switch(mode) {
82                         // do appropiate #ifdef here so support EMX
83 #ifndef __EMX__
84                 case read: strcpy(modestr, "r"); break;
85                 case write: strcpy(modestr, "w"); break;
86 #else
87                 case read: strcpy(modestr,"rt"); break; // Can read both DOS & UNIX text files.
88                 case write: strcpy(modestr,"w"); break; // Write UNIX text files.
89 #endif
90                         
91                 case update: strcpy(modestr, "r+"); break;
92                 case truncate: strcpy(modestr, "w+"); break;
93                 }
94                 // Should probably be rewritten to use open(2)
95                 if((p = fopen(name.c_str(), modestr))) {
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.print("FilePtr: Wrong parameter given to fopen.");
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 LString CreateBufferTmpDir (LString const & pathfor = LString());
122
123 /// Creates directory. Returns true on succes.
124 bool createDirectory(LString const & name, int permissions);
125
126 ///
127 LString CreateLyXTmpDir (LString const & deflt);
128
129 ///
130 int DestroyBufferTmpDir (LString const & tmpdir);
131
132 ///
133 int DestroyLyXTmpDir (LString 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 LString FileOpenSearch (LString const & path, LString const & name, 
143                         LString const & ext = LString());
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 LString FileSearch(LString const & path, LString const & name, 
151                    LString const & ext = LString());
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 (LString const & path);
160
161 /** Is a file readable ?
162   Returns true if the file `path' is readable.
163  */
164 bool IsFileReadable (LString 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 (LString const & path);
173
174 ///
175 bool IsLyXFilename(LString const & filename);
176
177 ///
178 bool IsSGMLFilename(LString 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 LString LibFileSearch(LString const & dir, LString const & name, 
190                       LString const & ext = LString());
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 LString i18nLibFileSearch(LString const & dir, LString const & name, 
197                           LString const & ext = LString());
198
199 /// Substitutes spaces with underscores in filename (and path)
200 LString SpaceLess(LString const & file);
201
202 /** Returns an unique name to be used as a temporary file. If given,
203   'mask' should the prefix to the temporary file, the rest of the
204   temporary filename will be made from the pid and three letters.
205   */
206 LString TmpFileName(LString const & dir = LString(), 
207                     LString const & mask = "lyx_tmp");
208
209 /// Is a filename/path absolute?
210 bool AbsolutePath(LString const &path);
211
212 /// Add a filename to a path. Any path from filename is stripped first.
213 LString AddName(LString const &Path, LString const &Filename);
214
215 /// Append sub-directory(ies) to path in an intelligent way
216 LString AddPath(LString const & path, LString const & path2);
217
218 /** Change extension of oldname to extension.
219  If no_path is true, the path is stripped from the filename.
220  If oldname does not have an extension, it is appended.
221  If the extension is empty, any extension is removed from the name.
222  */
223 LString ChangeExtension(LString const & oldname, LString const & extension, 
224                         bool no_path);
225
226 /// Create absolute path. If impossible, don't do anything
227 LString ExpandPath(LString const &path);
228
229 /// gets current working directory
230 LString GetCWD();
231
232 /// A helper function.
233 inline LString getEnvPath(char const *name)
234 {
235         LString pathlist;
236         pathlist = getenv(name);
237 #ifndef __EMX__
238         pathlist.subst(':', ';');
239 #else
240         pathlist.subst('\\', '/');
241 #endif
242         return pathlist.strip(';');
243 }
244
245 /** Convert relative path into absolute path based on a basepath.
246   If relpath is absolute, just use that.
247   If basepath doesn't exist use CWD.
248   */
249 LString MakeAbsPath(LString const &RelPath = LString(), 
250                     LString const &BasePath = LString());
251
252 /** Creates a nice compact path for displaying. The parameter
253   threshold, if given, specifies the maximal length of the path.
254   */
255 LString MakeDisplayPath(LString const & path, int threshold=1000);
256
257 /** Makes relative path out of absolute path.
258   If it is deeper than basepath,
259   it's easy. If basepath and abspath share something (they are all deeper
260   than some directory), it'll be rendered using ..'s. If they are completely
261   different, then the absolute path will be used as relative path
262   WARNING: the absolute path and base path must really be absolute paths!!!
263   */
264 LString MakeRelPath(LString const & abspath, LString const & basepath);
265
266 /// Strip filename from path name
267 LString OnlyPath(LString const &Filename);
268
269 /// Normalize a path. Constracts path/../path
270 LString NormalizePath(LString const &path);
271
272 /// Strips path from filename
273 LString OnlyFilename(LString const &Filename);
274
275 /// Cleanup a path if necessary. Currently only useful with OS/2
276 LString CleanupPath(LString const &path) ;
277
278 /** Check and Replace Environmentvariables ${NAME} in Path.
279     Replaces all occurences of these, if they are found in the
280     environment.
281     Variables are defined by Var := '${' [a-zA-Z_][a-zA-Z_0-9]* '}'
282 */
283 LString ReplaceEnvironmentPath(LString const &path);
284
285 /* Set Link to the path File Points to as a symbolic link.
286    Return True if succesfull, False other wise */
287 bool LyXReadLink(LString const & file, LString & Link);
288
289 #endif