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