KiCad PCB EDA Suite
Loading...
Searching...
No Matches
richio.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright (C) 2007-2011 SoftPLC Corporation, Dick Hollenbeck <[email protected]>
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software; you can redistribute it and/or
8 * modify it under the terms of the GNU General Public License
9 * as published by the Free Software Foundation; either version 2
10 * of the License, or (at your option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful,
13 * but WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15 * GNU General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program; if not, you may find one here:
19 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20 * or you may search the http://www.gnu.org website for the version 2 license,
21 * or you may write to the Free Software Foundation, Inc.,
22 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23 */
24
25
26#include <cstdarg>
27#include <config.h> // HAVE_FGETC_NOLOCK
28
29#include <kiplatform/io.h>
30#include <core/ignore.h>
31#include <richio.h>
32#include <errno.h>
33#include <advanced_config.h>
35
36#include <wx/translation.h>
37#include <wx/ffile.h>
38
39
40// Fall back to getc() when getc_unlocked() is not available on the target platform.
41#if !defined( HAVE_FGETC_NOLOCK )
42#ifdef _MSC_VER
43
44// getc is not a macro on windows and adds a tiny overhead for the indirection to eventually
45// calling fgetc
46#define getc_unlocked _fgetc_nolock
47#else
48#define getc_unlocked getc
49#endif
50#endif
51
52
53wxString SafeReadFile( const wxString& aFilePath, const wxString& aReadType )
54{
55 // Check the path exists as a file first
56 // the IsOpened check would be logical, but on linux you can fopen (in read mode) a directory
57 // And then everything else in here will barf
58 if( !wxFileExists( aFilePath ) )
59 THROW_IO_ERROR( wxString::Format( _( "File '%s' does not exist." ), aFilePath ) );
60
61 wxString contents;
62 wxFFile ff( aFilePath );
63
64 if( !ff.IsOpened() )
65 THROW_IO_ERROR( wxString::Format( _( "Cannot open file '%s'." ), aFilePath ) );
66
67 // Try to determine encoding
68 char bytes[2]{ 0 };
69 ff.Read( bytes, 2 );
70 bool utf16le = bytes[1] == 0;
71
72 ff.Seek( 0 );
73
74 bool readOk = false;
75
76 if( utf16le )
77 readOk = ff.ReadAll( &contents, wxMBConvUTF16LE() );
78 else
79 readOk = ff.ReadAll( &contents, wxMBConvUTF8() );
80
81 if( !readOk || contents.empty() )
82 {
83 ff.Seek( 0 );
84 ff.ReadAll( &contents, wxConvAuto( wxFONTENCODING_CP1252 ) );
85 }
86
87 if( contents.empty() )
88 THROW_IO_ERROR( wxString::Format( _( "Unable to read file '%s'." ), aFilePath ) );
89
90 // I'm not sure what the source of this style of line-endings is, but it can be
91 // found in some Fairchild Semiconductor SPICE files.
92 contents.Replace( wxS( "\r\r\n" ), wxS( "\n" ) );
93
94 return contents;
95}
96
97
98//-----<LINE_READER>------------------------------------------------------
99
100LINE_READER::LINE_READER( unsigned aMaxLineLength ) :
101 m_length( 0 ), m_lineNum( 0 ), m_line( nullptr ),
102 m_capacity( 0 ), m_maxLineLength( aMaxLineLength )
103{
104 if( aMaxLineLength != 0 )
105 {
106 // start at the INITIAL size, expand as needed up to the MAX size in maxLineLength
108
109 // but never go above user's aMaxLineLength, and leave space for trailing nul
110 if( m_capacity > aMaxLineLength+1 )
111 m_capacity = aMaxLineLength+1;
112
113 // Be sure there is room for a null EOL char, so reserve at least capacity+1 bytes
114 // to ensure capacity line length and avoid corner cases
115 // Use capacity+5 to cover and corner case
116 m_line = new char[m_capacity+5];
117
118 m_line[0] = '\0';
119 }
120}
121
122
124{
125 delete[] m_line;
126}
127
128
129void LINE_READER::expandCapacity( unsigned aNewsize )
130{
131 // m_length can equal maxLineLength and nothing breaks, there's room for
132 // the terminating nul. cannot go over this.
133 if( aNewsize > m_maxLineLength+1 )
134 aNewsize = m_maxLineLength+1;
135
136 if( aNewsize > m_capacity )
137 {
138 m_capacity = aNewsize;
139
140 // resize the buffer, and copy the original data
141 // Be sure there is room for the null EOL char, so reserve capacity+1 bytes
142 // to ensure capacity line length. Use capacity+5 to cover and corner case
143 char* bigger = new char[m_capacity+5];
144
145 wxASSERT( m_capacity >= m_length+1 );
146
147 memcpy( bigger, m_line, m_length );
148 bigger[m_length] = 0;
149
150 delete[] m_line;
151 m_line = bigger;
152 }
153}
154
155
156FILE_LINE_READER::FILE_LINE_READER( const wxString& aFileName, unsigned aStartingLineNumber,
157 unsigned aMaxLineLength ):
158 LINE_READER( aMaxLineLength ), m_iOwn( true )
159{
160 m_fp = KIPLATFORM::IO::SeqFOpen( aFileName, wxT( "rt" ) );
161
162 if( !m_fp )
163 {
164 wxString msg = wxString::Format( _( "Unable to open %s for reading." ),
165 aFileName.GetData() );
166 THROW_IO_ERROR( msg );
167 }
168
169 m_source = aFileName;
170 m_lineNum = aStartingLineNumber;
171}
172
173
174FILE_LINE_READER::FILE_LINE_READER( FILE* aFile, const wxString& aFileName,
175 bool doOwn,
176 unsigned aStartingLineNumber,
177 unsigned aMaxLineLength ) :
178 LINE_READER( aMaxLineLength ), m_iOwn( doOwn ), m_fp( aFile )
179{
180 m_source = aFileName;
181 m_lineNum = aStartingLineNumber;
182}
183
184
186{
187 if( m_iOwn && m_fp )
188 fclose( m_fp );
189}
190
191
193{
194 fseek( m_fp, 0, SEEK_END );
195 long int fileLength = ftell( m_fp );
196 rewind( m_fp );
197
198 return fileLength;
199}
200
201
203{
204 return ftell( m_fp );
205}
206
207
209{
210 m_length = 0;
211
212 for( ;; )
213 {
215 THROW_IO_ERROR( _( "Maximum line length exceeded" ) );
216
217 if( m_length >= m_capacity )
219
220 // faster, POSIX compatible fgetc(), no locking.
221 int cc = getc_unlocked( m_fp );
222
223 if( cc == EOF )
224 break;
225
226 m_line[ m_length++ ] = (char) cc;
227
228 if( cc == '\n' )
229 break;
230 }
231
232 m_line[ m_length ] = 0;
233
234 // m_lineNum is incremented even if there was no line read, because this
235 // leads to better error reporting when we hit an end of file.
236 ++m_lineNum;
237
238 return m_length ? m_line : nullptr;
239}
240
241
242STRING_LINE_READER::STRING_LINE_READER( const std::string& aString, const wxString& aSource ):
244 m_lines( aString ), m_ndx( 0 )
245{
246 // Clipboard text should be nice and _use multiple lines_ so that
247 // we can report _line number_ oriented error messages when parsing.
248 m_source = aSource;
249}
250
251
254 m_lines( aStartingPoint.m_lines ),
255 m_ndx( aStartingPoint.m_ndx )
256{
257 // since we are keeping the same "source" name, for error reporting purposes
258 // we need to have the same notion of line number and offset.
259
260 m_source = aStartingPoint.m_source;
261 m_lineNum = aStartingPoint.m_lineNum;
262}
263
264
266{
267 size_t nlOffset = m_lines.find( '\n', m_ndx );
268 unsigned new_length;
269
270 if( nlOffset == std::string::npos )
271 new_length = m_lines.length() - m_ndx;
272 else
273 new_length = nlOffset - m_ndx + 1; // include the newline, so +1
274
275 if( new_length )
276 {
277 if( new_length >= m_maxLineLength )
278 THROW_IO_ERROR( _("Line length exceeded") );
279
280 if( new_length+1 > m_capacity ) // +1 for terminating nul
281 expandCapacity( new_length+1 );
282
283 wxASSERT( m_ndx + new_length <= m_lines.length() );
284
285 memcpy( m_line, &m_lines[m_ndx], new_length );
286 m_ndx += new_length;
287 }
288
289 m_length = new_length;
290 ++m_lineNum; // this gets incremented even if no bytes were read
291 m_line[m_length] = 0;
292
293 return m_length ? m_line : nullptr;
294}
295
296
298 const wxString& aSource ) :
300 m_stream( aStream )
301{
302 m_source = aSource;
303}
304
305
307{
308 m_length = 0;
309
310 for( ;; )
311 {
313 THROW_IO_ERROR( _( "Maximum line length exceeded" ) );
314
315 if( m_length + 1 > m_capacity )
317
318 // this read may fail, docs say to test LastRead() before trusting cc.
319 char cc = m_stream->GetC();
320
321 if( !m_stream->LastRead() )
322 break;
323
324 m_line[ m_length++ ] = cc;
325
326 if( cc == '\n' )
327 break;
328 }
329
330 m_line[ m_length ] = 0;
331
332 // m_lineNum is incremented even if there was no line read, because this
333 // leads to better error reporting when we hit an end of file.
334 ++m_lineNum;
335
336 return m_length ? m_line : nullptr;
337}
338
339
340//-----<OUTPUTFORMATTER>----------------------------------------------------
341
342// factor out a common GetQuoteChar
343
344const char* OUTPUTFORMATTER::GetQuoteChar( const char* wrapee, const char* quote_char )
345{
346 // Include '#' so a symbol is not confused with a comment. We intend
347 // to wrap any symbol starting with a '#'.
348 // Our LEXER class handles comments, and comments appear to be an extension
349 // to the SPECCTRA DSN specification.
350 if( *wrapee == '#' )
351 return quote_char;
352
353 if( strlen( wrapee ) == 0 )
354 return quote_char;
355
356 bool isFirst = true;
357
358 for( ; *wrapee; ++wrapee, isFirst = false )
359 {
360 static const char quoteThese[] = "\t ()"
361 "%" // per Alfons of freerouting.net, he does not like this unquoted as of 1-Feb-2008
362 "{}" // guessing that these are problems too
363 ;
364
365 // if the string to be wrapped (wrapee) has a delimiter in it,
366 // return the quote_char so caller wraps the wrapee.
367 if( strchr( quoteThese, *wrapee ) )
368 return quote_char;
369
370 if( !isFirst && '-' == *wrapee )
371 return quote_char;
372 }
373
374 return ""; // caller does not need to wrap, can use an unwrapped string.
375}
376
377
378const char* OUTPUTFORMATTER::GetQuoteChar( const char* wrapee ) const
379{
380 return GetQuoteChar( wrapee, quoteChar );
381}
382
383
384int OUTPUTFORMATTER::vprint( const char* fmt, va_list ap )
385{
386 // This function can call vsnprintf twice.
387 // But internally, vsnprintf retrieves arguments from the va_list identified by arg as if
388 // va_arg was used on it, and thus the state of the va_list is likely to be altered by the call.
389 // see: www.cplusplus.com/reference/cstdio/vsnprintf
390 // we make a copy of va_list ap for the second call, if happens
391 va_list tmp;
392 va_copy( tmp, ap );
393 int ret = vsnprintf( &m_buffer[0], m_buffer.size(), fmt, ap );
394
395 if( ret >= (int) m_buffer.size() )
396 {
397 m_buffer.resize( ret + 1000 );
398 ret = vsnprintf( &m_buffer[0], m_buffer.size(), fmt, tmp );
399 }
400
401 va_end( tmp ); // Release the temporary va_list, initialised from ap
402
403 if( ret > 0 )
404 write( &m_buffer[0], ret );
405
406 return ret;
407}
408
409
410int OUTPUTFORMATTER::sprint( const char* fmt, ... )
411{
412 va_list args;
413
414 va_start( args, fmt );
415 int ret = vprint( fmt, args );
416 va_end( args );
417
418 return ret;
419}
420
421
422int OUTPUTFORMATTER::Print( int nestLevel, const char* fmt, ... )
423{
424#define NESTWIDTH 2
425
426 va_list args;
427
428 va_start( args, fmt );
429
430 int result = 0;
431 int total = 0;
432
433 for( int i = 0; i < nestLevel; ++i )
434 {
435 // no error checking needed, an exception indicates an error.
436 result = sprint( "%*c", NESTWIDTH, ' ' );
437
438 total += result;
439 }
440
441 // no error checking needed, an exception indicates an error.
442 result = vprint( fmt, args );
443
444 va_end( args );
445
446 total += result;
447 return total;
448}
449
450
451int OUTPUTFORMATTER::Print( const char* fmt, ... )
452{
453 va_list args;
454
455 va_start( args, fmt );
456
457 int result = 0;
458
459 // no error checking needed, an exception indicates an error.
460 result = vprint( fmt, args );
461
462 va_end( args );
463
464 return result;
465}
466
467
468std::string OUTPUTFORMATTER::Quotes( const std::string& aWrapee ) const
469{
470 std::string ret;
471
472 ret.reserve( aWrapee.size() * 2 + 2 );
473
474 ret += '"';
475
476 for( std::string::const_iterator it = aWrapee.begin(); it != aWrapee.end(); ++it )
477 {
478 switch( *it )
479 {
480 case '\n':
481 ret += '\\';
482 ret += 'n';
483 break;
484 case '\r':
485 ret += '\\';
486 ret += 'r';
487 break;
488 case '\\':
489 ret += '\\';
490 ret += '\\';
491 break;
492 case '"':
493 ret += '\\';
494 ret += '"';
495 break;
496 default:
497 ret += *it;
498 }
499 }
500
501 ret += '"';
502
503 return ret;
504}
505
506
507std::string OUTPUTFORMATTER::Quotew( const wxString& aWrapee ) const
508{
509 // wxStrings are always encoded as UTF-8 as we convert to a byte sequence.
510 // The non-virtual function calls the virtual workhorse function, and if
511 // a different quoting or escaping strategy is desired from the standard,
512 // a derived class can overload Quotes() above, but
513 // should never be a reason to overload this Quotew() here.
514 return Quotes( (const char*) aWrapee.utf8_str() );
515}
516
517
518//-----<STRING_FORMATTER>----------------------------------------------------
519
520void STRING_FORMATTER::write( const char* aOutBuf, int aCount )
521{
522 m_mystring.append( aOutBuf, aCount );
523}
524
525
527{
528 std::string copy = m_mystring;
529
530 m_mystring.clear();
531
532 for( std::string::iterator i = copy.begin(); i != copy.end(); ++i )
533 {
534 if( !isspace( *i ) && *i != ')' && *i != '(' && *i != '"' )
535 {
536 m_mystring += *i;
537 }
538 }
539}
540
541
542FILE_OUTPUTFORMATTER::FILE_OUTPUTFORMATTER( const wxString& aFileName, const wxChar* aMode,
543 char aQuoteChar ):
544 OUTPUTFORMATTER( OUTPUTFMTBUFZ, aQuoteChar ),
545 m_filename( aFileName )
546{
547 m_fp = wxFopen( aFileName, aMode );
548
549 if( !m_fp )
550 THROW_IO_ERROR( strerror( errno ) );
551}
552
553
555{
556 if( m_fp )
557 fclose( m_fp );
558}
559
560
561void FILE_OUTPUTFORMATTER::write( const char* aOutBuf, int aCount )
562{
563 if( fwrite( aOutBuf, (unsigned) aCount, 1, m_fp ) != 1 )
564 THROW_IO_ERROR( strerror( errno ) );
565}
566
567
569 KICAD_FORMAT::FORMAT_MODE aFormatMode,
570 const wxChar* aMode,
571 char aQuoteChar ) :
572 OUTPUTFORMATTER( OUTPUTFMTBUFZ, aQuoteChar ),
573 m_mode( aFormatMode )
574{
575 if( ADVANCED_CFG::GetCfg().m_CompactSave && m_mode == KICAD_FORMAT::FORMAT_MODE::NORMAL )
576 m_mode = KICAD_FORMAT::FORMAT_MODE::COMPACT_TEXT_PROPERTIES;
577
578 m_fp = wxFopen( aFileName, aMode );
579
580 if( !m_fp )
581 THROW_IO_ERROR( strerror( errno ) );
582}
583
584
594
595
597{
598 if( !m_fp )
599 return false;
600
602
603 if( fwrite( m_buf.c_str(), m_buf.length(), 1, m_fp ) != 1 )
604 THROW_IO_ERROR( strerror( errno ) );
605
606 fclose( m_fp );
607 m_fp = nullptr;
608
609 return true;
610}
611
612
613void PRETTIFIED_FILE_OUTPUTFORMATTER::write( const char* aOutBuf, int aCount )
614{
615 m_buf.append( aOutBuf, aCount );
616}
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
~FILE_LINE_READER()
May or may not close the open file, depending on doOwn in constructor.
Definition richio.cpp:185
FILE_LINE_READER(const wxString &aFileName, unsigned aStartingLineNumber=0, unsigned aMaxLineLength=LINE_READER_LINE_DEFAULT_MAX)
Take aFileName and the size of the desired line buffer and opens the file and assumes the obligation ...
Definition richio.cpp:156
FILE * m_fp
I may own this file, but might not.
Definition richio.h:218
char * ReadLine() override
Read a line of text into the buffer and increments the line number counter.
Definition richio.cpp:208
bool m_iOwn
if I own the file, I'll promise to close it, else not.
Definition richio.h:217
long int FileLength()
Definition richio.cpp:192
long int CurPos()
Definition richio.cpp:202
FILE * m_fp
takes ownership
Definition richio.h:488
FILE_OUTPUTFORMATTER(const wxString &aFileName, const wxChar *aMode=wxT("wt"), char aQuoteChar='"' )
Definition richio.cpp:542
void write(const char *aOutBuf, int aCount) override
Should be coded in the interface implementation (derived) classes.
Definition richio.cpp:561
wxString m_filename
Definition richio.h:489
wxInputStream * m_stream
The input stream to read. No ownership of this pointer.
Definition richio.h:273
INPUTSTREAM_LINE_READER(wxInputStream *aStream, const wxString &aSource)
Construct a LINE_READER from a wxInputStream object.
Definition richio.cpp:297
char * ReadLine() override
Read a line of text into the buffer and increments the line number counter.
Definition richio.cpp:306
LINE_READER(unsigned aMaxLineLength=LINE_READER_LINE_DEFAULT_MAX)
Build a line reader and fixes the length of the maximum supported line length to aMaxLineLength.
Definition richio.cpp:100
unsigned m_maxLineLength
maximum allowed capacity using resizing.
Definition richio.h:146
unsigned m_length
no. bytes in line before trailing nul.
Definition richio.h:140
unsigned m_capacity
no. bytes allocated for line.
Definition richio.h:144
void expandCapacity(unsigned aNewsize)
Will expand the capacity of line up to maxLineLength but not greater, so be careful about making assu...
Definition richio.cpp:129
char * m_line
the read line of UTF8 text
Definition richio.h:143
unsigned m_lineNum
Definition richio.h:141
virtual ~LINE_READER()
Definition richio.cpp:123
wxString m_source
origin of text lines, e.g. filename or "clipboard"
Definition richio.h:148
virtual void write(const char *aOutBuf, int aCount)=0
Should be coded in the interface implementation (derived) classes.
int sprint(const char *fmt,...)
Definition richio.cpp:410
std::vector< char > m_buffer
Definition richio.h:407
OUTPUTFORMATTER(int aReserve=OUTPUTFMTBUFZ, char aQuoteChar='"' )
Definition richio.h:297
char quoteChar[2]
Definition richio.h:408
int vprint(const char *fmt, va_list ap)
Definition richio.cpp:384
std::string Quotew(const wxString &aWrapee) const
Definition richio.cpp:507
int PRINTF_FUNC_N Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition richio.cpp:422
static const char * GetQuoteChar(const char *wrapee, const char *quote_char)
Perform quote character need determination according to the Specctra DSN specification.
Definition richio.cpp:344
virtual std::string Quotes(const std::string &aWrapee) const
Check aWrapee input string for a need to be quoted (e.g.
Definition richio.cpp:468
void write(const char *aOutBuf, int aCount) override
Should be coded in the interface implementation (derived) classes.
Definition richio.cpp:613
PRETTIFIED_FILE_OUTPUTFORMATTER(const wxString &aFileName, KICAD_FORMAT::FORMAT_MODE aFormatMode=KICAD_FORMAT::FORMAT_MODE::NORMAL, const wxChar *aMode=wxT("wt"), char aQuoteChar='"' )
Definition richio.cpp:568
bool Finish() override
Performs prettification and writes the stored buffer to the file.
Definition richio.cpp:596
KICAD_FORMAT::FORMAT_MODE m_mode
Definition richio.h:514
void write(const char *aOutBuf, int aCount) override
Should be coded in the interface implementation (derived) classes.
Definition richio.cpp:520
void StripUseless()
Removes whitespace, '(', and ')' from the string.
Definition richio.cpp:526
std::string m_mystring
Definition richio.h:459
std::string m_lines
Definition richio.h:228
STRING_LINE_READER(const std::string &aString, const wxString &aSource)
Construct a string line reader.
Definition richio.cpp:242
char * ReadLine() override
Read a line of text into the buffer and increments the line number counter.
Definition richio.cpp:265
#define _(s)
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
void Prettify(std::string &aSource, FORMAT_MODE aMode)
Pretty-prints s-expression text according to KiCad format rules.
FILE * SeqFOpen(const wxString &aPath, const wxString &mode)
Opens the file like fopen but sets flags (if available) for sequential read hinting.
Definition unix/io.cpp:31
#define NESTWIDTH
#define getc_unlocked
Definition richio.cpp:48
wxString SafeReadFile(const wxString &aFilePath, const wxString &aReadType)
Nominally opens a file and reads it into a string.
Definition richio.cpp:53
#define OUTPUTFMTBUFZ
default buffer size for any OUTPUT_FORMATTER
Definition richio.h:277
#define LINE_READER_LINE_INITIAL_SIZE
Definition richio.h:59
#define LINE_READER_LINE_DEFAULT_MAX
Definition richio.h:58
wxString result
Test unit parsing edge cases and error handling.