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
53static int vprint( std::string* result, const char* format, va_list ap )
54{
55 va_list tmp;
56 va_copy( tmp, ap );
57 size_t len = vsnprintf( nullptr, 0, format, tmp );
58 va_end( tmp );
59
60 // Resize the output to hold the required data
61 size_t size = result->size();
62 result->resize( size + len );
63
64 // Now do the actual printing
65 len = vsnprintf( result->data() + size, len + 1, format, ap );
66
67 return len;
68}
69
70
71int StrPrintf( std::string* result, const char* format, ... )
72{
73 va_list args;
74
75 va_start( args, format );
76 int ret = vprint( result, format, args );
77 va_end( args );
78
79 return ret;
80}
81
82
83std::string StrPrintf( const char* format, ... )
84{
85 std::string ret;
86 va_list args;
87
88 va_start( args, format );
89 ignore_unused( vprint( &ret, format, args ) );
90 va_end( args );
91
92 return ret;
93}
94
95
96wxString SafeReadFile( const wxString& aFilePath, const wxString& aReadType )
97{
98 // Check the path exists as a file first
99 // the IsOpened check would be logical, but on linux you can fopen (in read mode) a directory
100 // And then everything else in here will barf
101 if( !wxFileExists( aFilePath ) )
102 THROW_IO_ERROR( wxString::Format( _( "File '%s' does not exist." ), aFilePath ) );
103
104 wxString contents;
105 wxFFile ff( aFilePath );
106
107 if( !ff.IsOpened() )
108 THROW_IO_ERROR( wxString::Format( _( "Cannot open file '%s'." ), aFilePath ) );
109
110 // Try to determine encoding
111 char bytes[2]{ 0 };
112 ff.Read( bytes, 2 );
113 bool utf16le = bytes[1] == 0;
114
115 ff.Seek( 0 );
116
117 bool readOk = false;
118
119 if( utf16le )
120 readOk = ff.ReadAll( &contents, wxMBConvUTF16LE() );
121 else
122 readOk = ff.ReadAll( &contents, wxMBConvUTF8() );
123
124 if( !readOk || contents.empty() )
125 {
126 ff.Seek( 0 );
127 ff.ReadAll( &contents, wxConvAuto( wxFONTENCODING_CP1252 ) );
128 }
129
130 if( contents.empty() )
131 THROW_IO_ERROR( wxString::Format( _( "Unable to read file '%s'." ), aFilePath ) );
132
133 // I'm not sure what the source of this style of line-endings is, but it can be
134 // found in some Fairchild Semiconductor SPICE files.
135 contents.Replace( wxS( "\r\r\n" ), wxS( "\n" ) );
136
137 return contents;
138}
139
140
141//-----<LINE_READER>------------------------------------------------------
142
143LINE_READER::LINE_READER( unsigned aMaxLineLength ) :
144 m_length( 0 ), m_lineNum( 0 ), m_line( nullptr ),
145 m_capacity( 0 ), m_maxLineLength( aMaxLineLength )
146{
147 if( aMaxLineLength != 0 )
148 {
149 // start at the INITIAL size, expand as needed up to the MAX size in maxLineLength
151
152 // but never go above user's aMaxLineLength, and leave space for trailing nul
153 if( m_capacity > aMaxLineLength+1 )
154 m_capacity = aMaxLineLength+1;
155
156 // Be sure there is room for a null EOL char, so reserve at least capacity+1 bytes
157 // to ensure capacity line length and avoid corner cases
158 // Use capacity+5 to cover and corner case
159 m_line = new char[m_capacity+5];
160
161 m_line[0] = '\0';
162 }
163}
164
165
167{
168 delete[] m_line;
169}
170
171
172void LINE_READER::expandCapacity( unsigned aNewsize )
173{
174 // m_length can equal maxLineLength and nothing breaks, there's room for
175 // the terminating nul. cannot go over this.
176 if( aNewsize > m_maxLineLength+1 )
177 aNewsize = m_maxLineLength+1;
178
179 if( aNewsize > m_capacity )
180 {
181 m_capacity = aNewsize;
182
183 // resize the buffer, and copy the original data
184 // Be sure there is room for the null EOL char, so reserve capacity+1 bytes
185 // to ensure capacity line length. Use capacity+5 to cover and corner case
186 char* bigger = new char[m_capacity+5];
187
188 wxASSERT( m_capacity >= m_length+1 );
189
190 memcpy( bigger, m_line, m_length );
191 bigger[m_length] = 0;
192
193 delete[] m_line;
194 m_line = bigger;
195 }
196}
197
198
199FILE_LINE_READER::FILE_LINE_READER( const wxString& aFileName, unsigned aStartingLineNumber,
200 unsigned aMaxLineLength ):
201 LINE_READER( aMaxLineLength ), m_iOwn( true )
202{
203 m_fp = KIPLATFORM::IO::SeqFOpen( aFileName, wxT( "rt" ) );
204
205 if( !m_fp )
206 {
207 wxString msg = wxString::Format( _( "Unable to open %s for reading." ),
208 aFileName.GetData() );
209 THROW_IO_ERROR( msg );
210 }
211
212 m_source = aFileName;
213 m_lineNum = aStartingLineNumber;
214}
215
216
217FILE_LINE_READER::FILE_LINE_READER( FILE* aFile, const wxString& aFileName,
218 bool doOwn,
219 unsigned aStartingLineNumber,
220 unsigned aMaxLineLength ) :
221 LINE_READER( aMaxLineLength ), m_iOwn( doOwn ), m_fp( aFile )
222{
223 m_source = aFileName;
224 m_lineNum = aStartingLineNumber;
225}
226
227
229{
230 if( m_iOwn && m_fp )
231 fclose( m_fp );
232}
233
234
236{
237 fseek( m_fp, 0, SEEK_END );
238 long int fileLength = ftell( m_fp );
239 rewind( m_fp );
240
241 return fileLength;
242}
243
244
246{
247 return ftell( m_fp );
248}
249
250
252{
253 m_length = 0;
254
255 for( ;; )
256 {
258 THROW_IO_ERROR( _( "Maximum line length exceeded" ) );
259
260 if( m_length >= m_capacity )
262
263 // faster, POSIX compatible fgetc(), no locking.
264 int cc = getc_unlocked( m_fp );
265
266 if( cc == EOF )
267 break;
268
269 m_line[ m_length++ ] = (char) cc;
270
271 if( cc == '\n' )
272 break;
273 }
274
275 m_line[ m_length ] = 0;
276
277 // m_lineNum is incremented even if there was no line read, because this
278 // leads to better error reporting when we hit an end of file.
279 ++m_lineNum;
280
281 return m_length ? m_line : nullptr;
282}
283
284
285STRING_LINE_READER::STRING_LINE_READER( const std::string& aString, const wxString& aSource ):
287 m_lines( aString ), m_ndx( 0 )
288{
289 // Clipboard text should be nice and _use multiple lines_ so that
290 // we can report _line number_ oriented error messages when parsing.
291 m_source = aSource;
292}
293
294
297 m_lines( aStartingPoint.m_lines ),
298 m_ndx( aStartingPoint.m_ndx )
299{
300 // since we are keeping the same "source" name, for error reporting purposes
301 // we need to have the same notion of line number and offset.
302
303 m_source = aStartingPoint.m_source;
304 m_lineNum = aStartingPoint.m_lineNum;
305}
306
307
309{
310 size_t nlOffset = m_lines.find( '\n', m_ndx );
311 unsigned new_length;
312
313 if( nlOffset == std::string::npos )
314 new_length = m_lines.length() - m_ndx;
315 else
316 new_length = nlOffset - m_ndx + 1; // include the newline, so +1
317
318 if( new_length )
319 {
320 if( new_length >= m_maxLineLength )
321 THROW_IO_ERROR( _("Line length exceeded") );
322
323 if( new_length+1 > m_capacity ) // +1 for terminating nul
324 expandCapacity( new_length+1 );
325
326 wxASSERT( m_ndx + new_length <= m_lines.length() );
327
328 memcpy( m_line, &m_lines[m_ndx], new_length );
329 m_ndx += new_length;
330 }
331
332 m_length = new_length;
333 ++m_lineNum; // this gets incremented even if no bytes were read
334 m_line[m_length] = 0;
335
336 return m_length ? m_line : nullptr;
337}
338
339
341 const wxString& aSource ) :
343 m_stream( aStream )
344{
345 m_source = aSource;
346}
347
348
350{
351 m_length = 0;
352
353 for( ;; )
354 {
356 THROW_IO_ERROR( _( "Maximum line length exceeded" ) );
357
358 if( m_length + 1 > m_capacity )
360
361 // this read may fail, docs say to test LastRead() before trusting cc.
362 char cc = m_stream->GetC();
363
364 if( !m_stream->LastRead() )
365 break;
366
367 m_line[ m_length++ ] = cc;
368
369 if( cc == '\n' )
370 break;
371 }
372
373 m_line[ m_length ] = 0;
374
375 // m_lineNum is incremented even if there was no line read, because this
376 // leads to better error reporting when we hit an end of file.
377 ++m_lineNum;
378
379 return m_length ? m_line : nullptr;
380}
381
382
383//-----<OUTPUTFORMATTER>----------------------------------------------------
384
385// factor out a common GetQuoteChar
386
387const char* OUTPUTFORMATTER::GetQuoteChar( const char* wrapee, const char* quote_char )
388{
389 // Include '#' so a symbol is not confused with a comment. We intend
390 // to wrap any symbol starting with a '#'.
391 // Our LEXER class handles comments, and comments appear to be an extension
392 // to the SPECCTRA DSN specification.
393 if( *wrapee == '#' )
394 return quote_char;
395
396 if( strlen( wrapee ) == 0 )
397 return quote_char;
398
399 bool isFirst = true;
400
401 for( ; *wrapee; ++wrapee, isFirst = false )
402 {
403 static const char quoteThese[] = "\t ()"
404 "%" // per Alfons of freerouting.net, he does not like this unquoted as of 1-Feb-2008
405 "{}" // guessing that these are problems too
406 ;
407
408 // if the string to be wrapped (wrapee) has a delimiter in it,
409 // return the quote_char so caller wraps the wrapee.
410 if( strchr( quoteThese, *wrapee ) )
411 return quote_char;
412
413 if( !isFirst && '-' == *wrapee )
414 return quote_char;
415 }
416
417 return ""; // caller does not need to wrap, can use an unwrapped string.
418}
419
420
421const char* OUTPUTFORMATTER::GetQuoteChar( const char* wrapee ) const
422{
423 return GetQuoteChar( wrapee, quoteChar );
424}
425
426
427int OUTPUTFORMATTER::vprint( const char* fmt, va_list ap )
428{
429 // This function can call vsnprintf twice.
430 // But internally, vsnprintf retrieves arguments from the va_list identified by arg as if
431 // va_arg was used on it, and thus the state of the va_list is likely to be altered by the call.
432 // see: www.cplusplus.com/reference/cstdio/vsnprintf
433 // we make a copy of va_list ap for the second call, if happens
434 va_list tmp;
435 va_copy( tmp, ap );
436 int ret = vsnprintf( &m_buffer[0], m_buffer.size(), fmt, ap );
437
438 if( ret >= (int) m_buffer.size() )
439 {
440 m_buffer.resize( ret + 1000 );
441 ret = vsnprintf( &m_buffer[0], m_buffer.size(), fmt, tmp );
442 }
443
444 va_end( tmp ); // Release the temporary va_list, initialised from ap
445
446 if( ret > 0 )
447 write( &m_buffer[0], ret );
448
449 return ret;
450}
451
452
453int OUTPUTFORMATTER::sprint( const char* fmt, ... )
454{
455 va_list args;
456
457 va_start( args, fmt );
458 int ret = vprint( fmt, args );
459 va_end( args );
460
461 return ret;
462}
463
464
465int OUTPUTFORMATTER::Print( int nestLevel, const char* fmt, ... )
466{
467#define NESTWIDTH 2
468
469 va_list args;
470
471 va_start( args, fmt );
472
473 int result = 0;
474 int total = 0;
475
476 for( int i = 0; i < nestLevel; ++i )
477 {
478 // no error checking needed, an exception indicates an error.
479 result = sprint( "%*c", NESTWIDTH, ' ' );
480
481 total += result;
482 }
483
484 // no error checking needed, an exception indicates an error.
485 result = vprint( fmt, args );
486
487 va_end( args );
488
489 total += result;
490 return total;
491}
492
493
494int OUTPUTFORMATTER::Print( const char* fmt, ... )
495{
496 va_list args;
497
498 va_start( args, fmt );
499
500 int result = 0;
501
502 // no error checking needed, an exception indicates an error.
503 result = vprint( fmt, args );
504
505 va_end( args );
506
507 return result;
508}
509
510
511std::string OUTPUTFORMATTER::Quotes( const std::string& aWrapee ) const
512{
513 std::string ret;
514
515 ret.reserve( aWrapee.size() * 2 + 2 );
516
517 ret += '"';
518
519 for( std::string::const_iterator it = aWrapee.begin(); it != aWrapee.end(); ++it )
520 {
521 switch( *it )
522 {
523 case '\n':
524 ret += '\\';
525 ret += 'n';
526 break;
527 case '\r':
528 ret += '\\';
529 ret += 'r';
530 break;
531 case '\\':
532 ret += '\\';
533 ret += '\\';
534 break;
535 case '"':
536 ret += '\\';
537 ret += '"';
538 break;
539 default:
540 ret += *it;
541 }
542 }
543
544 ret += '"';
545
546 return ret;
547}
548
549
550std::string OUTPUTFORMATTER::Quotew( const wxString& aWrapee ) const
551{
552 // wxStrings are always encoded as UTF-8 as we convert to a byte sequence.
553 // The non-virtual function calls the virtual workhorse function, and if
554 // a different quoting or escaping strategy is desired from the standard,
555 // a derived class can overload Quotes() above, but
556 // should never be a reason to overload this Quotew() here.
557 return Quotes( (const char*) aWrapee.utf8_str() );
558}
559
560
561//-----<STRING_FORMATTER>----------------------------------------------------
562
563void STRING_FORMATTER::write( const char* aOutBuf, int aCount )
564{
565 m_mystring.append( aOutBuf, aCount );
566}
567
568
570{
571 std::string copy = m_mystring;
572
573 m_mystring.clear();
574
575 for( std::string::iterator i = copy.begin(); i != copy.end(); ++i )
576 {
577 if( !isspace( *i ) && *i != ')' && *i != '(' && *i != '"' )
578 {
579 m_mystring += *i;
580 }
581 }
582}
583
584
585FILE_OUTPUTFORMATTER::FILE_OUTPUTFORMATTER( const wxString& aFileName, const wxChar* aMode,
586 char aQuoteChar ):
587 OUTPUTFORMATTER( OUTPUTFMTBUFZ, aQuoteChar ),
588 m_filename( aFileName )
589{
590 m_fp = wxFopen( aFileName, aMode );
591
592 if( !m_fp )
593 THROW_IO_ERROR( strerror( errno ) );
594}
595
596
598{
599 if( m_fp )
600 fclose( m_fp );
601}
602
603
604void FILE_OUTPUTFORMATTER::write( const char* aOutBuf, int aCount )
605{
606 if( fwrite( aOutBuf, (unsigned) aCount, 1, m_fp ) != 1 )
607 THROW_IO_ERROR( strerror( errno ) );
608}
609
610
612 const wxChar* aMode,
613 char aQuoteChar ) :
614 OUTPUTFORMATTER( OUTPUTFMTBUFZ, aQuoteChar )
615{
616 m_fp = wxFopen( aFileName, aMode );
617
618 if( !m_fp )
619 THROW_IO_ERROR( strerror( errno ) );
620}
621
622
632
633
635{
636 if( !m_fp )
637 return false;
638
640
641 if( fwrite( m_buf.c_str(), m_buf.length(), 1, m_fp ) != 1 )
642 THROW_IO_ERROR( strerror( errno ) );
643
644 fclose( m_fp );
645 m_fp = nullptr;
646
647 return true;
648}
649
650
651void PRETTIFIED_FILE_OUTPUTFORMATTER::write( const char* aOutBuf, int aCount )
652{
653 m_buf.append( aOutBuf, aCount );
654}
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:228
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:199
FILE * m_fp
I may own this file, but might not.
Definition richio.h:245
char * ReadLine() override
Read a line of text into the buffer and increments the line number counter.
Definition richio.cpp:251
bool m_iOwn
if I own the file, I'll promise to close it, else not.
Definition richio.h:244
long int FileLength()
Definition richio.cpp:235
long int CurPos()
Definition richio.cpp:245
FILE * m_fp
takes ownership
Definition richio.h:510
FILE_OUTPUTFORMATTER(const wxString &aFileName, const wxChar *aMode=wxT("wt"), char aQuoteChar='"' )
Definition richio.cpp:585
void write(const char *aOutBuf, int aCount) override
Should be coded in the interface implementation (derived) classes.
Definition richio.cpp:604
wxString m_filename
Definition richio.h:511
wxInputStream * m_stream
The input stream to read. No ownership of this pointer.
Definition richio.h:300
INPUTSTREAM_LINE_READER(wxInputStream *aStream, const wxString &aSource)
Construct a LINE_READER from a wxInputStream object.
Definition richio.cpp:340
char * ReadLine() override
Read a line of text into the buffer and increments the line number counter.
Definition richio.cpp:349
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:143
unsigned m_maxLineLength
maximum allowed capacity using resizing.
Definition richio.h:173
unsigned m_length
no. bytes in line before trailing nul.
Definition richio.h:167
unsigned m_capacity
no. bytes allocated for line.
Definition richio.h:171
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:172
char * m_line
the read line of UTF8 text
Definition richio.h:170
unsigned m_lineNum
Definition richio.h:168
virtual ~LINE_READER()
Definition richio.cpp:166
wxString m_source
origin of text lines, e.g. filename or "clipboard"
Definition richio.h:175
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:453
std::vector< char > m_buffer
Definition richio.h:434
OUTPUTFORMATTER(int aReserve=OUTPUTFMTBUFZ, char aQuoteChar='"' )
Definition richio.h:324
char quoteChar[2]
Definition richio.h:435
int vprint(const char *fmt, va_list ap)
Definition richio.cpp:427
std::string Quotew(const wxString &aWrapee) const
Definition richio.cpp:550
int PRINTF_FUNC_N Print(int nestLevel, const char *fmt,...)
Format and write text to the output stream.
Definition richio.cpp:465
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:387
virtual std::string Quotes(const std::string &aWrapee) const
Check aWrapee input string for a need to be quoted (e.g.
Definition richio.cpp:511
void write(const char *aOutBuf, int aCount) override
Should be coded in the interface implementation (derived) classes.
Definition richio.cpp:651
PRETTIFIED_FILE_OUTPUTFORMATTER(const wxString &aFileName, const wxChar *aMode=wxT("wt"), char aQuoteChar='"' )
Definition richio.cpp:611
bool Finish() override
Performs prettification and writes the stored buffer to the file.
Definition richio.cpp:634
void write(const char *aOutBuf, int aCount) override
Should be coded in the interface implementation (derived) classes.
Definition richio.cpp:563
void StripUseless()
Removes whitespace, '(', and ')' from the string.
Definition richio.cpp:569
std::string m_mystring
Definition richio.h:481
std::string m_lines
Definition richio.h:255
STRING_LINE_READER(const std::string &aString, const wxString &aSource)
Construct a string line reader.
Definition richio.cpp:285
char * ReadLine() override
Read a line of text into the buffer and increments the line number counter.
Definition richio.cpp:308
#define _(s)
void ignore_unused(const T &)
Definition ignore.h:24
#define THROW_IO_ERROR(msg)
macro which captures the "call site" values of FILE_, __FUNCTION & LINE
void Prettify(std::string &aSource, bool aCompactSave)
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
static int vprint(std::string *result, const char *format, va_list ap)
Definition richio.cpp:53
#define NESTWIDTH
#define getc_unlocked
Definition richio.cpp:48
int StrPrintf(std::string *result, const char *format,...)
This is like sprintf() but the output is appended to a std::string instead of to a character array.
Definition richio.cpp:71
wxString SafeReadFile(const wxString &aFilePath, const wxString &aReadType)
Nominally opens a file and reads it into a string.
Definition richio.cpp:96
#define OUTPUTFMTBUFZ
default buffer size for any OUTPUT_FORMATTER
Definition richio.h:304
#define LINE_READER_LINE_INITIAL_SIZE
Definition richio.h:86
#define LINE_READER_LINE_DEFAULT_MAX
Definition richio.h:85
wxString result
Test unit parsing edge cases and error handling.