KiCad PCB EDA Suite
Loading...
Searching...
No Matches
filename_resolver.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) 2015-2020 Cirilo Bernardo <[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, see <https://www.gnu.org/licenses/>.
19 */
20
21#include <fstream>
22#include <mutex>
23#include <sstream>
24
25#include <wx/log.h>
26#include <wx/uri.h>
27#include <pgm_base.h>
28#include <trace_helpers.h>
29
30#include <common.h>
31#include <embedded_files.h>
32#include <env_vars.h>
33#include <filename_resolver.h>
34#include <confirm.h>
35#include <wx_filename.h>
36
37// configuration file version
38#define CFGFILE_VERSION 1
39
40// flag bits used to track different one-off messages to users
41#define ERRFLG_ALIAS (1)
42#define ERRFLG_RELPATH (2)
43#define ERRFLG_ENVPATH (4)
44
45#define MASK_3D_RESOLVER "3D_RESOLVER"
46
47static std::mutex mutex_resolver;
48
49
51 m_pgm( nullptr ),
52 m_project( nullptr )
53{
54 m_errflags = 0;
55}
56
57
58bool FILENAME_RESOLVER::Set3DConfigDir( const wxString& aConfigDir )
59{
60 if( aConfigDir.empty() )
61 return false;
62
63 wxFileName cfgdir( ExpandEnvVarSubstitutions( aConfigDir, m_project ), "" );
64
65 cfgdir.Normalize( FN_NORMALIZE_FLAGS );
66
67 if( !cfgdir.DirExists() )
68 return false;
69
70 m_configDir = cfgdir.GetPath();
72
73 return true;
74}
75
76
77bool FILENAME_RESOLVER::SetProject( const PROJECT* aProject, bool* flgChanged )
78{
79 m_project = aProject;
80
81 if( !aProject )
82 return false;
83
84 wxFileName projdir( ExpandEnvVarSubstitutions( aProject->GetProjectPath(), aProject ), "" );
85
86 projdir.Normalize( FN_NORMALIZE_FLAGS );
87
88 if( !projdir.DirExists() )
89 return false;
90
91 m_curProjDir = projdir.GetPath();
92
93 if( flgChanged )
94 *flgChanged = false;
95
96 if( m_paths.empty() )
97 {
98 SEARCH_PATH al;
99 al.m_Alias = wxS( "${KIPRJMOD}" );
100 al.m_Pathvar = wxS( "${KIPRJMOD}" );
102 m_paths.push_back( al );
103
104 if( flgChanged )
105 *flgChanged = true;
106 }
107 else
108 {
109 if( m_paths.front().m_Pathexp != m_curProjDir )
110 {
111 m_paths.front().m_Pathexp = m_curProjDir;
112
113 if( flgChanged )
114 *flgChanged = true;
115 }
116 else
117 {
118 return true;
119 }
120 }
121
122#ifdef DEBUG
123 {
124 std::ostringstream ostr;
125 ostr << __FILE__ << ": " << __FUNCTION__ << ": " << __LINE__ << "\n";
126 ostr << " * [INFO] changed project dir to ";
127 ostr << m_paths.front().m_Pathexp.ToUTF8();
128 wxLogTrace( MASK_3D_RESOLVER, "%s\n", ostr.str().c_str() );
129 }
130#endif
131
132 return true;
133}
134
135
137{
138 return m_curProjDir;
139}
140
141
143{
144 m_pgm = aBase;
145
146 if( !m_pgm || m_paths.empty() )
147 return;
148
149 // recreate the path list
150 m_paths.clear();
152}
153
154
156{
157 if( !m_paths.empty() )
158 return true;
159
160 // add an entry for the default search path; at this point
161 // we cannot set a sensible default so we use an empty string.
162 // the user may change this later with a call to SetProjectDir()
163
164 SEARCH_PATH lpath;
165 lpath.m_Alias = wxS( "${KIPRJMOD}" );
166 lpath.m_Pathvar = wxS( "${KIPRJMOD}" );
167 lpath.m_Pathexp = m_curProjDir;
168 m_paths.push_back( lpath );
169 wxFileName fndummy;
170 wxUniChar psep = fndummy.GetPathSeparator();
171 std::list< wxString > epaths;
172
173 if( GetKicadPaths( epaths ) )
174 {
175 for( const wxString& currPath : epaths )
176 {
177 wxString currPathVarFormat = currPath;
178 currPathVarFormat.Prepend( wxS( "${" ) );
179 currPathVarFormat.Append( wxS( "}" ) );
180
181 wxString pathVal = ExpandEnvVarSubstitutions( currPathVarFormat, m_project );
182
183 if( pathVal.empty() )
184 {
185 lpath.m_Pathexp.clear();
186 }
187 else
188 {
189 fndummy.Assign( pathVal, "" );
190 fndummy.Normalize( FN_NORMALIZE_FLAGS );
191 lpath.m_Pathexp = fndummy.GetFullPath();
192 }
193
194 lpath.m_Alias = currPath;
195 lpath.m_Pathvar = currPath;
196
197 if( !lpath.m_Pathexp.empty() && psep == *lpath.m_Pathexp.rbegin() )
198 lpath.m_Pathexp.erase( --lpath.m_Pathexp.end() );
199
200 // we add it first with the alias set to the non-variable format
201 m_paths.push_back( lpath );
202
203 // now add it with the "new variable format ${VAR}"
204 lpath.m_Alias = currPathVarFormat;
205 m_paths.push_back( lpath );
206 }
207 }
208
209 if( m_paths.empty() )
210 return false;
211
212#ifdef DEBUG
213 wxLogTrace( MASK_3D_RESOLVER, wxS( " * [3D model] search paths:\n" ) );
214 std::list< SEARCH_PATH >::const_iterator sPL = m_paths.begin();
215
216 while( sPL != m_paths.end() )
217 {
218 wxLogTrace( MASK_3D_RESOLVER, wxS( " + %s : '%s'\n" ), (*sPL).m_Alias.GetData(),
219 (*sPL).m_Pathexp.GetData() );
220 ++sPL;
221 }
222#endif
223
224 return true;
225}
226
227
228bool FILENAME_RESOLVER::UpdatePathList( const std::vector< SEARCH_PATH >& aPathList )
229{
230 wxUniChar envMarker( '$' );
231
232 while( !m_paths.empty() && envMarker != *m_paths.back().m_Alias.rbegin() )
233 m_paths.pop_back();
234
235 for( const SEARCH_PATH& path : aPathList )
236 addPath( path );
237
238 return true;
239}
240
241
242wxString FILENAME_RESOLVER::ResolvePath( const wxString& aFileName, const wxString& aWorkingPath,
243 std::vector<const EMBEDDED_FILES*> aEmbeddedFilesStack )
244{
245 std::lock_guard<std::mutex> lock( mutex_resolver );
246
247 if( aFileName.empty() )
248 return wxEmptyString;
249
250 if( m_paths.empty() )
252
253 // first attempt to use the name as specified:
254 wxString tname = aFileName;
255
256 // Swap separators for non-Windows, in case a Windows path is being passed
257#ifndef __WIN32__
258 tname.Replace( "\\", "/" );
259#endif
260
261 // Note: variable expansion must preferably be performed via a threadsafe wrapper for the
262 // getenv() system call. If we allow the wxFileName::Normalize() routine to perform expansion
263 // then we will have a race condition since wxWidgets does not assure a threadsafe wrapper
264 // for getenv().
265 tname = ExpandEnvVarSubstitutions( tname, m_project );
266
267 // Check to see if the file is a URI for an embedded file.
268 if( tname.StartsWith( FILEEXT::KiCadUriPrefix + "://" ) )
269 {
270 if( aEmbeddedFilesStack.empty() )
271 {
272 wxLogTrace( wxT( "KICAD_EMBED" ),
273 wxT( "No EMBEDDED_FILES object provided for kicad_embed URI" ) );
274 return wxEmptyString;
275 }
276
277 wxString path = tname.Mid( wxString( FILEEXT::KiCadUriPrefix + "://" ).length() );
278
279 // It's a "stack" stored in a std::vector. Search from the back.
280 int ii = (int) aEmbeddedFilesStack.size() - 1;
281 wxFileName temp_file = aEmbeddedFilesStack[ii--]->GetTemporaryFileName( path );
282
283 while( !temp_file.IsOk() && ii >= 0 )
284 temp_file = aEmbeddedFilesStack[ii--]->GetTemporaryFileName( path );
285
286 if( !temp_file.IsOk() )
287 {
288 wxLogTrace( wxT( "KICAD_EMBED" ), wxT( "Failed to get temp file '%s' for kicad_embed URI" ), path );
289 return wxEmptyString;
290 }
291
292 wxLogTrace( wxT( "KICAD_EMBED" ), wxT( "Opening embedded file '%s' as '%s'" ), tname, temp_file.GetFullPath() );
293
294 return temp_file.GetFullPath();
295 }
296
297 wxFileName tmpFN( tname );
298
299 // this case covers full paths, leading expanded vars, and paths relative to the current
300 // working directory (which is not necessarily the current project directory)
301 if( tmpFN.FileExists() )
302 {
303 tmpFN.Normalize( FN_NORMALIZE_FLAGS );
304 tname = tmpFN.GetFullPath();
305
306 // special case: if a path begins with ${ENV_VAR} but is not in the resolver's path list
307 // then add it.
308 if( aFileName.StartsWith( wxS( "${" ) ) || aFileName.StartsWith( wxS( "$(" ) ) )
309 checkEnvVarPath( aFileName );
310
311 return tname;
312 }
313
314 // if a path begins with ${ENV_VAR}/$(ENV_VAR) and is not resolved then either the ENV_VAR is
315 // not defined, or this is a user-defined alias that was incorrectly stored in ${} format by
316 // older versions of KiCad. Try to match against user-defined aliases before giving up.
317 if( aFileName.StartsWith( "${" ) || aFileName.StartsWith( "$(" ) )
318 {
319 // If expansion left the string unchanged, the variable was not found in the environment.
320 // Try matching the variable name against user-defined (non-env-var) aliases in m_paths.
321 if( tname == aFileName )
322 {
323 bool useBrace = aFileName.StartsWith( "${" );
324 size_t aliasEnd = aFileName.find( useBrace ? '}' : ')' );
325
326 // Require a non-empty variable name (aliasEnd > 2) so ${} / $() fall through.
327 if( aliasEnd != wxString::npos && aliasEnd > 2 )
328 {
329 wxString alias = aFileName.substr( 2, aliasEnd - 2 );
330
331 // Skip the separator if present
332 size_t relStart = aliasEnd + 1;
333
334 if( relStart < aFileName.length()
335 && ( aFileName[relStart] == '/' || aFileName[relStart] == '\\' ) )
336 {
337 relStart++;
338 }
339
340 wxString relpath;
341
342 if( relStart < aFileName.length() )
343 relpath = aFileName.substr( relStart );
344
345 for( const SEARCH_PATH& path : m_paths )
346 {
347 if( path.m_Alias.StartsWith( wxS( "${" ) ) || path.m_Alias.StartsWith( wxS( "$(" ) ) )
348 continue;
349
350 if( path.m_Alias == alias && !path.m_Pathexp.empty() )
351 {
352 wxFileName fpath( wxFileName::DirName( path.m_Pathexp ) );
353 wxString fullPath = fpath.GetPathWithSep() + relpath;
354
355 fullPath = ExpandEnvVarSubstitutions( fullPath, m_project );
356
357 if( wxFileName::FileExists( fullPath ) )
358 {
359 wxFileName tmp( fullPath );
360
361 if( tmp.Normalize( FN_NORMALIZE_FLAGS ) )
362 fullPath = tmp.GetFullPath();
363
364 return fullPath;
365 }
366 }
367 }
368 }
369 }
370
371 if( !( m_errflags & ERRFLG_ENVPATH ) )
372 {
374 wxString errmsg = "[3D File Resolver] No such path; ensure the environment var is "
375 "defined";
376 errmsg.append( "\n" );
377 errmsg.append( tname );
378 errmsg.append( "\n" );
379 wxLogTrace( tracePathsAndFiles, errmsg );
380 }
381
382 return wxEmptyString;
383 }
384
385 // at this point aFileName is:
386 // a. an aliased shortened name or
387 // b. cannot be determined
388
389 // check the path relative to the current project directory;
390 // NB: this is not necessarily the same as the current working directory, which has already
391 // been checked. This case accounts for partial paths which do not contain ${KIPRJMOD}.
392 // This check is performed before checking the path relative to ${KICAD7_3DMODEL_DIR} so that
393 // users can potentially override a model within ${KICAD7_3DMODEL_DIR}.
394 if( !m_paths.begin()->m_Pathexp.empty() && !tname.StartsWith( ":" ) )
395 {
396 tmpFN.Assign( m_paths.begin()->m_Pathexp, "" );
397 wxString fullPath = tmpFN.GetPathWithSep() + tname;
398
399 fullPath = ExpandEnvVarSubstitutions( fullPath, m_project );
400
401 if( wxFileName::FileExists( fullPath ) )
402 {
403 tmpFN.Assign( fullPath );
404 tmpFN.Normalize( FN_NORMALIZE_FLAGS );
405 tname = tmpFN.GetFullPath();
406 return tname;
407 }
408
409 }
410
411 // check path relative to search path
412 if( !aWorkingPath.IsEmpty() && !tname.StartsWith( ":" ) )
413 {
414 wxString tmp = aWorkingPath;
415 tmp.Append( tmpFN.GetPathSeparator() );
416 tmp.Append( tname );
417 tmpFN.Assign( tmp );
418
419 if( tmpFN.MakeAbsolute() && tmpFN.FileExists() )
420 {
421 tname = tmpFN.GetFullPath();
422 return tname;
423 }
424 }
425
426 // check the partial path relative to ${KICAD7_3DMODEL_DIR} (legacy behavior)
427 if( !tname.StartsWith( wxS( ":" ) ) )
428 {
429 wxFileName fpath;
430 wxString fullPath( wxString::Format( wxS( "${%s}" ),
431 ENV_VAR::GetVersionedEnvVarName( wxS( "3DMODEL_DIR" ) ) ) );
432 fullPath.Append( fpath.GetPathSeparator() );
433 fullPath.Append( tname );
434 fullPath = ExpandEnvVarSubstitutions( fullPath, m_project );
435 fpath.Assign( fullPath );
436
437 if( fpath.Normalize( FN_NORMALIZE_FLAGS ) && fpath.FileExists() )
438 {
439 tname = fpath.GetFullPath();
440 return tname;
441 }
442
443 }
444
445 // at this point the filename must contain an alias or else it is invalid
446 wxString alias; // the alias portion of the short filename
447 wxString relpath; // the path relative to the alias
448
449 if( !SplitAlias( tname, alias, relpath ) )
450 {
451 if( !( m_errflags & ERRFLG_RELPATH ) )
452 {
453 // this can happen if the file was intended to be relative to ${KICAD7_3DMODEL_DIR}
454 // but ${KICAD7_3DMODEL_DIR} is not set or is incorrect.
456 wxString errmsg = "[3D File Resolver] No such path";
457 errmsg.append( wxS( "\n" ) );
458 errmsg.append( tname );
459 errmsg.append( wxS( "\n" ) );
460 wxLogTrace( tracePathsAndFiles, errmsg );
461 }
462
463 return wxEmptyString;
464 }
465
466 for( const SEARCH_PATH& path : m_paths )
467 {
468 // ${ENV_VAR} paths have already been checked; skip them
469 if( path.m_Alias.StartsWith( wxS( "${" ) ) || path.m_Alias.StartsWith( wxS( "$(" ) ) )
470 continue;
471
472 if( path.m_Alias == alias && !path.m_Pathexp.empty() )
473 {
474 wxFileName fpath( wxFileName::DirName( path.m_Pathexp ) );
475 wxString fullPath = fpath.GetPathWithSep() + relpath;
476
477 fullPath = ExpandEnvVarSubstitutions( fullPath, m_project );
478
479 if( wxFileName::FileExists( fullPath ) )
480 {
481 tname = fullPath;
482
483 wxFileName tmp( fullPath );
484
485 if( tmp.Normalize( FN_NORMALIZE_FLAGS ) )
486 tname = tmp.GetFullPath();
487
488 return tname;
489 }
490 }
491 }
492
493 if( !( m_errflags & ERRFLG_ALIAS ) )
494 {
496 wxString errmsg = "[3D File Resolver] No such path; ensure the path alias is defined";
497 errmsg.append( "\n" );
498 errmsg.append( tname.substr( 1 ) );
499 errmsg.append( "\n" );
500 wxLogTrace( tracePathsAndFiles, errmsg );
501 }
502
503 return wxEmptyString;
504}
505
506
508{
509 if( aPath.m_Alias.empty() || aPath.m_Pathvar.empty() )
510 return false;
511
512 std::lock_guard<std::mutex> lock( mutex_resolver );
513
514 SEARCH_PATH tpath = aPath;
515
516 #ifdef _WIN32
517 while( tpath.m_Pathvar.EndsWith( wxT( "\\" ) ) )
518 tpath.m_Pathvar.erase( tpath.m_Pathvar.length() - 1 );
519 #else
520 while( tpath.m_Pathvar.EndsWith( wxT( "/" ) ) && tpath.m_Pathvar.length() > 1 )
521 tpath.m_Pathvar.erase( tpath.m_Pathvar.length() - 1 );
522 #endif
523
524 wxFileName path( ExpandEnvVarSubstitutions( tpath.m_Pathvar, m_project ), "" );
525
526 path.Normalize( FN_NORMALIZE_FLAGS );
527
528 if( !path.DirExists() )
529 {
530 wxString versionedPath = wxString::Format( wxS( "${%s}" ),
531 ENV_VAR::GetVersionedEnvVarName( wxS( "3DMODEL_DIR" ) ) );
532
533 if( aPath.m_Pathvar == versionedPath
534 || aPath.m_Pathvar == wxS( "${KIPRJMOD}" ) || aPath.m_Pathvar == wxS( "$(KIPRJMOD)" )
535 || aPath.m_Pathvar == wxS( "${KISYS3DMOD}" )
536 || aPath.m_Pathvar == wxS( "$(KISYS3DMOD)" ) )
537 {
538 // suppress the message if the missing pathvar is a system variable
539 }
540 else
541 {
542 wxString msg = _( "The given path does not exist" );
543 msg.append( wxT( "\n" ) );
544 msg.append( tpath.m_Pathvar );
545 DisplayErrorMessage( nullptr, msg );
546 }
547
548 tpath.m_Pathexp.clear();
549 }
550 else
551 {
552 tpath.m_Pathexp = path.GetFullPath();
553
554#ifdef _WIN32
555 while( tpath.m_Pathexp.EndsWith( wxT( "\\" ) ) )
556 tpath.m_Pathexp.erase( tpath.m_Pathexp.length() - 1 );
557#else
558 while( tpath.m_Pathexp.EndsWith( wxT( "/" ) ) && tpath.m_Pathexp.length() > 1 )
559 tpath.m_Pathexp.erase( tpath.m_Pathexp.length() - 1 );
560#endif
561 }
562
563 std::list< SEARCH_PATH >::iterator sPL = m_paths.begin();
564 std::list< SEARCH_PATH >::iterator ePL = m_paths.end();
565
566 while( sPL != ePL )
567 {
568 if( tpath.m_Alias == sPL->m_Alias )
569 {
570 wxString msg = _( "Alias: " );
571 msg.append( tpath.m_Alias );
572 msg.append( wxT( "\n" ) );
573 msg.append( _( "This path:" ) + wxS( " " ) );
574 msg.append( tpath.m_Pathvar );
575 msg.append( wxT( "\n" ) );
576 msg.append( _( "Existing path:" ) + wxS( " " ) );
577 msg.append( sPL->m_Pathvar );
578 DisplayErrorMessage( nullptr, _( "Bad alias (duplicate name)" ), msg );
579 return false;
580 }
581
582 ++sPL;
583 }
584
585 m_paths.push_back( tpath );
586 return true;
587}
588
589
590void FILENAME_RESOLVER::checkEnvVarPath( const wxString& aPath )
591{
592 bool useParen = false;
593
594 if( aPath.StartsWith( wxS( "$(" ) ) )
595 useParen = true;
596 else if( !aPath.StartsWith( wxS( "${" ) ) )
597 return;
598
599 size_t pEnd;
600
601 if( useParen )
602 pEnd = aPath.find( wxS( ")" ) );
603 else
604 pEnd = aPath.find( wxS( "}" ) );
605
606 if( pEnd == wxString::npos )
607 return;
608
609 wxString envar = aPath.substr( 0, pEnd + 1 );
610
611 // check if the alias exists; if not then add it to the end of the
612 // env var section of the path list
613 auto sPL = m_paths.begin();
614 auto ePL = m_paths.end();
615
616 while( sPL != ePL )
617 {
618 if( sPL->m_Alias == envar )
619 return;
620
621 if( !sPL->m_Alias.StartsWith( wxS( "${" ) ) )
622 break;
623
624 ++sPL;
625 }
626
627 SEARCH_PATH lpath;
628 lpath.m_Alias = envar;
629 lpath.m_Pathvar = lpath.m_Alias;
630 wxFileName tmpFN( ExpandEnvVarSubstitutions( lpath.m_Alias, m_project ), "" );
631
632 wxUniChar psep = tmpFN.GetPathSeparator();
633 tmpFN.Normalize( FN_NORMALIZE_FLAGS );
634
635 if( !tmpFN.DirExists() )
636 return;
637
638 lpath.m_Pathexp = tmpFN.GetFullPath();
639
640 if( !lpath.m_Pathexp.empty() && psep == *lpath.m_Pathexp.rbegin() )
641 lpath.m_Pathexp.erase( --lpath.m_Pathexp.end() );
642
643 if( lpath.m_Pathexp.empty() )
644 return;
645
646 m_paths.insert( sPL, lpath );
647}
648
649
650wxString FILENAME_RESOLVER::ShortenPath( const wxString& aFullPathName )
651{
652 wxString fname = aFullPathName;
653
654 if( m_paths.empty() )
656
657 std::lock_guard<std::mutex> lock( mutex_resolver );
658
659 std::list< SEARCH_PATH >::const_iterator sL = m_paths.begin();
660 size_t idx;
661
662 while( sL != m_paths.end() )
663 {
664 // undefined paths do not participate in the
665 // file name shortening procedure
666 if( sL->m_Pathexp.empty() )
667 {
668 ++sL;
669 continue;
670 }
671
672 wxFileName fpath;
673
674 // in the case of aliases, ensure that we use the most recent definition
675 if( sL->m_Alias.StartsWith( wxS( "${" ) ) || sL->m_Alias.StartsWith( wxS( "$(" ) ) )
676 {
677 wxString tpath = ExpandEnvVarSubstitutions( sL->m_Alias, m_project );
678
679 if( tpath.empty() )
680 {
681 ++sL;
682 continue;
683 }
684
685 fpath.Assign( tpath, wxT( "" ) );
686 }
687 else
688 {
689 fpath.Assign( sL->m_Pathexp, wxT( "" ) );
690 }
691
692 wxString fps = fpath.GetPathWithSep();
693 wxString tname;
694
695 idx = fname.find( fps );
696
697 if( idx == 0 )
698 {
699 fname = fname.substr( fps.size() );
700
701 #ifdef _WIN32
702 // ensure only the '/' separator is used in the internal name
703 fname.Replace( wxT( "\\" ), wxT( "/" ) );
704 #endif
705
706 if( sL->m_Alias.StartsWith( wxS( "${" ) ) || sL->m_Alias.StartsWith( wxS( "$(" ) ) )
707 {
708 // old style ENV_VAR
709 tname = sL->m_Alias;
710 tname.Append( wxS( "/" ) );
711 tname.append( fname );
712 }
713 else
714 {
715 // user-defined alias: use ${alias}/path format
716 tname = wxS( "${" );
717 tname.append( sL->m_Alias );
718 tname.append( wxS( "}/" ) );
719 tname.append( fname );
720 }
721
722 return tname;
723 }
724
725 ++sL;
726 }
727
728#ifdef _WIN32
729 // it is strange to convert an MSWin full path to use the
730 // UNIX separator but this is done for consistency and can
731 // be helpful even when transferring project files from
732 // MSWin to *NIX.
733 fname.Replace( wxT( "\\" ), wxT( "/" ) );
734#endif
735
736 return fname;
737}
738
739
740const std::list< SEARCH_PATH >* FILENAME_RESOLVER::GetPaths() const
741{
742 return &m_paths;
743}
744
745
746bool FILENAME_RESOLVER::SplitAlias( const wxString& aFileName,
747 wxString& anAlias, wxString& aRelPath ) const
748{
749 anAlias.clear();
750 aRelPath.clear();
751
752 size_t searchStart = 0;
753
754 if( aFileName.StartsWith( wxT( ":" ) ) )
755 searchStart = 1;
756
757 size_t tagpos = aFileName.find( wxT( ":" ), searchStart );
758
759 if( tagpos == wxString::npos || tagpos == searchStart )
760 return false;
761
762 if( tagpos + 1 >= aFileName.length() )
763 return false;
764
765 anAlias = aFileName.substr( searchStart, tagpos - searchStart );
766 aRelPath = aFileName.substr( tagpos + 1 );
767
768 return true;
769}
770
771
772bool FILENAME_RESOLVER::ValidateFileName( const wxString& aFileName, bool& hasAlias ) const
773{
774 // Rules:
775 // 1. The generic form of an aliased 3D relative path is:
776 // ALIAS:relative/path
777 // 2. ALIAS is a UTF string excluding wxT( "{}[]()%~<>\"='`;:.,&?/\\|$" )
778 // 3. The relative path must be a valid relative path for the platform
779 // 4. We allow a URI for embedded files, but only if it has a name
780
781 hasAlias = false;
782
783 if( aFileName.empty() )
784 return false;
785
786 if( aFileName.StartsWith( wxT( "file://" ) )
787 || aFileName.StartsWith( FILEEXT::KiCadUriPrefix + "://" ) )
788 {
789 size_t prefixLength = aFileName.StartsWith( wxT( "file://" ) ) ? 7 : 14;
790 if( aFileName.length() > prefixLength && aFileName[prefixLength] != '/' )
791 return true;
792 else
793 return false;
794 }
795
796 wxString filename = aFileName;
797 wxString lpath;
798 size_t aliasStart = aFileName.StartsWith( ':' ) ? 1 : 0;
799 size_t aliasEnd = aFileName.find( ':', aliasStart );
800
801 // ensure that the file separators suit the current platform
802#ifdef __WINDOWS__
803 filename.Replace( wxT( "/" ), wxT( "\\" ) );
804
805 // if we see the :\ pattern then it must be a drive designator
806 if( aliasEnd != wxString::npos )
807 {
808 size_t pos1 = filename.find( wxT( ":\\" ) );
809
810 if( pos1 != wxString::npos && ( pos1 != aliasEnd || pos1 != 1 ) )
811 return false;
812
813 // if we have a drive designator then we have no alias
814 if( pos1 != wxString::npos )
815 aliasEnd = wxString::npos;
816 }
817#else
818 filename.Replace( wxT( "\\" ), wxT( "/" ) );
819#endif
820
821 // names may not end with ':'
822 if( aliasEnd == aFileName.length() -1 )
823 return false;
824
825 if( aliasEnd != wxString::npos )
826 {
827 // ensure the alias component is not empty
828 if( aliasEnd == aliasStart )
829 return false;
830
831 lpath = filename.substr( aliasStart, aliasEnd );
832
833 // check the alias for restricted characters
834 if( wxString::npos != lpath.find_first_of( wxT( "{}[]()%~<>\"='`;:.,&?/\\|$" ) ) )
835 return false;
836
837 hasAlias = true;
838 lpath = aFileName.substr( aliasEnd + 1 );
839 }
840 else
841 {
842 lpath = aFileName;
843
844 // in the case of ${ENV_VAR}|$(ENV_VAR)/path, strip the
845 // environment string before testing
846 aliasEnd = wxString::npos;
847
848 if( aFileName.StartsWith( wxS( "${" ) ) )
849 aliasEnd = aFileName.find( '}' );
850 else if( aFileName.StartsWith( wxS( "$(" ) ) )
851 aliasEnd = aFileName.find( ')' );
852
853 if( aliasEnd != wxString::npos )
854 lpath = aFileName.substr( aliasEnd + 1 );
855
856 }
857
858 // Test for forbidden chars in filenames. Should be wxFileName::GetForbiddenChars()
859 // On MSW, the list returned by wxFileName::GetForbiddenChars() contains separators
860 // '\'and '/' used here because lpath can be a full path.
861 // So remove separators
862 wxString lpath_no_sep = lpath;
863
864#ifdef __WINDOWS__
865 lpath_no_sep.Replace( "/", " " );
866 lpath_no_sep.Replace( "\\", " " );
867
868 // A disk identifier is allowed, and therefore remove its separator
869 if( lpath_no_sep.Length() > 1 && lpath_no_sep[1] == ':' )
870 lpath_no_sep[1] = ' ';
871#endif
872
873 if( wxString::npos != lpath_no_sep.find_first_of( wxFileName::GetForbiddenChars() ) )
874 return false;
875
876 return true;
877}
878
879
880bool FILENAME_RESOLVER::GetKicadPaths( std::list< wxString >& paths ) const
881{
882 paths.clear();
883
884 if( !m_pgm )
885 return false;
886
887 bool hasKisys3D = false;
888
889
890 // iterate over the list of internally defined ENV VARs
891 // and add them to the paths list
892 ENV_VAR_MAP_CITER mS = m_pgm->GetLocalEnvVariables().begin();
893 ENV_VAR_MAP_CITER mE = m_pgm->GetLocalEnvVariables().end();
894
895 while( mS != mE )
896 {
897 // filter out URLs, template directories, and known system paths
898 if( mS->first == wxS( "KICAD_PTEMPLATES" )
899 || mS->first.Matches( wxS( "KICAD*_FOOTPRINT_DIR") ) )
900 {
901 ++mS;
902 continue;
903 }
904
905 if( wxString::npos != mS->second.GetValue().find( wxS( "://" ) ) )
906 {
907 ++mS;
908 continue;
909 }
910
911 //also add the path without the ${} to act as legacy alias support for older files
912 paths.push_back( mS->first );
913
914 if( mS->first.Matches( wxS("KICAD*_3DMODEL_DIR") ) )
915 hasKisys3D = true;
916
917 ++mS;
918 }
919
920 if( !hasKisys3D )
921 paths.emplace_back( ENV_VAR::GetVersionedEnvVarName( wxS( "3DMODEL_DIR" ) ) );
922
923 return true;
924}
bool ValidateFileName(const wxString &aFileName, bool &hasAlias) const
Return true if the given path is a valid aliased relative path.
bool createPathList(void)
Build the path list using available information such as KICAD7_3DMODEL_DIR and the 3d_path_list confi...
wxString ResolvePath(const wxString &aFileName, const wxString &aWorkingPath, std::vector< const EMBEDDED_FILES * > aEmbeddedFilesStack)
Determine the full path of the given file name.
bool addPath(const SEARCH_PATH &aPath)
Check that a path is valid and adds it to the search list.
wxString GetProjectDir() const
bool GetKicadPaths(std::list< wxString > &paths) const
Return a list of path environment variables local to KiCad.
bool Set3DConfigDir(const wxString &aConfigDir)
Set the user's configuration directory for 3D models.
void checkEnvVarPath(const wxString &aPath)
Check the ${ENV_VAR} component of a path and adds it to the resolver's path list if it is not yet in ...
std::list< SEARCH_PATH > m_paths
List of base paths to search from.
void SetProgramBase(PGM_BASE *aBase)
Set a pointer to the application's PGM_BASE instance used to extract the local env vars.
bool SplitAlias(const wxString &aFileName, wxString &anAlias, wxString &aRelPath) const
Return true if the given name contains an alias and populates the string anAlias with the alias and a...
wxString m_configDir
3D configuration directory.
const std::list< SEARCH_PATH > * GetPaths() const
Return a pointer to the internal path list; the items in:load.
bool SetProject(const PROJECT *aProject, bool *flgChanged=nullptr)
Set the current KiCad project directory as the first entry in the model path list.
const PROJECT * m_project
bool UpdatePathList(const std::vector< SEARCH_PATH > &aPathList)
Clear the current path list and substitutes the given path list and update the path configuration fil...
wxString ShortenPath(const wxString &aFullPathName)
Produce a relative path based on the existing search directories or returns the same path if the path...
Container for data for KiCad programs.
Definition pgm_base.h:102
Container for project specific data.
Definition project.h:63
virtual const wxString GetProjectPath() const
Return the full path of the project.
Definition project.cpp:277
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject, bool aAllowEscapes)
Replace any environment variable & text variable references with their values.
Definition common.cpp:777
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
This file is part of the common library.
#define _(s)
Functions related to environment variables, including help functions.
#define ERRFLG_RELPATH
static std::mutex mutex_resolver
#define ERRFLG_ENVPATH
#define MASK_3D_RESOLVER
#define ERRFLG_ALIAS
static const std::string KiCadUriPrefix
const wxChar *const tracePathsAndFiles
Flag to enable path and file name debug output.
std::map< wxString, ENV_VAR_ITEM >::const_iterator ENV_VAR_MAP_CITER
KICOMMON_API wxString GetVersionedEnvVarName(const wxString &aBaseName)
Construct a versioned environment variable based on this KiCad major version.
Definition env_vars.cpp:79
see class PGM_BASE
wxString m_Pathvar
Base path as stored in the configuration file.
wxString m_Pathexp
Expanded base path.
wxString m_Alias
Alias to the base path.
std::string path
wxLogTrace helper definitions.
#define FN_NORMALIZE_FLAGS
Default flags to pass to wxFileName::Normalize().
Definition wx_filename.h:35