]> git.saurik.com Git - wxWidgets.git/blob - src/common/textfile.cpp
fixed bug with redoing the command when there was nothing to redo
[wxWidgets.git] / src / common / textfile.cpp
1 ///////////////////////////////////////////////////////////////////////////////
2 // Name: textfile.cpp
3 // Purpose: implementation of wxTextFile class
4 // Author: Vadim Zeitlin
5 // Modified by:
6 // Created: 03.04.98
7 // RCS-ID: $Id$
8 // Copyright: (c) 1998 Vadim Zeitlin <zeitlin@dptmaths.ens-cachan.fr>
9 // Licence: wxWindows license
10 ///////////////////////////////////////////////////////////////////////////////
11
12 // ============================================================================
13 // headers
14 // ============================================================================
15
16 #ifdef __GNUG__
17 #pragma implementation "textfile.h"
18 #endif
19
20 #include "wx/wxprec.h"
21
22 #ifdef __BORLANDC__
23 #pragma hdrstop
24 #endif //__BORLANDC__
25
26 #if !wxUSE_FILE
27 #undef wxUSE_TEXTFILE
28 #define wxUSE_TEXTFILE 0
29 #endif // wxUSE_FILE
30
31 #ifndef WX_PRECOMP
32 #include "wx/string.h"
33 #include "wx/intl.h"
34 #include "wx/file.h"
35 #include "wx/log.h"
36 #endif
37
38 #include "wx/textfile.h"
39
40 // ============================================================================
41 // wxTextFile class implementation
42 // ============================================================================
43
44 // ----------------------------------------------------------------------------
45 // static methods (always compiled in)
46 // ----------------------------------------------------------------------------
47
48 // default type is the native one
49 // the native type under Mac OS X is:
50 // - Unix when compiling with the Apple Developer Tools (__UNIX__)
51 // - Mac when compiling with CodeWarrior (__WXMAC__)
52
53 const wxTextFileType wxTextFile::typeDefault =
54 #if defined(__WINDOWS__)
55 wxTextFileType_Dos;
56 #elif defined(__UNIX__)
57 wxTextFileType_Unix;
58 #elif defined(__WXMAC__)
59 wxTextFileType_Mac;
60 #elif defined(__WXPM__)
61 wxTextFileType_Os2;
62 #else
63 wxTextFileType_None;
64 #error "wxTextFile: unsupported platform."
65 #endif
66
67 const wxChar *wxTextFile::GetEOL(wxTextFileType type)
68 {
69 switch ( type ) {
70 default:
71 wxFAIL_MSG(wxT("bad file type in wxTextFile::GetEOL."));
72 // fall through nevertheless - we must return something...
73
74 case wxTextFileType_None: return wxT("");
75 case wxTextFileType_Unix: return wxT("\n");
76 case wxTextFileType_Dos: return wxT("\r\n");
77 case wxTextFileType_Mac: return wxT("\r");
78 }
79 }
80
81 wxString wxTextFile::Translate(const wxString& text, wxTextFileType type)
82 {
83 // don't do anything if there is nothing to do
84 if ( type == wxTextFileType_None )
85 return text;
86
87 // GRG: don't do anything either if it is empty
88 if ( text.IsEmpty() )
89 return text;
90
91 wxString eol = GetEOL(type), result;
92
93 // optimization: we know that the length of the new string will be about
94 // the same as the length of the old one, so prealloc memory to aviod
95 // unnecessary relocations
96 result.Alloc(text.Len());
97
98 wxChar chLast = 0;
99 for ( const wxChar *pc = text.c_str(); *pc; pc++ )
100 {
101 wxChar ch = *pc;
102 switch ( ch ) {
103 case _T('\n'):
104 // Dos/Unix line termination
105 result += eol;
106 chLast = 0;
107 break;
108
109 case _T('\r'):
110 if ( chLast == _T('\r') ) {
111 // Mac empty line
112 result += eol;
113 }
114 else {
115 // just remember it: we don't know whether it is just "\r"
116 // or "\r\n" yet
117 chLast = _T('\r');
118 }
119 break;
120
121 default:
122 if ( chLast == _T('\r') ) {
123 // Mac line termination
124 result += eol;
125
126 // reset chLast to avoid inserting another eol before the
127 // next character
128 chLast = 0;
129 }
130
131 // add to the current line
132 result += ch;
133 }
134 }
135
136 if ( chLast ) {
137 // trailing '\r'
138 result += eol;
139 }
140
141 return result;
142 }
143
144 #if wxUSE_TEXTFILE
145
146 // ----------------------------------------------------------------------------
147 // ctors & dtor
148 // ----------------------------------------------------------------------------
149
150 wxTextFile::wxTextFile(const wxString& strFile) : m_strFile(strFile)
151 {
152 m_nCurLine = 0;
153 m_isOpened = FALSE;
154 }
155
156 wxTextFile::~wxTextFile()
157 {
158 // m_file dtor called automatically
159 }
160
161 // ----------------------------------------------------------------------------
162 // file operations
163 // ----------------------------------------------------------------------------
164
165 bool wxTextFile::Exists() const
166 {
167 return wxFile::Exists(m_strFile);
168 }
169
170 bool wxTextFile::Create(const wxString& strFile)
171 {
172 m_strFile = strFile;
173
174 return Create();
175 }
176
177 bool wxTextFile::Create()
178 {
179 // file name must be either given in ctor or in Create(const wxString&)
180 wxASSERT( !m_strFile.IsEmpty() );
181
182 // if the file already exists do nothing
183 if ( Exists() ) return FALSE;
184
185 if ( m_file.Open(m_strFile, wxFile::write) )
186 {
187 m_file.Close();
188 return TRUE;
189 }
190 else
191 {
192 return FALSE;
193 }
194 }
195
196 bool wxTextFile::Open(const wxString& strFile, wxMBConv& conv)
197 {
198 m_strFile = strFile;
199
200 return Open(conv);
201 }
202
203 bool wxTextFile::Open(wxMBConv& conv)
204 {
205 // file name must be either given in ctor or in Open(const wxString&)
206 wxASSERT( !m_strFile.IsEmpty() );
207
208 // open file in read-only mode
209 if ( !m_file.Open(m_strFile) )
210 return FALSE;
211
212 // read file into memory
213 m_isOpened = Read(conv);
214
215 m_file.Close();
216
217 return m_isOpened;
218 }
219
220 // analyse some lines of the file trying to guess it's type.
221 // if it fails, it assumes the native type for our platform.
222 wxTextFileType wxTextFile::GuessType() const
223 {
224 wxASSERT( IsOpened() );
225
226 // scan the file lines
227 size_t nUnix = 0, // number of '\n's alone
228 nDos = 0, // number of '\r\n'
229 nMac = 0; // number of '\r's
230
231 // we take MAX_LINES_SCAN in the beginning, middle and the end of file
232 #define MAX_LINES_SCAN (10)
233 size_t nCount = m_aLines.Count() / 3,
234 nScan = nCount > 3*MAX_LINES_SCAN ? MAX_LINES_SCAN : nCount / 3;
235
236 #define AnalyseLine(n) \
237 switch ( m_aTypes[n] ) { \
238 case wxTextFileType_Unix: nUnix++; break; \
239 case wxTextFileType_Dos: nDos++; break; \
240 case wxTextFileType_Mac: nMac++; break; \
241 default: wxFAIL_MSG(_("unknown line terminator")); \
242 }
243
244 size_t n;
245 for ( n = 0; n < nScan; n++ ) // the beginning
246 AnalyseLine(n);
247 for ( n = (nCount - nScan)/2; n < (nCount + nScan)/2; n++ )
248 AnalyseLine(n);
249 for ( n = nCount - nScan; n < nCount; n++ )
250 AnalyseLine(n);
251
252 #undef AnalyseLine
253
254 // interpret the results (FIXME far from being even 50% fool proof)
255 if ( nScan > 0 && nDos + nUnix + nMac == 0 ) {
256 // no newlines at all
257 wxLogWarning(_("'%s' is probably a binary file."), m_strFile.c_str());
258 }
259 else {
260 #define GREATER_OF(t1, t2) n##t1 == n##t2 ? typeDefault \
261 : n##t1 > n##t2 \
262 ? wxTextFileType_##t1 \
263 : wxTextFileType_##t2
264
265 // Watcom C++ doesn't seem to be able to handle the macro
266 #if !defined(__WATCOMC__)
267 if ( nDos > nUnix )
268 return GREATER_OF(Dos, Mac);
269 else if ( nDos < nUnix )
270 return GREATER_OF(Unix, Mac);
271 else {
272 // nDos == nUnix
273 return nMac > nDos ? wxTextFileType_Mac : typeDefault;
274 }
275 #endif // __WATCOMC__
276
277 #undef GREATER_OF
278 }
279
280 return typeDefault;
281 }
282
283 bool wxTextFile::Read(wxMBConv& conv)
284 {
285 // file should be opened and we must be in it's beginning
286 wxASSERT( m_file.IsOpened() && m_file.Tell() == 0 );
287
288 #if wxUSE_UNICODE
289 char conv_mbBuf[2];
290 wchar_t conv_wcBuf[2];
291 conv_mbBuf[1] = 0;
292 #else
293 (void)conv;
294 #endif
295
296 wxString str;
297 char ch, chLast = '\0';
298 char buf[1024];
299 int n, nRead;
300 do {
301 nRead = m_file.Read(buf, WXSIZEOF(buf));
302 if ( nRead == wxInvalidOffset ) {
303 // read error (error message already given in wxFile::Read)
304 return FALSE;
305 }
306
307 for ( n = 0; n < nRead; n++ ) {
308 ch = buf[n];
309 switch ( ch ) {
310 case '\n':
311 // Dos/Unix line termination
312 m_aLines.Add(str);
313 m_aTypes.Add(chLast == '\r' ? wxTextFileType_Dos
314 : wxTextFileType_Unix);
315 str.Empty();
316 chLast = '\n';
317 break;
318
319 case '\r':
320 if ( chLast == '\r' ) {
321 // Mac empty line
322 m_aLines.Add(wxEmptyString);
323 m_aTypes.Add(wxTextFileType_Mac);
324 }
325 else
326 chLast = '\r';
327 break;
328
329 default:
330 if ( chLast == '\r' ) {
331 // Mac line termination
332 m_aLines.Add(str);
333 m_aTypes.Add(wxTextFileType_Mac);
334 chLast = ch;
335 #if wxUSE_UNICODE
336 if (conv.MB2WC(conv_wcBuf, conv_mbBuf, 2) == (size_t)-1)
337 conv_wcBuf[0] = ch;
338 str = conv_wcBuf[0];
339 #else
340 str = ch;
341 #endif
342 }
343 else {
344 // add to the current line
345 #if wxUSE_UNICODE
346 if (conv.MB2WC(conv_wcBuf, conv_mbBuf, 2) == (size_t)-1)
347 conv_wcBuf[0] = ch;
348 str += conv_wcBuf[0];
349 #else
350 str += ch;
351 #endif
352 }
353 }
354 }
355 } while ( nRead == WXSIZEOF(buf) );
356
357 // anything in the last line?
358 if ( !str.IsEmpty() ) {
359 m_aTypes.Add(wxTextFileType_None); // no line terminator
360 m_aLines.Add(str);
361 }
362
363 return TRUE;
364 }
365
366 bool wxTextFile::Close()
367 {
368 m_aTypes.Clear();
369 m_aLines.Clear();
370 m_nCurLine = 0;
371 m_isOpened = FALSE;
372
373 return TRUE;
374 }
375
376 bool wxTextFile::Write(wxTextFileType typeNew, wxMBConv& conv)
377 {
378 wxTempFile fileTmp(m_strFile);
379
380 if ( !fileTmp.IsOpened() ) {
381 wxLogError(_("can't write file '%s' to disk."), m_strFile.c_str());
382 return FALSE;
383 }
384
385 size_t nCount = m_aLines.Count();
386 for ( size_t n = 0; n < nCount; n++ ) {
387 fileTmp.Write(m_aLines[n] +
388 GetEOL(typeNew == wxTextFileType_None ? m_aTypes[n]
389 : typeNew), conv);
390 }
391
392 // replace the old file with this one
393 return fileTmp.Commit();
394 }
395
396 #endif // wxUSE_TEXTFILE
397