25#include <wx/display.h>
26#include <wx/filedlg.h>
28#include <wx/filename.h>
31#include <wx/settings.h>
32#include <wx/stdpaths.h>
120template <
typename MAP>
121static bool isAutofilled(
const MAP& aAutofilled,
const typename MAP::key_type& aKey,
const std::string& aValue )
123 auto it = aAutofilled.find( aKey );
125 return it != aAutofilled.end() && it->second == aValue;
154 return _(
"The database password is missing or wrong." );
156 return _(
"The server rejected the user name or password." );
158 case FAILURE::UNREACHABLE:
160 return _(
"Could not reach the database file; check that its drive or share is available." );
162 return _(
"Could not reach the database server; check that it is running." );
164 case FAILURE::TIMEOUT:
169 return wxString::Format( wxPLURAL(
"The database file '%s' did not respond within %d second.",
170 "The database file '%s' did not respond within %d seconds.",
171 static_cast<unsigned>( seconds ) ),
172 wxFileName(
From_UTF8( aSource.
path ) ).GetFullName(), seconds );
176 return _(
"The server did not answer in time." );
178 return wxString::Format( wxPLURAL(
"The server did not answer within %d second.",
179 "The server did not answer within %d seconds.",
180 static_cast<unsigned>( aSource.
timeout ) ),
183 case FAILURE::NO_DSN:
185 return _(
"The connection string names a data source or driver that is not configured." );
187 return wxString::Format(
_(
"There is no ODBC data source named '%s'." ),
From_UTF8( aSource.
dsn ) );
189 case FAILURE::NO_DRIVER:
190 return _(
"The ODBC driver for this data source is not installed." );
192 case FAILURE::FILE_NOT_FOUND:
return _(
"The database file was not found." );
194 case FAILURE::FILE_IN_USE:
return _(
"The database file is locked by another program." );
196 case FAILURE::PROVIDER_MISSING:
return _(
"The Microsoft Access Database Engine is not installed." );
198 case FAILURE::NOT_SUPPORTED_ON_PLATFORM:
return _(
"Microsoft Access databases can only be read on Windows." );
200 case FAILURE::INVALID_TYPE:
201 return wxString::Format(
_(
"This KiCad does not know the database type '%s'." ),
204 case FAILURE::NETWORK_WAL:
205 return _(
"A database in write-ahead log mode cannot be read safely from a network drive." );
207 case FAILURE::UNKNOWN:
break;
210 return _(
"Could not connect to the database." );
225 static const std::vector<AUTOFILL_FIELD> fields = {
226 {
"Value", {
_HKI(
"Value" ) },
true },
227 {
"Datasheet", {
_HKI(
"Datasheet" ),
_HKI(
"data sheet" ) },
false }
236 return std::string(
"field." ) + aFieldName;
244 for(
const wxString& term : aTerms )
246 role.
terms.push_back( term );
248 if( wxString translated = wxGetTranslation( term ); translated != term )
249 role.
terms.push_back( translated );
254 if(
auto it = cfg->m_DatabaseColumnChoices.find( aChoiceId ); it != cfg->m_DatabaseColumnChoices.end() )
266 if( wxString::FromUTF8( field.
name ).IsSameAs( aName,
false ) )
276 const wxString& aDefaultDir ) :
291 m_connectDebounce( [
this]()
298 m_providerTimer.SetOwner(
this );
303 { m_cbKeyCol, [](
DATABASE_LIB_TABLE& t ) -> std::string& {
return t.key_col; },
false,
_(
"key" ),
304 "key", {
_HKI(
"id" ),
_HKI(
"key" ) } },
305 { m_cbSymbolsCol, [](
DATABASE_LIB_TABLE& t ) -> std::string& {
return t.symbols_col; },
false,
306 _(
"symbols" ),
"symbols", {
_HKI(
"symbol" ),
_HKI(
"sym" ) } },
307 { m_cbFootprintsCol, [](
DATABASE_LIB_TABLE& t ) -> std::string& {
return t.footprints_col; },
false,
308 _(
"footprints" ),
"footprints", {
_HKI(
"footprint" ),
_HKI(
"fp" ) } },
309 { m_cbPinsCol, [](
DATABASE_LIB_TABLE& t ) -> std::string& {
return t.pins_col; },
true,
_(
"pin map" ),
310 "pins", {
_HKI(
"pin map" ),
_HKI(
"pins" ) } },
311 { m_cbDescriptionCol, [](
DATABASE_LIB_TABLE& t ) -> std::string& {
return t.properties.description; },
312 true,
_(
"description" ),
"description", {
_HKI(
"description" ),
_HKI(
"desc" ) } },
313 { m_cbKeywordsCol, [](
DATABASE_LIB_TABLE& t ) -> std::string& {
return t.properties.keywords; },
true,
314 _(
"keywords" ),
"keywords", {
_HKI(
"keywords" ),
_HKI(
"tags" ) } },
315 { m_cbFpFiltersCol, [](
DATABASE_LIB_TABLE& t ) -> std::string& {
return t.properties.footprint_filters; },
316 true,
_(
"footprint filters" ),
"footprint_filters",
317 {
_HKI(
"footprint filters" ),
_HKI(
"fp filters" ) } },
318 { m_cbExclSimCol, [](
DATABASE_LIB_TABLE& t ) -> std::string& {
return t.properties.exclude_from_sim; },
319 true,
_(
"exclude from simulation" ),
"exclude_from_sim",
320 {
_HKI(
"exclude from simulation" ),
_HKI(
"exclude from sim" ) } },
321 { m_cbExclBomCol, [](
DATABASE_LIB_TABLE& t ) -> std::string& {
return t.properties.exclude_from_bom; },
322 true,
_(
"exclude from BOM" ),
"exclude_from_bom", {
_HKI(
"exclude from BOM" ) } },
323 { m_cbExclBoardCol, [](
DATABASE_LIB_TABLE& t ) -> std::string& {
return t.properties.exclude_from_board; },
324 true,
_(
"exclude from board" ),
"exclude_from_board", {
_HKI(
"exclude from board" ) } }
334 m_settings = std::make_unique<DATABASE_LIB_SETTINGS>( std::string() );
335 m_settings->SetReadOnly(
true );
336 m_settings->ResetToDefaults();
341 fn.Assign( aDblPath );
343 m_path = fn.GetFullPath();
345 isNew = !wxFileExists( m_path );
348 m_canSave = loaded && !m_settings->IsFutureFormat();
353 for( wxWindow* window = aParent; window && !frame; window = window->GetParent() )
359 if( drawFrame && drawFrame->
GetCanvas() )
365 m_previewSizer->Add( m_preview, 1, wxEXPAND | wxALL, 5 );
380 wxGridCellAttr* attr =
new wxGridCellAttr;
381 attr->SetRenderer(
new wxGridCellBoolRenderer() );
382 attr->SetEditor(
new wxGridCellBoolEditor() );
383 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
384 m_fieldsGrid->SetColAttr( col, attr );
387 m_fieldsGrid->PushEventHandler(
new GRID_TRICKS( m_fieldsGrid ) );
388 m_dataGrid->PushEventHandler(
new GRID_TRICKS( m_dataGrid ) );
391 m_btnTest->SetMinSize( m_btnTest->GetBestSize() );
394 m_stConnectionStatus->SetMinSize( wxSize( FromDIP( 40 ), -1 ) );
395 m_stDsnDriver->SetMinSize( wxSize( FromDIP( 40 ), -1 ) );
396 m_stSymbolExample->SetMinSize( wxSize( FromDIP( 40 ), -1 ) );
398 if( m_unnamed && m_defaultDir.IsEmpty() )
399 m_defaultDir = wxStandardPaths::Get().GetDocumentsDir();
401 m_stCwdHelp->SetLabel( m_unnamed ? wxString::Format(
_(
"${CWD} is replaced by %s (the folder the file will "
404 : wxString::Format(
_(
"${CWD} is replaced by %s" ), fn.GetPath() ) );
407 m_stNoLibraries->Wrap( FromDIP( 160 ) );
411 m_infoBar->ShowMessage(
_(
"This file could not be read and is shown read-only." ), wxICON_ERROR );
413 else if( m_settings->IsFutureFormat() )
415 m_infoBar->ShowMessage(
_(
"This file was written by a newer version of KiCad and is shown read-only." ),
420 m_infoBar->ShowMessage(
_(
"Choose a data source and click Test Connection, then add a library on the "
422 wxICON_INFORMATION );
432 for(
const COLUMN_ROLE& role : m_roles )
436 role.combo->Bind( wxEVT_KILL_FOCUS,
437 [
this]( wxFocusEvent& aEvent )
448 m_fieldsGrid->GetGridColLabelWindow()->Bind( wxEVT_MOTION,
449 [
this]( wxMouseEvent& aEvent )
451 const wxString tips[] = {
452 _(
"Database column the field reads its value from" ),
453 _(
"Name of the symbol field" ),
454 _(
"Show the field on the schematic when the symbol is placed" ),
455 _(
"Show the field as a column in the symbol chooser" ),
456 _(
"Show the field name before its value" ),
457 _(
"Take position and style from the symbol's own field of the same name" )
460 int x = m_fieldsGrid->CalcUnscrolledPosition( aEvent.GetPosition() ).x;
461 int col = m_fieldsGrid->XToCol( x );
463 bool validCol = col >= 0 && col < static_cast<int>( std::size( tips ) );
465 m_fieldsGrid->GetGridColLabelWindow()->SetToolTip( validCol ? tips[col] : wxString() );
473 SetTitle( m_unnamed ?
_(
"New Database Library" )
474 : wxString::Format(
_(
"Database Library Settings (%s)" ), fn.GetFullName() ) );
476 SetupStandardButtons();
479 m_sdbSizerOK->Disable();
482 wxSize fullSize = GetBestSize();
485 for( wxScrolledWindow* page : { m_connectionPage, m_librariesPage } )
487 page->SetMinSize( wxSize( -1, FromDIP( 200 ) ) );
488 page->SetSize( wxSize( page->GetSize().x, FromDIP( 200 ) ) );
491 finishDialogSettings();
494 m_initialSize.IncTo( fullSize );
495 m_connectionPage->FitInside();
496 m_librariesPage->FitInside();
514 if( !wxTheApp || !wxIsMainThread() )
521 [holder = std::shared_ptr<DATABASE_CONNECTION>( std::move( aConn ) )]()
mutable
560 bool useConnectionString = !
source.connection_string.empty();
561 bool passwordInFile = !
source.password.empty();
574 m_rbDSN->SetValue( !useConnectionString );
637 std::string password =
source.password;
645 if( !password.empty() && ( !sameLogin || password !=
m_keyringLogin.password ) )
649 DisplayError(
this,
_(
"The password could not be saved in the system keyring, which needs a "
650 "user name and a running keyring service.\n\n"
651 "Check 'Save password in the library file' to keep it there instead." ) );
655 else if( password.empty() && sameLogin && !
m_keyringLogin.password.empty() )
671 source.password = password;
702 std::set<std::string> nicknames;
704 for(
size_t ii = 0; ii <
m_settings->m_Tables.size(); ++ii )
708 wxWindow* focus =
nullptr;
711 if(
table.table.empty() &&
table.key_col.empty() )
713 msg = wxString::Format(
_(
"Library '%s' needs a table and a key column." ),
name );
716 else if(
table.table.empty() )
718 msg = wxString::Format(
_(
"Library '%s' needs a table." ),
name );
721 else if(
table.key_col.empty() )
723 msg = wxString::Format(
_(
"Library '%s' needs a key column." ),
name );
726 else if( !nicknames.insert(
table.name ).second )
728 msg = wxString::Format(
_(
"More than one library is named '%s'." ),
name );
769 wxString
filter =
_(
"KiCad database library files" )
775 wxFileDialog dlg(
this,
_(
"Save Database Library" ), dir,
name + wxS(
"." ) + ext,
filter,
776 wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
780 if( dlg.ShowModal() != wxID_OK )
783 wxFileName fn( dlg.GetPath() );
787 if( fn.GetFullPath() != dlg.GetPath() && fn.FileExists()
788 && !
IsOK(
this, wxString::Format(
_(
"Overwrite '%s'?" ), fn.GetFullPath() ) ) )
793 wxString oldBase =
cwdDir();
794 m_path = fn.GetFullPath();
797 m_settings->Internals()->SetFromString(
"meta.filename", std::string(
m_settings->GetFullFilename().ToUTF8() ) );
798 m_stCwdHelp->SetLabel( wxString::Format(
_(
"${CWD} is replaced by %s" ),
cwdDir() ) );
808 || stored.
path.find(
"${CWD}" ) != std::string::npos ) )
811 showInfo(
_(
"The data source uses ${CWD} and was tested again in the folder you chose. "
812 "Check the result, then click OK to save." ),
813 wxICON_INFORMATION );
840 wxString prompt =
m_unnamed ?
_(
"Save the new database library before closing?" )
841 : wxString::Format(
_(
"Save changes to '%s' before closing?" ),
842 wxFileName(
m_path ).GetFullName() );
877 if( !aEvent.CanVeto() )
918 wxString current =
m_cbDSN->GetValue();
926 m_cbDSN->ChangeValue( current );
938 text =
_(
"Not configured on this computer" );
959 wxExecute( wxS(
"odbcad32.exe" ), wxEXEC_SYNC );
1006 if( selection < 0 || selection >=
static_cast<int>(
m_backendTypes.size() ) )
1073 const bool useDSN =
m_rbDSN->GetValue();
1074 wxSizer* sbSource =
m_rbDSN->GetContainingSizer();
1077 sbSource->Show(
m_rbDSN, odbc );
1079 sbSource->Show(
m_cbDSN->GetContainingSizer(), odbc && useDSN );
1082 sbSource->Show(
m_choiceDriver->GetContainingSizer(), odbc && !useDSN );
1086 fgBackend->Show(
m_txtDbFile->GetContainingSizer(), file );
1125 wxString dir = wxPathOnly(
m_dbFile );
1130 wxFileDialog dlg(
this,
_(
"Select the database file" ), dir, wxEmptyString,
1131 _(
"SQLite databases (*.sqlite;*.sqlite3;*.db)|*.sqlite;*.sqlite3;*.db|"
1132 "Access databases (*.accdb;*.mdb)|*.accdb;*.mdb|All files|*" ),
1133 wxFD_OPEN | wxFD_FILE_MUST_EXIST );
1137 if( dlg.ShowModal() != wxID_OK )
1187 wxString driver = wxString::Format( wxS(
"Driver={%s};" ),
m_choiceDriver->GetStringSelection() );
1189 wxRegEx existing( wxS(
"Driver=\\{[^}]*\\};?" ), wxRE_ICASE | wxRE_ADVANCED );
1191 if( !existing.Replace( &
text, driver, 1 ) )
1230 if(
source.type != type )
1233 source.type_name.clear();
1248 source.connection_string.clear();
1257 source.connection_string.clear();
1286 :
_(
"No database file chosen." ),
1292 auto job = std::make_shared<CONNECT_JOB>();
1306 const std::string sourceName =
m_settings->ExpandedSource(
cwdDir() ).Describe();
1309 : wxString::Format(
_(
"Connecting to %s..." ),
From_UTF8( sourceName ) ),
1318 job->started =
true;
1319 job->connected = job->conn->Connect();
1321 if( job->connected )
1322 job->conn->GetTables( job->tables );
1327 wxTheApp->CallAfter(
1328 [weak = std::weak_ptr<CONNECT_JOB>( job )]()
1330 std::shared_ptr<CONNECT_JOB> finished = weak.lock();
1332 if( finished && finished->owner )
1333 finished->owner->onConnectFinished( finished );
1347 m_btnTest->SetLabel(
_(
"Test Connection" ) );
1357 m_btnTest->SetLabel(
_(
"Test Connection" ) );
1359 if( aJob->connected )
1361 m_conn = std::move( aJob->conn );
1362 m_tables = std::move( aJob->tables );
1364 "Connected; %zu tables and views found.",
1365 static_cast<unsigned>(
m_tables.size() ) ),
1372 From_UTF8( aJob->conn->GetLastError() ) );
1386 wxArrayString tables;
1399 const wxString& aDetails )
1402 m_stConnectionStatus->SetToolTip( aDetails.IsEmpty() ? aText : aText + wxS(
"\n\n" ) + aDetails );
1421 static const std::vector<std::string>
empty;
1423 if( !
m_conn || aTable.empty() )
1430 it =
m_columns.emplace( aTable, std::vector<std::string>() ).first;
1431 m_conn->GetColumns( aTable, it->second );
1440 wxArrayString names;
1486 control->Enable( lib !=
nullptr );
1490 role.combo->Enable( lib !=
nullptr );
1513 wxArrayString columns;
1519 wxArrayString optionalColumns = columns;
1520 optionalColumns.Insert( wxEmptyString, 0 );
1526 role.combo->Set( role.optional ? optionalColumns : columns );
1527 role.combo->ChangeValue(
From_UTF8( role.value( shown ) ) );
1530 wxGridCellAttr* attr =
new wxGridCellAttr;
1552 std::string value =
TO_UTF8( role.combo->GetValue() );
1555 wxFont font = role.combo->GetFont();
1556 wxFontStyle style = autofilled ? wxFONTSTYLE_ITALIC : wxFONTSTYLE_NORMAL;
1560 wxWindow* focus = wxWindow::FindFocus();
1561 bool typing = focus && ( focus == role.combo || focus->GetParent() == role.combo );
1563 if( font.GetStyle() != style && !typing )
1565 font.SetStyle( style );
1566 role.combo->SetFont( font );
1582 std::erase( lib->
name,
'/' );
1587 role.value( *lib ) =
TO_UTF8( role.combo->GetValue() );
1621 copy.name +=
"-copy";
1684 if( aEvent.GetEventObject() == role.combo )
1760 std::set<std::string> taken;
1761 std::vector<const COLUMN_ROLE*> roles;
1762 std::vector<const AUTOFILL_FIELD*> fields;
1763 std::vector<DB_AUTOFILL::ROLE> requests;
1767 const std::string& value = role.value( *lib );
1772 taken.insert( value );
1776 roles.push_back( &role );
1777 requests.push_back(
autofillRole( role.autofillId, role.terms ) );
1784 requests.back().excluded.insert( column );
1796 fields.push_back( &def );
1803 taken.insert( field.
column );
1806 std::vector<std::string> columns;
1810 if( !taken.contains( column ) )
1811 columns.push_back( column );
1816 for(
size_t ii = 0; ii < roles.size(); ++ii )
1818 roles[ii]->value( *lib ) = chosen[ii];
1822 for(
size_t ii = 0; ii < fields.size(); ++ii )
1825 const std::string& column = chosen[roles.size() + ii];
1828 if( column.empty() )
1866 return aValue ? wxS(
"1" ) : wxS(
"" );
1869 for(
int row = 0; row < static_cast<int>( lib->
fields.size() ); ++row )
1882 for(
int col = 0; col <
m_fieldsGrid->GetNumberCols(); ++col )
1890 int row = aEvent.GetRow();
1892 if( !lib || row < 0 || row >=
static_cast<int>( lib->
fields.size() ) )
1897 wxString value =
m_fieldsGrid->GetCellValue( row, aEvent.GetCol() );
1898 bool checked = value == wxS(
"1" );
1900 switch( aEvent.GetCol() )
1915 if( wxString::FromUTF8( field.
name ).IsSameAs( def.name,
false ) )
1937 [&]() -> std::pair<int, int>
1939 lib->
fields.emplace_back();
1975 lib->fields.erase( lib->fields.begin() + row );
1992 std::set<std::string> mapped;
1995 mapped.insert( role.value( *lib ) );
1998 mapped.insert( field.
column );
2002 if( !mapped.contains( column ) )
2003 lib->
fields.emplace_back( column, column,
false,
false,
false,
false );
2021 if( field.
column == aColumn )
2047 for(
int col = 0; col < static_cast<int>(
m_sampleColumns.size() ); ++col )
2049 for(
int row = 0; row < static_cast<int>(
m_sampleRows.size() ); ++row )
2056 if(
const std::string* value = std::any_cast<std::string>( &it->second ) )
2086 if( symbol.IsEmpty() )
2088 wxString key =
_(
"<key>" );
2096 text = wxString::Format(
_(
"Symbols appear as %s" ), symbol );
2115 m_stDataStatus->SetLabel(
_(
"Choose a library on the Libraries page to see its table." ) );
2125 std::map<std::string, wxString> roles;
2129 const std::string& column = role.value( *lib );
2131 if( !column.empty() )
2132 roles.emplace( column, role.label );
2135 for(
int col = 0; col <
m_dataGrid->GetNumberCols(); ++col )
2140 if(
auto role = roles.find( column ); role != roles.end() )
2141 label += wxS(
"\n" ) + role->second;
2143 label += wxS(
"\n" ) + wxString::Format(
_(
"field '%s'" ), field->name_wx );
2148 const unsigned sampled =
static_cast<unsigned>(
m_sampleRows.size() );
2152 rows = wxString::Format( wxPLURAL(
"%zu row",
"%zu rows", sampled ),
m_sampleRows.size() );
2154 rows = wxString::Format( wxPLURAL(
"first %zu row",
"first %zu rows", sampled ),
m_sampleRows.size() );
2156 m_stDataStatus->SetLabel( wxString::Format(
_(
"Library '%s', table '%s', %s. Click a column header to map it." ),
2164 int col = aEvent.GetCol();
2176 int fieldId = wxWindow::NewControlId();
2178 menu.Append( fieldId, mapped ?
_(
"Remove Field Mapping" ) :
_(
"Map as Field" ) );
2179 menu.AppendSeparator();
2181 std::map<int, const COLUMN_ROLE*> roleIds;
2185 int id = wxWindow::NewControlId();
2186 roleIds[id] = &role;
2187 menu.AppendCheckItem(
id, wxString::Format(
_(
"Use for %s" ), role.label ) )
2188 ->Check( role.value( *lib ) == column );
2191 int choice = GetPopupMenuSelectionFromUser( menu );
2193 if(
auto it = roleIds.find( choice ); it != roleIds.end() )
2197 role.
value( *lib ) = role.
value( *lib ) == column ? std::string() : column;
2205 if( choice != fieldId )
2210 std::erase_if( lib->
fields,
2213 return aField.column == column;
2218 lib->
fields.emplace_back( column, column,
false,
false,
false,
false );
2230 int row = aEvent.GetRow();
2246 m_infoBar->ShowMessage( aMessage, aIcon );
2260 int overhead =
m_editPanel->GetSize().x - page->GetClientSize().x;
2264 if( !page->HasScrollbar( wxVERTICAL ) )
2265 overhead += wxSystemSettings::GetMetric( wxSYS_VSCROLL_X, page );
2268 needed = std::max( needed, page->GetSizer()->CalcMin().x + overhead );
2273 const int deficit = needed +
m_splitter->GetSashSize() + previewWidth -
m_splitter->GetClientSize().x;
2277 wxRect display = wxDisplay(
this ).GetClientArea();
2278 wxSize size = GetSize();
2280 SetSize( std::min( size.x + deficit, display.width ), size.y );
2286 std::max(
m_splitter->GetClientSize().x - previewWidth, 0 ) ) );
2289 wxSize
minSize = GetMinSize();
2305 if( !
m_conn || aTable.empty() )
2334 wxArrayString warnings;
2337 warnings.Add(
_(
"Choose a table." ) );
2352 const std::vector<std::string>* columns =
2361 repeats = it->second;
2364 for(
size_t ii = 0; ii <
m_roles.size(); ++ii )
2368 wxArrayString warnings;
2372 const std::string& value = role.
value( *lib );
2377 warnings.Add(
_(
"Choose a key column." ) );
2379 else if( columns && !columns->empty() && !
alg::contains( *columns, value ) )
2381 warnings.Add( wxString::Format(
_(
"Column '%s' is not in table '%s'." ),
From_UTF8( value ),
2385 if( isKey && repeats > 0 )
2387 warnings.Add( wxString::Format(
2388 wxPLURAL(
"'%s' repeats in %zu of the first %zu row, and parts that share a key hide each "
2389 "other. Choose a column with a unique value per part.",
2390 "'%s' repeats in %zu of the first %zu rows, and parts that share a key hide each "
2391 "other. Choose a column with a unique value per part.",
2427 wxArrayString messages;
2431 if( issue.field == aField )
2432 messages.Add( issue.message );
2444 [&](
const wxString& aStatus,
const wxString& aDetails = wxEmptyString )
2446 m_tableError = aDetails.IsEmpty() ? wxString() : aStatus + wxS(
"\n" ) + aDetails;
2450 m_preview->SetSymbols( wxEmptyString, {} );
2455 return clear(
_(
"Add a library on the Libraries page to preview it." ) );
2458 return clear(
_(
"Connecting..." ) );
2461 return clear(
_(
"Not connected to a database." ) );
2463 if( lib->
table.empty() )
2464 return clear(
_(
"Choose a table." ) );
2479 size_t count = symbols.size();
2483 status =
_(
"Choose a key column." );
2485 status = wxString::Format(
_(
"Key column '%s' is not in table '%s'." ),
From_UTF8( lib->
key_col ),
2488 status = wxString::Format( wxPLURAL(
"%zu symbol.",
"%zu symbols.",
static_cast<unsigned>( count ) ), count );
2490 status = wxString::Format( wxPLURAL(
"%zu symbol from the first %zu rows.",
2491 "%zu symbols from the first %zu rows.",
static_cast<unsigned>( count ) ),
static std::string describeFailure(const std::string &aPath, const CALL_RESULT &aResult, const std::string &aPassword)
Composes the message for a failed call, naming the file.
wxBitmapBundle KiBitmapBundle(BITMAPS aBitmap, int aMinHeight)
static PROVIDER_STATE ProviderState()
Tells whether the ACE OLE DB provider is installed and loads.
@ BUSY
The check could not start because the engine lock stayed out of reach.
@ PENDING
The check has not finished, so nothing is known yet.
Shows symbols that are not in any library table the way the symbol chooser does: a searchable library...
wxStaticText * m_stSymbolExample
STD_BITMAP_BUTTON * m_btnAddField
STD_BITMAP_BUTTON * m_btnMoveFieldDown
STD_BITMAP_BUTTON * m_btnMoveLibraryDown
STD_BITMAP_BUTTON * m_btnDuplicateLibrary
wxTextCtrl * m_txtFilePassword
wxStaticText * m_stDsnDriver
wxComboBox * m_cbSymbolsCol
DIALOG_DATABASE_LIB_SETTINGS_BASE(wxWindow *parent, wxWindowID id=wxID_ANY, const wxString &title=_("Database Library Settings"), const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxSize(1200, 760), long style=wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER)
wxScrolledWindow * m_connectionPage
wxScrolledWindow * m_librariesPage
STD_BITMAP_BUTTON * m_btnRemoveLibrary
wxStaticText * m_stDataStatus
STD_BITMAP_BUTTON * m_btnMoveLibraryUp
wxCheckBox * m_cbGloballyUniqueKeys
wxChoice * m_choiceBackend
wxStaticText * m_stCwdHelp
wxCheckBox * m_cbPasswordInFile
wxStaticText * m_stConnectionStatus
wxTextCtrl * m_txtDescription
void m_splitterOnIdle(wxIdleEvent &)
wxSpinCtrl * m_spinCacheSize
wxButton * m_btnAddUnmapped
wxRadioButton * m_rbConnectionString
wxStaticText * m_fileLabel
wxButton * m_btnAddFirstLibrary
STD_BITMAP_BUTTON * m_btnRemoveField
wxStaticText * m_stNoLibraries
wxTextCtrl * m_txtPassword
wxSpinCtrl * m_spinTimeout
STD_BITMAP_BUTTON * m_btnMoveFieldUp
wxChoice * m_choiceDriver
wxTextCtrl * m_txtLibName
wxSplitterWindow * m_splitter
wxTextCtrl * m_txtConnectionString
wxButton * m_btnManageDsn
wxSpinCtrl * m_spinCacheAge
wxStaticText * m_filePasswordLabel
void updateTableWarning()
Marks the table field when it is required and missing or could not be read.
void onConnectFinished(const std::shared_ptr< CONNECT_JOB > &aJob)
void onSplitterIdle(wxIdleEvent &aEvent)
bool m_loading
Set while controls are filled from the settings, so their change events are ignored.
SYMBOL_LIBRARY_ADAPTER * m_libs
int m_currentLibrary
Index into m_settings->m_Tables of the library shown on the Libraries page, or -1.
void updateLibraryListHints()
Shows the empty state of the library list only while it is empty.
std::set< wxComboBox * > m_userRoles
Role combos the user set for the current library, which autofill leaves alone.
std::map< std::string, std::string > m_newChoices
Columns the user chose this session, keyed like EESCHEMA_SETTINGS::m_DatabaseColumnChoices.
std::map< std::string, size_t > m_sampleRepeats
void OnSourceSpinChanged(wxSpinEvent &aEvent) override
wxArrayString previewIssues(SCH_IO_DATABASE::PREVIEW_ISSUE::FIELD aField) const
void markUserRole(const COLUMN_ROLE &aRole, const std::string &aValue)
Records that the user chose aValue for aRole, so autofill leaves it alone.
void loadBackends()
Fills the backend choice with what this computer offers, plus the one the file already names.
void autofillColumns()
Maps columns of the chosen table to roles and fields the user has not set.
bool m_canSave
False when the file is unreadable or from a newer KiCad, since saving would lose its contents.
void OnBrowseFile(wxCommandEvent &aEvent) override
bool sourceConfigured() const
void markDirty()
Restarts the debounce before the preview is rebuilt.
void updateDsnDriver()
Shows which driver the chosen data source uses.
void loadDataSources()
Fills the data source list from the ODBC driver manager, keeping what is typed.
bool TransferDataFromWindow() override
void autofillTable()
Picks the table named like the library while the user has not chosen one.
bool ensureSample(const std::string &aTable)
Reads aTable's first rows unless they are already loaded; false if they could not be read.
DATABASE_SOURCE m_loadedSource
The source as loaded, which an unknown type is restored from and source.path is kept from until a fil...
std::vector< DATABASE_CONNECTION::ROW > m_sampleRows
void onCancel(wxCommandEvent &aEvent)
DATABASE_SOURCE m_keyringLogin
DSN login and keyring password at load, so an untouched login never rewrites the keyring.
wxString m_dbFile
The database file as picked, which stays absolute so the stored path can follow the save location.
void updateAutofillStyle()
Italicizes the role combos that still hold an autofilled value.
@ STAY
The user wants to keep editing.
@ SAVED
The user chose to save, which ended the dialog with wxID_OK.
@ DISCARD
Nothing to keep, or the user chose to discard it.
bool m_unnamed
True until a new library has been given a file.
void OnSourceChanged(wxCommandEvent &aEvent) override
void updateSourceControls()
void OnDataLabelRightClick(wxGridEvent &aEvent) override
void OnMoveFieldUp(wxCommandEvent &aEvent) override
void OnAddField(wxCommandEvent &aEvent) override
~DIALOG_DATABASE_LIB_SETTINGS() override
DIALOG_DATABASE_LIB_SETTINGS(wxWindow *aParent, const wxString &aDblPath, SYMBOL_LIBRARY_ADAPTER *aLibs, const wxString &aDefaultDir=wxEmptyString)
WX_DEBOUNCED_ACTION m_previewDebounce
Coalesces edits into one preview refresh.
std::vector< COLUMN_ROLE > m_roles
void onProviderTimer(wxTimerEvent &aEvent)
Offers Access once the provider check, which does not block, has found the engine.
std::vector< std::string > m_sampleColumns
void refreshTables()
Refreshes the table list and everything built on it after the connection changes.
void moveLibrary(int aDelta)
void OnAddLibrary(wxCommandEvent &aEvent) override
void OnAddUnmappedColumns(wxCommandEvent &aEvent) override
void updateSymbolExample()
Shows how the current library's symbols will be named.
void updateDataLabels()
Refreshes only the Data page column labels, which follow mapping edits.
void OnMoveLibraryDown(wxCommandEvent &aEvent) override
bool m_flagMissing
Set once OK found a missing table or key, which is then flagged inline.
void connect()
Starts connecting with the current settings; the table list refreshes when it finishes.
void OnBackendChanged(wxCommandEvent &aEvent) override
std::map< std::string, std::vector< std::string > > m_columns
void OnInsertDriver(wxCommandEvent &aEvent) override
void OnLibraryChanged(wxCommandEvent &aEvent) override
DB_LIB_PREVIEW_PANEL * m_preview
DATABASE_SOURCE_TYPE selectedBackend() const
std::string m_cleanSnapshot
settingsSnapshot() when the dialog opened, to tell whether closing loses anything
std::vector< ODBC_BACKEND::DATA_SOURCE > m_dataSources
WX_DEBOUNCED_ACTION m_connectDebounce
Connects once typing in the file field pauses.
void swapFields(DATABASE_LIB_TABLE &aLib, int aRow, int aOther)
void OnFileTextChanged(wxCommandEvent &aEvent) override
wxString m_tableError
Why the table could not be read, shown on the table warning icon.
void OnMoveLibraryUp(wxCommandEvent &aEvent) override
bool chooseSavePath()
Asks where to save a library that has no file yet; false if the user cancelled.
bool TransferDataToWindow() override
void onCloseWindow(wxCloseEvent &aEvent)
const DATABASE_FIELD_MAPPING * fieldForColumn(const std::string &aColumn)
std::map< std::string, std::string > m_autoFields
void OnTestConnection(wxCommandEvent &aEvent) override
std::vector< FIELD_WARNING_ICON * > m_roleIcons
One per entry of m_roles.
SCH_IO_DATABASE::PREVIEW_ISSUES m_previewIssues
Problems found while building the preview symbols, shown on the icons of the fields they came from.
void sourceEdited()
Follows an edit of the data source by dropping the connection that no longer matches it.
void selectBackend(DATABASE_SOURCE_TYPE aType)
void updateColumnWarnings()
Marks each column field for a missing key, a column the table does not have, keys that repeat in the ...
FIELD_WARNING_ICON * m_tableIcon
void OnMoveFieldDown(wxCommandEvent &aEvent) override
std::map< wxComboBox *, std::string > m_autoRoles
CLOSE_ACTION confirmClose()
Asks what to do with unsaved edits before the dialog closes without OK.
void OnSourceTypeChanged(wxCommandEvent &aEvent) override
std::unique_ptr< DATABASE_CONNECTION > m_conn
void OnRemoveLibrary(wxCommandEvent &aEvent) override
void showInfo(const wxString &aMessage, int aIcon)
Replaces the info bar message, which can be dismissed.
void OnTableChanged(wxCommandEvent &aEvent) override
void OnManageDataSources(wxCommandEvent &aEvent) override
std::string m_autoTable
Autofilled values for the current library, which a later autofill may replace.
std::vector< std::string > m_tables
void OnSettingChanged(wxCommandEvent &aEvent) override
std::shared_ptr< CONNECT_JOB > m_connectJob
const std::vector< std::string > & columnsFor(const std::string &aTable)
bool validateLibraries()
Shows the first problem that stops the settings from being saved.
void OnRemoveField(wxCommandEvent &aEvent) override
std::string m_sampleTable
Rows of m_sampleTable shared by the Data page and the preview.
void OnDuplicateLibrary(wxCommandEvent &aEvent) override
void OnLibrarySelected(wxCommandEvent &aEvent) override
DATABASE_LIB_TABLE * currentLibrary()
void OnFieldCellChanged(wxGridEvent &aEvent) override
void cancelConnect()
Abandons a connection attempt in progress, whose result is then discarded.
std::vector< DATABASE_SOURCE_TYPE > m_backendTypes
The type each entry of the backend choice stands for.
std::unique_ptr< DATABASE_LIB_SETTINGS > m_settings
void setConnectionStatus(const wxString &aText, bool aError, const wxString &aDetails=wxEmptyString)
Shows a one-line status; the full driver report goes in the tooltip.
void OnDataCellSelected(wxGridEvent &aEvent) override
void OnSettingSpinChanged(wxSpinEvent &aEvent) override
std::string settingsSnapshot()
Every setting as the file would hold it, plus where the password is kept.
void EndDialogShim(int aReturnCode)
A mode agnostic way to close a dialog.
The base frame for deriving all KiCad main window classes.
The base class for create windows for drawing purpose.
virtual EDA_DRAW_PANEL_GAL * GetCanvas() const
Return a pointer to GAL-based canvas of given EDA draw frame.
GAL_TYPE GetBackend() const
Return the type of backend currently used by GAL canvas.
@ GAL_TYPE_OPENGL
OpenGL implementation.
static GAL_TYPE ResolveStoredCanvasType(int aStoredCanvasType)
Convert a stored canvas type setting into a backend that can actually be used.
A warning icon drawn inside the right edge of a field, left of its dropdown button when it has one,...
Add mouse and command handling (such as cut, copy, and paste) to a WX_GRID instance.
static std::vector< std::string > ListDrivers()
static std::vector< DATA_SOURCE > ListDataSourceDetails()
static wxString SymbolNameForRow(const DATABASE_LIB_TABLE &aTable, bool aGloballyUniqueKeys, const DATABASE_CONNECTION::ROW &aRow, std::string *aRawKey=nullptr)
static std::vector< std::unique_ptr< LIB_SYMBOL > > BuildPreviewSymbols(SYMBOL_LIBRARY_ADAPTER *aLibs, const DATABASE_LIB_TABLE &aTable, bool aGloballyUniqueKeys, const std::vector< DATABASE_CONNECTION::ROW > &aRows, PREVIEW_ISSUES *aIssues)
Builds symbols from already-fetched rows exactly as the library would name and load them,...
static CONNECTION_RESULT CreateConnection(const DATABASE_LIB_SETTINGS &aSettings, bool aConnectNow=true, const wxString &aBaseDir=wxEmptyString)
Opens a connection described by aSettings, expanding ${CWD} in a connection string to the directory h...
RAII class that sets an value at construction and resets it to the original value at destruction.
An interface to the global shared library manager that is schematic-specific and linked to one projec...
bool IsOK(wxWindow *aParent, const wxString &aMessage)
Display a yes/no dialog with aMessage and returns the user response.
bool HandleUnsavedChanges(wxWindow *aParent, const wxString &aMessage, const std::function< bool()> &aSaveFunction)
Display a dialog with Save, Cancel and Discard Changes buttons.
void DisplayError(wxWindow *aParent, const wxString &aText)
Display an error or warning message box with aMessage.
This file is part of the common library.
DB_FAILURE
Why a connection attempt failed, as far as the backend's report tells.
wxString DefaultDatabaseLibFileName(const wxString &aLibName)
std::unique_ptr< DATABASE_LIB_SETTINGS > LoadDatabaseLibSettingsReadOnly(const wxString &aPath, bool *aLoaded)
Loads a database library settings file without allowing the load itself (e.g.
std::string DatabasePathForStorage(const wxString &aPath, const wxString &aBaseDir)
wxString DatabasePathFromInput(const wxString &aInput, const wxString &aBaseDir)
bool StoreDatabasePassword(const DATABASE_SOURCE &aSource, const std::string &aPassword)
Stores the password for the source's DSN login in the system keyring, or removes the entry when the p...
bool GetDatabasePassword(const DATABASE_SOURCE &aSource, std::string &aPassword, const DATABASE_SECRET_LOOKUP &aLookup)
DSN passwords that are not saved in the (often shared) library file live in the system keyring,...
int DatabaseFileWaitSeconds(int aTimeoutSeconds)
static constexpr int CONNECT_DEBOUNCE_MS
Pause in typing a database file path before the connection is tried.
static DB_AUTOFILL::ROLE autofillRole(const std::string &aChoiceId, const std::vector< wxString > &aTerms)
static wxString describeFailure(DB_FAILURE aFailure, const DATABASE_SOURCE &aSource)
static DATABASE_FIELD_MAPPING * findField(DATABASE_LIB_TABLE &aLib, const char *aName)
static constexpr int PROVIDER_POLL_MS
How often the Access provider check is asked whether it has finished, and for how long.
static bool isAutofilled(const MAP &aAutofilled, const typename MAP::key_type &aKey, const std::string &aValue)
True if autofill wrote aValue for aKey and the user has not changed it since.
static ACCESS_PROVIDER accessProvider()
Whether this computer can read Access files, which never blocks.
static constexpr int PREVIEW_DEBOUNCE_MS
Delay after the last edit before the preview is rebuilt.
static void relayoutPage(wxScrolledWindow *aPage)
Re-lays out a scrolled page and refits its scroll area after its contents change size.
static constexpr int PREVIEW_MIN_WIDTH_DIP
Narrowest the preview next to the settings can be before its tree columns are cut off.
static wxString displayName(const DATABASE_LIB_TABLE &aTable)
static constexpr int PROVIDER_POLL_LIMIT
static constexpr size_t PREVIEW_ROW_LIMIT
Rows read for the Data page and preview; enough to judge a mapping without loading a whole table.
@ FIELD_COL_VISIBLE_ON_ADD
@ FIELD_COL_VISIBLE_IN_CHOOSER
static std::string fieldChoiceId(const char *aFieldName)
static void releaseConnection(std::unique_ptr< DATABASE_CONNECTION > aConn)
A connection closes with a bounded wait that a dead share can use up, so the UI thread hands it to th...
static const std::vector< AUTOFILL_FIELD > & autofillFields()
static wxString accessLabel(ACCESS_PROVIDER aProvider)
static bool empty(const wxTextEntryBase *aCtrl)
const int minSize
Push and Shove router track width and via size dialog.
static const std::string DatabaseLibraryFileExtension
Some functions to handle hotkeys in KiCad.
std::vector< std::string > AssignColumns(const std::vector< std::string > &aColumns, const std::vector< ROLE > &aRoles)
Chooses a column for each role, best scores first, so no column serves two roles.
void RememberChoice(std::vector< std::string > &aHistory, const std::string &aColumn)
Moves aColumn to the front of a role's history, dropping repeats and the oldest entries.
std::string MatchTable(const std::vector< std::string > &aTables, const std::string &aLibraryName)
std::map< std::string, size_t > RepeatCounts(const std::vector< std::map< std::string, std::any > > &aRows)
Counts, per column, the rows whose value already appeared in an earlier row, with NULL counted as emp...
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
PGM_BASE & Pgm()
The global program "get" accessor.
T * GetAppSettings(const char *aFilename)
KIWAY Kiway(KFCTL_STANDALONE)
wxString From_UTF8(const char *cstring)
#define TO_UTF8(wxstring)
Convert a wxString to a UTF8 encoded C string for all wxWidgets build modes.
A symbol field that autofill maps from a like-named column.
std::vector< wxString > terms
bool visible_in_chooser
Whether the column is shown by default in the chooser.
std::string column
Database column name.
std::string name
KiCad field name.
void SetName(const std::string &aName)
bool inherit_properties
Whether or not to inherit properties from symbol field.
bool visible_on_add
Whether to show the field when placing the symbol.
bool show_name
Whether or not to show the field name as well as its value.
A database library table will be mapped to a sub-library provided by the database library entry in th...
std::string key_col
Unique key column name (will form part of the LIB_ID)
std::string name
KiCad library nickname (will form part of the LIB_ID)
std::vector< DATABASE_FIELD_MAPPING > fields
std::string table
Database table to pull content from.
std::string type_name
Raw source.type as written, kept for the error when the type is INVALID.
std::string path
Database file of a SQLITE or ACCESS source.
std::string connection_string
DATABASE_SOURCE_TYPE type
One mapping to fill, such as the key column or the Value field.
std::vector< std::string > remembered
Columns the user chose before, most recent first.
std::vector< wxString > terms
Words to look for, in English and translated.
One column mapping on the Libraries page: its combo, its setting and its Data page label.
std::string &(* value)(DATABASE_LIB_TABLE &)
const char * autofillId
Key of the remembered column choices for this role.
std::atomic< bool > started
Set by the worker before it opens anything, so a job that never ran can be destroyed anywhere.
~CONNECT_JOB()
Lets the connection go on a pool thread, so a stalled close never blocks the UI thread while the app ...
std::unique_ptr< DATABASE_CONNECTION > conn
A data source configured in the ODBC driver manager.
A connection built from settings, or the reason none could be built.
std::unique_ptr< DATABASE_CONNECTION > connection
Null when no backend exists for the source type.
DB_FAILURE failure
Why connection is null.
std::string error
The message naming the problem when connection is null.
A problem found while previewing, tagged with the setting that caused it.
std::vector< DATABASE_CONNECTION::ROW > rows
PCB_VIA::VIA_PARAMETER_ERROR::FIELD FIELD
thread_pool & GetKiCadThreadPool()
Get a reference to the current thread pool.
wxString AddFileExtListToFilter(const std::vector< std::string > &aExts)
Build the wildcard extension file dialog wildcard filter to add to the base message dialog.
Definition of file extensions used in Kicad.