You can not select more than 25 topics Topics must start with a letter or number, can include dashes ('-') and can be up to 35 characters long.

570 lines
15 KiB

15 years ago
16 years ago
15 years ago
  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 <dick@softplc.com>
  5. * Copyright (C) 2017-2021 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. #include <cstdarg>
  25. #include <config.h> // HAVE_FGETC_NOLOCK
  26. #include <ignore.h>
  27. #include <richio.h>
  28. #include <errno.h>
  29. #include <wx/file.h>
  30. #include <wx/translation.h>
  31. // Fall back to getc() when getc_unlocked() is not available on the target platform.
  32. #if !defined( HAVE_FGETC_NOLOCK )
  33. #define getc_unlocked getc
  34. #endif
  35. static int vprint( std::string* result, const char* format, va_list ap )
  36. {
  37. char msg[512];
  38. // This function can call vsnprintf twice.
  39. // But internally, vsnprintf retrieves arguments from the va_list identified by arg as if
  40. // va_arg was used on it, and thus the state of the va_list is likely to be altered by the call.
  41. // see: www.cplusplus.com/reference/cstdio/vsnprintf
  42. // we make a copy of va_list ap for the second call, if happens
  43. va_list tmp;
  44. va_copy( tmp, ap );
  45. size_t len = vsnprintf( msg, sizeof(msg), format, ap );
  46. if( len < sizeof(msg) ) // the output fit into msg
  47. {
  48. result->append( msg, msg + len );
  49. }
  50. else
  51. {
  52. // output was too big, so now incur the expense of allocating
  53. // a buf for holding suffient characters.
  54. std::vector<char> buf;
  55. buf.reserve( len+1 ); // reserve(), not resize() which writes. +1 for trailing nul.
  56. len = vsnprintf( &buf[0], len+1, format, tmp );
  57. result->append( &buf[0], &buf[0] + len );
  58. }
  59. va_end( tmp ); // Release the temporary va_list, initialised from ap
  60. return len;
  61. }
  62. int StrPrintf( std::string* result, const char* format, ... )
  63. {
  64. va_list args;
  65. va_start( args, format );
  66. int ret = vprint( result, format, args );
  67. va_end( args );
  68. return ret;
  69. }
  70. std::string StrPrintf( const char* format, ... )
  71. {
  72. std::string ret;
  73. va_list args;
  74. va_start( args, format );
  75. ignore_unused( vprint( &ret, format, args ) );
  76. va_end( args );
  77. return ret;
  78. }
  79. //-----<LINE_READER>------------------------------------------------------
  80. LINE_READER::LINE_READER( unsigned aMaxLineLength ) :
  81. m_length( 0 ), m_lineNum( 0 ), m_line( nullptr ),
  82. m_capacity( 0 ), m_maxLineLength( aMaxLineLength )
  83. {
  84. if( aMaxLineLength != 0 )
  85. {
  86. // start at the INITIAL size, expand as needed up to the MAX size in maxLineLength
  87. m_capacity = LINE_READER_LINE_INITIAL_SIZE;
  88. // but never go above user's aMaxLineLength, and leave space for trailing nul
  89. if( m_capacity > aMaxLineLength+1 )
  90. m_capacity = aMaxLineLength+1;
  91. // Be sure there is room for a null EOL char, so reserve at least capacity+1 bytes
  92. // to ensure capacity line length and avoid corner cases
  93. // Use capacity+5 to cover and corner case
  94. m_line = new char[m_capacity+5];
  95. m_line[0] = '\0';
  96. }
  97. }
  98. LINE_READER::~LINE_READER()
  99. {
  100. delete[] m_line;
  101. }
  102. void LINE_READER::expandCapacity( unsigned aNewsize )
  103. {
  104. // m_length can equal maxLineLength and nothing breaks, there's room for
  105. // the terminating nul. cannot go over this.
  106. if( aNewsize > m_maxLineLength+1 )
  107. aNewsize = m_maxLineLength+1;
  108. if( aNewsize > m_capacity )
  109. {
  110. m_capacity = aNewsize;
  111. // resize the buffer, and copy the original data
  112. // Be sure there is room for the null EOL char, so reserve capacity+1 bytes
  113. // to ensure capacity line length. Use capacity+5 to cover and corner case
  114. char* bigger = new char[m_capacity+5];
  115. wxASSERT( m_capacity >= m_length+1 );
  116. memcpy( bigger, m_line, m_length );
  117. bigger[m_length] = 0;
  118. delete[] m_line;
  119. m_line = bigger;
  120. }
  121. }
  122. FILE_LINE_READER::FILE_LINE_READER( const wxString& aFileName, unsigned aStartingLineNumber,
  123. unsigned aMaxLineLength ):
  124. LINE_READER( aMaxLineLength ), m_iOwn( true )
  125. {
  126. m_fp = wxFopen( aFileName, wxT( "rt" ) );
  127. if( !m_fp )
  128. {
  129. wxString msg = wxString::Format( _( "Unable to open %s for reading." ),
  130. aFileName.GetData() );
  131. THROW_IO_ERROR( msg );
  132. }
  133. m_source = aFileName;
  134. m_lineNum = aStartingLineNumber;
  135. }
  136. FILE_LINE_READER::FILE_LINE_READER( FILE* aFile, const wxString& aFileName,
  137. bool doOwn,
  138. unsigned aStartingLineNumber,
  139. unsigned aMaxLineLength ) :
  140. LINE_READER( aMaxLineLength ), m_iOwn( doOwn ), m_fp( aFile )
  141. {
  142. m_source = aFileName;
  143. m_lineNum = aStartingLineNumber;
  144. }
  145. FILE_LINE_READER::~FILE_LINE_READER()
  146. {
  147. if( m_iOwn && m_fp )
  148. fclose( m_fp );
  149. }
  150. long int FILE_LINE_READER::FileLength()
  151. {
  152. fseek( m_fp, 0, SEEK_END );
  153. long int fileLength = ftell( m_fp );
  154. rewind( m_fp );
  155. return fileLength;
  156. }
  157. long int FILE_LINE_READER::CurPos()
  158. {
  159. return ftell( m_fp );
  160. }
  161. char* FILE_LINE_READER::ReadLine()
  162. {
  163. m_length = 0;
  164. for( ;; )
  165. {
  166. if( m_length >= m_maxLineLength )
  167. THROW_IO_ERROR( _( "Maximum line length exceeded" ) );
  168. if( m_length >= m_capacity )
  169. expandCapacity( m_capacity * 2 );
  170. // faster, POSIX compatible fgetc(), no locking.
  171. int cc = getc_unlocked( m_fp );
  172. if( cc == EOF )
  173. break;
  174. m_line[ m_length++ ] = (char) cc;
  175. if( cc == '\n' )
  176. break;
  177. }
  178. m_line[ m_length ] = 0;
  179. // m_lineNum is incremented even if there was no line read, because this
  180. // leads to better error reporting when we hit an end of file.
  181. ++m_lineNum;
  182. return m_length ? m_line : nullptr;
  183. }
  184. STRING_LINE_READER::STRING_LINE_READER( const std::string& aString, const wxString& aSource ):
  185. LINE_READER( LINE_READER_LINE_DEFAULT_MAX ),
  186. m_lines( aString ), m_ndx( 0 )
  187. {
  188. // Clipboard text should be nice and _use multiple lines_ so that
  189. // we can report _line number_ oriented error messages when parsing.
  190. m_source = aSource;
  191. }
  192. STRING_LINE_READER::STRING_LINE_READER( const STRING_LINE_READER& aStartingPoint ):
  193. LINE_READER( LINE_READER_LINE_DEFAULT_MAX ),
  194. m_lines( aStartingPoint.m_lines ),
  195. m_ndx( aStartingPoint.m_ndx )
  196. {
  197. // since we are keeping the same "source" name, for error reporting purposes
  198. // we need to have the same notion of line number and offset.
  199. m_source = aStartingPoint.m_source;
  200. m_lineNum = aStartingPoint.m_lineNum;
  201. }
  202. char* STRING_LINE_READER::ReadLine()
  203. {
  204. size_t nlOffset = m_lines.find( '\n', m_ndx );
  205. if( nlOffset == std::string::npos )
  206. m_length = m_lines.length() - m_ndx;
  207. else
  208. m_length = nlOffset - m_ndx + 1; // include the newline, so +1
  209. if( m_length )
  210. {
  211. if( m_length >= m_maxLineLength )
  212. THROW_IO_ERROR( _("Line length exceeded") );
  213. if( m_length+1 > m_capacity ) // +1 for terminating nul
  214. expandCapacity( m_length+1 );
  215. wxASSERT( m_ndx + m_length <= m_lines.length() );
  216. memcpy( m_line, &m_lines[m_ndx], m_length );
  217. m_ndx += m_length;
  218. }
  219. ++m_lineNum; // this gets incremented even if no bytes were read
  220. m_line[m_length] = 0;
  221. return m_length ? m_line : nullptr;
  222. }
  223. INPUTSTREAM_LINE_READER::INPUTSTREAM_LINE_READER( wxInputStream* aStream,
  224. const wxString& aSource ) :
  225. LINE_READER( LINE_READER_LINE_DEFAULT_MAX ),
  226. m_stream( aStream )
  227. {
  228. m_source = aSource;
  229. }
  230. char* INPUTSTREAM_LINE_READER::ReadLine()
  231. {
  232. m_length = 0;
  233. for( ;; )
  234. {
  235. if( m_length >= m_maxLineLength )
  236. THROW_IO_ERROR( _( "Maximum line length exceeded" ) );
  237. if( m_length + 1 > m_capacity )
  238. expandCapacity( m_capacity * 2 );
  239. // this read may fail, docs say to test LastRead() before trusting cc.
  240. char cc = m_stream->GetC();
  241. if( !m_stream->LastRead() )
  242. break;
  243. m_line[ m_length++ ] = cc;
  244. if( cc == '\n' )
  245. break;
  246. }
  247. m_line[ m_length ] = 0;
  248. // m_lineNum is incremented even if there was no line read, because this
  249. // leads to better error reporting when we hit an end of file.
  250. ++m_lineNum;
  251. return m_length ? m_line : nullptr;
  252. }
  253. //-----<OUTPUTFORMATTER>----------------------------------------------------
  254. // factor out a common GetQuoteChar
  255. const char* OUTPUTFORMATTER::GetQuoteChar( const char* wrapee, const char* quote_char )
  256. {
  257. // Include '#' so a symbol is not confused with a comment. We intend
  258. // to wrap any symbol starting with a '#'.
  259. // Our LEXER class handles comments, and comments appear to be an extension
  260. // to the SPECCTRA DSN specification.
  261. if( *wrapee == '#' )
  262. return quote_char;
  263. if( strlen( wrapee ) == 0 )
  264. return quote_char;
  265. bool isFirst = true;
  266. for( ; *wrapee; ++wrapee, isFirst = false )
  267. {
  268. static const char quoteThese[] = "\t ()"
  269. "%" // per Alfons of freerouting.net, he does not like this unquoted as of 1-Feb-2008
  270. "{}" // guessing that these are problems too
  271. ;
  272. // if the string to be wrapped (wrapee) has a delimiter in it,
  273. // return the quote_char so caller wraps the wrapee.
  274. if( strchr( quoteThese, *wrapee ) )
  275. return quote_char;
  276. if( !isFirst && '-' == *wrapee )
  277. return quote_char;
  278. }
  279. return ""; // caller does not need to wrap, can use an unwrapped string.
  280. }
  281. const char* OUTPUTFORMATTER::GetQuoteChar( const char* wrapee ) const
  282. {
  283. return GetQuoteChar( wrapee, quoteChar );
  284. }
  285. int OUTPUTFORMATTER::vprint( const char* fmt, va_list ap )
  286. {
  287. // This function can call vsnprintf twice.
  288. // But internally, vsnprintf retrieves arguments from the va_list identified by arg as if
  289. // va_arg was used on it, and thus the state of the va_list is likely to be altered by the call.
  290. // see: www.cplusplus.com/reference/cstdio/vsnprintf
  291. // we make a copy of va_list ap for the second call, if happens
  292. va_list tmp;
  293. va_copy( tmp, ap );
  294. int ret = vsnprintf( &m_buffer[0], m_buffer.size(), fmt, ap );
  295. if( ret >= (int) m_buffer.size() )
  296. {
  297. m_buffer.resize( ret + 1000 );
  298. ret = vsnprintf( &m_buffer[0], m_buffer.size(), fmt, tmp );
  299. }
  300. va_end( tmp ); // Release the temporary va_list, initialised from ap
  301. if( ret > 0 )
  302. write( &m_buffer[0], ret );
  303. return ret;
  304. }
  305. int OUTPUTFORMATTER::sprint( const char* fmt, ... )
  306. {
  307. va_list args;
  308. va_start( args, fmt );
  309. int ret = vprint( fmt, args);
  310. va_end( args );
  311. return ret;
  312. }
  313. int OUTPUTFORMATTER::Print( int nestLevel, const char* fmt, ... )
  314. {
  315. #define NESTWIDTH 2 ///< how many spaces per nestLevel
  316. va_list args;
  317. va_start( args, fmt );
  318. int result = 0;
  319. int total = 0;
  320. for( int i = 0; i < nestLevel; ++i )
  321. {
  322. // no error checking needed, an exception indicates an error.
  323. result = sprint( "%*c", NESTWIDTH, ' ' );
  324. total += result;
  325. }
  326. // no error checking needed, an exception indicates an error.
  327. result = vprint( fmt, args );
  328. va_end( args );
  329. total += result;
  330. return total;
  331. }
  332. std::string OUTPUTFORMATTER::Quotes( const std::string& aWrapee ) const
  333. {
  334. std::string ret;
  335. ret.reserve( aWrapee.size() * 2 + 2 );
  336. ret += '"';
  337. for( std::string::const_iterator it = aWrapee.begin(); it != aWrapee.end(); ++it )
  338. {
  339. switch( *it )
  340. {
  341. case '\n':
  342. ret += '\\';
  343. ret += 'n';
  344. break;
  345. case '\r':
  346. ret += '\\';
  347. ret += 'r';
  348. break;
  349. case '\\':
  350. ret += '\\';
  351. ret += '\\';
  352. break;
  353. case '"':
  354. ret += '\\';
  355. ret += '"';
  356. break;
  357. default:
  358. ret += *it;
  359. }
  360. }
  361. ret += '"';
  362. return ret;
  363. }
  364. std::string OUTPUTFORMATTER::Quotew( const wxString& aWrapee ) const
  365. {
  366. // wxStrings are always encoded as UTF-8 as we convert to a byte sequence.
  367. // The non-virtual function calls the virtual workhorse function, and if
  368. // a different quoting or escaping strategy is desired from the standard,
  369. // a derived class can overload Quotes() above, but
  370. // should never be a reason to overload this Quotew() here.
  371. return Quotes( (const char*) aWrapee.utf8_str() );
  372. }
  373. //-----<STRING_FORMATTER>----------------------------------------------------
  374. void STRING_FORMATTER::write( const char* aOutBuf, int aCount )
  375. {
  376. m_mystring.append( aOutBuf, aCount );
  377. }
  378. void STRING_FORMATTER::StripUseless()
  379. {
  380. std::string copy = m_mystring;
  381. m_mystring.clear();
  382. for( std::string::iterator i = copy.begin(); i != copy.end(); ++i )
  383. {
  384. if( !isspace( *i ) && *i != ')' && *i != '(' && *i != '"' )
  385. {
  386. m_mystring += *i;
  387. }
  388. }
  389. }
  390. FILE_OUTPUTFORMATTER::FILE_OUTPUTFORMATTER( const wxString& aFileName, const wxChar* aMode,
  391. char aQuoteChar ):
  392. OUTPUTFORMATTER( OUTPUTFMTBUFZ, aQuoteChar ),
  393. m_filename( aFileName )
  394. {
  395. m_fp = wxFopen( aFileName, aMode );
  396. if( !m_fp )
  397. THROW_IO_ERROR( strerror( errno ) );
  398. }
  399. FILE_OUTPUTFORMATTER::~FILE_OUTPUTFORMATTER()
  400. {
  401. if( m_fp )
  402. fclose( m_fp );
  403. }
  404. void FILE_OUTPUTFORMATTER::write( const char* aOutBuf, int aCount )
  405. {
  406. if( fwrite( aOutBuf, (unsigned) aCount, 1, m_fp ) != 1 )
  407. THROW_IO_ERROR( strerror( errno ) );
  408. }
  409. void STREAM_OUTPUTFORMATTER::write( const char* aOutBuf, int aCount )
  410. {
  411. int lastWrite;
  412. // This might delay awhile if you were writing to say a socket, but for
  413. // a file it should only go through the loop once.
  414. for( int total = 0; total<aCount; total += lastWrite )
  415. {
  416. lastWrite = m_os.Write( aOutBuf, aCount ).LastWrite();
  417. if( !m_os.IsOk() )
  418. {
  419. THROW_IO_ERROR( _( "OUTPUTSTREAM_OUTPUTFORMATTER write error" ) );
  420. }
  421. }
  422. }