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.

618 lines
18 KiB

  1. /*
  2. * This program source code file is part of KiCad, a free EDA CAD application.
  3. *
  4. * Copyright (C) 2014-2020 Jean-Pierre Charras, jp.charras at wanadoo.fr
  5. * Copyright (C) 2008 Wayne Stambaugh <stambaughw@gmail.com>
  6. * Copyright (C) 1992-2021 KiCad Developers, see AUTHORS.txt for contributors.
  7. *
  8. * This program is free software; you can redistribute it and/or
  9. * modify it under the terms of the GNU General Public License
  10. * as published by the Free Software Foundation; either version 2
  11. * of the License, or (at your option) any later version.
  12. *
  13. * This program is distributed in the hope that it will be useful,
  14. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  15. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  16. * GNU General Public License for more details.
  17. *
  18. * You should have received a copy of the GNU General Public License
  19. * along with this program; if not, you may find one here:
  20. * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
  21. * or you may search the http://www.gnu.org website for the version 2 license,
  22. * or you may write to the Free Software Foundation, Inc.,
  23. * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
  24. */
  25. #include <eda_base_frame.h>
  26. #include <kiplatform/app.h>
  27. #include <project.h>
  28. #include <common.h>
  29. #include <reporter.h>
  30. #include <macros.h>
  31. #include <mutex>
  32. #include <wx/config.h>
  33. #include <wx/log.h>
  34. #include <wx/msgdlg.h>
  35. #include <wx/stdpaths.h>
  36. #include <wx/url.h>
  37. #include <wx/utils.h>
  38. #ifdef _WIN32
  39. #include <Windows.h>
  40. #endif
  41. enum Bracket
  42. {
  43. Bracket_None,
  44. Bracket_Normal = ')',
  45. Bracket_Curly = '}',
  46. #ifdef __WINDOWS__
  47. Bracket_Windows = '%', // yeah, Windows people are a bit strange ;-)
  48. #endif
  49. Bracket_Max
  50. };
  51. wxString ExpandTextVars( const wxString& aSource, const PROJECT* aProject )
  52. {
  53. return ExpandTextVars( aSource, nullptr, nullptr, aProject );
  54. }
  55. wxString ExpandTextVars( const wxString& aSource,
  56. const std::function<bool( wxString* )>* aLocalResolver,
  57. const std::function<bool( wxString* )>* aFallbackResolver,
  58. const PROJECT* aProject )
  59. {
  60. wxString newbuf;
  61. size_t sourceLen = aSource.length();
  62. newbuf.Alloc( sourceLen ); // best guess (improves performance)
  63. for( size_t i = 0; i < sourceLen; ++i )
  64. {
  65. if( aSource[i] == '$' && i + 1 < sourceLen && aSource[i+1] == '{' )
  66. {
  67. wxString token;
  68. for( i = i + 2; i < sourceLen; ++i )
  69. {
  70. if( aSource[i] == '}' )
  71. break;
  72. else
  73. token.append( aSource[i] );
  74. }
  75. if( token.IsEmpty() )
  76. continue;
  77. if( aLocalResolver && (*aLocalResolver)( &token ) )
  78. {
  79. newbuf.append( token );
  80. }
  81. else if( aProject && aProject->TextVarResolver( &token ) )
  82. {
  83. newbuf.append( token );
  84. }
  85. else if( aFallbackResolver && (*aFallbackResolver)( &token ) )
  86. {
  87. newbuf.append( token );
  88. }
  89. else
  90. {
  91. // Token not resolved: leave the reference unchanged
  92. newbuf.append( "${" + token + "}" );
  93. }
  94. }
  95. else
  96. {
  97. newbuf.append( aSource[i] );
  98. }
  99. }
  100. return newbuf;
  101. }
  102. //
  103. // Stolen from wxExpandEnvVars and then heavily optimized
  104. //
  105. wxString KIwxExpandEnvVars( const wxString& str, const PROJECT* aProject )
  106. {
  107. size_t strlen = str.length();
  108. wxString strResult;
  109. strResult.Alloc( strlen ); // best guess (improves performance)
  110. for( size_t n = 0; n < strlen; n++ )
  111. {
  112. wxUniChar str_n = str[n];
  113. switch( str_n.GetValue() )
  114. {
  115. #ifdef __WINDOWS__
  116. case wxT( '%' ):
  117. #endif // __WINDOWS__
  118. case wxT( '$' ):
  119. {
  120. Bracket bracket;
  121. #ifdef __WINDOWS__
  122. if( str_n == wxT( '%' ) )
  123. bracket = Bracket_Windows;
  124. else
  125. #endif // __WINDOWS__
  126. if( n == strlen - 1 )
  127. {
  128. bracket = Bracket_None;
  129. }
  130. else
  131. {
  132. switch( str[n + 1].GetValue() )
  133. {
  134. case wxT( '(' ):
  135. bracket = Bracket_Normal;
  136. str_n = str[++n]; // skip the bracket
  137. break;
  138. case wxT( '{' ):
  139. bracket = Bracket_Curly;
  140. str_n = str[++n]; // skip the bracket
  141. break;
  142. default:
  143. bracket = Bracket_None;
  144. }
  145. }
  146. size_t m = n + 1;
  147. if( m >= strlen )
  148. break;
  149. wxUniChar str_m = str[m];
  150. while( wxIsalnum( str_m ) || str_m == wxT( '_' ) || str_m == wxT( ':' ) )
  151. {
  152. if( ++m == strlen )
  153. {
  154. str_m = 0;
  155. break;
  156. }
  157. str_m = str[m];
  158. }
  159. wxString strVarName( str.c_str() + n + 1, m - n - 1 );
  160. // NB: use wxGetEnv instead of wxGetenv as otherwise variables
  161. // set through wxSetEnv may not be read correctly!
  162. bool expanded = false;
  163. wxString tmp = strVarName;
  164. if( aProject && aProject->TextVarResolver( &tmp ) )
  165. {
  166. strResult += tmp;
  167. expanded = true;
  168. }
  169. else if( wxGetEnv( strVarName, &tmp ) )
  170. {
  171. strResult += tmp;
  172. expanded = true;
  173. }
  174. else
  175. {
  176. // variable doesn't exist => don't change anything
  177. #ifdef __WINDOWS__
  178. if ( bracket != Bracket_Windows )
  179. #endif
  180. if ( bracket != Bracket_None )
  181. strResult << str[n - 1];
  182. strResult << str_n << strVarName;
  183. }
  184. // check the closing bracket
  185. if( bracket != Bracket_None )
  186. {
  187. if( m == strlen || str_m != (wxChar)bracket )
  188. {
  189. // under MSW it's common to have '%' characters in the registry
  190. // and it's annoying to have warnings about them each time, so
  191. // ignore them silently if they are not used for env vars
  192. //
  193. // under Unix, OTOH, this warning could be useful for the user to
  194. // understand why isn't the variable expanded as intended
  195. #ifndef __WINDOWS__
  196. wxLogWarning( _( "Environment variables expansion failed: missing '%c' "
  197. "at position %u in '%s'." ),
  198. (char)bracket, (unsigned int) (m + 1), str.c_str() );
  199. #endif // __WINDOWS__
  200. }
  201. else
  202. {
  203. // skip closing bracket unless the variables wasn't expanded
  204. if( !expanded )
  205. strResult << (wxChar)bracket;
  206. m++;
  207. }
  208. }
  209. n = m - 1; // skip variable name
  210. str_n = str[n];
  211. }
  212. break;
  213. case wxT( '\\' ):
  214. // backslash can be used to suppress special meaning of % and $
  215. if( n < strlen - 1 && (str[n + 1] == wxT( '%' ) || str[n + 1] == wxT( '$' )) )
  216. {
  217. str_n = str[++n];
  218. strResult += str_n;
  219. break;
  220. }
  221. KI_FALLTHROUGH;
  222. default:
  223. strResult += str_n;
  224. }
  225. }
  226. return strResult;
  227. }
  228. const wxString ExpandEnvVarSubstitutions( const wxString& aString, PROJECT* aProject )
  229. {
  230. // wxGetenv( wchar_t* ) is not re-entrant on linux.
  231. // Put a lock on multithreaded use of wxGetenv( wchar_t* ), called from wxEpandEnvVars(),
  232. static std::mutex getenv_mutex;
  233. std::lock_guard<std::mutex> lock( getenv_mutex );
  234. // We reserve the right to do this another way, by providing our own member function.
  235. return KIwxExpandEnvVars( aString, aProject );
  236. }
  237. const wxString ResolveUriByEnvVars( const wxString& aUri, PROJECT* aProject )
  238. {
  239. wxString uri = ExpandTextVars( aUri, aProject );
  240. // URL-like URI: return as is.
  241. wxURL url( uri );
  242. if( url.GetError() == wxURL_NOERR )
  243. return uri;
  244. // Otherwise, the path points to a local file. Resolve environment variables if any.
  245. return ExpandEnvVarSubstitutions( aUri, aProject );
  246. }
  247. bool EnsureFileDirectoryExists( wxFileName* aTargetFullFileName,
  248. const wxString& aBaseFilename,
  249. REPORTER* aReporter )
  250. {
  251. wxString msg;
  252. wxString baseFilePath = wxFileName( aBaseFilename ).GetPath();
  253. // make aTargetFullFileName path, which is relative to aBaseFilename path (if it is not
  254. // already an absolute path) absolute:
  255. if( !aTargetFullFileName->MakeAbsolute( baseFilePath ) )
  256. {
  257. if( aReporter )
  258. {
  259. msg.Printf( _( "Cannot make path '%s' absolute with respect to '%s'." ),
  260. aTargetFullFileName->GetPath(),
  261. baseFilePath );
  262. aReporter->Report( msg, RPT_SEVERITY_ERROR );
  263. }
  264. return false;
  265. }
  266. // Ensure the path of aTargetFullFileName exists, and create it if needed:
  267. wxString outputPath( aTargetFullFileName->GetPath() );
  268. if( !wxFileName::DirExists( outputPath ) )
  269. {
  270. // Make every directory provided when the provided path doesn't exist
  271. if( wxFileName::Mkdir( outputPath, wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
  272. {
  273. if( aReporter )
  274. {
  275. msg.Printf( _( "Output directory '%s' created." ), outputPath );
  276. aReporter->Report( msg, RPT_SEVERITY_INFO );
  277. return true;
  278. }
  279. }
  280. else
  281. {
  282. if( aReporter )
  283. {
  284. msg.Printf( _( "Cannot create output directory '%s'." ), outputPath );
  285. aReporter->Report( msg, RPT_SEVERITY_ERROR );
  286. }
  287. return false;
  288. }
  289. }
  290. return true;
  291. }
  292. /**
  293. * Performance enhancements to file and directory operations.
  294. *
  295. * Note: while it's annoying to have to make copies of wxWidgets stuff and then
  296. * add platform-specific performance optimizations, the following routines offer
  297. * SIGNIFICANT performance benefits.
  298. */
  299. /**
  300. * A copy of wxMatchWild(), which wxWidgets attributes to Douglas A. Lewis
  301. * <dalewis@cs.Buffalo.EDU> and ircII's reg.c.
  302. *
  303. * This version is modified to skip any encoding conversions (for performance).
  304. */
  305. bool matchWild( const char* pat, const char* text, bool dot_special )
  306. {
  307. if( !*text )
  308. {
  309. /* Match if both are empty. */
  310. return !*pat;
  311. }
  312. const char *m = pat,
  313. *n = text,
  314. *ma = nullptr,
  315. *na = nullptr;
  316. int just = 0,
  317. acount = 0,
  318. count = 0;
  319. if( dot_special && (*n == '.') )
  320. {
  321. /* Never match so that hidden Unix files
  322. * are never found. */
  323. return false;
  324. }
  325. for(;;)
  326. {
  327. if( *m == '*' )
  328. {
  329. ma = ++m;
  330. na = n;
  331. just = 1;
  332. acount = count;
  333. }
  334. else if( *m == '?' )
  335. {
  336. m++;
  337. if( !*n++ )
  338. return false;
  339. }
  340. else
  341. {
  342. if( *m == '\\' )
  343. {
  344. m++;
  345. /* Quoting "nothing" is a bad thing */
  346. if( !*m )
  347. return false;
  348. }
  349. if( !*m )
  350. {
  351. /*
  352. * If we are out of both strings or we just
  353. * saw a wildcard, then we can say we have a
  354. * match
  355. */
  356. if( !*n )
  357. return true;
  358. if( just )
  359. return true;
  360. just = 0;
  361. goto not_matched;
  362. }
  363. /*
  364. * We could check for *n == NULL at this point, but
  365. * since it's more common to have a character there,
  366. * check to see if they match first (m and n) and
  367. * then if they don't match, THEN we can check for
  368. * the NULL of n
  369. */
  370. just = 0;
  371. if( *m == *n )
  372. {
  373. m++;
  374. count++;
  375. n++;
  376. }
  377. else
  378. {
  379. not_matched:
  380. /*
  381. * If there are no more characters in the
  382. * string, but we still need to find another
  383. * character (*m != NULL), then it will be
  384. * impossible to match it
  385. */
  386. if( !*n )
  387. return false;
  388. if( ma )
  389. {
  390. m = ma;
  391. n = ++na;
  392. count = acount;
  393. }
  394. else
  395. return false;
  396. }
  397. }
  398. }
  399. }
  400. /**
  401. * A copy of ConvertFileTimeToWx() because wxWidgets left it as a static function
  402. * private to src/common/filename.cpp.
  403. */
  404. #if wxUSE_DATETIME && defined(__WIN32__) && !defined(__WXMICROWIN__)
  405. // Convert between wxDateTime and FILETIME which is a 64-bit value representing
  406. // the number of 100-nanosecond intervals since January 1, 1601 UTC.
  407. //
  408. // This is the offset between FILETIME epoch and the Unix/wxDateTime Epoch.
  409. static wxInt64 EPOCH_OFFSET_IN_MSEC = wxLL(11644473600000);
  410. static void ConvertFileTimeToWx( wxDateTime* dt, const FILETIME& ft )
  411. {
  412. wxLongLong t( ft.dwHighDateTime, ft.dwLowDateTime );
  413. t /= 10000; // Convert hundreds of nanoseconds to milliseconds.
  414. t -= EPOCH_OFFSET_IN_MSEC;
  415. *dt = wxDateTime( t );
  416. }
  417. #endif // wxUSE_DATETIME && __WIN32__
  418. /**
  419. * This routine offers SIGNIFICANT performance benefits over using wxWidgets to gather
  420. * timestamps from matching files in a directory.
  421. *
  422. * @param aDirPath is the directory to search.
  423. * @param aFilespec is a (wildcarded) file spec to match against.
  424. * @return a hash of the last-mod-dates of all matching files in the directory.
  425. */
  426. long long TimestampDir( const wxString& aDirPath, const wxString& aFilespec )
  427. {
  428. long long timestamp = 0;
  429. #if defined( __WIN32__ )
  430. // Win32 version.
  431. // Save time by not searching for each path twice: once in wxDir.GetNext() and once in
  432. // wxFileName.GetModificationTime(). Also cuts out wxWidgets' string-matching and case
  433. // conversion by staying on the MSW side of things.
  434. std::wstring filespec( aDirPath.t_str() );
  435. filespec += '\\';
  436. filespec += aFilespec.t_str();
  437. WIN32_FIND_DATA findData;
  438. wxDateTime lastModDate;
  439. HANDLE fileHandle = ::FindFirstFile( filespec.data(), &findData );
  440. if( fileHandle != INVALID_HANDLE_VALUE )
  441. {
  442. do
  443. {
  444. ConvertFileTimeToWx( &lastModDate, findData.ftLastWriteTime );
  445. timestamp += lastModDate.GetValue().GetValue();
  446. // Get the file size (partial) as well to check for sneaky changes.
  447. timestamp += findData.nFileSizeLow;
  448. }
  449. while ( FindNextFile( fileHandle, &findData ) != 0 );
  450. }
  451. FindClose( fileHandle );
  452. #else
  453. // POSIX version.
  454. // Save time by not converting between encodings -- do everything on the file-system side.
  455. std::string filespec( aFilespec.fn_str() );
  456. std::string dir_path( aDirPath.fn_str() );
  457. DIR* dir = opendir( dir_path.c_str() );
  458. if( dir )
  459. {
  460. for( dirent* dir_entry = readdir( dir ); dir_entry; dir_entry = readdir( dir ) )
  461. {
  462. if( !matchWild( filespec.c_str(), dir_entry->d_name, true ) )
  463. continue;
  464. std::string entry_path = dir_path + '/' + dir_entry->d_name;
  465. struct stat entry_stat;
  466. if( wxCRT_Lstat( entry_path.c_str(), &entry_stat ) == 0 )
  467. {
  468. // Timestamp the source file, not the symlink
  469. if( S_ISLNK( entry_stat.st_mode ) ) // wxFILE_EXISTS_SYMLINK
  470. {
  471. char buffer[ PATH_MAX + 1 ];
  472. ssize_t pathLen = readlink( entry_path.c_str(), buffer, PATH_MAX );
  473. if( pathLen > 0 )
  474. {
  475. struct stat linked_stat;
  476. buffer[ pathLen ] = '\0';
  477. entry_path = dir_path + buffer;
  478. if( wxCRT_Lstat( entry_path.c_str(), &linked_stat ) == 0 )
  479. {
  480. entry_stat = linked_stat;
  481. }
  482. else
  483. {
  484. // if we couldn't lstat the linked file we'll have to just use
  485. // the symbolic link info
  486. }
  487. }
  488. }
  489. if( S_ISREG( entry_stat.st_mode ) ) // wxFileExists()
  490. {
  491. timestamp += entry_stat.st_mtime * 1000;
  492. // Get the file size as well to check for sneaky changes.
  493. timestamp += entry_stat.st_size;
  494. }
  495. }
  496. else
  497. {
  498. // if we couldn't lstat the file itself all we can do is use the name
  499. timestamp += (signed) std::hash<std::string>{}( std::string( dir_entry->d_name ) );
  500. }
  501. }
  502. closedir( dir );
  503. }
  504. #endif
  505. return timestamp;
  506. }
  507. bool WarnUserIfOperatingSystemUnsupported()
  508. {
  509. if( !KIPLATFORM::APP::IsOperatingSystemUnsupported() )
  510. return false;
  511. wxMessageDialog dialog( nullptr, _( "This operating system is not supported "
  512. "by KiCad and its dependencies." ),
  513. _( "Unsupported Operating System" ),
  514. wxOK | wxICON_EXCLAMATION );
  515. dialog.SetExtendedMessage( _( "Any issues with KiCad on this system cannot "
  516. "be reported to the official bugtracker." ) );
  517. dialog.ShowModal();
  518. return true;
  519. }