KiCad PCB EDA Suite
Loading...
Searching...
No Matches
lib_tree_model_adapter.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) 2017 Chris Pavlina <[email protected]>
5 * Copyright (C) 2014 Henner Zeller <[email protected]>
6 * Copyright (C) 2023 CERN
7 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
8 *
9 * This program is free software: you can redistribute it and/or modify it
10 * under the terms of the GNU General Public License as published by the
11 * Free Software Foundation, either version 3 of the License, or (at your
12 * option) any later version.
13 *
14 * This program is distributed in the hope that it will be useful, but
15 * WITHOUT ANY WARRANTY; without even the implied warranty of
16 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
17 * General Public License for more details.
18 *
19 * You should have received a copy of the GNU General Public License
20 * along with this program. If not, see <https://www.gnu.org/licenses/>.
21 */
22
23#include <eda_base_frame.h>
24#include <eda_pattern_match.h>
25#include <kiface_base.h>
26#include <kiplatform/ui.h>
30#include <widgets/ui_common.h>
32#include <wx/tokenzr.h>
33#include <wx/wupdlock.h>
34#include <wx/settings.h>
35#include <wx/dc.h>
36#include <wx/log.h>
37#include <string_utils.h>
38
39
40static const int kDataViewIndent = 20;
41
42
44{
45 // An out-of-range persisted width (seen after mixed-DPI monitor changes) can push the
46 // tree content out of view and leave the chooser unusable, so anything outside a width
47 // that could legitimately fit on a display is treated as corrupt rather than a resize.
48 return aWidth > 0 && aWidth <= MAX_COL_WIDTH;
49}
50
51
52class LIB_TREE_RENDERER : public wxDataViewCustomRenderer
53{
54public:
56 m_canvasItem( false )
57 {}
58
59 wxSize GetSize() const override
60 {
61 wxSize size( GetOwner()->GetWidth(), GetTextExtent( m_text ).y + 2 );
62
63#if defined( __WXGTK__ ) && !wxCHECK_VERSION( 3, 2, 7 )
64 // Somehow returning 0 or negative width prevents the returned height from
65 // being taken into account at all, even if we return strictly positive
66 // width from later calls to GetSize(), meaning that it's enough to return
67 // 0 from it once to completely break the layout for the entire lifetime of
68 // the control.
69 //
70 // As this is completely unexpected, forcefully prevent this from happening
71 size.IncTo( wxSize( 1, 1 ) );
72#endif
73
74 return size;
75 }
76
77 bool GetValue( wxVariant& aValue ) const override
78 {
79 aValue = m_text;
80 return true;
81 }
82
83 bool SetValue( const wxVariant& aValue ) override
84 {
85 m_text = aValue.GetString();
86 return true;
87 }
88
89 void SetAttr( const wxDataViewItemAttr& aAttr ) override
90 {
91 // Use strikethrough as a proxy for is-canvas-item
92 m_canvasItem = aAttr.GetStrikethrough();
93
94 wxDataViewItemAttr realAttr = aAttr;
95 realAttr.SetStrikethrough( false );
96
97 wxDataViewCustomRenderer::SetAttr( realAttr );
98 }
99
100 bool Render( wxRect aRect, wxDC *dc, int aState ) override
101 {
102 RenderBackground( dc, aRect );
103
104 if( m_canvasItem )
105 {
106 wxPoint points[6];
107 points[0] = aRect.GetTopLeft();
108 points[1] = aRect.GetTopRight() + wxPoint( -4, 0 );
109 points[2] = aRect.GetTopRight() + wxPoint( 0, aRect.GetHeight() / 2 );
110 points[3] = aRect.GetBottomRight() + wxPoint( -4, 1 );
111 points[4] = aRect.GetBottomLeft() + wxPoint( 0, 1 );
112 points[5] = aRect.GetTopLeft();
113
114 dc->SetPen( KIPLATFORM::UI::IsDarkTheme() ? *wxWHITE_PEN : *wxBLACK_PEN );
115 dc->DrawLines( 6, points );
116 }
117
118 aRect.Deflate( 1 );
119
120#ifdef __WXOSX__
121 // We should be able to pass wxDATAVIEW_CELL_SELECTED into RenderText() and have it do
122 // the right thing -- but it picks wxSYS_COLOUR_HIGHLIGHTTEXT on MacOS (instead
123 // of wxSYS_COLOUR_LISTBOXHIGHLIGHTTEXT).
124 if( aState & wxDATAVIEW_CELL_SELECTED )
125 dc->SetTextForeground( wxSystemSettings::GetColour( wxSYS_COLOUR_LISTBOXHIGHLIGHTTEXT ) );
126
127 RenderText( m_text, 0, aRect, dc, 0 );
128#else
129 RenderText( m_text, 0, aRect, dc, aState );
130#endif
131 return true;
132 }
133
134private:
136 wxString m_text;
137};
138
139
140wxDataViewItem LIB_TREE_MODEL_ADAPTER::ToItem( const LIB_TREE_NODE* aNode )
141{
142 return wxDataViewItem( const_cast<void*>( static_cast<void const*>( aNode ) ) );
143}
144
145
147{
148 return static_cast<LIB_TREE_NODE*>( aItem.GetID() );
149}
150
151
153 APP_SETTINGS_BASE::LIB_TREE& aSettingsStruct ) :
154 m_parent( aParent ),
155 m_cfg( aSettingsStruct ),
156 m_widget( nullptr ),
157 m_lazyLoadHandler( nullptr ),
159 m_show_units( true ),
160 m_preselect_unit( 0 ),
161 m_freeze( 0 ),
162 m_filter( nullptr )
163{
164 // Default column widths. Do not translate these names.
165 m_colWidths[ _HKI( "Item" ) ] = 300;
166 m_colWidths[ _HKI( "Description" ) ] = 600;
167
168 m_availableColumns = { _HKI( "Item" ), _HKI( "Description" ) };
169
171}
172
173
176
177
179 m_adapter( aAdapter )
180{
181 // A queued GtkTreeView scroll holds a row reference into the nodes the caller is about to
182 // free, so drop it while those rows are still valid (#24433, #24757)
184
185 m_adapter.Freeze();
186 m_adapter.BeforeReset();
187}
188
189
191{
192 // AfterReset rebuilds the view from GetParent(), which reports no parents while frozen
193 m_adapter.Thaw();
194 m_adapter.AfterReset();
195}
196
197
199{
200 return m_parent->GetToolDispatcher();
201}
202
203
205{
206 for( const std::pair<const wxString, int>& pair : m_cfg.column_widths )
207 {
208 if( IsValidColumnWidth( pair.second ) )
209 m_colWidths[pair.first] = pair.second;
210 }
211
212 m_shownColumns = m_cfg.columns;
213
214 if( m_shownColumns.empty() )
215 m_shownColumns = { _HKI( "Item" ), _HKI( "Description" ) };
216
217 if( m_shownColumns[0] != _HKI( "Item" ) )
218 m_shownColumns.insert( m_shownColumns.begin(), _HKI( "Item" ) );
219}
220
221
222std::vector<wxString> LIB_TREE_MODEL_ADAPTER::GetOpenLibs() const
223{
224 std::vector<wxString> openLibs;
225 wxDataViewItem rootItem( nullptr );
226 wxDataViewItemArray children;
227
228 GetChildren( rootItem, children );
229
230 for( const wxDataViewItem& child : children )
231 {
232 if( m_widget->IsExpanded( child ) )
233 openLibs.emplace_back( ToNode( child )->m_LibId.GetLibNickname().wx_str() );
234 }
235
236 return openLibs;
237}
238
239
240void LIB_TREE_MODEL_ADAPTER::OpenLibs( const std::vector<wxString>& aLibs )
241{
242 wxWindowUpdateLocker updateLock( m_widget );
243
244 for( const wxString& lib : aLibs )
245 {
246 wxDataViewItem item = FindItem( LIB_ID( lib, wxEmptyString ) );
247
248 if( item.IsOk() )
249 m_widget->Expand( item );
250 }
251}
252
253
255{
256 if( m_widget )
257 {
258 m_cfg.columns = GetShownColumns();
259 m_cfg.column_widths.clear();
260
261 for( const std::pair<const wxString, wxDataViewColumn*>& pair : m_colNameMap )
262 {
263 if( pair.second && IsValidColumnWidth( pair.second->GetWidth() ) )
264 m_cfg.column_widths[pair.first] = pair.second->GetWidth();
265 }
266
267 m_cfg.open_libs = GetOpenLibs();
268 }
269}
270
271
273{
274 m_show_units = aShow;
275}
276
277
278void LIB_TREE_MODEL_ADAPTER::SetPreselectNode( const LIB_ID& aLibId, int aUnit )
279{
280 m_preselect_lib_id = aLibId;
281 m_preselect_unit = aUnit;
282}
283
284
285LIB_TREE_NODE_LIBRARY& LIB_TREE_MODEL_ADAPTER::DoAddLibraryNode( const wxString& aNodeName, const wxString& aDesc,
286 bool pinned )
287{
288 LIB_TREE_NODE_LIBRARY& lib_node = m_tree.AddLib( aNodeName, aDesc );
289
290 lib_node.m_Pinned = pinned;
291
292 return lib_node;
293}
294
295
296LIB_TREE_NODE_LIBRARY& LIB_TREE_MODEL_ADAPTER::DoAddLibrary( const wxString& aNodeName, const wxString& aDesc,
297 const std::vector<LIB_TREE_ITEM*>& aItemList,
298 bool pinned, bool presorted )
299{
300 LIB_TREE_NODE_LIBRARY& lib_node = DoAddLibraryNode( aNodeName, aDesc, pinned );
301
302 for( LIB_TREE_ITEM* item: aItemList )
303 {
304 if( item )
305 lib_node.AddItem( item );
306 }
307
308 lib_node.AssignIntrinsicRanks( m_shownColumns, presorted );
309
310 return lib_node;
311}
312
313
314void LIB_TREE_MODEL_ADAPTER::RemoveGroup( bool aRecentGroup, bool aPlacedGroup )
315{
316 m_tree.RemoveGroup( aRecentGroup, aPlacedGroup );
317}
318
319
320void LIB_TREE_MODEL_ADAPTER::UpdateSearchString( const wxString& aSearch, bool aState )
321{
322 const LIB_TREE_NODE* firstMatch = nullptr;
323
324 {
325 wxWindowUpdateLocker updateLock( m_widget );
326
327 // Even with the updateLock, wxWidgets sometimes ties its knickers in a knot trying to
328 // run a wxdataview_selection_changed_callback() on a row that has been deleted.
329 // https://bugs.launchpad.net/kicad/+bug/1756255
330 m_widget->UnselectAll();
331
332 // This collapse is required before the call to "Freeze()" below. Once Freeze()
333 // is called, GetParent() will return nullptr. While this works for some calls, it
334 // segfaults when we have any expanded elements b/c the sub units in the tree don't
335 // have explicit references that are maintained over a search
336 // The tree will be expanded again below when we get our matches
337 //
338 // Also note that this cannot happen when we have deleted a symbol as GTK will also
339 // iterate over the tree in this case and find a symbol that has an invalid link
340 // and crash https://gitlab.com/kicad/code/kicad/-/issues/6910
341 if( !aState && !aSearch.IsNull() && m_tree.m_Children.size() )
342 {
343 for( std::unique_ptr<LIB_TREE_NODE>& child: m_tree.m_Children )
344 m_widget->Collapse( wxDataViewItem( &*child ) );
345 }
346
347 // Drop any pending scroll target before BeforeReset/AfterReset tears down the rows
348 // it points at. See KIPLATFORM::UI::CancelPendingScroll and #24433.
350
351 // DO NOT REMOVE THE FREEZE/THAW. This freeze/thaw is a flag for this model adapter
352 // that tells it when it shouldn't trust any of the data in the model. When set, it will
353 // not return invalid data to the UI, since this invalid data can cause crashes.
354 // This is different than the update locker, which locks the UI aspects only.
355 Freeze();
356 BeforeReset();
357
358 // Don't cause KiCad to hang if someone accidentally pastes the PCB or schematic into
359 // the search box.
360 constexpr int MAX_TERMS = 100;
361
362 wxString search( aSearch );
363
364 if( search.StartsWith( "::" ) )
365 search = search.Mid( 2 );
366
367 wxStringTokenizer tokenizer( search, " \t\r\n", wxTOKEN_STRTOK );
368 std::vector<std::unique_ptr<EDA_COMBINED_MATCHER>> termMatchers;
369
370 while( tokenizer.HasMoreTokens() && termMatchers.size() < MAX_TERMS )
371 {
372 wxString term = tokenizer.GetNextToken().Lower();
373 termMatchers.emplace_back( std::make_unique<EDA_COMBINED_MATCHER>( term, CTX_LIBITEM ) );
374 }
375
376 m_tree.UpdateScore( termMatchers, m_filter );
377
378 m_tree.SortNodes( m_sort_mode == BEST_MATCH );
379
380 // AfterReset rebuilds the view from GetParent(), which reports no parents while frozen
381 Thaw();
382 AfterReset();
383
384 // Move showResults inside the update locker to ensure all tree manipulation
385 // (including ExpandAncestors) happens while the window is frozen. This prevents
386 // GTK from rendering stale cached cell data during partial updates.
387 // https://gitlab.com/kicad/code/kicad/-/issues/18407
388 firstMatch = showResults();
389 }
390
391#ifdef __WXGTK__
392 // Ensure the control is repainted with the updated data. Without an explicit
393 // refresh the Gtk port can display stale rows until the user interacts with
394 // them, leading to mismatched tree contents.
395 m_widget->Refresh();
396 m_widget->Update();
397
398 // This causes crashes on Linux. Until someone can figure out why, please leave this commented
399 // out.
400 // wxSafeYield();
401#endif
402
403 if( firstMatch )
404 {
405 wxDataViewItem item = ToItem( firstMatch );
406 m_widget->Select( item );
407
408 // Make sure the *parent* item is visible. The selected item is the first (shown) child
409 // of the parent. So it's always right below the parent, and this way the user can also
410 // see what library the selected part belongs to, without having a case where the selection
411 // is off the screen (unless the window is a single row high, which is unlikely).
412 //
413 // This also happens to circumvent https://bugs.launchpad.net/kicad/+bug/1804400 which
414 // appears to be a GTK+3 bug.
417 }
418}
419
420
421void LIB_TREE_MODEL_ADAPTER::AttachTo( wxDataViewCtrl* aDataViewCtrl )
422{
423 m_widget = aDataViewCtrl;
424 aDataViewCtrl->SetIndent( kDataViewIndent );
425 aDataViewCtrl->AssociateModel( this );
427}
428
429
431{
432 m_widget->ClearColumns();
433
434 m_columns.clear();
435 m_colIdxMap.clear();
436 m_colNameMap.clear();
437
438 // The Item column is always shown
439 doAddColumn( wxT( "Item" ) );
441}
442
443
445{
446 for( const wxString& colName : m_shownColumns )
447 {
448 if( !m_colNameMap.count( colName ) )
449 doAddColumn( colName, colName == wxT( "Description" ) );
450 }
451}
452
453
455{
456 // See UpdateSearchString -- the resort tears down rows that any queued GtkTreeView
457 // scroll target may still reference (#24433).
459
460 Freeze();
461 BeforeReset();
462
463 m_tree.SortNodes( m_sort_mode == BEST_MATCH );
464
465 AfterReset();
466 Thaw();
467}
468
469
471{
472 m_parent->Prj().PinLibrary( aTreeNode->m_LibId.GetLibNickname(), getLibType() );
473 aTreeNode->m_Pinned = true;
474
475 resortTree();
476 EnsureVisibleIfEnabled( m_widget, ToItem( aTreeNode ) );
477}
478
479
481{
482 m_parent->Prj().UnpinLibrary( aTreeNode->m_LibId.GetLibNickname(), getLibType() );
483 aTreeNode->m_Pinned = false;
484
485 resortTree();
486 // Keep focus at top when unpinning
487}
488
489
491{
493
494 for( const std::unique_ptr<LIB_TREE_NODE>& lib: m_tree.m_Children )
495 {
496 if( lib->m_IsRecentlyUsedGroup )
497 lib->m_Name = wxT( "-- " ) + _( "Recently Used" ) + wxT( " --" );
498 else if( lib->m_IsAlreadyPlacedGroup )
499 lib->m_Name = wxT( "-- " ) + _( "Already Placed" ) + wxT( " --" );
500 }
501}
502
503
504wxDataViewColumn* LIB_TREE_MODEL_ADAPTER::doAddColumn( const wxString& aHeader, bool aTranslate )
505{
506 wxString translatedHeader = aTranslate ? wxGetTranslation( aHeader ) : aHeader;
507
508 // The extent of the text doesn't take into account the space on either side
509 // in the header, so artificially pad it
510 wxSize headerMinWidth = KIUI::GetTextSize( translatedHeader + wxT( "MMM" ), m_widget );
511
512 if( !m_colWidths.count( aHeader ) || m_colWidths[aHeader] < headerMinWidth.x )
513 m_colWidths[aHeader] = headerMinWidth.x;
514
515 int index = (int) m_columns.size();
516
517 wxDataViewColumn* col = new wxDataViewColumn( translatedHeader, new LIB_TREE_RENDERER(), index,
518 m_colWidths[aHeader], wxALIGN_NOT,
519 wxDATAVIEW_CELL_INERT | (int) wxDATAVIEW_COL_RESIZABLE );
520 m_widget->AppendColumn( col );
521
522 col->SetMinWidth( headerMinWidth.x );
523
524 m_columns.emplace_back( col );
525 m_colNameMap[aHeader] = col;
526 m_colIdxMap[m_columns.size() - 1] = aHeader;
527
528 return col;
529}
530
531
532void LIB_TREE_MODEL_ADAPTER::addColumnIfNecessary( const wxString& aHeader )
533{
534 if( m_colNameMap.count( aHeader ) )
535 return;
536
537 // Columns will be created later
538 m_colNameMap[aHeader] = nullptr;
539 m_availableColumns.emplace_back( aHeader );
540}
541
542
543void LIB_TREE_MODEL_ADAPTER::SetShownColumns( const std::vector<wxString>& aColumnNames )
544{
545 bool recreate = m_shownColumns != aColumnNames;
546
547 m_shownColumns = aColumnNames;
548
549 if( recreate && m_widget )
551
552 for( std::unique_ptr<LIB_TREE_NODE>& lib: m_tree.m_Children )
553 lib->AssignIntrinsicRanks( m_shownColumns );
554}
555
556
557LIB_ID LIB_TREE_MODEL_ADAPTER::GetAliasFor( const wxDataViewItem& aSelection ) const
558{
559 const LIB_TREE_NODE* node = ToNode( aSelection );
560 return node ? node->m_LibId : LIB_ID();
561}
562
563
564int LIB_TREE_MODEL_ADAPTER::GetUnitFor( const wxDataViewItem& aSelection ) const
565{
566 const LIB_TREE_NODE* node = ToNode( aSelection );
567 return node ? node->m_Unit : 0;
568}
569
570
571LIB_TREE_NODE::TYPE LIB_TREE_MODEL_ADAPTER::GetTypeFor( const wxDataViewItem& aSelection ) const
572{
573 const LIB_TREE_NODE* node = ToNode( aSelection );
574 return node ? node->m_Type : LIB_TREE_NODE::TYPE::INVALID;
575}
576
577
578LIB_TREE_NODE* LIB_TREE_MODEL_ADAPTER::GetTreeNodeFor( const wxDataViewItem& aSelection ) const
579{
580 return ToNode( aSelection );
581}
582
583
585{
586 int n = 0;
587
588 for( const std::unique_ptr<LIB_TREE_NODE>& lib: m_tree.m_Children )
589 {
590 if( m_filter )
591 {
592 for( const std::unique_ptr<LIB_TREE_NODE>& child : lib->m_Children )
593 {
594 if( (*m_filter)( *child ) )
595 n++;
596 }
597 }
598 else
599 {
600 n += lib->m_Children.size();
601 }
602 }
603
604 return n;
605}
606
607
608wxDataViewItem LIB_TREE_MODEL_ADAPTER::FindItem( const LIB_ID& aLibId )
609{
610 for( std::unique_ptr<LIB_TREE_NODE>& lib: m_tree.m_Children )
611 {
612 if( lib->m_Name != aLibId.GetLibNickname().wx_str() )
613 continue;
614
615 // if part name is not specified, return the library node
616 if( aLibId.GetLibItemName() == "" )
617 return ToItem( lib.get() );
618
619 for( std::unique_ptr<LIB_TREE_NODE>& alias: lib->m_Children )
620 {
621 if( alias->m_Name == aLibId.GetLibItemName().wx_str() )
622 return ToItem( alias.get() );
623 }
624
625 break; // could not find the part in the requested library
626 }
627
628 return wxDataViewItem();
629}
630
631
636
637
638unsigned int LIB_TREE_MODEL_ADAPTER::GetChildren( const wxDataViewItem& aItem,
639 wxDataViewItemArray& aChildren ) const
640{
641 const LIB_TREE_NODE* node = ( aItem.IsOk() ? ToNode( aItem ) : &m_tree );
642 unsigned int count = 0;
643
644 if( node->m_Type == LIB_TREE_NODE::TYPE::ROOT
645 || node->m_Type == LIB_TREE_NODE::TYPE::LIBRARY
646 || ( m_show_units && node->m_Type == LIB_TREE_NODE::TYPE::ITEM ) )
647 {
648 for( std::unique_ptr<LIB_TREE_NODE> const& child: node->m_Children )
649 {
650 if( child->m_Score > 0 )
651 {
652 aChildren.Add( ToItem( &*child ) );
653 ++count;
654 }
655 }
656 }
657
658 return count;
659}
660
661
663{
664 wxDataViewColumn* col = nullptr;
665 size_t idx = 0;
666 int totalWidth = 0;
667 wxString header;
668
669 for( ; idx < m_columns.size() - 1; idx++ )
670 {
671 wxASSERT( m_colIdxMap.count( idx ) );
672
673 col = m_columns[idx];
674 header = m_colIdxMap[idx];
675
676 wxASSERT( m_colWidths.count( header ) );
677
678 col->SetWidth( m_colWidths[header] );
679 totalWidth += col->GetWidth();
680 }
681
682 int remainingWidth = m_widget->GetSize().x - totalWidth;
683 header = m_colIdxMap[idx];
684
685 m_columns[idx]->SetWidth( std::max( m_colWidths[header], remainingWidth ) );
686}
687
688
690{
691 // Yes, this is an enormous hack. But it works on all platforms, it doesn't suffer
692 // the On^2 sorting issues that ItemChanged() does on OSX, and it doesn't lose the
693 // user's scroll position (which re-attaching or deleting/re-inserting columns does).
694 static int walk = 1;
695
696 wxASSERT( !m_columns.empty() );
697
698 // Only use the widths read back if they are non-zero.
699 // GTK returns the displayed width of the column, which is not calculated immediately
700 if( m_columns[0]->GetWidth() > 0 )
701 {
702 for( const auto& [ colName, colPtr ] : m_colNameMap )
703 {
704 if( !colPtr )
705 continue;
706
707 int width = colPtr->GetWidth();
708
709 // Keep the prior sane width if a DPI change handed back a corrupt one.
710 if( IsValidColumnWidth( width ) )
711 m_colWidths[ colName ] = width;
712 }
713 }
714
715 auto colIt = m_colWidths.begin();
716
717 colIt->second += walk;
718 colIt++;
719
720 if( colIt != m_colWidths.end() )
721 colIt->second -= walk;
722
723 for( const auto& [ colName, colPtr ] : m_colNameMap )
724 {
725 if( colPtr == m_columns[0] || colPtr == nullptr )
726 continue;
727
728 wxASSERT( m_colWidths.count( colName ) );
729 colPtr->SetWidth( m_colWidths[ colName ] );
730 }
731
732 walk = -walk;
733}
734
735
736bool LIB_TREE_MODEL_ADAPTER::HasContainerColumns( const wxDataViewItem& aItem ) const
737{
738 return IsContainer( aItem );
739}
740
741
742bool LIB_TREE_MODEL_ADAPTER::IsContainer( const wxDataViewItem& aItem ) const
743{
744 LIB_TREE_NODE* node = ToNode( aItem );
745 return node ? node->m_Children.size() : true;
746}
747
748
749wxDataViewItem LIB_TREE_MODEL_ADAPTER::GetParent( const wxDataViewItem& aItem ) const
750{
751 if( m_freeze )
752 return ToItem( nullptr );
753
754 LIB_TREE_NODE* node = ToNode( aItem );
755
756 if( !node || node->m_Type == LIB_TREE_NODE::TYPE::INVALID )
757 return ToItem( nullptr );
758
759 LIB_TREE_NODE* parent = node->m_Parent;
760
761 // wxDataViewModel has no root node, but rather top-level elements have an invalid (null) parent.
762 if( !parent || parent->m_Type == LIB_TREE_NODE::TYPE::ROOT )
763 return ToItem( nullptr );
764
765 return ToItem( parent );
766}
767
768
769void LIB_TREE_MODEL_ADAPTER::GetValue( wxVariant& aVariant, const wxDataViewItem& aItem,
770 unsigned int aCol ) const
771{
772 if( IsFrozen() )
773 {
774 aVariant = wxEmptyString;
775 return;
776 }
777
778 LIB_TREE_NODE* node = ToNode( aItem );
779 wxCHECK( node, /* void */ );
780 wxString valueStr;
781
782 switch( aCol )
783 {
784 case NAME_COL:
785 if( node->m_Pinned )
786 valueStr = GetPinningSymbol() + UnescapeString( node->m_Name );
787 else
788 valueStr = UnescapeString( node->m_Name );
789
790 break;
791
792 default:
793 if( m_colIdxMap.count( aCol ) )
794 {
795 const wxString& key = m_colIdxMap.at( aCol );
796
797 if( key == wxT( "Description" ) )
798 valueStr = UnescapeString( node->m_Desc );
799 else if( node->m_Fields.count( key ) )
800 valueStr = UnescapeString( node->m_Fields.at( key ) );
801 else
802 valueStr = wxEmptyString;
803 }
804
805 break;
806 }
807
808 valueStr.Replace( wxS( "\n" ), wxS( " " ) ); // Clear line breaks
809
810 aVariant = valueStr;
811}
812
813
814bool LIB_TREE_MODEL_ADAPTER::GetAttr( const wxDataViewItem& aItem, unsigned int aCol,
815 wxDataViewItemAttr& aAttr ) const
816{
817 if( IsFrozen() )
818 return false;
819
820 LIB_TREE_NODE* node = ToNode( aItem );
821 wxCHECK( node, false );
822
823 if( node->m_Type == LIB_TREE_NODE::TYPE::ITEM )
824 {
825 if( !node->m_IsRoot && aCol == 0 )
826 {
827 // Names of non-root aliases are italicized
828 aAttr.SetItalic( true );
829 return true;
830 }
831 }
832
833 return false;
834}
835
836
837void recursiveDescent( LIB_TREE_NODE& aNode, const std::function<int( const LIB_TREE_NODE* )>& f )
838{
839 for( std::unique_ptr<LIB_TREE_NODE>& node: aNode.m_Children )
840 {
841 int r = f( node.get() );
842
843 if( r == 0 )
844 break;
845 else if( r == -1 )
846 continue;
847
848 recursiveDescent( *node, f );
849 }
850}
851
852
854{
855 const LIB_TREE_NODE* firstMatch = nullptr;
856
857 // Expand parents of leaf nodes with some level of matching
859 [&]( const LIB_TREE_NODE* n )
860 {
861 if( n->m_Type == LIB_TREE_NODE::TYPE::ITEM && n->m_Score > 1 )
862 {
863 // Mirror the sort order (see LIB_TREE_NODE::Compare): an exact match
864 // outranks any score, otherwise the higher score wins. Otherwise the
865 // view would scroll to a high-scoring item that isn't at the top.
866 if( !firstMatch )
867 firstMatch = n;
868 else if( n->m_ExactMatch && !firstMatch->m_ExactMatch )
869 firstMatch = n;
870 else if( n->m_ExactMatch == firstMatch->m_ExactMatch && n->m_Score > firstMatch->m_Score )
871 firstMatch = n;
872
873 m_widget->ExpandAncestors( ToItem( n ) );
874 }
875
876 return 1; // keep going to expand ancestors of all found items
877 } );
878
879 // If no matches, find and show the preselect node
880 if( !firstMatch && m_preselect_lib_id.IsValid() )
881 {
883 [&]( const LIB_TREE_NODE* n )
884 {
885 // Don't match the recent and already placed libraries
886 if( n->m_Name.StartsWith( "-- " ) )
887 return -1; // Skip this node and its children
888
889 if( n->m_Type == LIB_TREE_NODE::TYPE::ITEM
890 && ( n->m_Children.empty() || !m_preselect_unit )
891 && m_preselect_lib_id == n->m_LibId )
892 {
893 firstMatch = n;
894 m_widget->ExpandAncestors( ToItem( n ) );
895 return 0;
896 }
897 else if( n->m_Type == LIB_TREE_NODE::TYPE::UNIT
900 {
901 firstMatch = n;
902 m_widget->ExpandAncestors( ToItem( n ) );
903 return 0;
904 }
905
906 return 1;
907 } );
908 }
909
910 // If still no matches expand a single library if there is only one
911 if( !firstMatch )
912 {
913 int libraries = 0;
914
915 for( const std::unique_ptr<LIB_TREE_NODE>& child : m_tree.m_Children )
916 {
917 if( !child->m_Name.StartsWith( "-- " ) )
918 libraries++;
919 }
920
921 if( libraries != 1 )
922 return nullptr;
923
925 [&]( const LIB_TREE_NODE* n )
926 {
927 if( n->m_Type == LIB_TREE_NODE::TYPE::ITEM )
928 {
929 firstMatch = n;
930 m_widget->ExpandAncestors( ToItem( n ) );
931 return 0;
932 }
933
934 return 1;
935 } );
936 }
937
938 return firstMatch;
939}
940
941
int index
The base frame for deriving all KiCad main window classes.
A logical library item identifier and consists of various portions much like a URI.
Definition lib_id.h:45
const UTF8 & GetLibItemName() const
Definition lib_id.h:98
const UTF8 & GetLibNickname() const
Return the logical library name portion of a LIB_ID.
Definition lib_id.h:83
A mix-in to provide polymorphism between items stored in libraries (symbols, aliases and footprints).
ResetTreeView(LIB_TREE_MODEL_ADAPTER &aAdapter)
LIB_TREE_MODEL_ADAPTER(EDA_BASE_FRAME *aParent, const wxString &aPinnedKey, APP_SETTINGS_BASE::LIB_TREE &aSettingsStruct)
Create the adapter.
std::vector< wxString > GetOpenLibs() const
int GetUnitFor(const wxDataViewItem &aSelection) const
Return the unit for the given item.
static bool IsValidColumnWidth(int aWidth)
LIB_TREE_NODE::TYPE GetTypeFor(const wxDataViewItem &aSelection) const
Return node type for the given item.
APP_SETTINGS_BASE::LIB_TREE & m_cfg
bool GetAttr(const wxDataViewItem &aItem, unsigned int aCol, wxDataViewItemAttr &aAttr) const override
Get any formatting for an item.
std::map< wxString, int > m_colWidths
const LIB_TREE_NODE * showResults()
Find and expand successful search results.
void FinishTreeInitialization()
A final-stage initialization to be called after the window hierarchy has been realized and the window...
void addColumnIfNecessary(const wxString &aHeader)
void PinLibrary(LIB_TREE_NODE *aTreeNode)
virtual PROJECT::LIB_TYPE_T getLibType()=0
virtual wxDataViewItem GetCurrentDataViewItem()
void SetPreselectNode(const LIB_ID &aLibId, int aUnit)
Set the symbol name to be selected if there are no search results.
static LIB_TREE_NODE * ToNode(wxDataViewItem aItem)
Convert wxDataViewItem -> LIB_TREE_NODE.
LIB_ID GetAliasFor(const wxDataViewItem &aSelection) const
Return the alias for the given item.
LIB_TREE_NODE_LIBRARY & DoAddLibrary(const wxString &aNodeName, const wxString &aDesc, const std::vector< LIB_TREE_ITEM * > &aItemList, bool aPinned, bool aPresorted)
Add the given list of symbols by alias.
TOOL_DISPATCHER * GetToolDispatcher() const
void AttachTo(wxDataViewCtrl *aDataViewCtrl)
Attach to a wxDataViewCtrl and initialize it.
void SetShownColumns(const std::vector< wxString > &aColumnNames)
Sets which columns are shown in the widget.
std::function< void()> m_lazyLoadHandler
static wxDataViewItem ToItem(const LIB_TREE_NODE *aNode)
Convert LIB_TREE_NODE -> wxDataViewItem.
bool IsContainer(const wxDataViewItem &aItem) const override
Check whether an item can have children.
static const wxString GetPinningSymbol()
void ShowUnits(bool aShow)
Whether or not to show units.
LIB_TREE_NODE * GetTreeNodeFor(const wxDataViewItem &aSelection) const
unsigned int GetChildren(const wxDataViewItem &aItem, wxDataViewItemArray &aChildren) const override
Populate a list of all the children of an item.
void SaveSettings()
Save the column widths to the config file.
@ NAME_COL
Library or library item name column.
std::map< unsigned, wxString > m_colIdxMap
wxDataViewColumn * doAddColumn(const wxString &aHeader, bool aTranslate=true)
std::vector< wxDataViewColumn * > m_columns
std::vector< wxString > GetShownColumns() const
int GetItemCount() const
Return the number of symbols loaded in the tree.
std::vector< wxString > m_shownColumns
void RemoveGroup(bool aRecentlyUsedGroup, bool aAlreadyPlacedGroup)
Remove one of the system groups from the library.
void GetValue(wxVariant &aVariant, const wxDataViewItem &aItem, unsigned int aCol) const override
Get the value of an item.
void UnpinLibrary(LIB_TREE_NODE *aTreeNode)
std::map< wxString, wxDataViewColumn * > m_colNameMap
bool HasContainerColumns(const wxDataViewItem &aItem) const override
Check whether a container has columns too.
wxDataViewItem GetParent(const wxDataViewItem &aItem) const override
Get the parent of an item.
LIB_TREE_NODE_LIBRARY & DoAddLibraryNode(const wxString &aNodeName, const wxString &aDesc, bool pinned)
std::vector< wxString > m_availableColumns
static constexpr int MAX_COL_WIDTH
Upper bound for a persisted column width; larger values are treated as corrupt settings.
wxDataViewItem FindItem(const LIB_ID &aLibId)
Returns tree item corresponding to part.
void UpdateSearchString(const wxString &aSearch, bool aState)
Set the search string provided by the user.
std::function< bool(LIB_TREE_NODE &aNode)> * m_filter
void OpenLibs(const std::vector< wxString > &aLibs)
Node type: library.
LIB_TREE_NODE_ITEM & AddItem(LIB_TREE_ITEM *aItem)
Construct a new alias node, add it to this library, and return it.
Model class in the component selector Model-View-Adapter (mediated MVC) architecture.
std::map< wxString, wxString > m_Fields
List of weighted search terms.
std::vector< std::unique_ptr< LIB_TREE_NODE > > m_Children
LIB_TREE_NODE * m_Parent
void AssignIntrinsicRanks(const std::vector< wxString > &aShownColumns, bool presorted=false)
Store intrinsic ranks on all children of this node.
void SetAttr(const wxDataViewItemAttr &aAttr) override
bool SetValue(const wxVariant &aValue) override
wxSize GetSize() const override
bool GetValue(wxVariant &aValue) const override
bool Render(wxRect aRect, wxDC *dc, int aState) override
wxString wx_str() const
Definition utf8.cpp:41
static void recursiveDescent(wxSizer *aSizer, std::map< int, wxString > &aLabels)
#define _(s)
Base window classes and related definitions.
Abstract pattern-matching tool and implementations.
@ CTX_LIBITEM
static const int kDataViewIndent
void CancelPendingScroll(wxDataViewCtrl *aCtrl)
Cancel any pending scroll-to-item request on aCtrl.
Definition wxgtk/ui.cpp:649
bool IsDarkTheme()
Determine if the desktop interface is currently using a dark theme or a light theme.
Definition wxgtk/ui.cpp:54
KICOMMON_API wxSize GetTextSize(const wxString &aSingleLine, wxWindow *aWindow)
Return the size of aSingleLine of text when it is rendered in aWindow using whatever font is currentl...
Definition ui_common.cpp:80
#define _HKI(x)
Definition page_info.cpp:40
wxString UnescapeString(const wxString &aSource)
DATABASE_CONNECTION dc(odbcBackend(cs))
Functions to provide common constants and other functions to assist in making a consistent UI.
void EnsureVisibleIfEnabled(wxDataViewCtrl *aWidget, const wxDataViewItem &aItem)
Scroll aItem into view only when aWidget is currently enabled.