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