KiCad PCB EDA Suite
Loading...
Searching...
No Matches
project_file.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) 2020 CERN
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 * @author Jon Evans <[email protected]>
7 *
8 * This program is free software: you can redistribute it and/or modify it
9 * under the terms of the GNU General Public License as published by the
10 * Free Software Foundation, either version 3 of the License, or (at your
11 * option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful, but
14 * WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
16 * 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, see <https://www.gnu.org/licenses/>.
20 */
21
22#include <project.h>
31#include <settings/parameters.h>
34#include <wx/config.h>
35#include <wx/filename.h>
36#include <wx/log.h>
37
38
41
42
43PROJECT_FILE::PROJECT_FILE( const wxString& aFullPath ) :
45 m_ErcSettings( nullptr ),
46 m_SchematicSettings( nullptr ),
48 m_sheets(),
50 m_boards(),
51 m_project( nullptr ),
52 m_wasMigrated( false ),
54{
55 // Keep old files around
57
58 m_params.emplace_back( new PARAM_LIST<FILE_INFO_PAIR>( "sheets", &m_sheets, {} ) );
59
60 m_params.emplace_back( new PARAM_LIST<TOP_LEVEL_SHEET_INFO>( "schematic.top_level_sheets",
61 &m_topLevelSheets, {} ) );
62
63 m_params.emplace_back( new PARAM_LIST<FILE_INFO_PAIR>( "boards", &m_boards, {} ) );
64
65 m_params.emplace_back( new PARAM_WXSTRING_MAP( "text_variables",
66 &m_TextVars, {}, false, true /* array behavior, even though stored as a map */ ) );
67
68 m_params.emplace_back( new PARAM_LAMBDA<nlohmann::json>(
69 "schematic.drawing.field_names",
70 [&]() -> nlohmann::json
71 {
72 nlohmann::json ret = nlohmann::json::array();
73
74 for( const TEMPLATE_FIELDNAME& field :
75 m_TemplateFieldNames.GetTemplateFieldNames( TEMPLATES::SCOPE::PROJECT ) )
76 {
77 ret.push_back( nlohmann::json( {
78 { "name", field.m_Name },
79 { "visible", field.m_Visible },
80 { "url", field.m_URL }
81 } ) );
82 }
83
84 return ret;
85 },
86 [&]( const nlohmann::json& aJson )
87 {
88 if( aJson.is_string() )
89 {
90 m_TemplateFieldNames.DeleteFieldNameTemplates( TEMPLATES::SCOPE::PROJECT );
91 m_TemplateFieldNames.AddTemplateFieldNames( wxString::FromUTF8( aJson.get<std::string>() ),
92 TEMPLATES::SCOPE::PROJECT );
93 }
94 else if( aJson.is_array() )
95 {
96 m_TemplateFieldNames.DeleteFieldNameTemplates( TEMPLATES::SCOPE::PROJECT );
97
98 for( const nlohmann::json& entry : aJson )
99 {
100 if( entry.contains( "name" ) && entry.contains( "url" )
101 && entry.contains( "visible" ) )
102 {
103 TEMPLATE_FIELDNAME field( entry["name"].get<wxString>() );
104 field.m_URL = entry["url"].get<bool>();
105 field.m_Visible = entry["visible"].get<bool>();
106 m_TemplateFieldNames.AddTemplateFieldName( field, TEMPLATES::SCOPE::PROJECT );
107 }
108 }
109 }
110 },
111 {} ) );
112
113 m_params.emplace_back( new PARAM_LIST<wxString>( "libraries.pinned_symbol_libs",
114 &m_PinnedSymbolLibs, {} ) );
115
116 m_params.emplace_back( new PARAM_LIST<wxString>( "libraries.pinned_footprint_libs",
117 &m_PinnedFootprintLibs, {} ) );
118
119 m_params.emplace_back( new PARAM_LIST<wxString>( "libraries.pinned_design_block_libs",
121
122 m_params.emplace_back(
123 new PARAM_LIST<wxString>( "pcbnew.find_by_properties.recent_queries", &m_FindByPropertiesQueries, {} ) );
124
125 m_params.emplace_back( new PARAM_PATH_LIST( "cvpcb.equivalence_files",
126 &m_EquivalenceFiles, {} ) );
127
128 m_params.emplace_back( new PARAM_PATH( "pcbnew.page_layout_descr_file",
130
131 m_params.emplace_back( new PARAM_PATH( "pcbnew.last_paths.netlist",
133
134 m_params.emplace_back( new PARAM_PATH( "pcbnew.last_paths.idf",
136
137 m_params.emplace_back( new PARAM_PATH( "pcbnew.last_paths.vrml",
139
140 m_params.emplace_back( new PARAM_PATH( "pcbnew.last_paths.specctra_dsn",
142
143 m_params.emplace_back( new PARAM_PATH( "pcbnew.last_paths.plot",
145
146 m_params.emplace_back( new PARAM_PATH( "pcbnew.last_paths.step", &m_PcbLastPath[LAST_PATH_STEP], "" ) );
147
148 m_params.emplace_back( new PARAM<wxString>( "schematic.legacy_lib_dir",
149 &m_LegacyLibDir, "" ) );
150
151 m_params.emplace_back( new PARAM_LAMBDA<nlohmann::json>( "schematic.legacy_lib_list",
152 [&]() -> nlohmann::json
153 {
154 nlohmann::json ret = nlohmann::json::array();
155
156 for( const wxString& libName : m_LegacyLibNames )
157 ret.push_back( libName );
158
159 return ret;
160 },
161 [&]( const nlohmann::json& aJson )
162 {
163 if( aJson.empty() || !aJson.is_array() )
164 return;
165
166 m_LegacyLibNames.clear();
167
168 for( const nlohmann::json& entry : aJson )
169 m_LegacyLibNames.push_back( entry.get<wxString>() );
170 }, {} ) );
171
172 m_params.emplace_back( new PARAM_LAMBDA<nlohmann::json>( "schematic.bus_aliases",
173 [&]() -> nlohmann::json
174 {
175 // A project may be saved before its legacy schematic aliases are imported
176 if( !m_BusAliasesDefined && m_BusAliases.empty() )
177 return nlohmann::json();
178
179 nlohmann::json ret = nlohmann::json::object();
180
181 for( const auto& alias : m_BusAliases )
182 {
183 nlohmann::json members = nlohmann::json::array();
184
185 for( const wxString& member : alias.second )
186 members.push_back( member );
187
188 ret[ alias.first.ToStdString() ] = members;
189 }
190
191 return ret;
192 },
193 [&]( const nlohmann::json& aJson )
194 {
195 m_BusAliasesDefined = aJson.is_object();
196 m_BusAliases.clear();
197
198 if( !aJson.is_object() )
199 return;
200
201 for( auto it = aJson.begin(); it != aJson.end(); ++it )
202 {
203 const nlohmann::json& membersJson = it.value();
204
205 if( !membersJson.is_array() )
206 continue;
207
208 std::vector<wxString> members;
209
210 for( const nlohmann::json& entry : membersJson )
211 {
212 if( entry.is_string() )
213 {
214 wxString member = entry.get<wxString>().Strip( wxString::both );
215
216 if( !member.IsEmpty() )
217 members.push_back( member );
218 }
219 }
220
221 wxString name = wxString::FromUTF8( it.key().c_str() ).Strip( wxString::both );
222
223 if( !name.IsEmpty() )
224 m_BusAliases.emplace( name, std::move( members ) );
225 }
226 }, {} ) );
227
228 // Let the save drop deleted aliases instead of merging them back in
229 m_params.back()->SetClearUnknownKeys();
230
231 m_NetSettings = std::make_shared<NET_SETTINGS>( this, "net_settings" );
232
234 std::make_shared<COMPONENT_CLASS_SETTINGS>( this, "component_class_settings" );
235
236 m_tuningProfileParameters = std::make_shared<TUNING_PROFILES>( this, "tuning_profiles" );
237
238 m_params.emplace_back( new PARAM_LAYER_PRESET( "board.layer_presets", &m_LayerPresets ) );
239
240 m_params.emplace_back( new PARAM_VIEWPORT( "board.viewports", &m_Viewports ) );
241
242 m_params.emplace_back( new PARAM_VIEWPORT3D( "board.3dviewports", &m_Viewports3D ) );
243
244 m_params.emplace_back( new PARAM_LAYER_PAIRS( "board.layer_pairs", m_LayerPairInfos ) );
245
246 m_params.emplace_back( new PARAM<wxString>( "board.ipc2581.internal_id",
247 &m_IP2581Bom.id, wxEmptyString ) );
248
249 m_params.emplace_back( new PARAM<wxString>( "board.ipc2581.mpn",
250 &m_IP2581Bom.MPN, wxEmptyString ) );
251
252 m_params.emplace_back( new PARAM<wxString>( "board.ipc2581.mfg",
253 &m_IP2581Bom.mfg, wxEmptyString ) );
254
255 m_params.emplace_back( new PARAM<wxString>( "board.ipc2581.distpn",
256 &m_IP2581Bom.distPN, wxEmptyString ) );
257
258 m_params.emplace_back( new PARAM<wxString>( "board.ipc2581.dist",
259 &m_IP2581Bom.dist, wxEmptyString ) );
260
261 m_params.emplace_back( new PARAM<wxString>( "board.ipc2581.bom_rev",
262 &m_IP2581Bom.bomRev, wxEmptyString ) );
263
264 m_params.emplace_back( new PARAM<wxString>( "board.ipc2581.sch_revision",
265 &m_IP2581Bom.schRevision, wxEmptyString ) );
266
267 m_params.emplace_back( new PARAM<wxString>( "board.ipc2581.mode",
268 &m_IP2581Bom.mode, wxEmptyString ) );
269
270 // An empty key alone means the mode picks the sections, so the flag marks an empty choice
271 m_params.emplace_back( new PARAM_LAMBDA<nlohmann::json>( "board.ipc2581.sections",
272 [this]() { return nlohmann::json( m_IP2581Bom.sections.value_or( wxString() ) ); },
273 [this]( const nlohmann::json& aVal )
274 {
275 wxString sections = aVal.is_string() ? aVal.get<wxString>() : wxString();
276 m_IP2581Bom.sections = sections.IsEmpty() ? std::nullopt : std::optional<wxString>( sections );
277 },
278 nlohmann::json( "" ) ) );
279
280 m_params.emplace_back( new PARAM_LAMBDA<nlohmann::json>( "board.ipc2581.custom_sections",
281 [this]() { return nlohmann::json( m_IP2581Bom.sections && m_IP2581Bom.sections->IsEmpty() ); },
282 [this]( const nlohmann::json& aVal )
283 {
284 if( aVal.is_boolean() && aVal.get<bool>() && !m_IP2581Bom.sections )
285 m_IP2581Bom.sections = wxString();
286 },
287 nlohmann::json( false ) ) );
288
289 m_params.emplace_back( new PARAM<wxString>( "board.ipc2581.net_names",
290 &m_IP2581Bom.netNames, wxEmptyString ) );
291
292 m_params.emplace_back( new PARAM<wxString>( "board.ipc2581.ref_des",
293 &m_IP2581Bom.refDes, wxEmptyString ) );
294
295 m_params.emplace_back( new PARAM_ENUM<IDF_SETTINGS::UNITS>( "board.idf_export.units",
298
300 "board.idf_export.origin_mode", &m_IdfExportSettings.originMode,
303
304 m_params.emplace_back( new PARAM<double>( "board.idf_export.user_origin_x",
305 &m_IdfExportSettings.userOriginX, 0.0 ) );
306
307 m_params.emplace_back( new PARAM<double>( "board.idf_export.user_origin_y",
308 &m_IdfExportSettings.userOriginY, 0.0 ) );
309
310 m_params.emplace_back( new PARAM<bool>( "board.idf_export.include_unspecified",
311 &m_IdfExportSettings.includeUnspecified, true ) );
312
313 m_params.emplace_back( new PARAM<bool>( "board.idf_export.include_dnp",
314 &m_IdfExportSettings.includeDNP, true ) );
315
316 m_params.emplace_back( new PARAM<bool>( "board.idf_export.calculate_height_from_models",
317 &m_IdfExportSettings.calculateHeightFromModels, true ) );
318
319 m_params.emplace_back( new PARAM<wxString>( "board.idf_export.part_number_field",
320 &m_IdfExportSettings.partNumberField, wxS( "Value" ) ) );
321
322
323 registerMigration( 1, 2, std::bind( &PROJECT_FILE::migrateSchema1To2, this ) );
324 registerMigration( 2, 3, std::bind( &PROJECT_FILE::migrateSchema2To3, this ) );
325 registerMigration( 3, 4, std::bind( &PROJECT_FILE::migrateSchema3To4, this ) );
326}
327
328
330{
331 auto p( "/board/layer_presets"_json_pointer );
332
333 if( !m_internals->contains( p ) || !m_internals->at( p ).is_array() )
334 return true;
335
336 nlohmann::json& presets = m_internals->at( p );
337
338 for( nlohmann::json& entry : presets )
340
341 m_wasMigrated = true;
342
343 return true;
344}
345
346
348{
349 auto p( "/board/layer_presets"_json_pointer );
350
351 if( !m_internals->contains( p ) || !m_internals->at( p ).is_array() )
352 return true;
353
354 nlohmann::json& presets = m_internals->at( p );
355
356 for( nlohmann::json& entry : presets )
358
359 m_wasMigrated = true;
360
361 return true;
362}
363
364
366{
367 const auto aliases = GetJson( "schematic.bus_aliases" );
368
369 if( aliases && aliases->is_object() && aliases->empty() )
370 {
371 // Older project-only saves wrote empty tables before importing legacy sheet aliases
372 Set( "schematic.bus_aliases", nlohmann::json() );
373 m_wasMigrated = true;
374 }
375
376 return true;
377}
378
379
380bool PROJECT_FILE::MigrateFromLegacy( wxConfigBase* aCfg )
381{
382 bool ret = true;
383 wxString str;
384 long index = 0;
385
386 std::set<wxString> group_blacklist;
387
388 // Legacy files don't store board info; they assume board matches project name
389 // We will leave m_boards empty here so it can be populated with other code
390
391 // First handle migration of data that will be stored locally in this object
392
393 auto loadPinnedLibs =
394 [&]( const std::string& aDest )
395 {
396 int libIndex = 1;
397 wxString libKey = wxT( "PinnedItems" );
398 libKey << libIndex;
399
400 nlohmann::json libs = nlohmann::json::array();
401
402 while( aCfg->Read( libKey, &str ) )
403 {
404 libs.push_back( str );
405
406 aCfg->DeleteEntry( libKey, true );
407
408 libKey = wxT( "PinnedItems" );
409 libKey << ++libIndex;
410 }
411
412 Set( aDest, libs );
413 };
414
415 aCfg->SetPath( wxT( "/LibeditFrame" ) );
416 loadPinnedLibs( "libraries.pinned_symbol_libs" );
417
418 aCfg->SetPath( wxT( "/ModEditFrame" ) );
419 loadPinnedLibs( "libraries.pinned_footprint_libs" );
420
421 aCfg->SetPath( wxT( "/cvpcb/equfiles" ) );
422
423 {
424 int eqIdx = 1;
425 wxString eqKey = wxT( "EquName" );
426 eqKey << eqIdx;
427
428 nlohmann::json eqs = nlohmann::json::array();
429
430 while( aCfg->Read( eqKey, &str ) )
431 {
432 eqs.push_back( str );
433
434 eqKey = wxT( "EquName" );
435 eqKey << ++eqIdx;
436 }
437
438 Set( "cvpcb.equivalence_files", eqs );
439 }
440
441 // All CvPcb params that we want to keep have been migrated above
442 group_blacklist.insert( wxT( "/cvpcb" ) );
443
444 aCfg->SetPath( wxT( "/eeschema" ) );
445 fromLegacyString( aCfg, "LibDir", "schematic.legacy_lib_dir" );
446
447 aCfg->SetPath( wxT( "/eeschema/libraries" ) );
448
449 {
450 int libIdx = 1;
451 wxString libKey = wxT( "LibName" );
452 libKey << libIdx;
453
454 nlohmann::json libs = nlohmann::json::array();
455
456 while( aCfg->Read( libKey, &str ) )
457 {
458 libs.push_back( str );
459
460 libKey = wxT( "LibName" );
461 libKey << ++libIdx;
462 }
463
464 Set( "schematic.legacy_lib_list", libs );
465 }
466
467 group_blacklist.insert( wxT( "/eeschema" ) );
468
469 aCfg->SetPath( wxT( "/text_variables" ) );
470
471 {
472 int txtIdx = 1;
473 wxString txtKey;
474 txtKey << txtIdx;
475
476 nlohmann::json vars = nlohmann::json();
477
478 while( aCfg->Read( txtKey, &str ) )
479 {
480 wxArrayString tokens = wxSplit( str, ':' );
481
482 if( tokens.size() == 2 )
483 vars[ tokens[0].ToStdString() ] = tokens[1];
484
485 txtKey.clear();
486 txtKey << ++txtIdx;
487 }
488
489 Set( "text_variables", vars );
490 }
491
492 group_blacklist.insert( wxT( "/text_variables" ) );
493
494 aCfg->SetPath( wxT( "/schematic_editor" ) );
495
496 fromLegacyString( aCfg, "PageLayoutDescrFile", "schematic.page_layout_descr_file" );
497 fromLegacyString( aCfg, "PlotDirectoryName", "schematic.plot_directory" );
498 fromLegacyString( aCfg, "NetFmtName", "schematic.net_format_name" );
499 fromLegacy<bool>( aCfg, "SpiceAjustPassiveValues", "schematic.spice_adjust_passive_values" );
500 fromLegacy<int>( aCfg, "SubpartIdSeparator", "schematic.subpart_id_separator" );
501 fromLegacy<int>( aCfg, "SubpartFirstId", "schematic.subpart_first_id" );
502
503 fromLegacy<int>( aCfg, "LineThickness", "schematic.drawing.default_line_thickness" );
504 fromLegacy<int>( aCfg, "WireThickness", "schematic.drawing.default_wire_thickness" );
505 fromLegacy<int>( aCfg, "BusThickness", "schematic.drawing.default_bus_thickness" );
506 fromLegacy<int>( aCfg, "LabSize", "schematic.drawing.default_text_size" );
507
508 if( !fromLegacy<int>( aCfg, "PinSymbolSize", "schematic.drawing.pin_symbol_size" ) )
509 {
510 // Use the default symbol size algorithm of Eeschema V5 (based on pin name/number size)
511 Set( "schematic.drawing.pin_symbol_size", 0 );
512 }
513
514 fromLegacy<int>( aCfg, "JunctionSize", "schematic.drawing.default_junction_size" );
515
516 fromLegacyString( aCfg, "FieldNameTemplates", "schematic.drawing.field_names" );
517
518 if( !fromLegacy<double>( aCfg, "TextOffsetRatio", "schematic.drawing.text_offset_ratio" ) )
519 {
520 // Use the spacing of Eeschema V5
521 Set( "schematic.drawing.text_offset_ratio", 0.08 );
522 Set( "schematic.drawing.label_size_ratio", 0.25 );
523 }
524
525 // All schematic_editor keys we keep are migrated above
526 group_blacklist.insert( wxT( "/schematic_editor" ) );
527
528 aCfg->SetPath( wxT( "/pcbnew" ) );
529
530 fromLegacyString( aCfg, "PageLayoutDescrFile", "pcbnew.page_layout_descr_file" );
531 fromLegacyString( aCfg, "LastNetListRead", "pcbnew.last_paths.netlist" );
532 fromLegacyString( aCfg, "LastSTEPExportPath", "pcbnew.last_paths.step" );
533 fromLegacyString( aCfg, "LastIDFExportPath", "pcbnew.last_paths.idf" );
534 fromLegacyString( aCfg, "LastVRMLExportPath", "pcbnew.last_paths.vrml" );
535 fromLegacyString( aCfg, "LastSpecctraDSNExportPath", "pcbnew.last_paths.specctra_dsn" );
536 fromLegacyString( aCfg, "LastGenCADExportPath", "pcbnew.last_paths.gencad" );
537
538 std::string bp = "board.design_settings.";
539
540 {
541 int idx = 1;
542 wxString key = wxT( "DRCExclusion" );
543 key << idx;
544
545 nlohmann::json exclusions = nlohmann::json::array();
546
547 while( aCfg->Read( key, &str ) )
548 {
549 exclusions.push_back( str );
550
551 key = wxT( "DRCExclusion" );
552 key << ++idx;
553 }
554
555 Set( bp + "drc_exclusions", exclusions );
556 }
557
558 fromLegacy<bool>( aCfg, "AllowMicroVias", bp + "rules.allow_microvias" );
559 fromLegacy<bool>( aCfg, "AllowBlindVias", bp + "rules.allow_blind_buried_vias" );
560 fromLegacy<double>( aCfg, "MinClearance", bp + "rules.min_clearance" );
561 fromLegacy<double>( aCfg, "MinTrackWidth", bp + "rules.min_track_width" );
562 fromLegacy<double>( aCfg, "MinViaAnnulus", bp + "rules.min_via_annulus" );
563 fromLegacy<double>( aCfg, "MinViaDiameter", bp + "rules.min_via_diameter" );
564
565 if( !fromLegacy<double>( aCfg, "MinThroughDrill", bp + "rules.min_through_hole_diameter" ) )
566 fromLegacy<double>( aCfg, "MinViaDrill", bp + "rules.min_through_hole_diameter" );
567
568 fromLegacy<double>( aCfg, "MinMicroViaDiameter", bp + "rules.min_microvia_diameter" );
569 fromLegacy<double>( aCfg, "MinMicroViaDrill", bp + "rules.min_microvia_drill" );
570 fromLegacy<double>( aCfg, "MinHoleToHole", bp + "rules.min_hole_to_hole" );
571 fromLegacy<double>( aCfg, "CopperEdgeClearance", bp + "rules.min_copper_edge_clearance" );
572 fromLegacy<double>( aCfg, "SolderMaskClearance", bp + "rules.solder_mask_clearance" );
573 fromLegacy<double>( aCfg, "SolderMaskMinWidth", bp + "rules.solder_mask_min_width" );
574 fromLegacy<double>( aCfg, "SolderPasteClearance", bp + "rules.solder_paste_clearance" );
575 fromLegacy<double>( aCfg, "SolderPasteRatio", bp + "rules.solder_paste_margin_ratio" );
576
577 if( !fromLegacy<double>( aCfg, "SilkLineWidth", bp + "defaults.silk_line_width" ) )
578 fromLegacy<double>( aCfg, "ModuleOutlineThickness", bp + "defaults.silk_line_width" );
579
580 if( !fromLegacy<double>( aCfg, "SilkTextSizeV", bp + "defaults.silk_text_size_v" ) )
581 fromLegacy<double>( aCfg, "ModuleTextSizeV", bp + "defaults.silk_text_size_v" );
582
583 if( !fromLegacy<double>( aCfg, "SilkTextSizeH", bp + "defaults.silk_text_size_h" ) )
584 fromLegacy<double>( aCfg, "ModuleTextSizeH", bp + "defaults.silk_text_size_h" );
585
586 if( !fromLegacy<double>( aCfg, "SilkTextSizeThickness", bp + "defaults.silk_text_thickness" ) )
587 fromLegacy<double>( aCfg, "ModuleTextSizeThickness", bp + "defaults.silk_text_thickness" );
588
589 fromLegacy<bool>( aCfg, "SilkTextItalic", bp + "defaults.silk_text_italic" );
590 fromLegacy<bool>( aCfg, "SilkTextUpright", bp + "defaults.silk_text_upright" );
591
592 if( !fromLegacy<double>( aCfg, "CopperLineWidth", bp + "defaults.copper_line_width" ) )
593 fromLegacy<double>( aCfg, "DrawSegmentWidth", bp + "defaults.copper_line_width" );
594
595 if( !fromLegacy<double>( aCfg, "CopperTextSizeV", bp + "defaults.copper_text_size_v" ) )
596 fromLegacy<double>( aCfg, "PcbTextSizeV", bp + "defaults.copper_text_size_v" );
597
598 if( !fromLegacy<double>( aCfg, "CopperTextSizeH", bp + "defaults.copper_text_size_h" ) )
599 fromLegacy<double>( aCfg, "PcbTextSizeH", bp + "defaults.copper_text_size_h" );
600
601 if( !fromLegacy<double>( aCfg, "CopperTextThickness", bp + "defaults.copper_text_thickness" ) )
602 fromLegacy<double>( aCfg, "PcbTextThickness", bp + "defaults.copper_text_thickness" );
603
604 fromLegacy<bool>( aCfg, "CopperTextItalic", bp + "defaults.copper_text_italic" );
605 fromLegacy<bool>( aCfg, "CopperTextUpright", bp + "defaults.copper_text_upright" );
606
607 if( !fromLegacy<double>( aCfg, "EdgeCutLineWidth", bp + "defaults.board_outline_line_width" ) )
608 fromLegacy<double>( aCfg, "BoardOutlineThickness",
609 bp + "defaults.board_outline_line_width" );
610
611 fromLegacy<double>( aCfg, "CourtyardLineWidth", bp + "defaults.courtyard_line_width" );
612
613 fromLegacy<double>( aCfg, "FabLineWidth", bp + "defaults.fab_line_width" );
614 fromLegacy<double>( aCfg, "FabTextSizeV", bp + "defaults.fab_text_size_v" );
615 fromLegacy<double>( aCfg, "FabTextSizeH", bp + "defaults.fab_text_size_h" );
616 fromLegacy<double>( aCfg, "FabTextSizeThickness", bp + "defaults.fab_text_thickness" );
617 fromLegacy<bool>( aCfg, "FabTextItalic", bp + "defaults.fab_text_italic" );
618 fromLegacy<bool>( aCfg, "FabTextUpright", bp + "defaults.fab_text_upright" );
619
620 if( !fromLegacy<double>( aCfg, "OthersLineWidth", bp + "defaults.other_line_width" ) )
621 fromLegacy<double>( aCfg, "ModuleOutlineThickness", bp + "defaults.other_line_width" );
622
623 fromLegacy<double>( aCfg, "OthersTextSizeV", bp + "defaults.other_text_size_v" );
624 fromLegacy<double>( aCfg, "OthersTextSizeH", bp + "defaults.other_text_size_h" );
625 fromLegacy<double>( aCfg, "OthersTextSizeThickness", bp + "defaults.other_text_thickness" );
626 fromLegacy<bool>( aCfg, "OthersTextItalic", bp + "defaults.other_text_italic" );
627 fromLegacy<bool>( aCfg, "OthersTextUpright", bp + "defaults.other_text_upright" );
628
629 fromLegacy<int>( aCfg, "DimensionUnits", bp + "defaults.dimension_units" );
630 fromLegacy<int>( aCfg, "DimensionPrecision", bp + "defaults.dimension_precision" );
631
632 std::string sev = bp + "rule_severities";
633
634 fromLegacy<bool>( aCfg, "RequireCourtyardDefinitions", sev + "legacy_no_courtyard_defined" );
635
636 fromLegacy<bool>( aCfg, "ProhibitOverlappingCourtyards", sev + "legacy_courtyards_overlap" );
637
638 {
639 int idx = 1;
640 wxString keyBase = "TrackWidth";
641 wxString key = keyBase;
642 double val;
643
644 nlohmann::json widths = nlohmann::json::array();
645
646 key << idx;
647
648 while( aCfg->Read( key, &val ) )
649 {
650 widths.push_back( val );
651 key = keyBase;
652 key << ++idx;
653 }
654
655 Set( bp + "track_widths", widths );
656 }
657
658 {
659 int idx = 1;
660 wxString keyBase = "ViaDiameter";
661 wxString key = keyBase;
662 double diameter;
663 double drill;
664
665 nlohmann::json vias = nlohmann::json::array();
666
667 key << idx;
668
669 while( aCfg->Read( key, &diameter ) )
670 {
671 key = "ViaDrill";
672 drill = 1.0;
673 aCfg->Read( key << idx, &drill );
674
675 nlohmann::json via = { { "diameter", diameter }, { "drill", drill } };
676 vias.push_back( via );
677
678 key = keyBase;
679 key << ++idx;
680 }
681
682 Set( bp + "via_dimensions", vias );
683 }
684
685 {
686 int idx = 1;
687 wxString keyBase = "dPairWidth";
688 wxString key = keyBase;
689 double width;
690 double gap;
691 double via_gap;
692
693 nlohmann::json pairs = nlohmann::json::array();
694
695 key << idx;
696
697 while( aCfg->Read( key, &width ) )
698 {
699 key = "dPairGap";
700 gap = 1.0;
701 aCfg->Read( key << idx, &gap );
702
703 key = "dPairViaGap";
704 via_gap = 1.0;
705 aCfg->Read( key << idx, &via_gap );
706
707 nlohmann::json pair = { { "width", width }, { "gap", gap }, { "via_gap", via_gap } };
708 pairs.push_back( pair );
709
710 key = keyBase;
711 key << ++idx;
712 }
713
714 Set( bp + "diff_pair_dimensions", pairs );
715 }
716
717 group_blacklist.insert( wxT( "/pcbnew" ) );
718
719 // General group is unused these days, we can throw it away
720 group_blacklist.insert( wxT( "/general" ) );
721
722 // Next load sheet names and put all other legacy data in the legacy dict
723 aCfg->SetPath( wxT( "/" ) );
724
725 auto loadSheetNames =
726 [&]() -> bool
727 {
728 int sheet = 1;
729 wxString entry;
730 nlohmann::json arr = nlohmann::json::array();
731
732 wxLogTrace( traceSettings, wxT( "Migrating sheet names" ) );
733
734 aCfg->SetPath( wxT( "/sheetnames" ) );
735
736 while( aCfg->Read( wxString::Format( "%d", sheet++ ), &entry ) )
737 {
738 wxArrayString tokens = wxSplit( entry, ':' );
739
740 if( tokens.size() == 2 )
741 {
742 wxLogTrace( traceSettings, wxT( "%d: %s = %s" ), sheet, tokens[0], tokens[1] );
743 arr.push_back( nlohmann::json::array( { tokens[0], tokens[1] } ) );
744 }
745 }
746
747 Set( "sheets", arr );
748
749 aCfg->SetPath( "/" );
750
751 return true;
752 };
753
754 std::vector<wxString> groups;
755
756 groups.emplace_back( wxEmptyString );
757
758 auto loadLegacyPairs =
759 [&]( const std::string& aGroup ) -> bool
760 {
761 wxLogTrace( traceSettings, wxT( "Migrating group %s" ), aGroup );
762 bool success = true;
763 wxString keyStr;
764 wxString val;
765
766 index = 0;
767
768 while( aCfg->GetNextEntry( keyStr, index ) )
769 {
770 if( !aCfg->Read( keyStr, &val ) )
771 continue;
772
773 std::string key( keyStr.ToUTF8() );
774
775 wxLogTrace( traceSettings, wxT( " %s = %s" ), key, val );
776
777 try
778 {
779 Set( "legacy." + aGroup + "." + key, val );
780 }
781 catch( ... )
782 {
783 success = false;
784 }
785 }
786
787 return success;
788 };
789
790 for( size_t i = 0; i < groups.size(); i++ )
791 {
792 aCfg->SetPath( groups[i] );
793
794 if( groups[i] == wxT( "/sheetnames" ) )
795 {
796 ret |= loadSheetNames();
797 continue;
798 }
799
800 aCfg->DeleteEntry( wxT( "last_client" ), true );
801 aCfg->DeleteEntry( wxT( "update" ), true );
802 aCfg->DeleteEntry( wxT( "version" ), true );
803
804 ret &= loadLegacyPairs( groups[i].ToStdString() );
805
806 index = 0;
807
808 while( aCfg->GetNextGroup( str, index ) )
809 {
810 wxString group = groups[i] + "/" + str;
811
812 if( !group_blacklist.count( group ) )
813 groups.emplace_back( group );
814 }
815
816 aCfg->SetPath( "/" );
817 }
818
819 return ret;
820}
821
822
823bool PROJECT_FILE::LoadFromFile( const wxString& aDirectory )
824{
825 std::vector<TOP_LEVEL_SHEET_INFO> previousSheets = m_topLevelSheets;
826 bool success = JSON_SETTINGS::LoadFromFile( aDirectory );
827
829
830 if( success )
831 {
832 // Migrate from old single-root format to top_level_sheets format
833 if( m_topLevelSheets.empty() && m_project )
834 {
835 // Create a default top-level sheet entry based on the project name
836 wxString projectName = m_project->GetProjectName();
837
838 TOP_LEVEL_SHEET_INFO defaultSheet;
839 defaultSheet.uuid = niluuid; // Use niluuid for the first/default sheet
840 defaultSheet.name = projectName;
841 defaultSheet.filename = projectName + ".kicad_sch";
842
843 m_topLevelSheets.push_back( std::move( defaultSheet ) );
844
845 // Mark as migrated so it will be saved with the new format
846 m_wasMigrated = true;
847
848 wxLogTrace( traceSettings, wxT( "PROJECT_FILE: Migrated old single-root format to top_level_sheets" ) );
849 }
850
851 // When a project is created from a template, the top_level_sheets entries may
852 // still reference the template's schematic filenames rather than the new project's.
853 // The template copy renames files on disk but doesn't update the .kicad_pro content.
854 // Detect this and fix the references so the schematic can be found.
855 if( !m_topLevelSheets.empty() && m_project )
856 {
857 wxString projectPath = m_project->GetProjectPath();
858 wxString projectName = m_project->GetProjectName();
859
860 for( TOP_LEVEL_SHEET_INFO& sheetInfo : m_topLevelSheets )
861 {
862 wxFileName referencedFile( sheetInfo.filename );
863 referencedFile.MakeAbsolute( projectPath );
864
865 if( referencedFile.FileExists() )
866 continue;
867
868 // Try the project-name-based filename
869 wxString expectedFile = projectName + wxS( "." ) + FILEEXT::KiCadSchematicFileExtension;
870
871 wxFileName candidateFile( projectPath, expectedFile );
872
873 if( candidateFile.FileExists() )
874 {
875 wxLogTrace( traceSettings,
876 wxT( "PROJECT_FILE: Fixing stale top_level_sheets reference '%s' -> '%s'" ),
877 sheetInfo.filename, expectedFile );
878
879 sheetInfo.filename = expectedFile;
880 sheetInfo.name = projectName;
881 m_wasMigrated = true;
882 }
883 }
884 }
885
886 // A first read, or one over a list never written, has nothing to differ from
887 m_topLevelSheetsChanged = !previousSheets.empty() && m_topLevelSheets != previousSheets;
888 }
889
890 return success;
891}
892
893
895{
896 // An absent alias table permits legacy imports; an explicitly empty table suppresses them
897 if( m_BusAliasesDefined && !GetJson( "schematic.bus_aliases" ) )
898 m_modified = true;
899
900 return JSON_SETTINGS::Store();
901}
902
903
904bool PROJECT_FILE::SaveToFile( const wxString& aDirectory, bool aForce )
905{
906 wxASSERT( m_project );
907
908 Set( "meta.filename", m_project->GetProjectName() + "." + FILEEXT::ProjectFileExtension );
909
910 // Even if parameters were not modified, we should resave after migration
911 bool force = aForce || m_wasMigrated;
912
913 // If we're actually going ahead and doing the save, the flag that keeps code from doing the
914 // save should be cleared at this.
915 m_wasMigrated = false;
916
917 bool saved = JSON_SETTINGS::SaveToFile( aDirectory, force );
918
919 // The file now holds the list in memory, so a change read before is settled
920 if( saved )
922
923 return saved;
924}
925
926
928{
929 wxASSERT( m_project );
930
931 Set( "meta.filename", m_project->GetProjectName() + "." + FILEEXT::ProjectFileExtension );
932
934
935 try
936 {
937 return formatFileContents();
938 }
939 catch( ... )
940 {
941 wxLogTrace( traceSettings, wxT( "Error: could not serialize %s" ), GetFullFilename() );
942 return std::string();
943 }
944}
945
946
947bool PROJECT_FILE::SaveAs( const wxString& aDirectory, const wxString& aFile )
948{
949 wxFileName oldFilename( GetFilename() );
950 wxString oldProjectName = oldFilename.GetName();
951 wxString oldProjectPath = oldFilename.GetPath();
952
953 Set( "meta.filename", aFile + "." + FILEEXT::ProjectFileExtension );
954 SetFilename( aFile );
955
956 auto updatePath =
957 [&]( wxString& aPath )
958 {
959 if( aPath.StartsWith( oldProjectName + wxS( "." ) ) )
960 aPath.Replace( oldProjectName, aFile, false );
961 else if( aPath.StartsWith( oldProjectPath + wxS( "/" ) ) )
962 aPath.Replace( oldProjectPath, aDirectory, false );
963 };
964
965 updatePath( m_BoardDrawingSheetFile );
966
967 for( int ii = LAST_PATH_FIRST; ii < (int) LAST_PATH_SIZE; ++ii )
968 updatePath( m_PcbLastPath[ ii ] );
969
970 auto updatePathByPtr =
971 [&]( const std::string& aPtr )
972 {
973 if( std::optional<wxString> path = Get<wxString>( aPtr ) )
974 {
975 updatePath( path.value() );
976 Set( aPtr, path.value() );
977 }
978 };
979
980 updatePathByPtr( "schematic.page_layout_descr_file" );
981 updatePathByPtr( "schematic.plot_directory" );
982 updatePathByPtr( "schematic.ngspice.workbook_filename" );
983 updatePathByPtr( "pcbnew.page_layout_descr_file" );
984
985 for( auto& sheetInfo : m_topLevelSheets )
986 {
987 updatePath( sheetInfo.filename );
988
989 // Also update the display name if it matches the old project name
990 if( sheetInfo.name == oldProjectName )
991 sheetInfo.name = aFile;
992 }
993
994 // If we're actually going ahead and doing the save, the flag that keeps code from doing the save
995 // should be cleared at this point
996 m_wasMigrated = false;
997
998 // While performing Save As, we have already checked that we can write to the directory
999 // so don't carry the previous flag
1000 SetReadOnly( false );
1001 return JSON_SETTINGS::SaveToFile( aDirectory, true );
1002}
1003
1004
1006{
1008}
1009
1010
1015
1016
1017void to_json( nlohmann::json& aJson, const FILE_INFO_PAIR& aPair )
1018{
1019 aJson = nlohmann::json::array( { aPair.first.AsString().ToUTF8(), aPair.second.ToUTF8() } );
1020}
1021
1022
1023void from_json( const nlohmann::json& aJson, FILE_INFO_PAIR& aPair )
1024{
1025 wxCHECK( aJson.is_array() && aJson.size() == 2, /* void */ );
1026 aPair.first = KIID( wxString( aJson[0].get<std::string>().c_str(), wxConvUTF8 ) );
1027 aPair.second = wxString( aJson[1].get<std::string>().c_str(), wxConvUTF8 );
1028}
1029
1030
1031void to_json( nlohmann::json& aJson, const TOP_LEVEL_SHEET_INFO& aInfo )
1032{
1033 aJson = nlohmann::json::object();
1034 aJson["uuid"] = aInfo.uuid.AsString().ToUTF8();
1035 aJson["name"] = aInfo.name.ToUTF8();
1036 aJson["filename"] = aInfo.filename.ToUTF8();
1037}
1038
1039
1040void from_json( const nlohmann::json& aJson, TOP_LEVEL_SHEET_INFO& aInfo )
1041{
1042 wxCHECK( aJson.is_object(), /* void */ );
1043
1044 if( aJson.contains( "uuid" ) )
1045 aInfo.uuid = KIID( wxString( aJson["uuid"].get<std::string>().c_str(), wxConvUTF8 ) );
1046
1047 if( aJson.contains( "name" ) )
1048 aInfo.name = wxString( aJson["name"].get<std::string>().c_str(), wxConvUTF8 );
1049
1050 if( aJson.contains( "filename" ) )
1051 aInfo.filename = wxString( aJson["filename"].get<std::string>().c_str(), wxConvUTF8 );
1052}
int index
const char * name
bool fromLegacyString(wxConfigBase *aConfig, const std::string &aKey, const std::string &aDest)
Translates a legacy wxConfig string value to a given JSON pointer value.
bool fromLegacy(wxConfigBase *aConfig, const std::string &aKey, const std::string &aDest)
Translates a legacy wxConfig value to a given JSON pointer value.
bool flushToStore()
Flushes nested settings and parameters into the JSON store.
void Set(const std::string &aPath, ValueType aVal)
Stores a value into the JSON document Will throw an exception if ValueType isn't something that the l...
std::optional< nlohmann::json > GetJson(const std::string &aPath) const
Fetches a JSON object that is a subset of this JSON_SETTINGS object, using a path of the form "key1....
bool m_modified
True if the JSON data store has been written to since the last file write.
virtual bool LoadFromFile(const wxString &aDirectory="")
Loads the backing file from disk and then calls Load()
void SetReadOnly(bool aReadOnly)
wxString GetFullFilename() const
std::optional< ValueType > Get(const std::string &aPath) const
Fetches a value from within the JSON document.
std::vector< PARAM_BASE * > m_params
The list of parameters (owned by this object)
void registerMigration(int aOldSchemaVersion, int aNewSchemaVersion, std::function< bool(void)> aMigrator)
Registers a migration from one schema version to another.
JSON_SETTINGS(const wxString &aFilename, SETTINGS_LOC aLocation, int aSchemaVersion)
bool m_deleteLegacyAfterMigration
Whether or not to delete legacy file after migration.
std::unique_ptr< JSON_SETTINGS_INTERNALS > m_internals
void SetFilename(const wxString &aFilename)
virtual bool SaveToFile(const wxString &aDirectory="", bool aForce=false)
Calls Store() and then writes the contents of the JSON document to a file.
std::string formatFileContents()
Overlays the current store on the original file contents.
virtual bool Store()
Stores the current parameters into the JSON document represented by this object Note: this doesn't do...
wxString GetFilename() const
Definition kiid.h:46
wxString AsString() const
Definition kiid.cpp:264
Stores an enum as an integer.
Definition parameters.h:232
Like a normal param, but with custom getter and setter functions.
Definition parameters.h:299
static void MigrateToV9Layers(nlohmann::json &aJson)
static void MigrateToNamedRenderLayers(nlohmann::json &aJson)
Represents a list of strings holding directory paths.
Definition parameters.h:693
Stores a path as a string with directory separators normalized to unix-style.
Definition parameters.h:178
A helper for <wxString, wxString> maps.
Definition parameters.h:840
std::map< wxString, wxString > m_TextVars
wxString getFileExt() const override
bool m_BusAliasesDefined
An explicit alias table was loaded or set, including a deliberately empty table.
std::vector< LAYER_PAIR_INFO > m_LayerPairInfos
List of stored 3D viewports (view matrixes)
ERC_SETTINGS * m_ErcSettings
Eeschema params.
wxString m_LegacyLibDir
SCHEMATIC_SETTINGS * m_SchematicSettings
bool migrateSchema1To2()
Schema version 2: Bump for KiCad 9 layer numbering changes.
wxString m_BoardDrawingSheetFile
PcbNew params.
std::shared_ptr< NET_SETTINGS > m_NetSettings
Net settings for this project (owned here)
struct IP2581_BOM m_IP2581Bom
Layer pair list for the board.
bool m_topLevelSheetsChanged
wxString m_PcbLastPath[LAST_PATH_SIZE]
MRU path storage.
TEMPLATES m_TemplateFieldNames
Project and global field name templates shared by project editors.
PROJECT * m_project
A link to the owning PROJECT.
std::vector< TOP_LEVEL_SHEET_INFO > m_topLevelSheets
A list of top-level schematic sheets in this project.
std::vector< VIEWPORT > m_Viewports
List of stored layer presets.
std::vector< wxString > m_PinnedDesignBlockLibs
The list of pinned design block libraries.
bool SaveAs(const wxString &aDirectory, const wxString &aFile)
std::map< wxString, std::vector< wxString > > m_BusAliases
Bus alias definitions for the schematic project.
std::vector< wxString > m_EquivalenceFiles
CvPcb params.
bool Store() override
Stores the current parameters into the JSON document represented by this object Note: this doesn't do...
bool migrateSchema2To3()
Schema version 3: move layer presets to use named render layers.
wxString getLegacyFileExt() const override
std::vector< wxString > m_PinnedFootprintLibs
The list of pinned footprint libraries.
bool LoadFromFile(const wxString &aDirectory="") override
Loads the backing file from disk and then calls Load()
bool migrateSchema3To4()
Schema version 4 distinguishes explicit empty alias tables from older default writes.
std::string SerializeToString()
Serialize to the bytes SaveToFile would write, without touching the file.
std::shared_ptr< BOARD_DESIGN_SETTINGS > m_BoardSettings
Board design settings for this project's board.
std::vector< FILE_INFO_PAIR > m_sheets
An list of schematic sheets in this project.
std::vector< wxString > m_FindByPropertiesQueries
Recent queries for Find by Properties dialog.
virtual bool MigrateFromLegacy(wxConfigBase *aCfg) override
Migrates from wxConfig to JSON-based configuration.
std::vector< LAYER_PRESET > m_LayerPresets
std::vector< FILE_INFO_PAIR > m_boards
A list of board files in this project.
std::shared_ptr< TUNING_PROFILES > m_tuningProfileParameters
Tuning profile parameters for this project.
wxArrayString m_LegacyLibNames
std::vector< wxString > m_PinnedSymbolLibs
Below are project-level settings that have not been moved to a dedicated file.
IDF_EXPORT_SETTINGS m_IdfExportSettings
IPC-2581 BOM settings.
std::vector< VIEWPORT3D > m_Viewports3D
List of stored viewports (pos + zoom)
bool SaveToFile(const wxString &aDirectory="", bool aForce=false) override
Calls Store() and then writes the contents of the JSON document to a file.
PROJECT_FILE(const wxString &aFullPath)
Construct the project file for a project.
std::shared_ptr< COMPONENT_CLASS_SETTINGS > m_ComponentClassSettings
Component class settings for the project (owned here)
Container for project specific data.
Definition project.h:63
static std::string ToStdString(const wxString &aStr)
static const std::string ProjectFileExtension
static const std::string LegacyProjectFileExtension
static const std::string KiCadSchematicFileExtension
SETTINGS_LOC
#define traceSettings
KIID niluuid(0)
void to_json(nlohmann::json &aJson, const FILE_INFO_PAIR &aPair)
void from_json(const nlohmann::json &aJson, FILE_INFO_PAIR &aPair)
const int projectFileSchemaVersion
! Update the schema version whenever a migration is required
@ LAST_PATH_PLOT
@ LAST_PATH_SPECCTRADSN
@ LAST_PATH_SIZE
@ LAST_PATH_FIRST
@ LAST_PATH_IDF
@ LAST_PATH_VRML
@ LAST_PATH_NETLIST
@ LAST_PATH_STEP
std::pair< KIID, wxString > FILE_INFO_PAIR
For files like sheets and boards, a pair of that object KIID and display name Display name is typical...
Hold a name of a symbol's field, field value, and default visibility.
Information about a top-level schematic sheet.
KIID uuid
Unique identifier for the sheet.
wxString name
Display name for the sheet.
wxString filename
Relative path to the sheet file.
std::string path
Definition of file extensions used in Kicad.