KiCad PCB EDA Suite
Loading...
Searching...
No Matches
remote_symbol_import_utils.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 The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation; either version 3 of the License, or (at your
9 * option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program. If not, see <https://www.gnu.org/licenses/>.
18 */
19
21
22#include <common.h>
23#include <eeschema_settings.h>
24#include <io/io_mgr.h>
25#include <lib_symbol.h>
28#include <pgm_base.h>
30#include <sch_edit_frame.h>
31#include <sch_io/sch_io.h>
32#include <sch_io/sch_io_mgr.h>
33#include <sch_symbol.h>
35#include <tool/tool_manager.h>
36#include <tools/sch_actions.h>
37
38#include <wx/ffile.h>
39#include <wx/filefn.h>
40#include <wx/intl.h>
41
42
43wxString SanitizeRemoteFileComponent( const wxString& aValue, const wxString& aDefault, bool aLower )
44{
45 wxString result = aValue;
46 result.Trim( true ).Trim( false );
47
48 if( result.IsEmpty() )
49 result = aDefault;
50
51 for( size_t i = 0; i < result.length(); ++i )
52 {
53 const wxUniChar ch = result[i];
54
55 if( !( wxIsalnum( ch ) || ch == '_' || ch == '-' || ch == '.' ) )
56 result[i] = '_';
57 }
58
59 return aLower ? result.Lower() : result;
60}
61
62
64{
66 wxString prefix = settings ? settings->m_RemoteSymbol.library_prefix : wxString();
67
68 if( prefix.IsEmpty() )
70
71 return SanitizeRemoteFileComponent( prefix, wxS( "remote" ), true );
72}
73
74
75bool WriteRemoteBinaryFile( const wxFileName& aOutput, const std::vector<uint8_t>& aPayload,
76 wxString& aError )
77{
78 if( aPayload.empty() )
79 {
80 aError = _( "Payload was empty." );
81 return false;
82 }
83
84 wxFileName targetDir = aOutput;
85 targetDir.SetFullName( wxEmptyString );
86
87 if( !targetDir.DirExists() && !targetDir.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
88 {
89 aError = wxString::Format( _( "Unable to create '%s'." ), targetDir.GetFullPath() );
90 return false;
91 }
92
93 wxFFile file( aOutput.GetFullPath(), wxS( "wb" ) );
94
95 if( !file.IsOpened() )
96 {
97 aError = wxString::Format( _( "Unable to open '%s' for writing." ), aOutput.GetFullPath() );
98 return false;
99 }
100
101 if( file.Write( aPayload.data(), aPayload.size() ) != aPayload.size() )
102 {
103 aError = wxString::Format( _( "Failed to write '%s'." ), aOutput.GetFullPath() );
104 return false;
105 }
106
107 file.Close();
108 return true;
109}
110
111
112bool EnsureRemoteDestinationRoot( wxFileName& aOutDir, wxString& aError )
113{
115
116 if( !settings )
117 {
118 aError = _( "Unable to load schematic settings." );
119 return false;
120 }
121
122 wxString destination = settings->m_RemoteSymbol.destination_dir;
123
124 if( destination.IsEmpty() )
126
127 destination = ExpandEnvVarSubstitutions( destination, &Pgm().GetSettingsManager().Prj() );
128 destination.Trim( true ).Trim( false );
129
130 if( destination.IsEmpty() )
131 {
132 aError = _( "Destination directory is not configured." );
133 return false;
134 }
135
136 wxFileName dir = wxFileName::DirName( destination );
137 dir.Normalize( FN_NORMALIZE_FLAGS );
138
139 if( !dir.DirExists() && !dir.Mkdir( wxS_DIR_DEFAULT, wxPATH_MKDIR_FULL ) )
140 {
141 aError = wxString::Format( _( "Unable to create directory '%s'." ), dir.GetFullPath() );
142 return false;
143 }
144
145 aOutDir = dir;
146 return true;
147}
148
149
150bool EnsureRemoteLibraryEntry( LIBRARY_TABLE_TYPE aTableType, const wxFileName& aLibraryPath,
151 const wxString& aNickname, bool aGlobalTable, bool aStrict,
152 wxString& aError )
153{
155 std::optional<LIBRARY_TABLE*> tableOpt = manager.Table(
156 aTableType,
158
159 if( !tableOpt )
160 {
161 if( aStrict )
162 aError = _( "Unable to access the library table." );
163
164 return !aStrict;
165 }
166
167 LIBRARY_TABLE* table = *tableOpt;
168 const wxString fullPath = aLibraryPath.GetFullPath();
169
170 if( table->HasRow( aNickname ) )
171 {
172 if( std::optional<LIBRARY_TABLE_ROW*> rowOpt = table->Row( aNickname ); rowOpt )
173 {
174 LIBRARY_TABLE_ROW* row = *rowOpt;
175
176 if( row->URI() != fullPath )
177 {
178 row->SetURI( fullPath );
179
180 if( !table->Save() )
181 {
182 aError = _( "Failed to update the library table." );
183 return false;
184 }
185 }
186 }
187
188 return true;
189 }
190
191 LIBRARY_TABLE_ROW& row = table->InsertRow();
192 row.SetNickname( aNickname );
193 row.SetURI( fullPath );
194 row.SetType( wxS( "KiCad" ) );
195 row.SetOptions( wxString() );
196 row.SetDescription( _( "Remote download" ) );
197 row.SetOk( true );
198
199 if( !table->Save() )
200 {
201 aError = _( "Failed to save the library table." );
202 return false;
203 }
204
205 return true;
206}
207
208
209bool SaveRemoteSymbolToLibrary( SYMBOL_LIBRARY_ADAPTER& aAdapter, const wxFileName& aLibraryFile,
210 const wxString& aNickname, bool aGlobalTable,
211 std::unique_ptr<LIB_SYMBOL> aSymbol, wxString& aError )
212{
213 if( !EnsureRemoteLibraryEntry( LIBRARY_TABLE_TYPE::SYMBOL, aLibraryFile, aNickname, aGlobalTable, true,
214 aError ) )
215 {
216 return false;
217 }
218
219 // The sexpr plugin refuses to save into a library file that does not exist yet
220 if( !aLibraryFile.FileExists() && !aAdapter.CreateLibrary( aNickname ) )
221 {
222 aError = wxString::Format( _( "Unable to create '%s'." ), aLibraryFile.GetFullPath() );
223 return false;
224 }
225
226 if( aAdapter.SaveSymbol( aNickname, std::move( aSymbol ), true ) != SYMBOL_LIBRARY_ADAPTER::SAVE_OK )
227 {
228 aError = _( "Unable to save the downloaded symbol." );
229 return false;
230 }
231
233
234 // Without the load the library stays in LOADING state and placement cannot see the symbol
236 aAdapter.LoadOne( aNickname );
237
238 return true;
239}
240
241
242bool PlaceRemoteDownloadedSymbol( SCH_EDIT_FRAME* aFrame, const wxString& aNickname,
243 const wxString& aLibItemName, wxString& aError )
244{
245 if( !aFrame )
246 {
247 aError = _( "No schematic editor is available for placement." );
248 return false;
249 }
250
251 LIB_ID libId;
252 libId.SetLibNickname( aNickname );
253 libId.SetLibItemName( aLibItemName );
254
255 LIB_SYMBOL* libSymbol = aFrame->GetLibSymbol( libId );
256
257 if( !libSymbol )
258 {
259 aError = _( "Unable to load the downloaded symbol for placement." );
260 return false;
261 }
262
263 SCH_SYMBOL* symbol = new SCH_SYMBOL( *libSymbol, libId, &aFrame->GetCurrentSheet(), 1 );
264 symbol->SetParent( aFrame->GetScreen() );
265
266 if( EESCHEMA_SETTINGS* cfg = aFrame->eeconfig(); cfg && cfg->m_AutoplaceFields.enable )
267 symbol->AutoplaceFields( nullptr, AUTOPLACE_AUTO );
268
269 TOOL_MANAGER* toolMgr = aFrame->GetToolManager();
270
271 if( !toolMgr )
272 {
273 delete symbol;
274 aError = _( "Unable to access the schematic placement tools." );
275 return false;
276 }
277
278 aFrame->Raise();
280 SCH_ACTIONS::PLACE_SYMBOL_PARAMS{ symbol, true, symbol->IsMultiUnit() } );
281 return true;
282}
283
284
285std::unique_ptr<LIB_SYMBOL> LoadRemoteSymbolFromPayload( const std::vector<uint8_t>& aPayload,
286 const wxString& aLibItemName,
287 wxString& aError )
288{
289 if( aPayload.empty() )
290 {
291 aError = _( "Symbol payload was empty." );
292 return nullptr;
293 }
294
295 wxString tempPath = wxFileName::CreateTempFileName( wxS( "remote_symbol" ) );
296
297 if( tempPath.IsEmpty() )
298 {
299 aError = _( "Unable to create a temporary file for the symbol payload." );
300 return nullptr;
301 }
302
303 wxFileName tempFile( tempPath );
304 wxFFile file( tempFile.GetFullPath(), wxS( "wb" ) );
305
306 if( !file.IsOpened() )
307 {
308 aError = _( "Unable to create a temporary file for the symbol payload." );
309 wxRemoveFile( tempFile.GetFullPath() );
310 return nullptr;
311 }
312
313 if( file.Write( aPayload.data(), aPayload.size() ) != aPayload.size() )
314 {
315 aError = _( "Failed to write the temporary symbol payload." );
316 file.Close();
317 wxRemoveFile( tempFile.GetFullPath() );
318 return nullptr;
319 }
320
321 file.Close();
322
323 IO_RELEASER<SCH_IO> plugin( SCH_IO_MGR::FindPlugin( SCH_IO_MGR::SCH_KICAD ) );
324
325 if( !plugin )
326 {
327 aError = _( "Unable to access the KiCad symbol plugin." );
328 wxRemoveFile( tempFile.GetFullPath() );
329 return nullptr;
330 }
331
332 std::unique_ptr<LIB_SYMBOL> symbol;
333
334 try
335 {
336 LIB_SYMBOL* loaded = plugin->LoadSymbol( tempFile.GetFullPath(), aLibItemName );
337
338 if( loaded )
339 symbol = std::make_unique<LIB_SYMBOL>( *loaded );
340 else
341 aError = _( "Symbol payload did not include the expected symbol." );
342 }
343 catch( const IO_ERROR& e )
344 {
345 aError = wxString::Format( _( "Unable to decode the symbol payload: %s" ), e.What() );
346 }
347
348 wxRemoveFile( tempFile.GetFullPath() );
349 return symbol;
350}
351
352
353LIB_ID BuildRemoteLibId( const wxString& aResolvedLibrary, const wxString& aResolvedItemName )
354{
355 const wxString nickname =
356 RemoteLibraryPrefix() + wxS( "_" )
357 + SanitizeRemoteFileComponent( aResolvedLibrary, wxS( "footprints" ), true );
358
359 const wxString itemName = SanitizeRemoteFileComponent( aResolvedItemName, wxS( "footprint" ) );
360
361 LIB_ID id;
362 id.SetLibNickname( nickname );
363 id.SetLibItemName( itemName );
364 return id;
365}
366
367
368void ApplyFootprintLinks( LIB_SYMBOL& aSymbol, const std::vector<LIB_ID>& aLinks )
369{
370 if( aLinks.empty() )
371 return;
372
373 aSymbol.SetFootprintProp( aLinks.front().GetUniStringLibId() );
374
375 if( aLinks.size() == 1 )
376 return;
377
378 wxArrayString filters = aSymbol.GetFPFilters();
379
380 for( size_t i = 1; i < aLinks.size(); ++i )
381 filters.Add( aLinks[i].GetUniStringLibItemName() );
382
383 aSymbol.SetFPFilters( filters );
384}
virtual void SetParent(EDA_ITEM *aParent)
Definition eda_item.cpp:153
REMOTE_PROVIDER_SETTINGS m_RemoteSymbol
AUTOPLACE_FIELDS m_AutoplaceFields
Hold an error message and may be used when throwing exceptions containing meaningful error messages.
virtual const wxString What() const
A composite of Problem() and Where()
bool CreateLibrary(const wxString &aNickname)
Creates the library (i.e. saves to disk) for the given row if it exists.
void ReloadLibraryEntry(LIBRARY_TABLE_TYPE aType, const wxString &aNickname, LIBRARY_TABLE_SCOPE aScope=LIBRARY_TABLE_SCOPE::BOTH)
std::optional< LIBRARY_TABLE * > Table(LIBRARY_TABLE_TYPE aType, LIBRARY_TABLE_SCOPE aScope)
Retrieves a given table; creating a new empty project table if a valid project is loaded and the give...
void SetOptions(const wxString &aOptions)
void SetNickname(const wxString &aNickname)
void SetOk(bool aOk=true)
void SetType(const wxString &aType)
void SetDescription(const wxString &aDescription)
void SetURI(const wxString &aUri)
const wxString & URI() const
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
int SetLibItemName(const UTF8 &aLibItemName)
Override the library item name portion of the LIB_ID to aLibItemName.
Definition lib_id.cpp:124
int SetLibNickname(const UTF8 &aLibNickname)
Override the logical library name portion of the LIB_ID to aLibNickname.
Definition lib_id.cpp:113
Define a library symbol object.
Definition lib_symbol.h:119
wxArrayString GetFPFilters() const
Definition lib_symbol.h:247
void SetFootprintProp(const wxString &aFootprint)
Definition lib_symbol.h:497
void SetFPFilters(const wxArrayString &aFilters)
Definition lib_symbol.h:245
virtual LIBRARY_MANAGER & GetLibraryManager() const
Definition pgm_base.h:125
static TOOL_ACTION placeSymbol
Definition sch_actions.h:71
EESCHEMA_SETTINGS * eeconfig() const
LIB_SYMBOL * GetLibSymbol(const LIB_ID &aLibId, bool aUseCacheLib=false, bool aShowErrorMsg=false)
Load symbol from symbol library table.
Schematic editor (Eeschema) main window.
SCH_SCREEN * GetScreen() const override
Return a pointer to a BASE_SCREEN or one of its derivatives.
SCH_SHEET_PATH & GetCurrentSheet() const
Schematic symbol object.
Definition sch_symbol.h:75
void AutoplaceFields(SCH_SCREEN *aScreen, AUTOPLACE_ALGO aAlgo) override
Automatically orient all the fields in the symbol.
bool IsMultiUnit() const override
Definition sch_symbol.h:256
An interface to the global shared library manager that is schematic-specific and linked to one projec...
std::optional< LIB_STATUS > LoadOne(LIB_DATA *aLib) override
Loads or reloads the given library, if it exists.
SAVE_T SaveSymbol(const wxString &aNickname, std::unique_ptr< LIB_SYMBOL > aSymbol, bool aOverwrite=true)
Write aSymbol to an existing library given by aNickname.
TOOL_MANAGER * GetToolManager() const
Return the MVC controller.
Master controller class:
bool PostAction(const std::string &aActionName, T aParam)
Run the specified action after the current action (coroutine) ends.
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject)
Replace any environment variable & text variable references with their values.
Definition common.cpp:776
#define _(s)
std::unique_ptr< T > IO_RELEASER
Helper to hold and release an IO_BASE object when exceptions are thrown.
Definition io_mgr.h:33
PROJECT & Prj()
Definition kicad.cpp:727
LIBRARY_TABLE_TYPE
LIBRARY_TABLE_SCOPE
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
void ApplyFootprintLinks(LIB_SYMBOL &aSymbol, const std::vector< LIB_ID > &aLinks)
Apply a list of footprint LIB_IDs to a symbol about to be saved.
std::unique_ptr< LIB_SYMBOL > LoadRemoteSymbolFromPayload(const std::vector< uint8_t > &aPayload, const wxString &aLibItemName, wxString &aError)
Deserialize a remote-downloaded symbol payload into a LIB_SYMBOL.
LIB_ID BuildRemoteLibId(const wxString &aResolvedLibrary, const wxString &aResolvedItemName)
Build the local LIB_ID for a remote-downloaded library item.
bool PlaceRemoteDownloadedSymbol(SCH_EDIT_FRAME *aFrame, const wxString &aNickname, const wxString &aLibItemName, wxString &aError)
Place a symbol from a remote download into the schematic editor.
bool EnsureRemoteLibraryEntry(LIBRARY_TABLE_TYPE aTableType, const wxFileName &aLibraryPath, const wxString &aNickname, bool aGlobalTable, bool aStrict, wxString &aError)
Add or update a library table entry for a remote download library.
bool WriteRemoteBinaryFile(const wxFileName &aOutput, const std::vector< uint8_t > &aPayload, wxString &aError)
Write binary data to a file, creating parent directories as needed.
bool SaveRemoteSymbolToLibrary(SYMBOL_LIBRARY_ADAPTER &aAdapter, const wxFileName &aLibraryFile, const wxString &aNickname, bool aGlobalTable, std::unique_ptr< LIB_SYMBOL > aSymbol, wxString &aError)
Save a downloaded symbol into the remote symbol library aNickname backed by aLibraryFile.
bool EnsureRemoteDestinationRoot(wxFileName &aOutDir, wxString &aError)
Resolve and create the configured destination root directory for remote symbol downloads.
wxString RemoteLibraryPrefix()
Return the configured (or default) library prefix for remote downloads, sanitized for use as a filena...
wxString SanitizeRemoteFileComponent(const wxString &aValue, const wxString &aDefault, bool aLower)
Replace non-alphanumeric characters (other than _ - .) with underscores.
@ AUTOPLACE_AUTO
Definition sch_item.h:70
T * GetAppSettings(const char *aFilename)
wxString result
Test unit parsing edge cases and error handling.
#define FN_NORMALIZE_FLAGS
Default flags to pass to wxFileName::Normalize().
Definition wx_filename.h:35