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 )
264 continue;
265
266 int width = KIPLATFORM::UI::GetColumnWidth( pair.second ) - redrawNudge( pair.first );
267
268 if( IsValidColumnWidth( width ) )
269 m_cfg.column_widths[pair.first] = width;
270 }
271
272 m_cfg.open_libs = GetOpenLibs();
273 }
274}
275
276
278{
279 m_show_units = aShow;
280}
281
282
283void LIB_TREE_MODEL_ADAPTER::SetPreselectNode( const LIB_ID& aLibId, int aUnit )
284{
285 m_preselect_lib_id = aLibId;
286 m_preselect_unit = aUnit;
287}
288
289
290LIB_TREE_NODE_LIBRARY& LIB_TREE_MODEL_ADAPTER::DoAddLibraryNode( const wxString& aNodeName, const wxString& aDesc,
291 bool pinned )
292{
293 LIB_TREE_NODE_LIBRARY& lib_node = m_tree.AddLib( aNodeName, aDesc );
294
295 lib_node.m_Pinned = pinned;
296
297 return lib_node;
298}
299
300
301LIB_TREE_NODE_LIBRARY& LIB_TREE_MODEL_ADAPTER::DoAddLibrary( const wxString& aNodeName, const wxString& aDesc,
302 const std::vector<LIB_TREE_ITEM*>& aItemList,
303 bool pinned, bool presorted )
304{
305 LIB_TREE_NODE_LIBRARY& lib_node = DoAddLibraryNode( aNodeName, aDesc, pinned );
306
307 for( LIB_TREE_ITEM* item: aItemList )
308 {
309 if( item )
310 lib_node.AddItem( item );
311 }
312
313 lib_node.AssignIntrinsicRanks( m_shownColumns, presorted );
314
315 return lib_node;
316}
317
318
319void LIB_TREE_MODEL_ADAPTER::RemoveGroup( bool aRecentGroup, bool aPlacedGroup )
320{
321 m_tree.RemoveGroup( aRecentGroup, aPlacedGroup );
322}
323
324
325void LIB_TREE_MODEL_ADAPTER::UpdateSearchString( const wxString& aSearch, bool aState )
326{
327 const LIB_TREE_NODE* firstMatch = nullptr;
328
329 {
330 wxWindowUpdateLocker updateLock( m_widget );
331
332 // Even with the updateLock, wxWidgets sometimes ties its knickers in a knot trying to
333 // run a wxdataview_selection_changed_callback() on a row that has been deleted.
334 // https://bugs.launchpad.net/kicad/+bug/1756255
335 m_widget->UnselectAll();
336
337 // This collapse is required before the call to "Freeze()" below. Once Freeze()
338 // is called, GetParent() will return nullptr. While this works for some calls, it
339 // segfaults when we have any expanded elements b/c the sub units in the tree don't
340 // have explicit references that are maintained over a search
341 // The tree will be expanded again below when we get our matches
342 //
343 // Also note that this cannot happen when we have deleted a symbol as GTK will also
344 // iterate over the tree in this case and find a symbol that has an invalid link
345 // and crash https://gitlab.com/kicad/code/kicad/-/issues/6910
346 if( !aState && !aSearch.IsNull() && m_tree.m_Children.size() )
347 {
348 for( std::unique_ptr<LIB_TREE_NODE>& child: m_tree.m_Children )
349 m_widget->Collapse( wxDataViewItem( &*child ) );
350 }
351
352 // Drop any pending scroll target before BeforeReset/AfterReset tears down the rows
353 // it points at. See KIPLATFORM::UI::CancelPendingScroll and #24433.
355
356 // DO NOT REMOVE THE FREEZE/THAW. This freeze/thaw is a flag for this model adapter
357 // that tells it when it shouldn't trust any of the data in the model. When set, it will
358 // not return invalid data to the UI, since this invalid data can cause crashes.
359 // This is different than the update locker, which locks the UI aspects only.
360 Freeze();
361 BeforeReset();
362
363 // Don't cause KiCad to hang if someone accidentally pastes the PCB or schematic into
364 // the search box.
365 constexpr int MAX_TERMS = 100;
366
367 wxString search( aSearch );
368
369 if( search.StartsWith( "::" ) )
370 search = search.Mid( 2 );
371
372 wxStringTokenizer tokenizer( search, " \t\r\n", wxTOKEN_STRTOK );
373 std::vector<std::unique_ptr<EDA_COMBINED_MATCHER>> termMatchers;
374
375 while( tokenizer.HasMoreTokens() && termMatchers.size() < MAX_TERMS )
376 {
377 wxString term = tokenizer.GetNextToken().Lower();
378 termMatchers.emplace_back( std::make_unique<EDA_COMBINED_MATCHER>( term, CTX_LIBITEM ) );
379 }
380
381 m_tree.UpdateScore( termMatchers, m_filter );
382
383 m_tree.SortNodes( m_sort_mode == BEST_MATCH );
384
385 // AfterReset rebuilds the view from GetParent(), which reports no parents while frozen
386 Thaw();
387 AfterReset();
388
389 // Move showResults inside the update locker to ensure all tree manipulation
390 // (including ExpandAncestors) happens while the window is frozen. This prevents
391 // GTK from rendering stale cached cell data during partial updates.
392 // https://gitlab.com/kicad/code/kicad/-/issues/18407
393 firstMatch = showResults();
394 }
395
396#ifdef __WXGTK__
397 // Ensure the control is repainted with the updated data. Without an explicit
398 // refresh the Gtk port can display stale rows until the user interacts with
399 // them, leading to mismatched tree contents.
400 m_widget->Refresh();
401 m_widget->Update();
402
403 // This causes crashes on Linux. Until someone can figure out why, please leave this commented
404 // out.
405 // wxSafeYield();
406#endif
407
408 if( firstMatch )
409 {
410 wxDataViewItem item = ToItem( firstMatch );
411 m_widget->Select( item );
412
413 // Make sure the *parent* item is visible. The selected item is the first (shown) child
414 // of the parent. So it's always right below the parent, and this way the user can also
415 // see what library the selected part belongs to, without having a case where the selection
416 // is off the screen (unless the window is a single row high, which is unlikely).
417 //
418 // This also happens to circumvent https://bugs.launchpad.net/kicad/+bug/1804400 which
419 // appears to be a GTK+3 bug.
422 }
423}
424
425
426void LIB_TREE_MODEL_ADAPTER::AttachTo( wxDataViewCtrl* aDataViewCtrl )
427{
428 m_widget = aDataViewCtrl;
429 aDataViewCtrl->SetIndent( kDataViewIndent );
430 aDataViewCtrl->AssociateModel( this );
432}
433
434
436{
437 m_widget->ClearColumns();
438
439 m_columns.clear();
440 m_colIdxMap.clear();
441 m_colNameMap.clear();
442 m_redrawNudge.clear();
443
444 // The Item column is always shown
445 doAddColumn( wxT( "Item" ) );
447}
448
449
451{
452 for( const wxString& colName : m_shownColumns )
453 {
454 if( !m_colNameMap.count( colName ) )
455 doAddColumn( colName, colName == wxT( "Description" ) );
456 }
457}
458
459
461{
462 // See UpdateSearchString -- the resort tears down rows that any queued GtkTreeView
463 // scroll target may still reference (#24433).
465
466 Freeze();
467 BeforeReset();
468
469 m_tree.SortNodes( m_sort_mode == BEST_MATCH );
470
471 AfterReset();
472 Thaw();
473}
474
475
477{
478 m_parent->Prj().PinLibrary( aTreeNode->m_LibId.GetLibNickname(), getLibType() );
479 aTreeNode->m_Pinned = true;
480
481 resortTree();
482 EnsureVisibleIfEnabled( m_widget, ToItem( aTreeNode ) );
483}
484
485
487{
488 m_parent->Prj().UnpinLibrary( aTreeNode->m_LibId.GetLibNickname(), getLibType() );
489 aTreeNode->m_Pinned = false;
490
491 resortTree();
492 // Keep focus at top when unpinning
493}
494
495
497{
499
500 for( const std::unique_ptr<LIB_TREE_NODE>& lib: m_tree.m_Children )
501 {
502 if( lib->m_IsRecentlyUsedGroup )
503 lib->m_Name = wxT( "-- " ) + _( "Recently Used" ) + wxT( " --" );
504 else if( lib->m_IsAlreadyPlacedGroup )
505 lib->m_Name = wxT( "-- " ) + _( "Already Placed" ) + wxT( " --" );
506 }
507}
508
509
510wxDataViewColumn* LIB_TREE_MODEL_ADAPTER::doAddColumn( const wxString& aHeader, bool aTranslate )
511{
512 wxString translatedHeader = aTranslate ? wxGetTranslation( aHeader ) : aHeader;
513
514 // The extent of the text doesn't take into account the space on either side
515 // in the header, so artificially pad it
516 wxSize headerMinWidth = KIUI::GetTextSize( translatedHeader + wxT( "MMM" ), m_widget );
517
518 if( !m_colWidths.count( aHeader ) || m_colWidths[aHeader] < headerMinWidth.x )
519 m_colWidths[aHeader] = headerMinWidth.x;
520
521 int index = (int) m_columns.size();
522
523 wxDataViewColumn* col = new wxDataViewColumn( translatedHeader, new LIB_TREE_RENDERER(), index,
524 m_colWidths[aHeader], wxALIGN_NOT,
525 wxDATAVIEW_CELL_INERT | (int) wxDATAVIEW_COL_RESIZABLE );
526 m_widget->AppendColumn( col );
527
528 col->SetMinWidth( headerMinWidth.x );
529
530 m_columns.emplace_back( col );
531 m_colNameMap[aHeader] = col;
532 m_colIdxMap[m_columns.size() - 1] = aHeader;
533
534 return col;
535}
536
537
538void LIB_TREE_MODEL_ADAPTER::addColumnIfNecessary( const wxString& aHeader )
539{
540 if( m_colNameMap.count( aHeader ) )
541 return;
542
543 // Columns will be created later
544 m_colNameMap[aHeader] = nullptr;
545 m_availableColumns.emplace_back( aHeader );
546}
547
548
549void LIB_TREE_MODEL_ADAPTER::SetShownColumns( const std::vector<wxString>& aColumnNames )
550{
551 bool recreate = m_shownColumns != aColumnNames;
552
553 m_shownColumns = aColumnNames;
554
555 if( recreate && m_widget )
557
558 for( std::unique_ptr<LIB_TREE_NODE>& lib: m_tree.m_Children )
559 lib->AssignIntrinsicRanks( m_shownColumns );
560}
561
562
563LIB_ID LIB_TREE_MODEL_ADAPTER::GetAliasFor( const wxDataViewItem& aSelection ) const
564{
565 const LIB_TREE_NODE* node = ToNode( aSelection );
566 return node ? node->m_LibId : LIB_ID();
567}
568
569
570int LIB_TREE_MODEL_ADAPTER::GetUnitFor( const wxDataViewItem& aSelection ) const
571{
572 const LIB_TREE_NODE* node = ToNode( aSelection );
573 return node ? node->m_Unit : 0;
574}
575
576
577LIB_TREE_NODE::TYPE LIB_TREE_MODEL_ADAPTER::GetTypeFor( const wxDataViewItem& aSelection ) const
578{
579 const LIB_TREE_NODE* node = ToNode( aSelection );
580 return node ? node->m_Type : LIB_TREE_NODE::TYPE::INVALID;
581}
582
583
584LIB_TREE_NODE* LIB_TREE_MODEL_ADAPTER::GetTreeNodeFor( const wxDataViewItem& aSelection ) const
585{
586 return ToNode( aSelection );
587}
588
589
591{
592 int n = 0;
593
594 for( const std::unique_ptr<LIB_TREE_NODE>& lib: m_tree.m_Children )
595 {
596 if( m_filter )
597 {
598 for( const std::unique_ptr<LIB_TREE_NODE>& child : lib->m_Children )
599 {
600 if( (*m_filter)( *child ) )
601 n++;
602 }
603 }
604 else
605 {
606 n += lib->m_Children.size();
607 }
608 }
609
610 return n;
611}
612
613
614wxDataViewItem LIB_TREE_MODEL_ADAPTER::FindItem( const LIB_ID& aLibId )
615{
616 for( std::unique_ptr<LIB_TREE_NODE>& lib: m_tree.m_Children )
617 {
618 if( lib->m_Name != aLibId.GetLibNickname().wx_str() )
619 continue;
620
621 // if part name is not specified, return the library node
622 if( aLibId.GetLibItemName() == "" )
623 return ToItem( lib.get() );
624
625 for( std::unique_ptr<LIB_TREE_NODE>& alias: lib->m_Children )
626 {
627 if( alias->m_Name == aLibId.GetLibItemName().wx_str() )
628 return ToItem( alias.get() );
629 }
630
631 break; // could not find the part in the requested library
632 }
633
634 return wxDataViewItem();
635}
636
637
642
643
644unsigned int LIB_TREE_MODEL_ADAPTER::GetChildren( const wxDataViewItem& aItem,
645 wxDataViewItemArray& aChildren ) const
646{
647 const LIB_TREE_NODE* node = ( aItem.IsOk() ? ToNode( aItem ) : &m_tree );
648 unsigned int count = 0;
649
650 if( node->m_Type == LIB_TREE_NODE::TYPE::ROOT
651 || node->m_Type == LIB_TREE_NODE::TYPE::LIBRARY
652 || ( m_show_units && node->m_Type == LIB_TREE_NODE::TYPE::ITEM ) )
653 {
654 for( std::unique_ptr<LIB_TREE_NODE> const& child: node->m_Children )
655 {
656 if( child->m_Score > 0 )
657 {
658 aChildren.Add( ToItem( &*child ) );
659 ++count;
660 }
661 }
662 }
663
664 return count;
665}
666
667
669{
670 wxDataViewColumn* col = nullptr;
671 size_t idx = 0;
672 int totalWidth = 0;
673 wxString header;
674
675 for( ; idx < m_columns.size() - 1; idx++ )
676 {
677 wxASSERT( m_colIdxMap.count( idx ) );
678
679 col = m_columns[idx];
680 header = m_colIdxMap[idx];
681
682 wxASSERT( m_colWidths.count( header ) );
683
684 col->SetWidth( m_colWidths[header] );
685 totalWidth += col->GetWidth();
686 }
687
688 int remainingWidth = m_widget->GetSize().x - totalWidth;
689 header = m_colIdxMap[idx];
690
691 m_columns[idx]->SetWidth( std::max( m_colWidths[header], remainingWidth ) );
692}
693
694
696{
697 // Yes, this is an enormous hack. But it works on all platforms, it doesn't suffer
698 // the On^2 sorting issues that ItemChanged() does on OSX, and it doesn't lose the
699 // user's scroll position (which re-attaching or deleting/re-inserting columns does).
700 static int walk = 1;
701
702 wxASSERT( !m_columns.empty() );
703
704 // Only use the widths read back if they are non-zero.
705 // GTK returns the displayed width of the column, which is not calculated immediately
706 if( m_columns[0]->GetWidth() > 0 )
707 {
708 for( const auto& [ colName, colPtr ] : m_colNameMap )
709 {
710 if( !colPtr )
711 continue;
712
713 int width = KIPLATFORM::UI::GetColumnWidth( colPtr ) - redrawNudge( colName );
714
715 // Keep the prior sane width if a DPI change handed back a corrupt one.
716 if( IsValidColumnWidth( width ) )
717 m_colWidths[ colName ] = width;
718 }
719 }
720
721 // The nudge only forces the redraw; the widths read back and saved leave it out
722 auto first = m_colWidths.begin();
723 auto second = std::next( first );
724
725 m_redrawNudge.clear();
726
727 for( const auto& [ colName, colPtr ] : m_colNameMap )
728 {
729 if( colPtr == m_columns[0] || colPtr == nullptr )
730 continue;
731
732 wxASSERT( m_colWidths.count( colName ) );
733
734 if( colName == first->first )
735 m_redrawNudge[colName] = walk;
736 else if( second != m_colWidths.end() && colName == second->first )
737 m_redrawNudge[colName] = -walk;
738
739 colPtr->SetWidth( m_colWidths[ colName ] + redrawNudge( colName ) );
740 }
741
742 walk = -walk;
743}
744
745
746int LIB_TREE_MODEL_ADAPTER::redrawNudge( const wxString& aColumn ) const
747{
748 auto it = m_redrawNudge.find( aColumn );
749 return it == m_redrawNudge.end() ? 0 : it->second;
750}
751
752
753bool LIB_TREE_MODEL_ADAPTER::HasContainerColumns( const wxDataViewItem& aItem ) const
754{
755 return IsContainer( aItem );
756}
757
758
759bool LIB_TREE_MODEL_ADAPTER::IsContainer( const wxDataViewItem& aItem ) const
760{
761 LIB_TREE_NODE* node = ToNode( aItem );
762 return node ? node->m_Children.size() : true;
763}
764
765
766wxDataViewItem LIB_TREE_MODEL_ADAPTER::GetParent( const wxDataViewItem& aItem ) const
767{
768 if( m_freeze )
769 return ToItem( nullptr );
770
771 LIB_TREE_NODE* node = ToNode( aItem );
772
773 if( !node || node->m_Type == LIB_TREE_NODE::TYPE::INVALID )
774 return ToItem( nullptr );
775
776 LIB_TREE_NODE* parent = node->m_Parent;
777
778 // wxDataViewModel has no root node, but rather top-level elements have an invalid (null) parent.
779 if( !parent || parent->m_Type == LIB_TREE_NODE::TYPE::ROOT )
780 return ToItem( nullptr );
781
782 return ToItem( parent );
783}
784
785
786void LIB_TREE_MODEL_ADAPTER::GetValue( wxVariant& aVariant, const wxDataViewItem& aItem,
787 unsigned int aCol ) const
788{
789 if( IsFrozen() )
790 {
791 aVariant = wxEmptyString;
792 return;
793 }
794
795 LIB_TREE_NODE* node = ToNode( aItem );
796 wxCHECK( node, /* void */ );
797 wxString valueStr;
798
799 switch( aCol )
800 {
801 case NAME_COL:
802 if( node->m_Pinned )
803 valueStr = GetPinningSymbol() + UnescapeString( node->m_Name );
804 else
805 valueStr = UnescapeString( node->m_Name );
806
807 break;
808
809 default:
810 if( m_colIdxMap.count( aCol ) )
811 {
812 const wxString& key = m_colIdxMap.at( aCol );
813
814 if( key == wxT( "Description" ) )
815 valueStr = UnescapeString( node->m_Desc );
816 else if( node->m_Fields.count( key ) )
817 valueStr = UnescapeString( node->m_Fields.at( key ) );
818 else
819 valueStr = wxEmptyString;
820 }
821
822 break;
823 }
824
825 valueStr.Replace( wxS( "\n" ), wxS( " " ) ); // Clear line breaks
826
827 aVariant = valueStr;
828}
829
830
831bool LIB_TREE_MODEL_ADAPTER::GetAttr( const wxDataViewItem& aItem, unsigned int aCol,
832 wxDataViewItemAttr& aAttr ) const
833{
834 if( IsFrozen() )
835 return false;
836
837 LIB_TREE_NODE* node = ToNode( aItem );
838 wxCHECK( node, false );
839
840 if( node->m_Type == LIB_TREE_NODE::TYPE::ITEM )
841 {
842 if( !node->m_IsRoot && aCol == 0 )
843 {
844 // Names of non-root aliases are italicized
845 aAttr.SetItalic( true );
846 return true;
847 }
848 }
849
850 return false;
851}
852
853
854void recursiveDescent( LIB_TREE_NODE& aNode, const std::function<int( const LIB_TREE_NODE* )>& f )
855{
856 for( std::unique_ptr<LIB_TREE_NODE>& node: aNode.m_Children )
857 {
858 int r = f( node.get() );
859
860 if( r == 0 )
861 break;
862 else if( r == -1 )
863 continue;
864
865 recursiveDescent( *node, f );
866 }
867}
868
869
871{
872 const LIB_TREE_NODE* firstMatch = nullptr;
873
874 // Expand parents of leaf nodes with some level of matching
876 [&]( const LIB_TREE_NODE* n )
877 {
878 if( n->m_Type == LIB_TREE_NODE::TYPE::ITEM && n->m_Score > 1 )
879 {
880 // Mirror the sort order (see LIB_TREE_NODE::Compare): an exact match
881 // outranks any score, otherwise the higher score wins. Otherwise the
882 // view would scroll to a high-scoring item that isn't at the top.
883 if( !firstMatch )
884 firstMatch = n;
885 else if( n->m_ExactMatch && !firstMatch->m_ExactMatch )
886 firstMatch = n;
887 else if( n->m_ExactMatch == firstMatch->m_ExactMatch && n->m_Score > firstMatch->m_Score )
888 firstMatch = n;
889
890 m_widget->ExpandAncestors( ToItem( n ) );
891 }
892
893 return 1; // keep going to expand ancestors of all found items
894 } );
895
896 // If no matches, find and show the preselect node
897 if( !firstMatch && m_preselect_lib_id.IsValid() )
898 {
900 [&]( const LIB_TREE_NODE* n )
901 {
902 // Don't match the recent and already placed libraries
903 if( n->m_Name.StartsWith( "-- " ) )
904 return -1; // Skip this node and its children
905
906 // A row the filter hides has no native row to select
907 if( n->m_Score <= 0 )
908 return -1;
909
910 if( n->m_Type == LIB_TREE_NODE::TYPE::ITEM
911 && ( n->m_Children.empty() || !m_preselect_unit )
912 && m_preselect_lib_id == n->m_LibId )
913 {
914 firstMatch = n;
915 m_widget->ExpandAncestors( ToItem( n ) );
916 return 0;
917 }
918 else if( n->m_Type == LIB_TREE_NODE::TYPE::UNIT
921 {
922 firstMatch = n;
923 m_widget->ExpandAncestors( ToItem( n ) );
924 return 0;
925 }
926
927 return 1;
928 } );
929 }
930
931 // If still no matches expand a single library if there is only one
932 if( !firstMatch )
933 {
934 int libraries = 0;
935
936 for( const std::unique_ptr<LIB_TREE_NODE>& child : m_tree.m_Children )
937 {
938 if( !child->m_Name.StartsWith( "-- " ) )
939 libraries++;
940 }
941
942 if( libraries != 1 )
943 return nullptr;
944
946 [&]( const LIB_TREE_NODE* n )
947 {
948 if( n->m_Score <= 0 )
949 return -1;
950
951 if( n->m_Type == LIB_TREE_NODE::TYPE::ITEM )
952 {
953 firstMatch = n;
954 m_widget->ExpandAncestors( ToItem( n ) );
955 return 0;
956 }
957
958 return 1;
959 } );
960 }
961
962 return firstMatch;
963}
964
965
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
std::map< wxString, int > m_redrawNudge
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
int redrawNudge(const wxString &aColumn) const
What RefreshTree last added to aColumn's shown width to force a redraw.
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
int GetColumnWidth(const wxDataViewColumn *aColumn)
The width last asked of aColumn, by SetWidth or by the user dragging its border.
Definition wxgtk/ui.cpp:750
void CancelPendingScroll(wxDataViewCtrl *aCtrl)
Cancel any pending scroll-to-item request on aCtrl.
Definition wxgtk/ui.cpp:759
bool IsDarkTheme()
Determine if the desktop interface is currently using a dark theme or a light theme.
Definition wxgtk/ui.cpp:57
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.