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.

646 lines
17 KiB

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