KiCad PCB EDA Suite
Loading...
Searching...
No Matches
wx_grid.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 The 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 3
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 <wx/colour.h>
25#include <wx/tokenzr.h>
26#include <wx/dc.h>
27#include <wx/settings.h>
28#include <wx/event.h> // Needed for textentry.h on MSW
29#include <wx/textentry.h>
30
33#include <widgets/wx_grid.h>
34#include <widgets/ui_common.h>
35#include <algorithm>
36#include <core/kicad_algo.h>
37#include <gal/color4d.h>
38#include <kiplatform/ui.h>
39#include <utility>
40
41#include <pgm_base.h>
43#include <dialog_shim.h>
44
45
46wxGridCellAttr* WX_GRID_TABLE_BASE::enhanceAttr( wxGridCellAttr* aInputAttr, int aRow, int aCol,
47 wxGridCellAttr::wxAttrKind aKind )
48{
49 wxGridCellAttr* attr = aInputAttr;
50
51 if( wxGridCellAttrProvider* provider = GetAttrProvider() )
52 {
53 wxGridCellAttr* providerAttr = provider->GetAttr( aRow, aCol, aKind );
54
55 if( providerAttr )
56 {
57 attr = new wxGridCellAttr;
58 attr->SetKind( wxGridCellAttr::Merged );
59
60 if( aInputAttr )
61 {
62 attr->MergeWith( aInputAttr );
63 aInputAttr->DecRef();
64 }
65
66 attr->MergeWith( providerAttr );
67 providerAttr->DecRef();
68 }
69 }
70
71 return attr;
72}
73
74
75#define MIN_GRIDCELL_MARGIN FromDIP( 2 )
76
77
78void WX_GRID::CellEditorSetMargins( wxTextEntryBase* aEntry )
79{
80 // This is consistent with wxGridCellTextEditor. But works differently across platforms of course.
81 aEntry->SetMargins( 0, 0 );
82}
83
84
86{
87#if defined( __WXMSW__ ) || defined( __WXGTK__ )
88 aRect.Deflate( 2 );
89#endif
90}
91
92
94{
95 KIGFX::COLOR4D bg = wxSystemSettings::GetColour( wxSYS_COLOUR_FRAMEBK );
96 KIGFX::COLOR4D fg = wxSystemSettings::GetColour( wxSYS_COLOUR_ACTIVEBORDER );
97 KIGFX::COLOR4D border = fg.Mix( bg, 0.50 );
98 return border.ToColour();
99}
100
101
102class WX_GRID_CORNER_HEADER_RENDERER : public wxGridCornerHeaderRendererDefault
103{
104public:
105 void DrawBorder( const wxGrid& grid, wxDC& dc, wxRect& rect ) const override
106 {
107 wxDCBrushChanger SetBrush( dc, *wxTRANSPARENT_BRUSH );
108 wxDCPenChanger SetPen( dc, wxPen( getBorderColour(), 1 ) );
109
110 rect.SetTop( rect.GetTop() + 1 );
111 rect.SetLeft( rect.GetLeft() + 1 );
112 rect.SetBottom( rect.GetBottom() - 1 );
113 rect.SetRight( rect.GetRight() - 1 );
114 dc.DrawRectangle( rect );
115 }
116};
117
118
119class WX_GRID_COLUMN_HEADER_RENDERER : public wxGridColumnHeaderRendererDefault
120{
121public:
122 void DrawBorder( const wxGrid& grid, wxDC& dc, wxRect& rect ) const override
123 {
124 wxDCBrushChanger SetBrush( dc, *wxTRANSPARENT_BRUSH );
125 wxDCPenChanger SetPen( dc, wxPen( getBorderColour(), 1 ) );
126
127 rect.SetTop( rect.GetTop() + 1 );
128 rect.SetLeft( rect.GetLeft() );
129 rect.SetBottom( rect.GetBottom() - 1 );
130 rect.SetRight( rect.GetRight() - 1 );
131 dc.DrawRectangle( rect );
132 }
133};
134
135
136class WX_GRID_ROW_HEADER_RENDERER : public wxGridRowHeaderRendererDefault
137{
138public:
139 void DrawBorder( const wxGrid& grid, wxDC& dc, wxRect& rect ) const override
140 {
141 wxDCBrushChanger SetBrush( dc, *wxTRANSPARENT_BRUSH );
142 wxDCPenChanger SetPen( dc, wxPen( getBorderColour(), 1 ) );
143
144 rect.SetTop( rect.GetTop() + 1 );
145 rect.SetLeft( rect.GetLeft() + 1 );
146 rect.SetBottom( rect.GetBottom() - 1 );
147 rect.SetRight( rect.GetRight() );
148 dc.DrawRectangle( rect );
149 }
150};
151
152
157class WX_GRID_ALT_ROW_COLOR_PROVIDER : public wxGridCellAttrProvider
158{
159public:
160 WX_GRID_ALT_ROW_COLOR_PROVIDER( const wxColor& aBaseColor ) :
161 wxGridCellAttrProvider(),
162 m_attrEven( new wxGridCellAttr() )
163 {
164 UpdateColors( aBaseColor );
165 }
166
167 void UpdateColors( const wxColor& aBaseColor )
168 {
169 // Choose the default color, taking into account if the dark mode theme is enabled
170 wxColor rowColor = aBaseColor.ChangeLightness( KIPLATFORM::UI::IsDarkTheme() ? 105 : 95 );
171
172 m_attrEven->SetBackgroundColour( rowColor );
173 }
174
175 wxGridCellAttr* GetAttr( int row, int col, wxGridCellAttr::wxAttrKind kind ) const override
176 {
177 wxGridCellAttrPtr cellAttr( wxGridCellAttrProvider::GetAttr( row, col, kind ) );
178
179 // Just pass through the cell attribute on odd rows (start normal to allow for the
180 // header row)
181 if( !( row % 2 ) )
182 return cellAttr.release();
183
184 if( !cellAttr )
185 {
186 cellAttr = m_attrEven;
187 }
188 else
189 {
190 if( !cellAttr->HasBackgroundColour() )
191 {
192 cellAttr = cellAttr->Clone();
193 cellAttr->SetBackgroundColour( m_attrEven->GetBackgroundColour() );
194 }
195 }
196
197 return cellAttr.release();
198 }
199
200private:
201 wxGridCellAttrPtr m_attrEven;
202};
203
204
205WX_GRID::WX_GRID( wxWindow *parent, wxWindowID id, const wxPoint& pos, const wxSize& size, long style,
206 const wxString& name ) :
207 wxGrid( parent, id, pos, size, style, name ),
208 m_weOwnTable( false )
209{
210 // Grids with comboboxes need a bit of extra height; other grids look better if they're consistent.
211 SetDefaultRowSize( GetDefaultRowSize() + FromDIP( 4 ) );
212
213 SetDefaultCellOverflow( false );
214
215 // Make sure the GUI font scales properly
216 SetDefaultCellFont( KIUI::GetControlFont( this ) );
218
220
221 Connect( wxEVT_DPI_CHANGED, wxDPIChangedEventHandler( WX_GRID::onDPIChanged ), nullptr, this );
222 Connect( wxEVT_GRID_EDITOR_SHOWN, wxGridEventHandler( WX_GRID::onCellEditorShown ), nullptr, this );
223 Connect( wxEVT_GRID_EDITOR_HIDDEN, wxGridEventHandler( WX_GRID::onCellEditorHidden ), nullptr, this );
224}
225
226
228{
229 if( m_weOwnTable )
230 DestroyTable( GetTable() );
231
232 delete m_rowIconProvider;
233
234 Disconnect( wxEVT_GRID_EDITOR_SHOWN, wxGridEventHandler( WX_GRID::onCellEditorShown ), nullptr, this );
235 Disconnect( wxEVT_GRID_EDITOR_HIDDEN, wxGridEventHandler( WX_GRID::onCellEditorHidden ), nullptr, this );
236 Disconnect( wxEVT_DPI_CHANGED, wxDPIChangedEventHandler( WX_GRID::onDPIChanged ), nullptr, this );
237}
238
239
240void WX_GRID::onDPIChanged(wxDPIChangedEvent& aEvt)
241{
242 CallAfter( [&]()
243 {
244 wxGrid::SetColLabelSize( wxGRID_AUTOSIZE );
245 } );
246
247 // Don't skip, otherwise the grid gets too big
248}
249
250
251void WX_GRID::SetColLabelSize( int aHeight )
252{
253 if( aHeight == 0 || aHeight == wxGRID_AUTOSIZE )
254 {
255 wxGrid::SetColLabelSize( aHeight );
256 return;
257 }
258
259 // Correct wxFormBuilder height for large fonts
260 int minHeight = GetCharHeight() + 2 * MIN_GRIDCELL_MARGIN;
261
262 wxGrid::SetColLabelSize( std::max( aHeight, minHeight ) );
263}
264
265
266void WX_GRID::SetLabelFont( const wxFont& aFont )
267{
268 wxGrid::SetLabelFont( KIUI::GetControlFont( this ) );
269}
270
271
272void WX_GRID::SetTable( wxGridTableBase* aTable, bool aTakeOwnership )
273{
274 // wxGrid::SetTable() messes up the column widths from wxFormBuilder so we have to save
275 // and restore them.
276 int numberCols = GetNumberCols();
277 int* formBuilderColWidths = new int[numberCols];
278
279 for( int i = 0; i < numberCols; ++i )
280 formBuilderColWidths[ i ] = GetColSize( i );
281
282 wxGrid::SetTable( aTable );
283
284 // wxGrid::SetTable() may change the number of columns, so prevent out-of-bounds access
285 // to formBuilderColWidths
286 numberCols = std::min( numberCols, GetNumberCols() );
287
288 for( int i = 0; i < numberCols; ++i )
289 {
290 // correct wxFormBuilder width for large fonts and/or long translations
291 int headingWidth = GetTextExtent( GetColLabelValue( i ) ).x + 2 * MIN_GRIDCELL_MARGIN;
292
293 SetColSize( i, std::max( formBuilderColWidths[ i ], headingWidth ) );
294 }
295
296 delete[] formBuilderColWidths;
297
298 EnableAlternateRowColors( Pgm().GetCommonSettings() && Pgm().GetCommonSettings()->m_Appearance.grid_striping );
299
300 Connect( wxEVT_GRID_COL_MOVE, wxGridEventHandler( WX_GRID::onGridColMove ), nullptr, this );
301 Connect( wxEVT_GRID_SELECT_CELL, wxGridEventHandler( WX_GRID::onGridCellSelect ), nullptr, this );
302
303 m_weOwnTable = aTakeOwnership;
304}
305
306
308{
309 wxGridTableBase* table = wxGrid::GetTable();
310
311 wxCHECK_MSG( table, /* void */, "Tried to enable alternate row colors without a table assigned to the grid" );
312
313 if( aEnable )
314 {
315 wxColor color = wxGrid::GetDefaultCellBackgroundColour();
316 table->SetAttrProvider( new WX_GRID_ALT_ROW_COLOR_PROVIDER( color ) );
317 }
318 else
319 {
320 table->SetAttrProvider( nullptr );
321 }
322}
323
324
325void WX_GRID::onGridCellSelect( wxGridEvent& aEvent )
326{
327 // Highlight the selected cell.
328 // Calling SelectBlock() allows a visual effect when cells are selected by tab or arrow keys.
329 // Otherwise, one cannot really know what actual cell is selected.
330 int row = aEvent.GetRow();
331 int col = aEvent.GetCol();
332
333 if( row >= 0 && row < GetNumberRows() && col >= 0 && col < GetNumberCols() )
334 {
335 if( GetSelectionMode() == wxGrid::wxGridSelectCells )
336 {
337 SelectBlock( row, col, row, col, false );
338 }
339 else if( GetSelectionMode() == wxGrid::wxGridSelectRows
340 || GetSelectionMode() == wxGrid::wxGridSelectRowsOrColumns )
341 {
342 SelectBlock( row, 0, row, GetNumberCols() - 1, false );
343 }
344 else if( GetSelectionMode() == wxGrid::wxGridSelectColumns )
345 {
346 SelectBlock( 0, col, GetNumberRows() - 1, col, false );
347 }
348 }
349}
350
351
352void WX_GRID::onCellEditorShown( wxGridEvent& aEvent )
353{
354 if( alg::contains( m_autoEvalCols, aEvent.GetCol() ) )
355 {
356 int row = aEvent.GetRow();
357 int col = aEvent.GetCol();
358
359 const std::pair<wxString, wxString>& beforeAfter = m_evalBeforeAfter[ { row, col } ];
360
361 if( GetCellValue( row, col ) == beforeAfter.second )
362 SetCellValue( row, col, beforeAfter.first );
363 }
364}
365
366
367void WX_GRID::onCellEditorHidden( wxGridEvent& aEvent )
368{
369 const int col = aEvent.GetCol();
370
371 if( alg::contains( m_autoEvalCols, col ) )
372 {
373 UNITS_PROVIDER* unitsProvider = getUnitsProvider( col );
374
375 auto cellUnitsData = getColumnUnits( col );
376 EDA_UNITS cellUnits = cellUnitsData.first;
377 EDA_DATA_TYPE cellDataType = cellUnitsData.second;
378
379 m_eval->SetDefaultUnits( cellUnits );
380
381 const int row = aEvent.GetRow();
382
383 // Determine if this cell is marked as holding nullable values
384 bool isNullable = false;
385 wxGridCellEditor* cellEditor = GetCellEditor( row, col );
386
387 if( cellEditor )
388 {
389 if( const GRID_CELL_NULLABLE_INTERFACE* nullable =
390 dynamic_cast<GRID_CELL_NULLABLE_INTERFACE*>( cellEditor ) )
391 isNullable = nullable->IsNullable();
392
393 cellEditor->DecRef();
394 }
395
396 CallAfter(
397 [this, row, col, isNullable, unitsProvider, cellDataType]()
398 {
399 // Careful; if called from CommitPendingChange() in a delete operation, the cell may
400 // no longer exist.
401 if( row >= GetNumberRows() || col >= GetNumberCols() )
402 return;
403
404 wxString stringValue = GetCellValue( row, col );
405 bool processedOk = true;
406
407 if( stringValue != UNITS_PROVIDER::NullUiString )
408 processedOk = m_eval->Process( stringValue );
409
410 if( processedOk )
411 {
412 wxString evalValue;
413
414 if( isNullable )
415 {
416 std::optional<int> val;
417
418 if( stringValue == UNITS_PROVIDER::NullUiString )
419 {
421 cellDataType );
422 }
423 else
424 {
425 val = unitsProvider->OptionalValueFromString( m_eval->Result(), cellDataType );
426 }
427
428 evalValue = unitsProvider->StringFromOptionalValue( val, true, cellDataType );
429 }
430 else
431 {
432 int val = unitsProvider->ValueFromString( m_eval->Result(), cellDataType );
433 evalValue = unitsProvider->StringFromValue( val, true, cellDataType );
434 }
435
436 if( stringValue != evalValue )
437 {
438 SetCellValue( row, col, evalValue );
439 m_evalBeforeAfter[{ row, col }] = { stringValue, evalValue };
440 }
441 }
442 } );
443 }
444
445 aEvent.Skip();
446}
447
448
449void WX_GRID::DestroyTable( wxGridTableBase* aTable )
450{
451 // wxGrid's destructor will crash trying to look up the cell attr if the edit control
452 // is left open. Normally it's closed in Validate(), but not if the user hit Cancel.
453 CommitPendingChanges( true /* quiet mode */ );
454
455 Disconnect( wxEVT_GRID_COL_MOVE, wxGridEventHandler( WX_GRID::onGridColMove ), nullptr, this );
456 Disconnect( wxEVT_GRID_SELECT_CELL, wxGridEventHandler( WX_GRID::onGridCellSelect ), nullptr, this );
457
458 wxGrid::SetTable( nullptr );
459 delete aTable;
460}
461
462
464{
465 wxString shownColumns;
466
467 for( int i = 0; i < GetNumberCols(); ++i )
468 {
469 if( IsColShown( i ) )
470 {
471 if( shownColumns.Length() )
472 shownColumns << wxT( " " );
473
474 shownColumns << i;
475 }
476 }
477
478 return shownColumns;
479}
480
481
483{
484 std::bitset<64> shownColumns;
485
486 for( int ii = 0; ii < GetNumberCols(); ++ii )
487 shownColumns[ii] = IsColShown( ii );
488
489 return shownColumns;
490}
491
492
493void WX_GRID::ShowHideColumns( const wxString& shownColumns )
494{
495 for( int i = 0; i < GetNumberCols(); ++i )
496 HideCol( i );
497
498 wxStringTokenizer shownTokens( shownColumns, " \t\r\n", wxTOKEN_STRTOK );
499
500 while( shownTokens.HasMoreTokens() )
501 {
502 long colNumber;
503 shownTokens.GetNextToken().ToLong( &colNumber );
504
505 if( colNumber >= 0 && colNumber < GetNumberCols() )
506 ShowCol( (int) colNumber );
507 }
508}
509
510
512{
513 if( m_nativeColumnLabels )
514 wxGrid::DrawCornerLabel( dc );
515
516 wxRect rect( wxSize( m_rowLabelWidth, m_colLabelHeight ) );
517
519
520 // It is reported that we need to erase the background to avoid display artifacts; see #12055.
521 {
522 wxDCBrushChanger setBrush( dc, m_colLabelWin->GetBackgroundColour() );
523 wxDCPenChanger setPen( dc, m_colLabelWin->GetBackgroundColour() );
524 dc.DrawRectangle( rect.Inflate( 1 ) );
525 }
526
527 rend.DrawBorder( *this, dc, rect );
528}
529
530
531void WX_GRID::DrawColLabel( wxDC& dc, int col )
532{
533 if( m_nativeColumnLabels )
534 wxGrid::DrawColLabel( dc, col );
535
536 if( GetColWidth( col ) <= 0 || m_colLabelHeight <= 0 )
537 return;
538
539 wxRect rect( GetColLeft( col ), 0, GetColWidth( col ), m_colLabelHeight );
540
542
543 // It is reported that we need to erase the background to avoid display artifacts; see #12055.
544 {
545 wxDCBrushChanger setBrush( dc, m_colLabelWin->GetBackgroundColour() );
546 wxDCPenChanger setPen( dc, m_colLabelWin->GetBackgroundColour() );
547 dc.DrawRectangle( rect.Inflate( 1 ) );
548 }
549
550 rend.DrawBorder( *this, dc, rect );
551
552 // Make sure fonts get scaled correctly on GTK HiDPI monitors
553 dc.SetFont( GetLabelFont() );
554
555 int hAlign, vAlign;
556 GetColLabelAlignment( &hAlign, &vAlign );
557 const int orient = GetColLabelTextOrientation();
558
559 if( col == 0 )
560 hAlign = wxALIGN_LEFT;
561
562 if( hAlign == wxALIGN_LEFT )
563 rect.SetLeft( rect.GetLeft() + MIN_GRIDCELL_MARGIN );
564
565 rend.DrawLabel( *this, dc, GetColLabelValue( col ), rect, hAlign, vAlign, orient );
566}
567
568
569void WX_GRID::DrawRowLabel( wxDC& dc, int row )
570{
571 if( GetRowHeight( row ) <= 0 || m_rowLabelWidth <= 0 )
572 return;
573
574 wxRect rect( 0, GetRowTop( row ), m_rowLabelWidth, GetRowHeight( row ) );
575
576 static WX_GRID_ROW_HEADER_RENDERER rend;
577
578 // It is reported that we need to erase the background to avoid display artifacts; see #12055.
579 {
580 wxDCBrushChanger setBrush( dc, m_colLabelWin->GetBackgroundColour() );
581 wxDCPenChanger setPen( dc, m_colLabelWin->GetBackgroundColour() );
582 dc.DrawRectangle( rect.Inflate( 1 ) );
583 }
584
585 rend.DrawBorder( *this, dc, rect );
586
587 // Make sure fonts get scaled correctly on GTK HiDPI monitors
588 dc.SetFont( GetLabelFont() );
589
590 int hAlign, vAlign;
591 GetRowLabelAlignment(&hAlign, &vAlign);
592
593 if( hAlign == wxALIGN_LEFT )
594 rect.SetLeft( rect.GetLeft() + MIN_GRIDCELL_MARGIN );
595
596 rend.DrawLabel( *this, dc, GetRowLabelValue( row ), rect, hAlign, vAlign, wxHORIZONTAL );
597}
598
599
601{
602 if( !IsCellEditControlEnabled() )
603 return true;
604
605 HideCellEditControl();
606
607 // do it after HideCellEditControl()
608 m_cellEditCtrlEnabled = false;
609
610 int row = m_currentCellCoords.GetRow();
611 int col = m_currentCellCoords.GetCol();
612
613 wxString oldval = GetCellValue( row, col );
614 wxString newval;
615
616 wxGridCellAttr* attr = GetCellAttr( row, col );
617 wxGridCellEditor* editor = attr->GetEditor( this, row, col );
618
619 editor->EndEdit( row, col, this, oldval, &newval );
620
621 editor->DecRef();
622 attr->DecRef();
623
624 return true;
625}
626
627
628bool WX_GRID::CommitPendingChanges( bool aQuietMode )
629{
630 if( !IsCellEditControlEnabled() )
631 return true;
632
633 if( !aQuietMode && SendEvent( wxEVT_GRID_EDITOR_HIDDEN ) == -1 )
634 return false;
635
636 HideCellEditControl();
637
638 // do it after HideCellEditControl()
639 m_cellEditCtrlEnabled = false;
640
641 int row = m_currentCellCoords.GetRow();
642 int col = m_currentCellCoords.GetCol();
643
644 wxString oldval = GetCellValue( row, col );
645 wxString newval;
646
647 wxGridCellAttr* attr = GetCellAttr( row, col );
648 wxGridCellEditor* editor = attr->GetEditor( this, row, col );
649
650 bool changed = editor->EndEdit( row, col, this, oldval, &newval );
651
652 editor->DecRef();
653 attr->DecRef();
654
655 if( changed )
656 {
657 if( !aQuietMode && SendEvent( wxEVT_GRID_CELL_CHANGING, newval ) == -1 )
658 return false;
659
660 editor->ApplyEdit( row, col, this );
661
662 // for compatibility reasons dating back to wx 2.8 when this event
663 // was called wxEVT_GRID_CELL_CHANGE and wxEVT_GRID_CELL_CHANGING
664 // didn't exist we allow vetoing this one too
665 if( !aQuietMode && SendEvent( wxEVT_GRID_CELL_CHANGED, oldval ) == -1 )
666 {
667 // Event has been vetoed, set the data back.
668 SetCellValue( row, col, oldval );
669 return false;
670 }
671
672 if( DIALOG_SHIM* dlg = dynamic_cast<DIALOG_SHIM*>( wxGetTopLevelParent( this ) ) )
673 dlg->OnModify();
674 }
675
676 return true;
677}
678
679
680void WX_GRID::OnAddRow( const std::function<std::pair<int, int>()>& aAdder )
681{
682 if( !CommitPendingChanges() )
683 return;
684
685 auto [row, editCol] = aAdder();
686
687 // wx documentation is wrong, SetGridCursor does not make visible.
688 SetFocus();
689 MakeCellVisible( row, std::max( editCol, 0 ) );
690 SetGridCursor( row, std::max( editCol, 0 ) );
691
692 if( editCol >= 0 )
693 {
694 EnableCellEditControl( true );
695 ShowCellEditControl();
696 }
697}
698
699
700void WX_GRID::OnDeleteRows( const std::function<void( int row )>& aDeleter )
701{
703 []( int row )
704 {
705 return true;
706 },
707 aDeleter );
708}
709
710
711void WX_GRID::OnDeleteRows( const std::function<bool( int row )>& aFilter,
712 const std::function<void( int row )>& aDeleter )
713{
714 wxArrayInt selectedRows = GetSelectedRows();
715
716 if( selectedRows.empty() && GetGridCursorRow() >= 0 )
717 selectedRows.push_back( GetGridCursorRow() );
718
719 if( selectedRows.empty() )
720 return;
721
722 for( int row : selectedRows )
723 {
724 if( !aFilter( row ) )
725 return;
726 }
727
728 if( !CommitPendingChanges() )
729 return;
730
731 // Reverse sort so deleting a row doesn't change the indexes of the other rows.
732 selectedRows.Sort(
733 []( int* first, int* second )
734 {
735 return *second - *first;
736 } );
737
738 int nextSelRow = selectedRows.back() - 1;
739
740 if( nextSelRow >= 0 )
741 {
742 GoToCell( nextSelRow, GetGridCursorCol() );
743 SetGridCursor( nextSelRow, GetGridCursorCol() );
744 }
745
746 for( int row : selectedRows )
747 aDeleter( row );
748}
749
750
751void WX_GRID::SwapRows( int aRowA, int aRowB )
752{
753 for( int col = 0; col < GetNumberCols(); ++col )
754 {
755 wxString temp = GetCellValue( aRowA, col );
756 SetCellValue( aRowA, col, GetCellValue( aRowB, col ) );
757 SetCellValue( aRowB, col, temp );
758 }
759}
760
761
762void WX_GRID::OnMoveRowUp( const std::function<void( int row )>& aMover )
763{
765 []( int row )
766 {
767 return true;
768 },
769 aMover );
770}
771
772
773void WX_GRID::OnMoveRowUp( const std::function<bool( int row )>& aFilter,
774 const std::function<void( int row )>& aMover )
775{
776 if( !CommitPendingChanges() )
777 return;
778
779 int i = GetGridCursorRow();
780
781 if( i > 0 && aFilter( i ) )
782 {
783 aMover( i );
784
785 SetGridCursor( i - 1, GetGridCursorCol() );
786 MakeCellVisible( GetGridCursorRow(), GetGridCursorCol() );
787 }
788 else
789 {
790 wxBell();
791 }
792}
793
794
795void WX_GRID::OnMoveRowDown( const std::function<void( int row )>& aMover )
796{
798 []( int row )
799 {
800 return true;
801 },
802 aMover );
803}
804
805
806void WX_GRID::OnMoveRowDown( const std::function<bool( int row )>& aFilter,
807 const std::function<void( int row )>& aMover )
808{
809 if( !CommitPendingChanges() )
810 return;
811
812 int i = GetGridCursorRow();
813
814 if( i + 1 < GetNumberRows() && aFilter( i ) )
815 {
816 aMover( i );
817
818 SetGridCursor( i + 1, GetGridCursorCol() );
819 MakeCellVisible( GetGridCursorRow(), GetGridCursorCol() );
820 }
821 else
822 {
823 wxBell();
824 }
825}
826
827
828void WX_GRID::SetUnitsProvider( UNITS_PROVIDER* aProvider, int aCol )
829{
830 m_unitsProviders[ aCol ] = aProvider;
831
832 if( !m_eval )
833 m_eval = std::make_unique<NUMERIC_EVALUATOR>( aProvider->GetUserUnits() );
834}
835
836
837void WX_GRID::SetAutoEvalColUnits( const int col, EDA_UNITS aUnit, EDA_DATA_TYPE aUnitType )
838{
839 m_autoEvalColsUnits[col] = std::make_pair( aUnit, aUnitType );
840}
841
842
843void WX_GRID::SetAutoEvalColUnits( const int col, EDA_UNITS aUnit )
844{
846 SetAutoEvalColUnits( col, aUnit, type );
847}
848
849
850int WX_GRID::GetUnitValue( int aRow, int aCol )
851{
852 wxString stringValue = GetCellValue( aRow, aCol );
853
854 auto [cellUnits, cellDataType] = getColumnUnits( aCol );
855
856 if( alg::contains( m_autoEvalCols, aCol ) )
857 {
858 m_eval->SetDefaultUnits( cellUnits );
859
860 if( m_eval->Process( stringValue ) )
861 stringValue = m_eval->Result();
862 }
863
864 return getUnitsProvider( aCol )->ValueFromString( stringValue, cellDataType );
865}
866
867
868std::optional<int> WX_GRID::GetOptionalUnitValue( int aRow, int aCol )
869{
870 wxString stringValue = GetCellValue( aRow, aCol );
871
872 auto [cellUnits, cellDataType] = getColumnUnits( aCol );
873
874 if( alg::contains( m_autoEvalCols, aCol ) )
875 {
876 m_eval->SetDefaultUnits( cellUnits );
877
878 if( stringValue != UNITS_PROVIDER::NullUiString && m_eval->Process( stringValue ) )
879 stringValue = m_eval->Result();
880 }
881
882 return getUnitsProvider( aCol )->OptionalValueFromString( stringValue, cellDataType );
883}
884
885
886void WX_GRID::SetUnitValue( int aRow, int aCol, int aValue )
887{
888 EDA_DATA_TYPE cellDataType;
889
890 if( m_autoEvalColsUnits.contains( aCol ) )
891 cellDataType = m_autoEvalColsUnits[aCol].second;
892 else
893 cellDataType = EDA_DATA_TYPE::DISTANCE;
894
895 SetCellValue( aRow, aCol, getUnitsProvider( aCol )->StringFromValue( aValue, true, cellDataType ) );
896}
897
898
899void WX_GRID::SetOptionalUnitValue( int aRow, int aCol, std::optional<int> aValue )
900{
901 EDA_DATA_TYPE cellDataType;
902
903 if( m_autoEvalColsUnits.contains( aCol ) )
904 cellDataType = m_autoEvalColsUnits[aCol].second;
905 else
906 cellDataType = EDA_DATA_TYPE::DISTANCE;
907
908 SetCellValue( aRow, aCol, getUnitsProvider( aCol )->StringFromOptionalValue( aValue, true, cellDataType ) );
909}
910
911
912void WX_GRID::onGridColMove( wxGridEvent& aEvent )
913{
914 // wxWidgets won't move an open editor, so better just to close it
915 CommitPendingChanges( true );
916}
917
918
919int WX_GRID::GetVisibleWidth( int aCol, bool aHeader, bool aContents, bool aKeep )
920{
921 int size = 0;
922
923 if( aCol < 0 )
924 {
925 if( aKeep )
926 size = GetRowLabelSize();
927
928 for( int row = 0; aContents && row < GetNumberRows(); row++ )
929 size = std::max( size, int( GetTextExtent( GetRowLabelValue( row ) + wxS( "M" ) ).x ) );
930 }
931 else
932 {
933 if( aKeep )
934 size = GetColSize( aCol );
935
936 // 'M' is generally the widest character, so we buffer the column width by default to
937 // ensure we don't write a continuous line of text at the column header
938 if( aHeader )
939 {
941
942 size = std::max( size, int( GetTextExtent( GetColLabelValue( aCol ) + wxS( "M" ) ).x ) );
943 }
944
945 for( int row = 0; aContents && row < GetNumberRows(); row++ )
946 {
947 // If we have text, get the size. Otherwise, use a placeholder for the checkbox
948 if( GetTable()->CanGetValueAs( row, aCol, wxGRID_VALUE_STRING ) )
949 size = std::max( size, GetTextExtent( GetCellValue( row, aCol ) + wxS( "M" ) ).x );
950 else
951 size = std::max( size, GetTextExtent( "MM" ).x );
952 }
953 }
954
955 return size;
956}
957
958
960{
961 int line_height = int( GetTextExtent( "Mj" ).y ) + 3;
962 int row_height = GetColLabelSize();
963 int initial_row_height = row_height;
964
965 // Headers can be multiline. Fix the Column Label Height to show the full header
966 // However GetTextExtent does not work on multiline strings,
967 // and do not return the full text height (only the height of one line)
968 for( int col = 0; col < GetNumberCols(); col++ )
969 {
970 int nl_count = GetColLabelValue( col ).Freq( '\n' );
971
972 if( nl_count )
973 {
974 // Col Label height must be able to show nl_count+1 lines
975 if( row_height < line_height * ( nl_count+1 ) )
976 row_height += line_height * nl_count;
977 }
978 }
979
980 // Update the column label size, but only if needed, to avoid generating useless
981 // and perhaps annoying UI events when the size does not change
982 if( initial_row_height != row_height )
983 SetColLabelSize( row_height );
984}
985
986
987std::pair<EDA_UNITS, EDA_DATA_TYPE> WX_GRID::getColumnUnits( const int aCol ) const
988{
989 if( m_autoEvalColsUnits.contains( aCol ) )
990 return { m_autoEvalColsUnits.at( aCol ).first, m_autoEvalColsUnits.at( aCol ).second };
991
992 // Legacy - default always DISTANCE
994}
995
996
997void WX_GRID::SetupColumnAutosizer( int aFlexibleCol )
998{
999 const int colCount = GetNumberCols();
1000
1001 for( int ii = 0; ii < GetNumberCols(); ++ii )
1002 m_autosizedCols[ii] = GetColSize( ii );
1003
1004 m_flexibleCol = aFlexibleCol;
1005
1006 wxASSERT_MSG( m_flexibleCol < colCount, "Flexible column index does not exist in grid" );
1007
1008 Bind( wxEVT_UPDATE_UI,
1009 [this]( wxUpdateUIEvent& aEvent )
1010 {
1012 aEvent.Skip();
1013 } );
1014
1015 Bind( wxEVT_SIZE,
1016 [this]( wxSizeEvent& aEvent )
1017 {
1018 onSizeEvent( aEvent );
1019 aEvent.Skip();
1020 } );
1021
1022 // Handles the case when the user changes the cell content to be longer than the current column size
1023 Bind( wxEVT_GRID_CELL_CHANGED,
1024 [this]( wxGridEvent& aEvent )
1025 {
1026 m_gridWidthsDirty = true;
1027 aEvent.Skip();
1028 } );
1029}
1030
1031
1033{
1034 if( m_gridWidthsDirty )
1035 {
1036 const int width = GetSize().GetX() - wxSystemSettings::GetMetric( wxSYS_VSCROLL_X );
1037
1038 std::optional<int> flexibleMinWidth;
1039
1040 for( const auto& [colIndex, minWidth] : m_autosizedCols )
1041 {
1042 if( GetColSize( colIndex ) != 0 )
1043 {
1044 AutoSizeColumn( colIndex );
1045 const int colSize = GetColSize( colIndex );
1046
1047 int minWidthScaled = FromDIP( minWidth );
1048 SetColSize( colIndex, std::max( minWidthScaled, colSize ) );
1049
1050 if( colIndex == m_flexibleCol )
1051 flexibleMinWidth = minWidthScaled;
1052 }
1053 }
1054
1055 // Gather all the widths except the flexi one
1056 int nonFlexibleWidth = 0;
1057
1058 for( int i = 0; i < GetNumberCols(); ++i )
1059 {
1060 if( i != m_flexibleCol )
1061 nonFlexibleWidth += GetColSize( i );
1062 }
1063
1064 if( GetColSize( m_flexibleCol ) != 0 )
1065 SetColSize( m_flexibleCol, std::max( flexibleMinWidth.value_or( 0 ), width - nonFlexibleWidth ) );
1066
1067 // Store the state for next time
1068 m_gridWidth = GetSize().GetX();
1069 m_gridWidthsDirty = false;
1070 }
1071}
1072
1073
1074void WX_GRID::onSizeEvent( wxSizeEvent& aEvent )
1075{
1076 const int width = aEvent.GetSize().GetX();
1077
1078 if( width != m_gridWidth )
1079 m_gridWidthsDirty = true;
1080}
int color
const char * name
Dialog helper object to sit in the inheritance tree between wxDialog and any class written by wxFormB...
Definition dialog_shim.h:68
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:104
wxColour ToColour() const
Definition color4d.cpp:220
COLOR4D Mix(const COLOR4D &aColor, double aFactor) const
Return a color that is mixed with the input by a factor.
Definition color4d.h:295
Icon provider for the "standard" row indicators, for example in layer selection lists.
static const wxString NullUiString
The string that is used in the UI to represent a null value.
std::optional< int > OptionalValueFromString(const wxString &aTextValue, EDA_DATA_TYPE aType=EDA_DATA_TYPE::DISTANCE) const
Converts aTextValue in aUnits to internal units used by the frame.
wxString StringFromOptionalValue(std::optional< int > aValue, bool aAddUnitLabel=false, EDA_DATA_TYPE aType=EDA_DATA_TYPE::DISTANCE) const
Converts an optional aValue in internal units into a united string.
EDA_UNITS GetUserUnits() const
static EDA_DATA_TYPE GetTypeFromUnits(const EDA_UNITS aUnits)
Gets the inferred type from the given units.
wxString StringFromValue(double aValue, bool aAddUnitLabel=false, EDA_DATA_TYPE aType=EDA_DATA_TYPE::DISTANCE) const
Converts aValue in internal units into a united string.
int ValueFromString(const wxString &aTextValue, EDA_DATA_TYPE aType=EDA_DATA_TYPE::DISTANCE) const
Converts aTextValue in aUnits to internal units used by the frame.
Attribute provider that provides attributes (or modifies the existing attribute) to alternate a row c...
Definition wx_grid.cpp:158
WX_GRID_ALT_ROW_COLOR_PROVIDER(const wxColor &aBaseColor)
Definition wx_grid.cpp:160
wxGridCellAttr * GetAttr(int row, int col, wxGridCellAttr::wxAttrKind kind) const override
Definition wx_grid.cpp:175
wxGridCellAttrPtr m_attrEven
Definition wx_grid.cpp:201
void UpdateColors(const wxColor &aBaseColor)
Definition wx_grid.cpp:167
void DrawBorder(const wxGrid &grid, wxDC &dc, wxRect &rect) const override
Definition wx_grid.cpp:122
void DrawBorder(const wxGrid &grid, wxDC &dc, wxRect &rect) const override
Definition wx_grid.cpp:105
void DrawBorder(const wxGrid &grid, wxDC &dc, wxRect &rect) const override
Definition wx_grid.cpp:139
wxGridCellAttr * enhanceAttr(wxGridCellAttr *aInputAttr, int aRow, int aCol, wxGridCellAttr::wxAttrKind aKind)
Definition wx_grid.cpp:46
int GetVisibleWidth(int aCol, bool aHeader=true, bool aContents=true, bool aKeep=false)
Calculate the specified column based on the actual size of the text on screen.
Definition wx_grid.cpp:919
int m_flexibleCol
Definition wx_grid.h:360
void onGridCellSelect(wxGridEvent &aEvent)
Definition wx_grid.cpp:325
std::map< int, int > m_autosizedCols
Definition wx_grid.h:359
bool m_gridWidthsDirty
Definition wx_grid.h:362
~WX_GRID() override
Definition wx_grid.cpp:227
void SetLabelFont(const wxFont &aFont)
Hide wxGrid's SetLabelFont() because for some reason on MSW it's a one-shot and subsequent calls to i...
Definition wx_grid.cpp:266
bool m_weOwnTable
Definition wx_grid.h:349
void onDPIChanged(wxDPIChangedEvent &event)
Definition wx_grid.cpp:240
void ShowHideColumns(const wxString &shownColumns)
Show/hide the grid columns based on a tokenized string of shown column indexes.
Definition wx_grid.cpp:493
void OnMoveRowUp(const std::function< void(int row)> &aMover)
Definition wx_grid.cpp:762
std::map< int, UNITS_PROVIDER * > m_unitsProviders
Definition wx_grid.h:351
void SetTable(wxGridTableBase *table, bool aTakeOwnership=false)
Hide wxGrid's SetTable() method with one which doesn't mess up the grid column widths when setting th...
Definition wx_grid.cpp:272
void DestroyTable(wxGridTableBase *aTable)
Work-around for a bug in wxGrid which crashes when deleting the table if the cell edit control was no...
Definition wx_grid.cpp:449
std::unordered_map< int, std::pair< EDA_UNITS, EDA_DATA_TYPE > > m_autoEvalColsUnits
Definition wx_grid.h:354
void SetAutoEvalColUnits(int col, EDA_UNITS aUnit, EDA_DATA_TYPE aUnitType)
Set the unit and unit data type to use for a given column.
Definition wx_grid.cpp:837
bool CancelPendingChanges()
Definition wx_grid.cpp:600
void SetColLabelSize(int aHeight)
Hide wxGrid's SetColLabelSize() method with one which makes sure the size is tall enough for the syst...
Definition wx_grid.cpp:251
void SwapRows(int aRowA, int aRowB)
These aren't that tricky, but might as well share code.
Definition wx_grid.cpp:751
std::pair< EDA_UNITS, EDA_DATA_TYPE > getColumnUnits(int aCol) const
Returns the units and data type associated with a given column.
Definition wx_grid.cpp:987
void SetUnitValue(int aRow, int aCol, int aValue)
Set a unitized cell's value.
Definition wx_grid.cpp:886
WX_GRID(wxWindow *parent, wxWindowID id, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxDefaultSize, long style=wxWANTS_CHARS, const wxString &name=wxGridNameStr)
Definition wx_grid.cpp:205
int GetUnitValue(int aRow, int aCol)
Apply standard KiCad unit and eval services to a numeric cell.
Definition wx_grid.cpp:850
std::vector< int > m_autoEvalCols
Definition wx_grid.h:353
UNITS_PROVIDER * getUnitsProvider(int aCol) const
Definition wx_grid.h:330
std::map< std::pair< int, int >, std::pair< wxString, wxString > > m_evalBeforeAfter
Definition wx_grid.h:355
void DrawCornerLabel(wxDC &dc) override
A re-implementation of wxGrid::DrawCornerLabel which draws flat borders.
Definition wx_grid.cpp:511
ROW_ICON_PROVIDER * m_rowIconProvider
Definition wx_grid.h:365
void onCellEditorHidden(wxGridEvent &aEvent)
Definition wx_grid.cpp:367
void SetupColumnAutosizer(int aFlexibleCol)
Set autosize behaviour using wxFormBuilder column widths as minimums, with a single specified growabl...
Definition wx_grid.cpp:997
void OnMoveRowDown(const std::function< void(int row)> &aMover)
Definition wx_grid.cpp:795
void onGridColMove(wxGridEvent &aEvent)
Definition wx_grid.cpp:912
void SetOptionalUnitValue(int aRow, int aCol, std::optional< int > aValue)
Set a unitized cell's optional value.
Definition wx_grid.cpp:899
void onSizeEvent(wxSizeEvent &aEvent)
Definition wx_grid.cpp:1074
void onCellEditorShown(wxGridEvent &aEvent)
Definition wx_grid.cpp:352
void recomputeGridWidths()
Definition wx_grid.cpp:1032
void EnsureColLabelsVisible()
Ensure the height of the row displaying the column labels is enough, even if labels are multiline tex...
Definition wx_grid.cpp:959
void OnDeleteRows(const std::function< void(int row)> &aDeleter)
Handles a row deletion event.
Definition wx_grid.cpp:700
wxString GetShownColumnsAsString()
Get a tokenized string containing the shown column indexes.
Definition wx_grid.cpp:463
void OnAddRow(const std::function< std::pair< int, int >()> &aAdder)
Definition wx_grid.cpp:680
int m_gridWidth
Definition wx_grid.h:363
void DrawRowLabel(wxDC &dc, int row) override
A re-implementation of wxGrid::DrawRowLabel which draws flat borders.
Definition wx_grid.cpp:569
std::bitset< 64 > GetShownColumns()
Definition wx_grid.cpp:482
static void CellEditorSetMargins(wxTextEntryBase *aEntry)
A helper function to set OS-specific margins for text-based cell editors.
Definition wx_grid.cpp:78
std::optional< int > GetOptionalUnitValue(int aRow, int aCol)
Apply standard KiCad unit and eval services to a numeric cell.
Definition wx_grid.cpp:868
void EnableAlternateRowColors(bool aEnable=true)
Enable alternate row highlighting, where every odd row has a different background color than the even...
Definition wx_grid.cpp:307
void SetUnitsProvider(UNITS_PROVIDER *aProvider, int aCol=0)
Set a EUNITS_PROVIDER to enable use of unit- and eval-based Getters.
Definition wx_grid.cpp:828
bool CommitPendingChanges(bool aQuietMode=false)
Close any open cell edit controls.
Definition wx_grid.cpp:628
std::unique_ptr< NUMERIC_EVALUATOR > m_eval
Definition wx_grid.h:352
void DrawColLabel(wxDC &dc, int col) override
A re-implementation of wxGrid::DrawColLabel which left-aligns the first column and draws flat borders...
Definition wx_grid.cpp:531
static void CellEditorTransformSizeRect(wxRect &aRect)
A helper function to tweak sizes of text-based cell editors depending on OS.
Definition wx_grid.cpp:85
EDA_DATA_TYPE
The type of unit.
Definition eda_units.h:38
EDA_UNITS
Definition eda_units.h:48
bool IsDarkTheme()
Determine if the desktop interface is currently using a dark theme or a light theme.
Definition wxgtk/ui.cpp:48
KICOMMON_API wxFont GetControlFont(wxWindow *aWindow)
const int c_IndicatorSizeDIP
Definition ui_common.h:52
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:100
PGM_BASE & Pgm()
The global program "get" accessor.
Definition pgm_base.cpp:946
see class PGM_BASE
Functions to provide common constants and other functions to assist in making a consistent UI.
wxColour getBorderColour()
Definition wx_grid.cpp:93
#define MIN_GRIDCELL_MARGIN
Definition wx_grid.cpp:75