KiCad PCB EDA Suite
Loading...
Searching...
No Matches
panel_design_block_chooser.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) 2016-2024 KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 2
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU 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, you may find one here:
18 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
19 * or you may search the http://www.gnu.org website for the version 2 license,
20 * or you may write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 */
23
24#include <pgm_base.h>
25#include <design_block.h>
29#include <kiface_base.h>
30#include <sch_edit_frame.h>
31#include <project_sch.h>
32#include <widgets/lib_tree.h>
35#include <eeschema_settings.h>
37#include <string_utils.h>
38#include <wx/button.h>
39#include <wx/clipbrd.h>
40#include <wx/log.h>
41#include <wx/panel.h>
42#include <wx/sizer.h>
43#include <wx/splitter.h>
44#include <wx/timer.h>
45#include <wx/wxhtml.h>
46#include <wx/msgdlg.h>
48
49
51
52
54 std::vector<LIB_ID>& aHistoryList,
55 std::function<void()> aSelectHandler ) :
56 wxPanel( aParent, wxID_ANY, wxDefaultPosition, wxDefaultSize ),
57 m_vsplitter( nullptr ),
58 m_tree( nullptr ),
59 m_preview( nullptr ),
60 m_frame( aFrame ),
61 m_selectHandler( std::move( aSelectHandler ) ),
62 m_historyList( aHistoryList )
63{
65
66 // Make sure settings are loaded before we start running multi-threaded design block loaders
68
69 // Load design block files:
70 WX_PROGRESS_REPORTER* progressReporter =
71 new WX_PROGRESS_REPORTER( aParent, _( "Loading Design Block Libraries" ), 3 );
72 DESIGN_BLOCK_LIB_TABLE::GetGlobalList().ReadDesignBlockFiles( libs, nullptr, progressReporter );
73
74 // Force immediate deletion of the WX_PROGRESS_REPORTER. Do not use Destroy(), or use
75 // Destroy() followed by wxSafeYield() because on Windows, APP_PROGRESS_DIALOG and
76 // WX_PROGRESS_REPORTER have some side effects on the event loop manager. For instance, a
77 // subsequent call to ShowModal() or ShowQuasiModal() for a dialog following the use of a
78 // WX_PROGRESS_REPORTER results in incorrect modal or quasi modal behavior.
79 delete progressReporter;
80
81 if( DESIGN_BLOCK_LIB_TABLE::GetGlobalList().GetErrorCount() )
82 displayErrors( aFrame );
83
85
86 // -------------------------------------------------------------------------------------
87 // Construct the actual panel
88 //
89
90 wxBoxSizer* sizer = new wxBoxSizer( wxVERTICAL );
91
92 m_vsplitter = new wxSplitterWindow( this, wxID_ANY, wxDefaultPosition, wxDefaultSize,
93 wxSP_LIVE_UPDATE | wxSP_NOBORDER | wxSP_3DSASH );
94
95
96 // Avoid the splitter window being assigned as the parent to additional windows.
97 m_vsplitter->SetExtraStyle( wxWS_EX_TRANSIENT );
98
99 wxPanel* treePanel = new wxPanel( m_vsplitter );
100 wxBoxSizer* treeSizer = new wxBoxSizer( wxVERTICAL );
101 treePanel->SetSizer( treeSizer );
102
103 wxPanel* detailsPanel = new wxPanel( m_vsplitter );
104 wxBoxSizer* detailsSizer = new wxBoxSizer( wxVERTICAL );
105 detailsPanel->SetSizer( detailsSizer );
106
107 m_preview = new DESIGN_BLOCK_PREVIEW_WIDGET( detailsPanel, false,
109 detailsSizer->Add( m_preview, 1, wxEXPAND, 5 );
110 detailsPanel->Layout();
111 detailsSizer->Fit( detailsPanel );
112
113 m_vsplitter->SetSashGravity( 0.5 );
114 m_vsplitter->SetMinimumPaneSize( 20 );
115 m_vsplitter->SplitHorizontally( treePanel, detailsPanel );
116
117 sizer->Add( m_vsplitter, 1, wxEXPAND, 5 );
118
119
120 m_tree = new LIB_TREE( treePanel, wxT( "design_blocks" ), libs, m_adapter,
122
123 treeSizer->Add( m_tree, 1, wxEXPAND, 5 );
124 treePanel->Layout();
125 treeSizer->Fit( treePanel );
126
127 RefreshLibs();
128 m_adapter->FinishTreeInitialization();
129
131
132 m_dbl_click_timer = new wxTimer( this );
133 m_open_libs_timer = new wxTimer( this );
134
135 SetSizer( sizer );
136
137 Layout();
138
139 Bind( wxEVT_TIMER, &PANEL_DESIGN_BLOCK_CHOOSER::onCloseTimer, this,
140 m_dbl_click_timer->GetId() );
141 Bind( wxEVT_TIMER, &PANEL_DESIGN_BLOCK_CHOOSER::onOpenLibsTimer, this,
142 m_open_libs_timer->GetId() );
143 Bind( EVT_LIBITEM_CHOSEN, &PANEL_DESIGN_BLOCK_CHOOSER::onDesignBlockChosen, this );
144 Bind( wxEVT_CHAR_HOOK, &PANEL_DESIGN_BLOCK_CHOOSER::OnChar, this );
145
146 // Open the user's previously opened libraries on timer expiration.
147 // This is done on a timer because we need a gross hack to keep GTK from garbling the
148 // display. Must be longer than the search debounce timer.
149 m_open_libs_timer->StartOnce( 300 );
150}
151
152
154{
155 Unbind( wxEVT_TIMER, &PANEL_DESIGN_BLOCK_CHOOSER::onCloseTimer, this );
156 Unbind( EVT_LIBITEM_SELECTED, &PANEL_DESIGN_BLOCK_CHOOSER::onDesignBlockSelected, this );
157 Unbind( EVT_LIBITEM_CHOSEN, &PANEL_DESIGN_BLOCK_CHOOSER::onDesignBlockChosen, this );
158 Unbind( wxEVT_CHAR_HOOK, &PANEL_DESIGN_BLOCK_CHOOSER::OnChar, this );
159
160 // Stop the timer during destruction early to avoid potential race conditions (that do happen)
161 m_dbl_click_timer->Stop();
162 m_open_libs_timer->Stop();
163 delete m_dbl_click_timer;
164 delete m_open_libs_timer;
165
167
168 if( EESCHEMA_SETTINGS* cfg = dynamic_cast<EESCHEMA_SETTINGS*>( Kiface().KifaceSettings() ) )
169 {
170 // Save any changes to column widths, etc.
171 m_adapter->SaveSettings();
172
173 cfg->m_DesignBlockChooserPanel.width = GetParent()->GetSize().x;
174 cfg->m_DesignBlockChooserPanel.height = GetParent()->GetSize().y;
175
176 if( m_vsplitter )
177 cfg->m_DesignBlockChooserPanel.sash_pos_v = m_vsplitter->GetSashPosition();
178
179 cfg->m_DesignBlockChooserPanel.sort_mode = m_tree->GetSortMode();
180 }
181}
182
183
184void PANEL_DESIGN_BLOCK_CHOOSER::OnChar( wxKeyEvent& aEvent )
185{
186 if( aEvent.GetKeyCode() == WXK_ESCAPE )
187 {
188 wxObject* eventSource = aEvent.GetEventObject();
189
190 if( wxTextCtrl* textCtrl = dynamic_cast<wxTextCtrl*>( eventSource ) )
191 {
192 // First escape cancels search string value
193 if( textCtrl->GetValue() == m_tree->GetSearchString()
194 && !m_tree->GetSearchString().IsEmpty() )
195 {
196 m_tree->SetSearchString( wxEmptyString );
197 return;
198 }
199 }
200 }
201 else
202 {
203 aEvent.Skip();
204 }
205}
206
207
209{
210 if( EESCHEMA_SETTINGS* cfg = dynamic_cast<EESCHEMA_SETTINGS*>( Kiface().KifaceSettings() ) )
211 {
212 auto horizPixelsFromDU =
213 [&]( int x ) -> int
214 {
215 wxSize sz( x, 0 );
216 return GetParent()->ConvertDialogToPixels( sz ).x;
217 };
218
219 EESCHEMA_SETTINGS::PANEL_DESIGN_BLOCK_CHOOSER& panelCfg = cfg->m_DesignBlockChooserPanel;
220
221 int w = panelCfg.width > 40 ? panelCfg.width : horizPixelsFromDU( 440 );
222 int h = panelCfg.height > 40 ? panelCfg.height : horizPixelsFromDU( 340 );
223
224 GetParent()->SetSize( wxSize( w, h ) );
225 GetParent()->Layout();
226
227 // We specify the width of the right window (m_design_block_view_panel), because specify
228 // the width of the left window does not work as expected when SetSashGravity() is called
229
230 if( panelCfg.sash_pos_h < 0 )
231 panelCfg.sash_pos_h = horizPixelsFromDU( 220 );
232
233 if( panelCfg.sash_pos_v < 0 )
234 panelCfg.sash_pos_v = horizPixelsFromDU( 230 );
235
236 if( m_vsplitter )
237 m_vsplitter->SetSashPosition( panelCfg.sash_pos_v );
238
239 m_adapter->SetSortMode( (LIB_TREE_MODEL_ADAPTER::SORT_MODE) panelCfg.sort_mode );
240 }
241}
242
243
245{
246 // Unselect before syncing to avoid null reference in the adapter
247 // if a selected item is removed during the sync
248 m_tree->Unselect();
249
251 static_cast<DESIGN_BLOCK_TREE_MODEL_ADAPTER*>( m_adapter.get() );
252
253 // Clear all existing libraries then re-add
254 adapter->ClearLibraries();
255
256 // Read the libraries from disk if they've changed
258
259 // Sync FOOTPRINT_INFO list to the libraries on disk
260 if( aProgress )
261 {
262 WX_PROGRESS_REPORTER progressReporter( this, _( "Updating Design Block Libraries" ), 2 );
264 &progressReporter );
265 progressReporter.Show( false );
266 }
267 else
268 {
269 DESIGN_BLOCK_LIB_TABLE::GetGlobalList().ReadDesignBlockFiles( fpTable, nullptr, nullptr );
270 }
271
273
274 if( !m_historyList.empty() )
275 adapter->SetPreselectNode( m_historyList[0], 0 );
276
277 adapter->AddLibraries( m_frame );
278
279 m_tree->Regenerate( true );
280}
281
282
284{
285 m_adapter->SetPreselectNode( aPreselect, 0 );
286}
287
288
290{
291 return m_tree->GetSelectedLibId( aUnit );
292}
293
294
296{
297 m_tree->CenterLibId( aLibId );
298 m_tree->SelectLibId( aLibId );
299}
300
301
303{
304 // Hack because of eaten MouseUp event. See PANEL_DESIGN_BLOCK_CHOOSER::onDesignBlockChosen
305 // for the beginning of this spaghetti noodle.
306
307 wxMouseState state = wxGetMouseState();
308
309 if( state.LeftIsDown() )
310 {
311 // Mouse hasn't been raised yet, so fire the timer again. Otherwise the
312 // purpose of this timer is defeated.
314 }
315 else
316 {
319 }
320}
321
322
324{
325 if( EESCHEMA_SETTINGS* cfg = dynamic_cast<EESCHEMA_SETTINGS*>( Kiface().KifaceSettings() ) )
326 m_adapter->OpenLibs( cfg->m_LibTree.open_libs );
327
328 // Bind this now se we don't spam the event queue with EVT_LIBITEM_SELECTED events during
329 // the initial load.
330 Bind( EVT_LIBITEM_SELECTED, &PANEL_DESIGN_BLOCK_CHOOSER::onDesignBlockSelected, this );
331}
332
333
335{
336 if( GetSelectedLibId().IsValid() )
338}
339
340
342{
344 {
345 // Got a selection. We can't just end the modal dialog here, because wx leaks some events
346 // back to the parent window (in particular, the MouseUp following a double click).
347 //
348 // NOW, here's where it gets really fun. wxTreeListCtrl eats MouseUp. This isn't really
349 // feasible to bypass without a fully custom wxDataViewCtrl implementation, and even then
350 // might not be fully possible (docs are vague). To get around this, we use a one-shot
351 // timer to schedule the dialog close.
352 //
353 // See PANEL_DESIGN_BLOCK_CHOOSER::onCloseTimer for the other end of this spaghetti noodle.
355 }
356}
357
359{
360 LIB_ID savedId = GetSelectedLibId();
361
362 m_tree->Unselect();
363
364 // Remove duplicates
365 for( int i = (int) m_historyList.size() - 1; i >= 0; --i )
366 {
367 if( m_historyList[i] == aLibId )
368 m_historyList.erase( m_historyList.begin() + i );
369 }
370
371 // Add the new name at the beginning of the history list
372 m_historyList.insert( m_historyList.begin(), aLibId );
373
374 // Remove extra names
375 while( m_historyList.size() >= 8 )
376 m_historyList.pop_back();
377
379 m_tree->Regenerate( true );
380
381 SelectLibId( savedId );
382}
383
384
386{
387 wxString history = wxT( "-- " ) + _( "Recently Used" ) + wxT( " --" );
388
389 m_adapter->DoRemoveLibrary( history );
390
391 // Build the history list
392 std::vector<LIB_TREE_ITEM*> historyInfos;
393
394 for( const LIB_ID& lib : m_historyList )
395 {
397 lib.GetLibNickname(), lib.GetLibItemName() );
398
399 // this can be null, for example, if the design block has been deleted from a library.
400 if( fp_info != nullptr )
401 historyInfos.push_back( fp_info );
402 }
403
404 m_adapter->DoAddLibrary( history, wxEmptyString, historyInfos, false, true );
405}
406
407
408void PANEL_DESIGN_BLOCK_CHOOSER::displayErrors( wxTopLevelWindow* aWindow )
409{
410 // @todo: go to a more HTML !<table>! ? centric output, possibly with recommendations
411 // for remedy of errors. Add numeric error codes to PARSE_ERROR, and switch on them for
412 // remedies, etc. Full access is provided to everything in every exception!
413
414 HTML_MESSAGE_BOX dlg( aWindow, _( "Load Error" ) );
415
416 dlg.MessageSet( _( "Errors were encountered loading footprints:" ) );
417
418 wxString msg;
419
420 while( std::unique_ptr<IO_ERROR> error = DESIGN_BLOCK_LIB_TABLE::GetGlobalList().PopError() )
421 {
422 wxString tmp = EscapeHTML( error->Problem() );
423
424 // Preserve new lines in error messages so queued errors don't run together.
425 tmp.Replace( wxS( "\n" ), wxS( "<BR>" ) );
426 msg += wxT( "<p>" ) + tmp + wxT( "</p>" );
427 }
428
429 dlg.AddHTML_Text( msg );
430
431 dlg.ShowModal();
432}
KIFACE_BASE & Kiface()
Global KIFACE_BASE "get" accessor.
static DESIGN_BLOCK_LIST_IMPL & GetGlobalList()
bool ReadDesignBlockFiles(DESIGN_BLOCK_LIB_TABLE *aTable, const wxString *aNickname=nullptr, PROGRESS_REPORTER *aProgressReporter=nullptr) override
Read all the design blocks provided by the combination of aTable and aNickname.
DESIGN_BLOCK_INFO * GetDesignBlockInfo(const wxString &aDesignBlockName)
Get info for a design block by id.
void DisplayDesignBlock(DESIGN_BLOCK *aDesignBlock)
Set the currently displayed symbol.
static wxObjectDataPtr< LIB_TREE_MODEL_ADAPTER > Create(EDA_BASE_FRAME *aParent, LIB_TABLE *aLibs)
Factory function: create a model adapter in a reference-counting container.
int ShowModal() override
@ GAL_TYPE_OPENGL
OpenGL implementation.
void MessageSet(const wxString &message)
Add a message (in bold) to message list.
void AddHTML_Text(const wxString &message)
Add HTML text (without any change) to message list.
PROJECT & Prj() const
Return a reference to the PROJECT associated with this KIWAY.
A logical library item identifier and consists of various portions much like a URI.
Definition: lib_id.h:49
bool IsValid() const
Check if this LID_ID is valid.
Definition: lib_id.h:172
A mix-in to provide polymorphism between items stored in libraries (symbols, aliases and footprints).
Definition: lib_tree_item.h:41
void SetPreselectNode(const LIB_ID &aLibId, int aUnit)
Set the symbol name to be selected if there are no search results.
Widget displaying a tree of symbols with optional search text control and description panel....
Definition: lib_tree.h:49
void CenterLibId(const LIB_ID &aLibId)
Ensure that an item is visible (preferably centered).
Definition: lib_tree.cpp:349
void SelectLibId(const LIB_ID &aLibId)
Select an item in the tree widget.
Definition: lib_tree.cpp:343
LIB_TREE_MODEL_ADAPTER::SORT_MODE GetSortMode() const
Definition: lib_tree.h:141
wxString GetSearchString() const
Definition: lib_tree.cpp:387
void Unselect()
Unselect currently selected item in wxDataViewCtrl.
Definition: lib_tree.cpp:355
LIB_ID GetSelectedLibId(int *aUnit=nullptr) const
For multi-unit symbols, if the user selects the symbol itself rather than picking an individual unit,...
Definition: lib_tree.cpp:301
@ ALL_WIDGETS
Definition: lib_tree.h:58
void SetSearchString(const wxString &aSearchString)
Save/restore search string.
Definition: lib_tree.cpp:381
void Regenerate(bool aKeepState)
Regenerate the tree.
Definition: lib_tree.cpp:422
DESIGN_BLOCK_PREVIEW_WIDGET * m_preview
std::function< void()> m_selectHandler
void onOpenLibsTimer(wxTimerEvent &aEvent)
void addDesignBlockToHistory(const LIB_ID &aLibId)
void SetPreselect(const LIB_ID &aPreselect)
void onCloseTimer(wxTimerEvent &aEvent)
void displayErrors(wxTopLevelWindow *aWindow)
LIB_ID GetSelectedLibId(int *aUnit=nullptr) const
To be called after this dialog returns from ShowModal().
PANEL_DESIGN_BLOCK_CHOOSER(SCH_EDIT_FRAME *aFrame, wxWindow *aParent, std::vector< LIB_ID > &aHistoryList, std::function< void()> aSelectHandler)
Create dialog to choose design_block.
void RefreshLibs(bool aProgress=false)
wxObjectDataPtr< LIB_TREE_MODEL_ADAPTER > m_adapter
void onDesignBlockSelected(wxCommandEvent &aEvent)
void onDesignBlockChosen(wxCommandEvent &aEvent)
Handle the selection of an item.
void SelectLibId(const LIB_ID &aLibId)
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition: pgm_base.h:142
virtual DESIGN_BLOCK_LIB_TABLE * DesignBlockLibs()
Return the table of design block libraries.
Definition: project.cpp:418
Schematic editor (Eeschema) main window.
DESIGN_BLOCK * GetDesignBlock(const LIB_ID &aLibId, bool aUseCacheLib=false, bool aShowErrorMsg=false)
Load design block from design block library table.
T * GetAppSettings()
Returns a handle to the a given settings by type If the settings have already been loaded,...
Multi-thread safe progress reporter dialog, intended for use of tasks that parallel reporting back of...
#define _(s)
STL namespace.
PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: pgm_base.cpp:1060
see class PGM_BASE
wxString EscapeHTML(const wxString &aString)
Return a new wxString escaped for embedding in HTML.