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.

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