KiCad PCB EDA Suite
Loading...
Searching...
No Matches
dialog_fields_table.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) Mike Williams
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * This program is free software: you can redistribute it and/or modify it
8 * under the terms of the GNU General Public License as published by the
9 * Free Software Foundation, either version 3 of the License, or (at your
10 * option) any later version.
11 *
12 * This program is distributed in the hope that it will be useful, but
13 * WITHOUT ANY WARRANTY; without even the implied warranty of
14 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
15 * General Public License for more details.
16 *
17 * You should have received a copy of the GNU General Public License
18 * along with this program. If not, see <https://www.gnu.org/licenses/>.
19 */
20
21#include "dialog_fields_table.h"
23
24#include <algorithm>
25#include <functional>
26#include <string>
27#include <bitmaps.h>
28#include <common.h>
29#include <confirm.h>
30#include <core/kicad_algo.h>
31#include <eda_base_frame.h>
32#include <eda_list_dialog.h>
34#include <grid_tricks.h>
35#include <jobs/job_export_bom.h>
36#include <kiplatform/ui.h>
37#include <reporter.h>
39#include <template_fieldnames.h>
40#include <validators.h>
46#include <widgets/ui_common.h>
47#include <wx/ffile.h>
48#include <wx/filedlg.h>
49#include <wx/filename.h>
50#include <wx/grid.h>
51#include <wx/msgdlg.h>
52#include <wx/textdlg.h>
53
54#ifdef __WXMAC__
55#define COLUMN_MARGIN 4
56#else
57#define COLUMN_MARGIN 15
58#endif
59
60
61static constexpr int MAX_COL_WIDTH = 100000;
62
63
64static bool isValidColumnWidth( int aWidth )
65{
66 return aWidth > 0 && aWidth <= MAX_COL_WIDTH;
67}
68
69
70namespace
71{
72template <typename PRESET>
73int findPresetIndexByPointer( const wxChoice* aChoice, const PRESET* aPreset )
74{
75 for( unsigned i = 0; i < aChoice->GetCount(); ++i )
76 {
77 if( aChoice->GetClientData( i ) == static_cast<const void*>( aPreset ) )
78 return static_cast<int>( i );
79 }
80
81 return wxNOT_FOUND;
82}
83
84
85template <typename PRESET>
86int findPresetIndexByName( const wxChoice* aChoice, const std::map<wxString, PRESET>& aPresets,
87 const wxString& aName )
88{
89 auto presetIt = aPresets.find( aName );
90
91 return presetIt == aPresets.end() ? wxNOT_FOUND : findPresetIndexByPointer( aChoice, &presetIt->second );
92}
93
94
95enum
96{
97 MYID_REVERT_ROW = GRIDTRICKS_FIRST_CLIENT_ID,
98 MYID_CLEAR_CELL
99};
100
101
102class VIEW_CONTROLS_GRID_TRICKS : public GRID_TRICKS
103{
104public:
105 VIEW_CONTROLS_GRID_TRICKS( WX_GRID* aGrid ) :
106 GRID_TRICKS( aGrid )
107 {
108 }
109
110protected:
111 void doPopupSelection( wxCommandEvent& aEvent ) override
112 {
113 if( aEvent.GetId() >= GRIDTRICKS_FIRST_SHOWHIDE )
114 m_grid->PostSizeEvent();
115
117 }
118};
119} // namespace
120
121
123 FIELDS_TABLE_DATA_MODEL_BASE* aDataModel ) :
124 GRID_TRICKS( aGrid ),
125 m_dialog( aDialog ),
126 m_dataModel( aDataModel )
127{
128}
129
130
131void FIELDS_TABLE_GRID_TRICKS::showPopupMenu( wxMenu& aMenu, wxGridEvent& aEvent )
132{
133 int row = m_grid->GetGridCursorRow();
134 int col = m_grid->GetGridCursorCol();
135
136 wxMenuItem* revertMenu = aMenu.Append( MYID_REVERT_ROW, _( "Revert Row" ),
137 _( "Revert the fields in this row" ) );
138 wxMenuItem* clearMenu = aMenu.Append( MYID_CLEAR_CELL, _( "Clear Cell" ),
139 _( "Clear the cell value" ) );
140 aMenu.AppendSeparator();
141
142 if( row >= 0 && col >= 0 )
143 {
144 revertMenu->Enable( m_grid->IsEditable() && m_dataModel->IsRowEdited( row ) );
145 clearMenu->Enable( m_grid->IsEditable() && m_dataModel->CanClearCell( row, col ) );
146 }
147 else
148 {
149 revertMenu->Enable( false );
150 clearMenu->Enable( false );
151 }
152
153 showFieldsTablePopupMenu( aMenu, aEvent );
154}
155
156
158{
159 if( m_dialog->m_variantListBox->GetCount() < 2 )
160 return;
161
162 // Snapshot the selection before showing the menu, which can change the grid selection.
163 std::vector<wxGridCellCoords> cells;
164 bool hasSelection = m_grid->IsSelection();
165
166 if( m_grid->IsEditable() )
167 {
168 for( int row = 0; row < m_grid->GetNumberRows(); ++row )
169 {
170 for( int col = 0; col < m_grid->GetNumberCols(); ++col )
171 {
172 bool selected = hasSelection ? m_grid->IsInSelection( row, col )
173 : row == m_grid->GetGridCursorRow() && col == m_grid->GetGridCursorCol();
174
175 if( selected && m_grid->IsColShown( col ) && m_dataModel->CanCopyCellFromVariant( row, col ) )
176 {
177 cells.emplace_back( row, col );
178 }
179 }
180 }
181 }
182
183 wxMenu* variantsMenu = new wxMenu;
184
185 for( unsigned int i = 0; i < m_dialog->m_variantListBox->GetCount(); ++i )
186 {
187 wxString name = m_dialog->m_variantListBox->GetString( i );
188 wxString variant = name == GetDefaultVariantName() ? wxString() : name;
189 wxString label = name;
190 label.Replace( wxS( "&" ), wxS( "&&" ) );
191
192 wxMenuItem* item = variantsMenu->Append( wxID_ANY, label );
193 item->Enable( !cells.empty() && variant != m_dataModel->GetCurrentVariant() );
194
195 variantsMenu->Bind(
196 wxEVT_COMMAND_MENU_SELECTED,
197 [this, variant, cells]( wxCommandEvent& )
198 {
199 copyFromVariant( variant, cells );
200 },
201 item->GetId() );
202 }
203
204 aMenu.AppendSeparator();
205 aMenu.AppendSubMenu( variantsMenu, _( "Copy from Variant" ) )->Enable( !cells.empty() );
206}
207
208
209void FIELDS_TABLE_GRID_TRICKS::copyFromVariant( const wxString& aVariant, const std::vector<wxGridCellCoords>& aCells )
210{
211 if( !m_grid->CommitPendingChanges( false ) || aCells.empty() )
212 return;
213
214 for( const wxGridCellCoords& cell : aCells )
215 m_dataModel->CopyCellFromVariant( cell.GetRow(), cell.GetCol(), aVariant );
216
217 if( m_dataModel->IsEdited() )
218 m_dialog->OnModify();
219 else
220 m_dialog->ClearModify();
221
222 // One change event records the entire copy as a single dialog undo step.
223 wxGridEvent event( m_grid->GetId(), wxEVT_GRID_CELL_CHANGED, m_grid, aCells.front().GetRow(),
224 aCells.front().GetCol() );
225 m_grid->GetEventHandler()->ProcessEvent( event );
226 m_grid->ForceRefresh();
227}
228
229
230void FIELDS_TABLE_GRID_TRICKS::doPopupSelection( wxCommandEvent& aEvent )
231{
232 int row = m_grid->GetGridCursorRow();
233 int col = m_grid->GetGridCursorCol();
234
235 if( aEvent.GetId() == MYID_REVERT_ROW )
236 {
237 if( m_grid->CommitPendingChanges( false ) )
238 m_dataModel->RevertRow( row );
239
240 if( m_dataModel->IsEdited() )
241 m_dialog->OnModify();
242 else
243 m_dialog->ClearModify();
244
245 m_grid->ForceRefresh();
246 }
247 else if( aEvent.GetId() == MYID_CLEAR_CELL )
248 {
249 if( m_grid->CommitPendingChanges( false ) )
250 m_dataModel->ClearCell( row, col );
251
252 if( m_dataModel->IsEdited() )
253 m_dialog->OnModify();
254 else
255 m_dialog->ClearModify();
256
257 m_grid->ForceRefresh();
258 }
259 else
260 {
262 }
263}
264
265
266void FIELDS_TABLE_GRID_TRICKS::showFieldsTablePopupMenu( wxMenu& aMenu, wxGridEvent& aEvent )
267{
268 GRID_TRICKS::showPopupMenu( aMenu, aEvent );
269}
270
271
273{
275}
276
277
279 FIELDS_TABLE_BOM_SETTINGS& aBomSettings,
280 JOB_EXPORT_BOM* aJob ) :
281 DIALOG_FIELDS_TABLE_BASE( aParent ),
282 m_cfgDialogSettings( aPanelSettings ),
283 m_cfgBomSettings( aBomSettings ),
284 m_job( aJob )
285{
287 m_bMenu->SetBitmap( KiBitmapBundle( BITMAPS::config ) );
290
294
300
302
303 // Don't save scope, we don't want users opening up the table for the first
304 // on program launch stuck with Selection scope and seeing a blank table
305 OptOut( m_scope );
306
308
309 m_viewControlsGrid->UseNativeColHeader( true );
311
312 // must be done after SetTable(), which appears to re-set it
313 m_viewControlsGrid->SetSelectionMode( wxGrid::wxGridSelectCells );
314
315 // add Cut, Copy, and Paste to wxGrid
316 m_viewControlsGrid->PushEventHandler( new VIEW_CONTROLS_GRID_TRICKS( m_viewControlsGrid ) );
317
318 wxGridCellAttr* attr = new wxGridCellAttr;
319 attr->SetReadOnly( true );
320 m_viewControlsDataModel->SetColAttr( attr, DISPLAY_NAME_COLUMN );
321
322 attr = new wxGridCellAttr;
323 attr->SetRenderer( new wxGridCellBoolRenderer() );
324 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
325 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
326 m_viewControlsDataModel->SetColAttr( attr, SHOW_FIELD_COLUMN );
327
328 attr = new wxGridCellAttr;
329 attr->SetRenderer( new wxGridCellBoolRenderer() );
330 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
331 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
332 m_viewControlsDataModel->SetColAttr( attr, GROUP_BY_COLUMN );
333
334 // Compress the view controls grid. (We want it to look different from the fields grid.)
335 m_viewControlsGrid->SetDefaultRowSize( m_viewControlsGrid->GetDefaultRowSize() - FromDIP( 4 ) );
336
337 m_filter->SetDescriptiveText( _( "Filter" ) );
338
339 m_expanderWidth = m_grid->GetRowLabelSize();
340 m_grid->EnableCursorRowColumnHighlight();
341 m_grid->GetGridWindow()->Bind( wxEVT_MOUSEWHEEL, &DIALOG_FIELDS_TABLE::OnGridMouseWheel, this );
342}
343
344
346{
347 m_grid->GetGridWindow()->Unbind( wxEVT_MOUSEWHEEL, &DIALOG_FIELDS_TABLE::OnGridMouseWheel, this );
348 m_viewControlsGrid->PopEventHandler( true );
349}
350
351
353{
354 m_nbPages->SetSelection( 0 );
355}
356
357
359{
360 m_nbPages->SetSelection( 1 );
361}
362
363
364void DIALOG_FIELDS_TABLE::ShowHideColumn( int aCol, bool aShow )
365{
366 if( aShow )
367 m_grid->ShowCol( aCol );
368 else
369 m_grid->HideCol( aCol );
370
371 getDataModel()->SetShowColumn( aCol, aShow );
372
373 if( getDataModel()->GetFilterScope() == BOM_FILTER_SCOPE::VISIBLE
374 && !getDataModel()->GetFilter().IsEmpty() )
375 {
377 }
378
380
381 if( m_nbPages->GetSelection() == 1 )
383 else
384 m_grid->ForceRefresh();
385
386 OnModify();
387}
388
389
390void DIALOG_FIELDS_TABLE::AddField( const wxString& aFieldName, const wxString& aLabelValue, bool aShow, bool aGroupBy,
391 bool aAddedByUser )
392{
393 // Users can add fields with variable names that match the special names in the grid,
394 // e.g. ${QUANTITY} so make sure we don't add them twice
395 for( int row = 0; row < m_viewControlsDataModel->GetNumberRows(); row++ )
396 {
397 if( FieldNamesAreDuplicates( m_viewControlsDataModel->GetUntranslatedFieldName( row ), aFieldName ) )
398 {
399 return;
400 }
401 }
402
403 getDataModel()->AddColumn( aFieldName, aLabelValue, aAddedByUser );
404
405 m_viewControlsGrid->OnAddRow(
406 [&]() -> std::pair<int, int>
407 {
408 m_viewControlsDataModel->AppendRow( aFieldName, aLabelValue, aShow, aGroupBy );
409
410 return { m_viewControlsDataModel->GetNumberRows() - 1, -1 };
411 } );
412}
413
414
415wxString DIALOG_FIELDS_TABLE::GetDefaultBomFileName( const wxString& aInputFileName )
416{
417 if( aInputFileName.IsEmpty() )
418 return wxEmptyString;
419
420 wxFileName fn( aInputFileName );
421 fn.SetExt( FILEEXT::CsvFileExtension );
422
423 return fn.GetFullPath();
424}
425
426
427void DIALOG_FIELDS_TABLE::loadJobBomPreset( const JOB_EXPORT_BOM& aJob, BOM_PRESET& aPreset )
428{
429 aPreset.name = aJob.m_bomPresetName;
430 aPreset.excludeDNP = aJob.m_excludeDNP;
431 aPreset.filterString = aJob.m_filterString;
432 aPreset.filterScope = aJob.m_filterScope;
433 aPreset.sortAsc = aJob.m_sortAsc;
434 aPreset.sortField = aJob.m_sortField;
435 aPreset.groupSymbols = aJob.m_groupSymbols;
436
437 aPreset.fieldsOrdered.clear();
438
439 size_t i = 0;
440
441 for( const wxString& fieldName : aJob.m_fieldsOrdered )
442 {
443 BOM_FIELD field;
444 field.name = fieldName;
445 field.show = !fieldName.StartsWith( wxT( "__" ), &field.name );
446 field.groupBy = alg::contains( aJob.m_fieldsGroupBy, field.name );
447
448 if( ( aJob.m_fieldsLabels.size() > i ) && !aJob.m_fieldsLabels[i].IsEmpty() )
449 field.label = aJob.m_fieldsLabels[i];
450 else if( IsGeneratedField( field.name ) )
451 field.label = GetGeneratedFieldDisplayName( field.name );
452 else
453 field.label = field.name;
454
455 aPreset.fieldsOrdered.emplace_back( field );
456 i++;
457 }
458}
459
460
462{
463 aPreset.name = aJob.m_bomFmtPresetName;
464 aPreset.fieldDelimiter = aJob.m_fieldDelimiter;
465 aPreset.keepLineBreaks = aJob.m_keepLineBreaks;
466 aPreset.keepTabs = aJob.m_keepTabs;
468 aPreset.refDelimiter = aJob.m_refDelimiter;
470 aPreset.stringDelimiter = aJob.m_stringDelimiter;
471}
472
473
475{
476 aJob.SetConfiguredOutputPath( m_outputFileName->GetValue() );
477 aJob.m_bomFmtPresetName = wxEmptyString;
478 aJob.m_bomPresetName = wxEmptyString;
479
481 aJob.m_fieldDelimiter = fmtSettings.fieldDelimiter;
482 aJob.m_stringDelimiter = fmtSettings.stringDelimiter;
483 aJob.m_refDelimiter = fmtSettings.refDelimiter;
484 aJob.m_refRangeDelimiter = fmtSettings.refRangeDelimiter;
485 aJob.m_keepTabs = fmtSettings.keepTabs;
486 aJob.m_keepLineBreaks = fmtSettings.keepLineBreaks;
488
489 BOM_PRESET presetFields = getDataModel()->GetBomSettings();
490 aJob.m_sortAsc = presetFields.sortAsc;
491 aJob.m_excludeDNP = presetFields.excludeDNP;
492 aJob.m_filterString = presetFields.filterString;
493 aJob.m_filterScope = presetFields.filterScope;
494 aJob.m_sortField = presetFields.sortField;
495 aJob.m_groupSymbols = presetFields.groupSymbols;
496
497 aJob.m_fieldsOrdered.clear();
498 aJob.m_fieldsLabels.clear();
499 aJob.m_fieldsGroupBy.clear();
500
501 for( const BOM_FIELD& modelField : getDataModel()->GetFieldsOrdered() )
502 {
503 if( modelField.show )
504 aJob.m_fieldsOrdered.emplace_back( modelField.name );
505 else
506 aJob.m_fieldsOrdered.emplace_back( wxT( "__" ) + modelField.name );
507
508 aJob.m_fieldsLabels.emplace_back( modelField.label );
509
510 if( modelField.groupBy )
511 aJob.m_fieldsGroupBy.emplace_back( modelField.name );
512 }
513
515}
516
517
525
526
527bool DIALOG_FIELDS_TABLE::savePresets( bool aSaveCurrentSettings )
528{
529 bool modified = false;
530
531 // Compare with the presets as loaded, so a stored preset the load merely normalized stays untouched
532 std::vector<BOM_PRESET> presets = GetUserBomPresets();
533
534 if( m_loadedSettings.m_BomPresets != presets )
535 {
536 modified = true;
537 m_cfgBomSettings.m_BomPresets = presets;
538 }
539
540 BOM_PRESET bomSettings = getDataModel()->GetBomSettings();
541
542 if( aSaveCurrentSettings && m_loadedSettings.m_BomSettings != bomSettings )
543 {
544 modified = true;
545 m_cfgBomSettings.m_BomSettings = bomSettings;
546 }
547
548 std::vector<BOM_FMT_PRESET> fmts = GetUserBomFmtPresets();
549
550 if( m_loadedSettings.m_BomFmtPresets != fmts )
551 {
552 modified = true;
553 m_cfgBomSettings.m_BomFmtPresets = fmts;
554 }
555
557
558 if( aSaveCurrentSettings && m_loadedSettings.m_BomFmtSettings != fmtSettings )
559 {
560 modified = true;
561 m_cfgBomSettings.m_BomFmtSettings = fmtSettings;
562 }
563
564 return modified;
565}
566
567
569{
570 return ConvertDialogToPixels( wxSize( 600, 300 ) );
571}
572
573
575{
576 m_grid->Connect( wxEVT_GRID_RANGE_SELECTED,
577 wxGridRangeSelectEventHandler( DIALOG_FIELDS_TABLE::OnTableRangeSelectionChanged ), nullptr,
578 this );
579}
580
581
583{
584 m_grid->Disconnect( wxEVT_GRID_RANGE_SELECTED,
585 wxGridRangeSelectEventHandler( DIALOG_FIELDS_TABLE::OnTableRangeSelectionChanged ), nullptr,
586 this );
587}
588
589
594
595
597{
598 std::set<int> selectedRows;
599
600 wxGridCellCoordsArray topLeft = m_grid->GetSelectionBlockTopLeft();
601 wxGridCellCoordsArray bottomRight = m_grid->GetSelectionBlockBottomRight();
602
603 for( size_t i = 0; i < topLeft.size(); ++i )
604 {
605 for( int row = topLeft[i].GetRow(); row <= bottomRight[i].GetRow(); ++row )
606 selectedRows.insert( row );
607 }
608
609 wxGridCellCoordsArray selectedCells = m_grid->GetSelectedCells();
610
611 for( size_t i = 0; i < selectedCells.size(); ++i )
612 selectedRows.insert( selectedCells[i].GetRow() );
613
614 for( int row : m_grid->GetSelectedRows() )
615 selectedRows.insert( row );
616
617 int cursorRow = m_grid->GetGridCursorRow();
618
619 if( selectedRows.empty() && cursorRow >= 0 && cursorRow < getDataModel()->GetNumberRows() )
620 selectedRows.insert( cursorRow );
621
622 return selectedRows;
623}
624
625
627{
628 std::set<KIID_PATH> selectedItemKeys;
629
630 for( int row : GetSelectedGridRows() )
631 {
632 for( const KIID_PATH& key : getDataModel()->GetRowItemKeys( row ) )
633 selectedItemKeys.insert( key );
634 }
635
636 return selectedItemKeys;
637}
638
639
640void DIALOG_FIELDS_TABLE::RestoreGridSelection( const std::set<KIID_PATH>& aItemKeys )
641{
642 if( aItemKeys.empty() )
643 return;
644
645 m_grid->ClearSelection();
646
647 bool firstSelection = true;
648
649 for( int row = 0; row < getDataModel()->GetNumberRows(); ++row )
650 {
651 for( const KIID_PATH& key : getDataModel()->GetRowItemKeys( row ) )
652 {
653 if( aItemKeys.count( key ) )
654 {
655 m_grid->SelectRow( row, true );
656
657 if( firstSelection )
658 {
659 m_grid->SetGridCursor( row, m_grid->GetGridCursorCol() );
660 firstSelection = false;
661 }
662
663 break;
664 }
665 }
666 }
667}
668
669
671{
672 bool sidebarCollapsed = m_cfgDialogSettings.sidebar_collapsed;
673 int sashPosition = m_cfgDialogSettings.sash_pos;
674 int variantSashPosition = m_cfgDialogSettings.variant_sash_pos;
675
676 m_viewControlsGrid->ShowHideColumns( "0 1 2 3" );
677
678 CallAfter(
679 [this, sidebarCollapsed, sashPosition, variantSashPosition]()
680 {
681 if( sidebarCollapsed )
683 else
684 m_splitterMainWindow->SetSashPosition( sashPosition );
685
686 setSideBarButtonLook( sidebarCollapsed );
687
688 m_splitter_left->SetSashPosition( variantSashPosition );
689 } );
690}
691
692
694{
695 if( !m_cfgDialogSettings.sidebar_collapsed )
696 m_cfgDialogSettings.sash_pos = m_splitterMainWindow->GetSashPosition();
697
698 m_cfgDialogSettings.variant_sash_pos = m_splitter_left->GetSashPosition();
699}
700
701
702int DIALOG_FIELDS_TABLE::getStoredColumnWidth( const std::string& aFieldName ) const
703{
704 auto it = m_cfgDialogSettings.field_widths.find( aFieldName );
705
706 if( it == m_cfgDialogSettings.field_widths.end() || !isValidColumnWidth( it->second ) )
707 return 0;
708
709 return m_grid->FromDIP( it->second );
710}
711
712
714{
715 for( int i = 0; i < m_grid->GetNumberCols(); i++ )
716 {
717 if( m_grid->IsColShown( i ) )
718 {
719 int width = m_grid->ToDIP( m_grid->GetColSize( i ) );
720
721 if( !isValidColumnWidth( width ) )
722 continue;
723
724 std::string fieldName( getDataModel()->GetColFieldName( i ).ToUTF8() );
725 m_cfgDialogSettings.field_widths[fieldName] = width;
726 }
727 }
728}
729
730
731// TODO: this probably needs more validation once reference field editing
732// is actually enabled for non-lib-symbol tables
739
740
742{
743 return new GRID_CELL_FPID_EDITOR( this );
744}
745
746
748{
749 m_grid->EnableEditing( !aReadOnly );
750 m_addFieldButton->Enable( !aReadOnly );
751 m_renameFieldButton->Enable( !aReadOnly );
752 m_removeFieldButton->Enable( !aReadOnly );
753 m_buttonApply->Enable( !aReadOnly );
754}
755
756
761
762
764{
765 wxGridCellAttr* attr = new wxGridCellAttr;
766 attr->SetReadOnly( false );
767
768 // Set some column types to specific editors
769 if( getDataModel()->ColIsItemIdentifier( aCol ) )
770 {
771 attr->SetReadOnly();
772 attr->SetRenderer( new wxGridCellStringRenderer() );
773 getDataModel()->SetColAttr( attr, aCol );
774 }
775 else if( getDataModel()->ColIsReference( aCol ) )
776 {
777 // Keep this after item identifiers so Reference remains read-only in tables where it
778 // identifies the item.
779 attr->SetRenderer( new wxGridCellStringRenderer() );
780 attr->SetEditor( createReferenceEditor() );
781 getDataModel()->SetColAttr( attr, aCol );
782 }
783 else if( getDataModel()->GetColFieldName( aCol ) == GetDefaultFieldName( FIELD_T::FOOTPRINT, UNTRANSLATED ) )
784 {
785 attr->SetEditor( createFootprintEditor() );
786 getDataModel()->SetColAttr( attr, aCol );
787 }
788 else if( getDataModel()->GetColFieldName( aCol ) == GetDefaultFieldName( FIELD_T::DATASHEET, UNTRANSLATED ) )
789 {
790 // set datasheet column viewer button
791 attr->SetEditor( createDatasheetEditor() );
792 getDataModel()->SetColAttr( attr, aCol );
793 }
794 else if( getDataModel()->ColIsQuantity( aCol ) || getDataModel()->ColIsItemNumber( aCol ) )
795 {
796 attr->SetReadOnly();
797 attr->SetAlignment( wxALIGN_RIGHT, wxALIGN_CENTER );
798 attr->SetRenderer( new wxGridCellNumberRenderer() );
799 getDataModel()->SetColAttr( attr, aCol );
800 }
801 else if( getDataModel()->ColIsAttribute( aCol ) )
802 {
803 attr->SetAlignment( wxALIGN_CENTER, wxALIGN_CENTER );
804 attr->SetRenderer( new GRID_CELL_CHECKBOX_RENDERER() );
805 attr->SetReadOnly(); // not really; we delegate interactivity to GRID_TRICKS
806 getDataModel()->SetColAttr( attr, aCol );
807 }
808 else if( getDataModel()->ColIsReadOnly( aCol ) )
809 {
810 attr->SetReadOnly();
811 getDataModel()->SetColAttr( attr, aCol );
812 }
813 else
814 {
815 attr->SetRenderer( new wxGridCellStringRenderer() );
816 attr->SetEditor( m_grid->GetDefaultEditor() );
817 getDataModel()->SetColAttr( attr, aCol );
818 }
819}
820
821
823{
825
826 wxSize defaultDlgSize = GetDefaultDialogSize();
827
828 // Restore column sorting order and widths
829 m_grid->AutoSizeColumns( false );
830 int sortCol = 0;
831 bool sortAscending = true;
832
833 for( int col = 0; col < m_grid->GetNumberCols(); ++col )
834 {
836
837 if( col == getDataModel()->GetSortCol() )
838 {
839 sortCol = col;
840 sortAscending = getDataModel()->GetSortAsc();
841 }
842 }
843
844 // sync m_grid's column visibilities to Show checkboxes in m_viewControlsGrid
845 for( int i = 0; i < m_viewControlsDataModel->GetNumberRows(); ++i )
846 {
847 int col = getDataModel()->GetFieldNameCol( m_viewControlsDataModel->GetUntranslatedFieldName( i ) );
848
849 if( col == -1 )
850 continue;
851
852 bool show = m_viewControlsDataModel->GetValueAsBool( i, SHOW_FIELD_COLUMN );
853 getDataModel()->SetShowColumn( col, show );
854
855 if( show )
856 {
857 m_grid->ShowCol( col );
858
859 std::string key( getDataModel()->GetColFieldName( col ).ToUTF8() );
860
861 if( int storedWidth = getStoredColumnWidth( key ); storedWidth > 0 )
862 {
863 m_grid->SetColSize( col, storedWidth );
864 }
865 else
866 {
867 int textWidth = getDataModel()->GetColDataWidth( col ) + COLUMN_MARGIN;
868 int maxWidth = defaultDlgSize.x / 3;
869
870 m_grid->SetColSize( col, std::clamp( textWidth, 100, maxWidth ) );
871 }
872 }
873 else
874 {
875 m_grid->HideCol( col );
876 }
877 }
878
879 getDataModel()->SetSorting( sortCol, sortAscending );
880 m_grid->SetSortingColumn( sortCol, sortAscending );
881}
882
883
885{
886 m_grid->SetRowLabelSize( getDataModel()->GetGroupingEnabled() ? m_grid->FromDIP( m_expanderWidth ) : 0 );
887}
888
889
890void DIALOG_FIELDS_TABLE::setSideBarButtonLook( bool aIsLeftPanelCollapsed )
891{
892 // Set bitmap and tooltip according to left panel visibility
893
894 if( aIsLeftPanelCollapsed )
895 {
897 m_sidebarButton->SetToolTip( _( "Expand left panel" ) );
898 }
899 else
900 {
902 m_sidebarButton->SetToolTip( _( "Collapse left panel" ) );
903 }
904}
905
906
907void DIALOG_FIELDS_TABLE::OnSidebarToggle( wxCommandEvent& event )
908{
909 if( m_cfgDialogSettings.sidebar_collapsed )
910 {
911 m_cfgDialogSettings.sidebar_collapsed = false;
913 }
914 else
915 {
916 m_cfgDialogSettings.sash_pos = m_splitterMainWindow->GetSashPosition();
917
918 m_cfgDialogSettings.sidebar_collapsed = true;
920 }
921
922 setSideBarButtonLook( m_cfgDialogSettings.sidebar_collapsed );
923}
924
925
927{
928 m_grid->ForceRefresh();
929}
930
931
932void DIALOG_FIELDS_TABLE::OnTableColSize( wxGridSizeEvent& aEvent )
933{
934 aEvent.Skip();
935
936 m_grid->ForceRefresh();
937}
938
939
940void DIALOG_FIELDS_TABLE::OnTableLabelClick( wxGridEvent& aEvent )
941{
942 int row = aEvent.GetRow();
943
944 // Column headers and the corner retain their normal sorting/selection behavior.
945 if( aEvent.GetCol() != -1 || row < 0 || row >= getDataModel()->GetNumberRows() )
946 {
947 aEvent.Skip();
948 return;
949 }
950
951 ROW_STATE state = getDataModel()->GetRowState( row );
952
953 if( !IsRowCollapsed( state ) && !IsRowExpanded( state ) )
954 {
955 aEvent.Skip();
956 return;
957 }
958
959 if( !m_grid->CommitPendingChanges() )
960 return;
961
962 int col = m_grid->GetGridCursorCol();
963 m_grid->ClearSelection();
965
966 if( col >= 0 && col < m_grid->GetNumberCols() )
967 m_grid->SetGridCursor( row, col );
968
969 // Refresh the parent arrow as well as the inserted/deleted child rows.
970 m_grid->ForceRefresh();
971}
972
973
974void DIALOG_FIELDS_TABLE::OnFilterMouseMoved( wxMouseEvent& aEvent )
975{
976#if defined( __WXOSX__ ) // Doesn't work properly on other ports
977 wxPoint pos = aEvent.GetPosition();
978 wxRect ctrlRect = m_filter->GetScreenRect();
979 int buttonWidth = ctrlRect.GetHeight(); // Presume buttons are square
980
981 // TODO: restore cursor when mouse leaves the filter field (or is it a MSW bug?)
982 if( m_filter->IsSearchButtonVisible() && pos.x < buttonWidth )
983 SetCursor( wxCURSOR_ARROW );
984 else if( m_filter->IsCancelButtonVisible() && pos.x > ctrlRect.GetWidth() - buttonWidth )
985 SetCursor( wxCURSOR_ARROW );
986 else
987 SetCursor( wxCURSOR_IBEAM );
988#endif
989}
990
991
993{
994 const wxString& showColLabel = m_viewControlsGrid->GetColLabelValue( SHOW_FIELD_COLUMN );
995 const wxString& groupByColLabel = m_viewControlsGrid->GetColLabelValue( GROUP_BY_COLUMN );
996 int showColWidth = KIUI::GetTextSize( showColLabel, m_viewControlsGrid ).x + COLUMN_MARGIN;
997 int groupByColWidth = KIUI::GetTextSize( groupByColLabel, m_viewControlsGrid ).x + COLUMN_MARGIN;
998 int remainingWidth = m_viewControlsGrid->GetSize().GetX() - showColWidth - groupByColWidth;
999
1000 m_viewControlsGrid->SetColSize( SHOW_FIELD_COLUMN, showColWidth );
1001 m_viewControlsGrid->SetColSize( GROUP_BY_COLUMN, groupByColWidth );
1002
1003 if( m_viewControlsGrid->IsColShown( DISPLAY_NAME_COLUMN ) && m_viewControlsGrid->IsColShown( LABEL_COLUMN ) )
1004 {
1005 m_viewControlsGrid->SetColSize( DISPLAY_NAME_COLUMN, std::max( remainingWidth / 2, 60 ) );
1006 m_viewControlsGrid->SetColSize( LABEL_COLUMN, std::max( remainingWidth - ( remainingWidth / 2 ), 60 ) );
1007 }
1008 else if( m_viewControlsGrid->IsColShown( DISPLAY_NAME_COLUMN ) )
1009 {
1010 m_viewControlsGrid->SetColSize( DISPLAY_NAME_COLUMN, std::max( remainingWidth, 60 ) );
1011 }
1012 else if( m_viewControlsGrid->IsColShown( LABEL_COLUMN ) )
1013 {
1014 m_viewControlsGrid->SetColSize( LABEL_COLUMN, std::max( remainingWidth, 60 ) );
1015 }
1016
1017 event.Skip();
1018}
1019
1020
1022{
1023 int row = aEvent.GetRow();
1024
1025 wxCHECK( row < m_viewControlsGrid->GetNumberRows(), /* void */ );
1026
1027 switch( aEvent.GetCol() )
1028 {
1029 case LABEL_COLUMN:
1030 {
1031 wxString label = m_viewControlsDataModel->GetValue( row, LABEL_COLUMN );
1032 wxString fieldName = m_viewControlsDataModel->GetUntranslatedFieldName( row );
1033 int dataCol = getDataModel()->GetFieldNameCol( fieldName );
1034
1035 if( dataCol != -1 )
1036 {
1037 getDataModel()->SetColLabelValue( dataCol, label );
1038 m_grid->SetColLabelValue( dataCol, label );
1039
1040 if( m_nbPages->GetSelection() == 1 )
1042 else
1043 m_grid->ForceRefresh();
1044
1046 OnModify();
1047 }
1048
1049 break;
1050 }
1051
1052 case SHOW_FIELD_COLUMN:
1053 {
1054 wxString fieldName = m_viewControlsDataModel->GetUntranslatedFieldName( row );
1055 bool value = m_viewControlsDataModel->GetValueAsBool( row, SHOW_FIELD_COLUMN );
1056 int dataCol = getDataModel()->GetFieldNameCol( fieldName );
1057
1058 if( dataCol != -1 )
1059 ShowHideColumn( dataCol, value );
1060
1061 break;
1062 }
1063
1064 case GROUP_BY_COLUMN:
1065 {
1066 wxString fieldName = m_viewControlsDataModel->GetUntranslatedFieldName( row );
1067 bool value = m_viewControlsDataModel->GetValueAsBool( row, GROUP_BY_COLUMN );
1068 int dataCol = getDataModel()->GetFieldNameCol( fieldName );
1069
1070 if( getDataModel()->ColIsQuantity( dataCol ) && value )
1071 {
1072 DisplayError( this, _( "The Quantity column cannot be grouped by." ) );
1073
1074 value = false;
1075 m_viewControlsDataModel->SetValueAsBool( row, GROUP_BY_COLUMN, value );
1076 m_viewControlsGrid->ForceRefresh();
1077 break;
1078 }
1079
1080 if( getDataModel()->ColIsItemNumber( dataCol ) && value )
1081 {
1082 DisplayError( this, _( "The Item Number column cannot be grouped by." ) );
1083
1084 value = false;
1085 m_viewControlsDataModel->SetValueAsBool( row, GROUP_BY_COLUMN, value );
1086 m_viewControlsGrid->ForceRefresh();
1087 break;
1088 }
1089
1090 getDataModel()->SetGroupColumn( dataCol, value );
1092
1093 if( m_nbPages->GetSelection() == 1 )
1095 else
1096 m_grid->ForceRefresh();
1097
1099 OnModify();
1100 break;
1101 }
1102
1103 default: break;
1104 }
1105}
1106
1107
1108void DIALOG_FIELDS_TABLE::OnAddField( wxCommandEvent& aEvent )
1109{
1110 wxTextEntryDialog dlg( this, _( "New field name:" ), _( "Add Field" ) );
1111
1112 if( dlg.ShowModal() != wxID_OK )
1113 return;
1114
1115 wxString fieldName = dlg.GetValue();
1116
1117 if( fieldName.IsEmpty() )
1118 {
1119 DisplayError( this, _( "Field must have a name." ) );
1120 return;
1121 }
1122
1123 for( int i = 0; i < getDataModel()->GetNumberCols(); ++i )
1124 {
1125 if( FieldNamesAreDuplicates( fieldName, getDataModel()->GetColFieldName( i ) ) )
1126 {
1127 DisplayError( this, wxString::Format( _( "Field name '%s' already in use." ), fieldName ) );
1128 return;
1129 }
1130 }
1131
1132 AddField( fieldName, GetGeneratedFieldDisplayName( fieldName ), true, false, true );
1133
1134 SetupColumnProperties( getDataModel()->GetColsCount() - 1 );
1135
1137 OnModify();
1138}
1139
1140
1141void DIALOG_FIELDS_TABLE::OnRemoveField( wxCommandEvent& aEvent )
1142{
1143 m_viewControlsGrid->OnDeleteRows(
1144 [&]( int row )
1145 {
1146 for( FIELD_T id : MANDATORY_FIELDS )
1147 {
1148 if( m_mandatoryFieldListIndexes[id] == row )
1149 {
1150 DisplayError( this, wxString::Format( _( "The first %d fields are mandatory." ),
1151 (int) m_mandatoryFieldListIndexes.size() ) );
1152 return false;
1153 }
1154 }
1155
1156 wxString fieldName = m_viewControlsDataModel->GetUntranslatedFieldName( row );
1157 int col = getDataModel()->GetFieldNameCol( fieldName );
1158
1159 if( col != -1 && getDataModel()->ColIsItemIdentifier( col ) )
1160 {
1161 DisplayError( this, wxString::Format( _( "The '%s' field cannot be removed." ),
1162 m_viewControlsDataModel->GetValue(
1163 row, DISPLAY_NAME_COLUMN ) ) );
1164 return false;
1165 }
1166
1167 return IsOK( this, wxString::Format( _( "Are you sure you want to remove the field '%s'?" ),
1168 m_viewControlsDataModel->GetValue( row, DISPLAY_NAME_COLUMN ) ) );
1169 },
1170 [&]( int row )
1171 {
1172 wxString fieldName = m_viewControlsDataModel->GetUntranslatedFieldName( row );
1173 int col = getDataModel()->GetFieldNameCol( fieldName );
1174
1175 if( col != -1 )
1176 getDataModel()->RemoveColumn( col );
1177
1178 m_viewControlsDataModel->DeleteRow( row );
1179
1180 for( auto& [name, preset] : m_bomPresets )
1181 std::erase_if( preset.fieldsOrdered,
1182 [&]( BOM_FIELD const& f )
1183 {
1184 return f.name == fieldName;
1185 } );
1186
1188 OnModify();
1189 } );
1190}
1191
1192
1193void DIALOG_FIELDS_TABLE::OnRenameField( wxCommandEvent& aEvent )
1194{
1195 wxArrayInt selectedRows = m_viewControlsGrid->GetSelectedRows();
1196
1197 if( selectedRows.empty() && m_viewControlsGrid->GetGridCursorRow() >= 0 )
1198 selectedRows.push_back( m_viewControlsGrid->GetGridCursorRow() );
1199
1200 if( selectedRows.empty() )
1201 return;
1202
1203 int row = selectedRows[0];
1204
1205 for( FIELD_T id : MANDATORY_FIELDS )
1206 {
1207 if( m_mandatoryFieldListIndexes[id] == row )
1208 {
1209 DisplayError( this, wxString::Format( _( "The first %d fields are mandatory and names cannot be changed." ),
1210 (int) m_mandatoryFieldListIndexes.size() ) );
1211 return;
1212 }
1213 }
1214
1215 wxString fieldName = m_viewControlsDataModel->GetUntranslatedFieldName( row );
1216 wxString label = m_viewControlsDataModel->GetValue( row, LABEL_COLUMN );
1217 bool labelIsAutogenerated = label.IsSameAs( GetGeneratedFieldDisplayName( fieldName ) );
1218
1219 int col = getDataModel()->GetFieldNameCol( fieldName );
1220 wxCHECK_RET( col != -1, wxS( "Existing field name missing from data model" ) );
1221
1222 if( getDataModel()->ColIsItemIdentifier( col ) )
1223 {
1224 DisplayError( this, wxString::Format( _( "The '%s' field cannot be renamed." ),
1225 m_viewControlsDataModel->GetValue( row, DISPLAY_NAME_COLUMN ) ) );
1226 return;
1227 }
1228
1229 wxTextEntryDialog dlg( this, _( "New field name:" ), _( "Rename Field" ), fieldName );
1230
1231 if( dlg.ShowModal() != wxID_OK )
1232 return;
1233
1234 wxString newFieldName = dlg.GetValue();
1235
1236 // No change, no-op
1237 if( newFieldName == fieldName )
1238 return;
1239
1240 if( newFieldName.IsEmpty() )
1241 {
1242 DisplayError( this, _( "Field must have a name." ) );
1243 return;
1244 }
1245
1246 // New field name already exists
1247 if( getDataModel()->GetFieldNameCol( newFieldName ) != -1 )
1248 {
1249 wxString confirm_msg = wxString::Format( _( "Field name %s already exists." ), newFieldName );
1250 DisplayError( this, confirm_msg );
1251 return;
1252 }
1253
1254 getDataModel()->RenameColumn( col, newFieldName );
1255 m_viewControlsDataModel->SetUntranslatedFieldName( row, newFieldName );
1256 m_viewControlsDataModel->SetValue( row, DISPLAY_NAME_COLUMN, newFieldName );
1257
1258 if( labelIsAutogenerated )
1259 {
1260 m_viewControlsDataModel->SetValue( row, LABEL_COLUMN, GetGeneratedFieldDisplayName( newFieldName ) );
1261 wxGridEvent evt( m_viewControlsGrid->GetId(), wxEVT_GRID_CELL_CHANGED, m_viewControlsGrid, row, LABEL_COLUMN );
1263 }
1264
1265 if( m_nbPages->GetSelection() == 1 )
1267 else
1268 {
1270 m_grid->ForceRefresh();
1271 }
1272
1274 OnModify();
1275}
1276
1277
1278void DIALOG_FIELDS_TABLE::OnFilterText( wxCommandEvent& aEvent )
1279{
1280 getDataModel()->SetFilter( m_filter->GetValue() );
1282 m_grid->ForceRefresh();
1283
1285}
1286
1287
1288void DIALOG_FIELDS_TABLE::OnFilterScope( wxCommandEvent& aEvent )
1289{
1290 getDataModel()->SetFilterScope( static_cast<BOM_FILTER_SCOPE>( m_filterScope->GetSelection() ) );
1292 m_grid->ForceRefresh();
1293
1295}
1296
1297
1299{
1303 m_grid->ForceRefresh();
1304
1306}
1307
1308
1309void DIALOG_FIELDS_TABLE::OnRegroupSymbols( wxCommandEvent& aEvent )
1310{
1312 m_grid->ForceRefresh();
1313}
1314
1315
1316void DIALOG_FIELDS_TABLE::OnColSort( wxGridEvent& aEvent )
1317{
1318 int sortCol = aEvent.GetCol();
1319 bool ascending;
1320
1321 // Don't sort by item number, it is generated by the sort
1322 if( getDataModel()->ColIsItemNumber( sortCol ) )
1323 {
1324 aEvent.Veto();
1325 return;
1326 }
1327
1328 // This is bonkers, but wxWidgets doesn't tell us ascending/descending in the event, and
1329 // if we ask it will give us pre-event info.
1330 if( m_grid->IsSortingBy( sortCol ) )
1331 {
1332 // same column; invert ascending
1333 ascending = !m_grid->IsSortOrderAscending();
1334 }
1335 else
1336 {
1337 // different column; start with ascending
1338 ascending = true;
1339 }
1340
1341 getDataModel()->SetSorting( sortCol, ascending );
1343 m_grid->ForceRefresh();
1344
1346}
1347
1348
1349void DIALOG_FIELDS_TABLE::OnColMove( wxGridEvent& aEvent )
1350{
1351 int origPos = aEvent.GetCol();
1352
1353 // Save column widths since the setup function uses the saved config values
1355
1356 CallAfter(
1357 [origPos, this]()
1358 {
1359 int newPos = m_grid->GetColPos( origPos );
1360
1361#ifdef __WXMAC__
1362 if( newPos < origPos )
1363 newPos += 1;
1364#endif
1365
1366 getDataModel()->MoveColumn( origPos, newPos );
1367
1368 // "Unmove" the column since we've moved the column internally
1369 m_grid->ResetColPos();
1370
1371 // We need to reset all the column attr's to the correct column order
1373
1374 m_grid->ForceRefresh();
1376 } );
1377}
1378
1379
1380void DIALOG_FIELDS_TABLE::OnGridMouseMove( wxMouseEvent& aEvent )
1381{
1382 aEvent.Skip();
1383
1384 wxPoint pos = aEvent.GetPosition();
1385 int ux, uy;
1386 m_grid->CalcUnscrolledPosition( pos.x, pos.y, &ux, &uy );
1387 int row = m_grid->YToRow( uy );
1388 int col = m_grid->XToCol( ux );
1389
1390 if( row == wxNOT_FOUND || col == wxNOT_FOUND )
1391 {
1392 m_grid->GetGridWindow()->UnsetToolTip();
1393 return;
1394 }
1395
1396 wxString rawValue = getDataModel()->GetValue( row, col );
1397
1398 if( rawValue.Contains( wxT( "${" ) ) )
1399 m_grid->GetGridWindow()->SetToolTip( rawValue );
1400 else
1401 m_grid->GetGridWindow()->UnsetToolTip();
1402}
1403
1404
1405void DIALOG_FIELDS_TABLE::OnGridMouseWheel( wxMouseEvent& aEvent )
1406{
1407 if( aEvent.GetWheelAxis() != wxMOUSE_WHEEL_VERTICAL || aEvent.GetModifiers() != wxMOD_SHIFT )
1408 {
1409 aEvent.Skip();
1410 return;
1411 }
1412
1413 // Accumulate so high-resolution wheels and trackpads aren't truncated.
1414 m_gridWheelRotation += aEvent.GetWheelRotation();
1415
1416 int lines = m_gridWheelRotation / aEvent.GetWheelDelta();
1417 m_gridWheelRotation -= lines * aEvent.GetWheelDelta();
1418
1419 if( lines == 0 )
1420 return;
1421
1422 int scrollLines = aEvent.IsPageScroll() ? m_grid->GetScrollPageSize( wxHORIZONTAL )
1423 : aEvent.GetLinesPerAction();
1424
1425 wxPoint viewStart = m_grid->GetViewStart();
1426 m_grid->Scroll( viewStart.x - lines * scrollLines, viewStart.y );
1427}
1428
1429
1430void DIALOG_FIELDS_TABLE::OnPageChanged( wxNotebookEvent& aEvent )
1431{
1432 if( getDataModel()->GetColsCount() )
1434}
1435
1436
1437void DIALOG_FIELDS_TABLE::OnPreviewRefresh( wxCommandEvent& aEvent )
1438{
1441}
1442
1443
1445{
1446 // Build the absolute path of current output directory to preselect it in the file browser.
1447 wxString path = ResolveProjectPath( m_outputFileName->GetValue(), &Prj() );
1448
1449 // Calculate the export filename
1450 wxFileName fn( Prj().AbsolutePath( m_parentFrame->GetCurrentFileName() ) );
1451 fn.SetExt( FILEEXT::CsvFileExtension );
1452
1453 wxFileDialog saveDlg( this, _( "Bill of Materials Output File" ), path, fn.GetFullName(),
1454 FILEEXT::CsvFileWildcard(), wxFD_SAVE | wxFD_OVERWRITE_PROMPT );
1455
1457
1458 if( saveDlg.ShowModal() == wxID_CANCEL )
1459 return;
1460
1461 wxFileName file = wxFileName( saveDlg.GetPath() );
1462 wxString defaultPath = fn.GetPathWithSep();
1463
1464 if( IsOK( this, wxString::Format( _( "Do you want to use a path relative to\n'%s'?" ), defaultPath ) ) )
1465 {
1466 if( !file.MakeRelativeTo( defaultPath ) )
1467 {
1468 DisplayErrorMessage( this, _( "Cannot make path relative (target volume different from file "
1469 "volume)!" ) );
1470 }
1471 }
1472
1473 m_outputFileName->SetValue( file.GetFullPath() );
1474}
1475
1476
1477void DIALOG_FIELDS_TABLE::OnExport( wxCommandEvent& aEvent )
1478{
1479 if( getDataModel()->IsEdited() )
1480 {
1481 if( OKOrCancelDialog( nullptr, _( "Unsaved data" ),
1482 _( "Changes have not yet been saved. Export unsaved data?" ), "", _( "OK" ),
1483 _( "Cancel" ) )
1484 == wxID_CANCEL )
1485 {
1486 return;
1487 }
1488 }
1489
1490 // Create output directory if it does not exist (also transform it in absolute form).
1491 // Bail if it fails.
1492
1493 std::function<bool( wxString* )> textResolver =
1494 [&]( wxString* token ) -> bool
1495 {
1496 return resolveTextVar( token );
1497 };
1498
1499 wxString sourceFileName = m_parentFrame->GetCurrentFileName();
1500 wxString path = m_outputFileName->GetValue();
1501
1502 if( path.IsEmpty() )
1503 {
1504 // Match the behaviour of other exporters and default to the source filename with a CSV
1505 // extension in the project directory when the user leaves the field blank.
1506 path = GetDefaultBomFileName( sourceFileName );
1507
1508 if( path.IsEmpty() )
1509 {
1510 DisplayError( this, _( "No output file specified in Export tab." ) );
1511 return;
1512 }
1513
1514 m_outputFileName->SetValue( path );
1515 }
1516
1519
1520 wxFileName outputFile = wxFileName::FileName( path );
1521 wxString msg;
1522
1523 if( !EnsureFileDirectoryExists( &outputFile, Prj().AbsolutePath( sourceFileName ), &NULL_REPORTER::GetInstance() ) )
1524 {
1525 msg.Printf( _( "Could not open/create path '%s'." ), outputFile.GetPath() );
1526 DisplayError( this, msg );
1527 return;
1528 }
1529
1530 wxFFile out( outputFile.GetFullPath(), "wb" );
1531
1532 if( !out.IsOpened() )
1533 {
1534 msg.Printf( _( "Could not create BOM output '%s'." ), outputFile.GetFullPath() );
1535 DisplayError( this, msg );
1536 return;
1537 }
1538
1540
1541 if( !out.Write( m_textOutput->GetValue() ) )
1542 {
1543 msg.Printf( _( "Could not write BOM output '%s'." ), outputFile.GetFullPath() );
1544 DisplayError( this, msg );
1545 return;
1546 }
1547
1548 // close the file before we tell the user it's done with the info modal :workflow meme:
1549 out.Close();
1550
1551 if( m_cfgBomSettings.m_BomExportFileName != m_outputFileName->GetValue() )
1552 {
1553 m_cfgBomSettings.m_BomExportFileName = m_outputFileName->GetValue();
1555 }
1556
1557 msg.Printf( _( "Wrote BOM output to '%s'" ), outputFile.GetFullPath() );
1558 DisplayInfoMessage( this, msg );
1559}
1560
1561
1563{
1564 bool saveIncludeExcudedFromBOM = getDataModel()->GetIncludeExcludedFromBOM();
1565
1568
1569 m_textOutput->SetValue( getDataModel()->Export( GetCurrentBomFmtSettings() ) );
1570
1571 if( saveIncludeExcudedFromBOM )
1572 {
1575 }
1576}
1577
1578
1580{
1581 wxString retv;
1582
1583 int selection = m_variantListBox->GetSelection();
1584
1585 if( ( selection == wxNOT_FOUND ) || ( m_variantListBox->GetString( selection ) == GetDefaultVariantName() ) )
1586 return retv;
1587
1588 return m_variantListBox->GetString( selection );
1589}
1590
1591
1592std::vector<BOM_PRESET> DIALOG_FIELDS_TABLE::GetUserBomPresets() const
1593{
1594 std::vector<BOM_PRESET> ret;
1595
1596 for( const std::pair<const wxString, BOM_PRESET>& pair : m_bomPresets )
1597 {
1598 if( !pair.second.readOnly )
1599 ret.emplace_back( pair.second );
1600 }
1601
1602 return ret;
1603}
1604
1605
1606void DIALOG_FIELDS_TABLE::SetUserBomPresets( std::vector<BOM_PRESET>& aPresetList )
1607{
1608 // Reset to defaults
1610
1611 for( const BOM_PRESET& preset : aPresetList )
1612 {
1613 if( m_bomPresets.count( preset.name ) )
1614 continue;
1615
1616 m_bomPresets[preset.name] = preset;
1617
1618 m_bomPresetMRU.Add( preset.name );
1619 }
1620
1622}
1623
1624
1625void DIALOG_FIELDS_TABLE::ApplyBomPreset( const wxString& aPresetName )
1626{
1627 updateBomPresetSelection( aPresetName );
1628
1629 wxCommandEvent dummy;
1631}
1632
1633
1634void DIALOG_FIELDS_TABLE::ApplyBomPreset( const BOM_PRESET& aPreset )
1635{
1636 BOM_PRESET preset = aPreset;
1637
1638 if( preset.fieldsOrdered.empty() )
1639 {
1640 for( const BOM_PRESET& builtIn : getBuiltInBomPresets() )
1641 {
1642 if( builtIn.name == BOM_PRESET::DefaultEditing().name )
1643 {
1644 preset = builtIn;
1645 break;
1646 }
1647 }
1648 }
1649
1650 if( m_bomPresets.count( preset.name ) )
1651 m_currentBomPreset = &m_bomPresets[preset.name];
1652 else
1653 m_currentBomPreset = nullptr;
1654
1655 if( m_currentBomPreset && !m_currentBomPreset->readOnly )
1657 else
1658 m_lastSelectedBomPreset = nullptr;
1659
1660 updateBomPresetSelection( preset.name );
1661 doApplyBomPreset( preset );
1662}
1663
1664
1665void DIALOG_FIELDS_TABLE::doApplyBomPreset( const BOM_PRESET& aPreset )
1666{
1667 // Disable rebuilds while we're applying the preset otherwise we'll be
1668 // rebuilding the model constantly while firing off wx events
1670
1671 // Basically, we apply the BOM preset to the data model and then
1672 // update our UI to reflect resulting the data model state, not the preset.
1674 getDataModel()->ApplyBomPreset( aPreset );
1675
1676 // BOM Presets can add, but not remove, columns, so make sure the view controls
1677 // grid has all of them before starting
1678 for( int i = 0; i < getDataModel()->GetColsCount(); i++ )
1679 {
1680 const wxString& fieldName( getDataModel()->GetColFieldName( i ) );
1681 bool found = false;
1682
1683 for( int j = 0; j < m_viewControlsDataModel->GetNumberRows(); j++ )
1684 {
1685 if( m_viewControlsDataModel->GetUntranslatedFieldName( j ) == fieldName )
1686 {
1687 found = true;
1688 break;
1689 }
1690 }
1691
1692 // Properties like label, etc. will be added in the next loop
1693 if( !found )
1694 AddField( fieldName, GetGeneratedFieldDisplayName( fieldName ), false, false );
1695 }
1696
1697 // Sync all fields
1698 for( int i = 0; i < m_viewControlsDataModel->GetNumberRows(); i++ )
1699 {
1700 const wxString& fieldName( m_viewControlsDataModel->GetUntranslatedFieldName( i ) );
1701 int col = getDataModel()->GetFieldNameCol( fieldName );
1702
1703 if( col == -1 )
1704 {
1705 wxASSERT_MSG( true, "Fields control has a field not found in the data model." );
1706 continue;
1707 }
1708
1709 std::string fieldNameStr( fieldName.ToUTF8() );
1710
1711 // Set column labels
1712 const wxString& label = getDataModel()->GetColLabelValue( col );
1713 m_viewControlsDataModel->SetValue( i, LABEL_COLUMN, label );
1714 m_grid->SetColLabelValue( col, label );
1715
1716 if( int storedWidth = getStoredColumnWidth( fieldNameStr ); storedWidth > 0 )
1717 m_grid->SetColSize( col, storedWidth );
1718
1719 // Set shown columns
1720 bool show = getDataModel()->GetShowColumn( col );
1721 m_viewControlsDataModel->SetValueAsBool( i, SHOW_FIELD_COLUMN, show );
1722
1723 if( show )
1724 m_grid->ShowCol( col );
1725 else
1726 m_grid->HideCol( col );
1727
1728 // Set grouped columns
1729 bool groupBy = getDataModel()->GetGroupColumn( col );
1730 m_viewControlsDataModel->SetValueAsBool( i, GROUP_BY_COLUMN, groupBy );
1731 }
1732
1733 m_grid->SetSortingColumn( getDataModel()->GetSortCol(), getDataModel()->GetSortAsc() );
1734 m_groupSymbolsBox->SetValue( getDataModel()->GetGroupingEnabled() );
1735 m_filter->ChangeValue( getDataModel()->GetFilter() );
1736 m_filterScope->SetSelection( static_cast<int>( getDataModel()->GetFilterScope() ) );
1737
1738 // Rebuild before sizing columns so their widths account for the current row data.
1741
1743
1744 if( m_nbPages->GetSelection() == 1 )
1746 else
1747 m_grid->ForceRefresh();
1748}
1749
1750
1752{
1753 m_bomPresets.clear();
1754 m_bomPresetMRU.clear();
1755
1756 // Load the read-only defaults
1757 for( const BOM_PRESET& preset : getBuiltInBomPresets() )
1758 {
1759 m_bomPresets[preset.name] = preset;
1760 m_bomPresets[preset.name].readOnly = true;
1761
1762 m_bomPresetMRU.Add( preset.name );
1763 }
1764}
1765
1766
1767std::vector<BOM_PRESET> DIALOG_FIELDS_TABLE::getBuiltInBomPresets() const
1768{
1769 return BOM_PRESET::BuiltInPresets();
1770}
1771
1772
1774{
1775 m_cbBomPresets->Clear();
1776
1777 int idx = 0;
1778 int default_idx = 0;
1779
1780 for( const auto& [presetName, preset] : m_bomPresets )
1781 {
1782 wxString label = preset.readOnly ? wxGetTranslation( presetName ) : presetName;
1783 m_cbBomPresets->Append( label, (void*) &preset );
1784
1785 if( presetName == BOM_PRESET::DefaultEditing().name )
1786 default_idx = idx;
1787
1788 idx++;
1789 }
1790
1791 m_cbBomPresets->Append( wxT( "---" ) );
1792
1793 if( !m_job )
1794 {
1795 m_cbBomPresets->Append( _( "Save preset..." ) );
1796 m_cbBomPresets->Append( _( "Delete preset..." ) );
1797 }
1798
1799 // At least the built-in presets should always be present
1800 wxASSERT( !m_bomPresets.empty() );
1801
1802 m_cbBomPresets->SetSelection( default_idx );
1803 m_currentBomPreset = static_cast<BOM_PRESET*>( m_cbBomPresets->GetClientData( default_idx ) );
1804}
1805
1806
1808{
1809 return aPresetCount - ( m_job ? 1 : 3 );
1810}
1811
1812
1814{
1815 return m_job ? wxNOT_FOUND : aPresetCount - 2;
1816}
1817
1818
1820{
1821 return m_job ? wxNOT_FOUND : aPresetCount - 1;
1822}
1823
1824
1829
1830
1832{
1833 BOM_PRESET current = getDataModelBomPreset();
1834
1835 auto it = std::find_if( m_bomPresets.begin(), m_bomPresets.end(),
1836 [&]( const std::pair<const wxString, BOM_PRESET>& aPair )
1837 {
1838 const BOM_PRESET& preset = aPair.second;
1839
1840 // Check the simple settings first
1841 if( !( preset.sortAsc == current.sortAsc
1842 && preset.filterString == current.filterString
1843 && preset.filterScope == current.filterScope
1844 && preset.groupSymbols == current.groupSymbols
1845 && preset.excludeDNP == current.excludeDNP
1846 && preset.includeExcludedFromBOM == current.includeExcludedFromBOM ) )
1847 {
1848 return false;
1849 }
1850
1851 if( preset.sortField != current.sortField )
1852 return false;
1853
1854 // Only compare shown or grouped fields
1855 std::vector<BOM_FIELD> A, B;
1856
1857 for( const BOM_FIELD& field : preset.fieldsOrdered )
1858 {
1859 if( field.show || field.groupBy )
1860 A.emplace_back( field );
1861 }
1862
1863 for( const BOM_FIELD& field : current.fieldsOrdered )
1864 {
1865 if( field.show || field.groupBy )
1866 B.emplace_back( field );
1867 }
1868
1869 return A == B;
1870 } );
1871
1872 if( it != m_bomPresets.end() )
1873 {
1874 m_cbBomPresets->SetSelection( findPresetIndexByPointer( m_cbBomPresets, &it->second ) );
1875 }
1876 else
1877 {
1878 m_cbBomPresets->SetSelection( presetDashDashDashIndex( m_cbBomPresets->GetCount() ) );
1879 }
1880
1881 m_currentBomPreset = static_cast<BOM_PRESET*>( m_cbBomPresets->GetClientData( m_cbBomPresets->GetSelection() ) );
1882}
1883
1884
1886{
1887 int idx = findPresetIndexByName( m_cbBomPresets, m_bomPresets, aName );
1888
1889 if( idx >= 0 && m_cbBomPresets->GetSelection() != idx )
1890 {
1891 m_cbBomPresets->SetSelection( idx );
1892 m_currentBomPreset = static_cast<BOM_PRESET*>( m_cbBomPresets->GetClientData( idx ) );
1893 }
1894 else if( idx < 0 )
1895 {
1896 m_cbBomPresets->SetSelection( presetDashDashDashIndex( m_cbBomPresets->GetCount() ) );
1897 }
1898}
1899
1900
1901void DIALOG_FIELDS_TABLE::onBomPresetChanged( wxCommandEvent& aEvent )
1902{
1903 int count = m_cbBomPresets->GetCount();
1904 int index = m_cbBomPresets->GetSelection();
1905
1906 auto resetSelection =
1907 [&]()
1908 {
1909 int presetIndex = findPresetIndexByPointer( m_cbBomPresets, m_currentBomPreset );
1910
1911 if( presetIndex == wxNOT_FOUND )
1912 m_cbBomPresets->SetSelection( presetDashDashDashIndex( m_cbBomPresets->GetCount() ) );
1913 else
1914 m_cbBomPresets->SetSelection( presetIndex );
1915 };
1916
1917 if( index == presetDashDashDashIndex( count ) )
1918 {
1919 // Separator: reject the selection
1920 resetSelection();
1921 return;
1922 }
1923 else if( index == presetSavePresetIndex( count ) )
1924 {
1925 // Save current state to new preset
1926 wxString name;
1927
1930
1931 wxTextEntryDialog dlg( this, _( "BOM preset name:" ), _( "Save BOM Preset" ), name );
1932
1933 if( dlg.ShowModal() != wxID_OK )
1934 {
1935 resetSelection();
1936 return;
1937 }
1938
1939 name = dlg.GetValue();
1940 bool exists = m_bomPresets.count( name );
1941
1942 if( !exists )
1943 {
1945 m_bomPresets[name].readOnly = false;
1946 m_bomPresets[name].name = name;
1947 }
1948
1949 BOM_PRESET* preset = &m_bomPresets[name];
1950
1951 if( !exists )
1952 {
1953 index = m_cbBomPresets->Insert( name, index - 1, static_cast<void*>( preset ) );
1954 }
1955 else if( preset->readOnly )
1956 {
1957 wxMessageBox( _( "Default presets cannot be modified.\nPlease use a different name." ),
1958 _( "Error" ), wxOK | wxICON_ERROR, this );
1959 resetSelection();
1960 return;
1961 }
1962 else
1963 {
1964 // Ask the user if they want to overwrite the existing preset
1965 if( !IsOK( this, _( "Overwrite existing preset?" ) ) )
1966 {
1967 resetSelection();
1968 return;
1969 }
1970
1971 *preset = getDataModelBomPreset();
1972 preset->name = name;
1973
1974 index = findPresetIndexByPointer( m_cbBomPresets, preset );
1975
1976 if( m_bomPresetMRU.Index( name ) != wxNOT_FOUND )
1977 m_bomPresetMRU.Remove( name );
1978 }
1979
1980 m_currentBomPreset = preset;
1981 m_cbBomPresets->SetSelection( index );
1982 m_bomPresetMRU.Insert( name, 0 );
1983
1984 return;
1985 }
1986 else if( index == presetDeletePresetIndex( count ) )
1987 {
1988 // Delete a preset
1989 wxArrayString headers;
1990 std::vector<wxArrayString> items;
1991
1992 headers.Add( _( "Presets" ) );
1993
1994 for( const auto& [name, preset] : m_bomPresets )
1995 {
1996 if( !preset.readOnly )
1997 {
1998 wxArrayString item;
1999 item.Add( name );
2000 items.emplace_back( item );
2001 }
2002 }
2003
2004 EDA_LIST_DIALOG dlg( this, _( "Delete Preset" ), headers, items );
2005 dlg.SetListLabel( _( "Select preset:" ) );
2006
2007 if( dlg.ShowModal() == wxID_OK )
2008 {
2009 wxString presetName = dlg.GetTextSelection();
2010 auto presetIt = m_bomPresets.find( presetName );
2011 int idx = findPresetIndexByName( m_cbBomPresets, m_bomPresets, presetName );
2012
2013 if( idx != wxNOT_FOUND && presetIt != m_bomPresets.end() )
2014 {
2015 if( m_lastSelectedBomPreset == &presetIt->second )
2016 m_lastSelectedBomPreset = nullptr;
2017
2018 m_currentBomPreset = nullptr;
2019 m_cbBomPresets->Delete( idx );
2020 m_bomPresets.erase( presetIt );
2021 }
2022
2023 if( m_bomPresetMRU.Index( presetName ) != wxNOT_FOUND )
2024 m_bomPresetMRU.Remove( presetName );
2025 }
2026
2027 resetSelection();
2028 return;
2029 }
2030
2031 BOM_PRESET* preset = static_cast<BOM_PRESET*>( m_cbBomPresets->GetClientData( index ) );
2032 m_currentBomPreset = preset;
2033
2034 m_lastSelectedBomPreset = ( !preset || preset->readOnly ) ? nullptr : preset;
2035
2036 if( preset )
2037 {
2038 doApplyBomPreset( *preset );
2040 m_currentBomPreset = preset;
2041
2042 if( !m_currentBomPreset->name.IsEmpty() )
2043 {
2044 if( m_bomPresetMRU.Index( preset->name ) != wxNOT_FOUND )
2045 m_bomPresetMRU.Remove( preset->name );
2046
2047 m_bomPresetMRU.Insert( preset->name, 0 );
2048 }
2049 }
2050}
2051
2052
2054{
2055 BOM_FMT_PRESET current;
2056
2057 int selection = m_cbBomFmtPresets->GetSelection();
2058
2059 if( selection != wxNOT_FOUND )
2060 {
2061 if( auto* preset = static_cast<BOM_FMT_PRESET*>( m_cbBomFmtPresets->GetClientData( selection ) ) )
2062 current.name = preset->name;
2063 else
2064 current.name = m_cbBomFmtPresets->GetString( selection );
2065 }
2066
2067 current.fieldDelimiter = m_textFieldDelimiter->GetValue();
2068 current.stringDelimiter = m_textStringDelimiter->GetValue();
2069 current.refDelimiter = m_textRefDelimiter->GetValue();
2070 current.refRangeDelimiter = m_textRefRangeDelimiter->GetValue();
2071 current.keepTabs = m_checkKeepTabs->GetValue();
2072 current.keepLineBreaks = m_checkKeepLineBreaks->GetValue();
2074
2075 return current;
2076}
2077
2078
2079std::vector<BOM_FMT_PRESET> DIALOG_FIELDS_TABLE::GetUserBomFmtPresets() const
2080{
2081 std::vector<BOM_FMT_PRESET> ret;
2082
2083 for( const auto& [name, preset] : m_bomFmtPresets )
2084 {
2085 if( !preset.readOnly )
2086 ret.emplace_back( preset );
2087 }
2088
2089 return ret;
2090}
2091
2092
2093void DIALOG_FIELDS_TABLE::SetUserBomFmtPresets( std::vector<BOM_FMT_PRESET>& aPresetList )
2094{
2095 // Reset to defaults
2097
2098 for( const BOM_FMT_PRESET& preset : aPresetList )
2099 {
2100 if( m_bomFmtPresets.count( preset.name ) )
2101 continue;
2102
2103 m_bomFmtPresets[preset.name] = preset;
2104
2105 m_bomFmtPresetMRU.Add( preset.name );
2106 }
2107
2109}
2110
2111
2112void DIALOG_FIELDS_TABLE::ApplyBomFmtPreset( const wxString& aPresetName )
2113{
2114 updateBomFmtPresetSelection( aPresetName );
2115
2116 wxCommandEvent dummy;
2118}
2119
2120
2122{
2123 m_currentBomFmtPreset = nullptr;
2125
2126 if( m_bomFmtPresets.count( aPreset.name ) )
2128
2131
2133 doApplyBomFmtPreset( aPreset );
2134}
2135
2136
2138{
2139 m_textFieldDelimiter->ChangeValue( aPreset.fieldDelimiter );
2140 m_textStringDelimiter->ChangeValue( aPreset.stringDelimiter );
2141 m_textRefDelimiter->ChangeValue( aPreset.refDelimiter );
2142 m_textRefRangeDelimiter->ChangeValue( aPreset.refRangeDelimiter );
2143 m_checkKeepTabs->SetValue( aPreset.keepTabs );
2144 m_checkKeepLineBreaks->SetValue( aPreset.keepLineBreaks );
2146
2147 // Refresh the preview if that's the current page
2148 if( m_nbPages->GetSelection() == 1 )
2150}
2151
2152
2154{
2155 m_bomFmtPresets.clear();
2156 m_bomFmtPresetMRU.clear();
2157
2158 // Load the read-only defaults
2159 for( const BOM_FMT_PRESET& preset : BOM_FMT_PRESET::BuiltInPresets() )
2160 {
2161 m_bomFmtPresets[preset.name] = preset;
2162 m_bomFmtPresets[preset.name].readOnly = true;
2163
2164 m_bomFmtPresetMRU.Add( preset.name );
2165 }
2166}
2167
2168
2170{
2171 m_cbBomFmtPresets->Clear();
2172
2173 int idx = 0;
2174 int default_idx = 0;
2175
2176 for( const auto& [presetName, preset] : m_bomFmtPresets )
2177 {
2178 wxString label = preset.readOnly ? wxGetTranslation( presetName ) : presetName;
2179 m_cbBomFmtPresets->Append( label, (void*) &preset );
2180
2181 if( presetName == BOM_FMT_PRESET::CSV().name )
2182 default_idx = idx;
2183
2184 idx++;
2185 }
2186
2187 m_cbBomFmtPresets->Append( wxT( "---" ) );
2188
2189 if( !m_job )
2190 {
2191 m_cbBomFmtPresets->Append( _( "Save preset..." ) );
2192 m_cbBomFmtPresets->Append( _( "Delete preset..." ) );
2193 }
2194
2195 // At least the built-in presets should always be present
2196 wxASSERT( !m_bomFmtPresets.empty() );
2197
2198 m_cbBomFmtPresets->SetSelection( default_idx );
2199 m_currentBomFmtPreset = static_cast<BOM_FMT_PRESET*>( m_cbBomFmtPresets->GetClientData( default_idx ) );
2200}
2201
2202
2204{
2206
2207 auto it = std::find_if( m_bomFmtPresets.begin(), m_bomFmtPresets.end(),
2208 [&]( const std::pair<const wxString, BOM_FMT_PRESET>& aPair )
2209 {
2210 return ( aPair.second.fieldDelimiter == current.fieldDelimiter
2211 && aPair.second.stringDelimiter == current.stringDelimiter
2212 && aPair.second.refDelimiter == current.refDelimiter
2213 && aPair.second.refRangeDelimiter == current.refRangeDelimiter
2214 && aPair.second.keepTabs == current.keepTabs
2215 && aPair.second.keepLineBreaks == current.keepLineBreaks
2216 && aPair.second.includeByteOrderMark == current.includeByteOrderMark );
2217 } );
2218
2219 if( it != m_bomFmtPresets.end() )
2220 {
2221 m_cbBomFmtPresets->SetSelection( findPresetIndexByPointer( m_cbBomFmtPresets, &it->second ) );
2222 }
2223 else
2224 {
2225 m_cbBomFmtPresets->SetSelection( presetDashDashDashIndex( m_cbBomFmtPresets->GetCount() ) );
2226 }
2227
2228 int idx = m_cbBomFmtPresets->GetSelection();
2229 m_currentBomFmtPreset = static_cast<BOM_FMT_PRESET*>( m_cbBomFmtPresets->GetClientData( idx ) );
2230}
2231
2232
2234{
2235 int idx = findPresetIndexByName( m_cbBomFmtPresets, m_bomFmtPresets, aName );
2236
2237 if( idx >= 0 && m_cbBomFmtPresets->GetSelection() != idx )
2238 {
2239 m_cbBomFmtPresets->SetSelection( idx );
2240 m_currentBomFmtPreset = static_cast<BOM_FMT_PRESET*>( m_cbBomFmtPresets->GetClientData( idx ) );
2241 }
2242 else if( idx < 0 )
2243 {
2244 m_cbBomFmtPresets->SetSelection( presetDashDashDashIndex( m_cbBomFmtPresets->GetCount() ) );
2245 }
2246}
2247
2248
2250{
2251 int count = m_cbBomFmtPresets->GetCount();
2252 int index = m_cbBomFmtPresets->GetSelection();
2253
2254 auto resetSelection =
2255 [&]()
2256 {
2257 int presetIndex = findPresetIndexByPointer( m_cbBomFmtPresets, m_currentBomFmtPreset );
2258
2259 if( presetIndex == wxNOT_FOUND )
2260 m_cbBomFmtPresets->SetSelection( presetDashDashDashIndex( m_cbBomFmtPresets->GetCount() ) );
2261 else
2262 m_cbBomFmtPresets->SetSelection( presetIndex );
2263 };
2264
2265 if( index == presetDashDashDashIndex( count ) )
2266 {
2267 // Separator: reject the selection
2268 resetSelection();
2269 return;
2270 }
2271 else if( index == presetSavePresetIndex( count ) )
2272 {
2273 // Save current state to new preset
2274 wxString name;
2275
2278
2279 wxTextEntryDialog dlg( this, _( "BOM preset name:" ), _( "Save BOM Preset" ), name );
2280
2281 if( dlg.ShowModal() != wxID_OK )
2282 {
2283 resetSelection();
2284 return;
2285 }
2286
2287 name = dlg.GetValue();
2288 bool exists = m_bomFmtPresets.count( name );
2289
2290 if( !exists )
2291 {
2293 m_bomFmtPresets[name].readOnly = false;
2294 m_bomFmtPresets[name].name = name;
2295 }
2296
2298
2299 if( !exists )
2300 {
2301 index = m_cbBomFmtPresets->Insert( name, index - 1, static_cast<void*>( preset ) );
2302 }
2303 else if( preset->readOnly )
2304 {
2305 wxMessageBox( _( "Default presets cannot be modified.\nPlease use a different name." ),
2306 _( "Error" ), wxOK | wxICON_ERROR, this );
2307 resetSelection();
2308 return;
2309 }
2310 else
2311 {
2312 // Ask the user if they want to overwrite the existing preset
2313 if( !IsOK( this, _( "Overwrite existing preset?" ) ) )
2314 {
2315 resetSelection();
2316 return;
2317 }
2318
2319 *preset = GetCurrentBomFmtSettings();
2320 preset->name = name;
2321
2322 index = findPresetIndexByPointer( m_cbBomFmtPresets, preset );
2323
2324 if( m_bomFmtPresetMRU.Index( name ) != wxNOT_FOUND )
2325 m_bomFmtPresetMRU.Remove( name );
2326 }
2327
2328 m_currentBomFmtPreset = preset;
2329 m_cbBomFmtPresets->SetSelection( index );
2330 m_bomFmtPresetMRU.Insert( name, 0 );
2331
2332 return;
2333 }
2334 else if( index == presetDeletePresetIndex( count ) )
2335 {
2336 // Delete a preset
2337 wxArrayString headers;
2338 std::vector<wxArrayString> items;
2339
2340 headers.Add( _( "Presets" ) );
2341
2342 for( std::pair<const wxString, BOM_FMT_PRESET>& pair : m_bomFmtPresets )
2343 {
2344 if( !pair.second.readOnly )
2345 {
2346 wxArrayString item;
2347 item.Add( pair.first );
2348 items.emplace_back( item );
2349 }
2350 }
2351
2352 EDA_LIST_DIALOG dlg( this, _( "Delete Preset" ), headers, items );
2353 dlg.SetListLabel( _( "Select preset:" ) );
2354
2355 if( dlg.ShowModal() == wxID_OK )
2356 {
2357 wxString presetName = dlg.GetTextSelection();
2358 auto presetIt = m_bomFmtPresets.find( presetName );
2359 int idx = findPresetIndexByName( m_cbBomFmtPresets, m_bomFmtPresets, presetName );
2360
2361 if( idx != wxNOT_FOUND && presetIt != m_bomFmtPresets.end() )
2362 {
2363 if( m_lastSelectedBomFmtPreset == &presetIt->second )
2365
2366 m_currentBomFmtPreset = nullptr;
2367 m_cbBomFmtPresets->Delete( idx );
2368 m_bomFmtPresets.erase( presetIt );
2369 }
2370
2371 if( m_bomFmtPresetMRU.Index( presetName ) != wxNOT_FOUND )
2372 m_bomFmtPresetMRU.Remove( presetName );
2373 }
2374
2375 resetSelection();
2376 return;
2377 }
2378
2379 auto* preset = static_cast<BOM_FMT_PRESET*>( m_cbBomFmtPresets->GetClientData( index ) );
2380 m_currentBomFmtPreset = preset;
2381
2382 m_lastSelectedBomFmtPreset = ( !preset || preset->readOnly ) ? nullptr : preset;
2383
2384 if( preset )
2385 {
2386 doApplyBomFmtPreset( *preset );
2388 m_currentBomFmtPreset = preset;
2389
2390 if( !m_currentBomFmtPreset->name.IsEmpty() )
2391 {
2392 if( m_bomFmtPresetMRU.Index( preset->name ) != wxNOT_FOUND )
2393 m_bomFmtPresetMRU.Remove( preset->name );
2394
2395 m_bomFmtPresetMRU.Insert( preset->name, 0 );
2396 }
2397 }
2398}
int index
const char * name
wxBitmapBundle KiBitmapBundle(BITMAPS aBitmap, int aMinHeight)
Definition bitmap.cpp:106
BOM_FILTER_SCOPE
STD_BITMAP_BUTTON * m_addVariantButton
STD_BITMAP_BUTTON * m_renameVariantButton
DIALOG_FIELDS_TABLE_BASE(wxWindow *parent, wxWindowID id=wxID_ANY, const wxString &title=_("Fields Table"), const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxSize(-1,-1), long style=wxDEFAULT_DIALOG_STYLE|wxMAXIMIZE_BOX|wxRESIZE_BORDER)
STD_BITMAP_BUTTON * m_removeFieldButton
STD_BITMAP_BUTTON * m_renameFieldButton
wxSplitterWindow * m_splitterMainWindow
STD_BITMAP_BUTTON * m_copyVariantButton
STD_BITMAP_BUTTON * m_deleteVariantButton
STD_BITMAP_BUTTON * m_editVariantDescButton
std::map< wxString, BOM_PRESET > m_bomPresets
BOM_PRESET * m_lastSelectedBomPreset
void saveJobSettings(JOB_EXPORT_BOM &aJob)
virtual wxGridCellEditor * createReferenceEditor()
void SetUserBomFmtPresets(std::vector< BOM_FMT_PRESET > &aPresetList)
wxSize GetDefaultDialogSize() const
virtual wxGridCellEditor * createDatasheetEditor()=0
virtual bool resolveTextVar(wxString *aToken) const =0
int getStoredColumnWidth(const std::string &aFieldName) const
BOM_FMT_PRESET * m_lastSelectedBomFmtPreset
void OnColMove(wxGridEvent &aEvent)
int presetDashDashDashIndex(int aPresetCount) const
void OnColSort(wxGridEvent &aEvent)
void OnGridMouseMove(wxMouseEvent &aEvent)
bool savePresets(bool aSaveCurrentSettings)
Store what changed since rememberLoadedPresets(); true if anything did.
wxArrayString m_bomFmtPresetMRU
void OnSizeViewControlsGrid(wxSizeEvent &event) override
void OnViewControlsCellChanged(wxGridEvent &aEvent) override
BOM_FMT_PRESET * m_currentBomFmtPreset
int presetDeletePresetIndex(int aPresetCount) const
void OnTableRangeSelectionChanged(wxGridRangeSelectEvent &aEvent)
wxString getSelectedVariant() const
void rememberLoadedPresets()
Remember the presets as loaded, which may differ from the stored ones after normalization.
void doApplyBomFmtPreset(const BOM_FMT_PRESET &aPreset)
void OnFilterText(wxCommandEvent &aEvent) override
void doApplyBomPreset(const BOM_PRESET &aPreset)
void OnPageChanged(wxNotebookEvent &aEvent) override
void ShowHideColumn(int aCol, bool aShow)
void OnExport(wxCommandEvent &aEvent) override
virtual void OnTableSelectionChanged(const std::set< int > &aRows)=0
void updateBomPresetSelection(const wxString &aName)
void OnFilterScope(wxCommandEvent &aEvent) override
BOM_FMT_PRESET GetCurrentBomFmtSettings()
Returns a formatting configuration corresponding to the values in the UI controls of the dialog.
void RestoreGridSelection(const std::set< KIID_PATH > &aItemKeys)
Restore a selection previously returned by SaveGridSelection().
std::map< FIELD_T, int > m_mandatoryFieldListIndexes
virtual wxGridCellEditor * createFootprintEditor()
void onBomFmtPresetChanged(wxCommandEvent &aEvent)
int presetSavePresetIndex(int aPresetCount) const
void OnRenameField(wxCommandEvent &aEvent) override
void OnGroupSymbolsToggled(wxCommandEvent &aEvent) override
void OnPreviewRefresh(wxCommandEvent &aEvent) override
virtual std::vector< BOM_PRESET > getBuiltInBomPresets() const
void updateBomFmtPresetSelection(const wxString &aName)
void OnTableColSize(wxGridSizeEvent &event) override
void SetUserBomPresets(std::vector< BOM_PRESET > &aPresetList)
void ApplyBomFmtPreset(const wxString &aPresetName)
DIALOG_FIELDS_TABLE(wxWindow *aParent, FIELDS_TABLE_SETTINGS &aPanelSettings, FIELDS_TABLE_BOM_SETTINGS &aBomSettings, JOB_EXPORT_BOM *aJob)
void SetupColumnProperties(int aCol)
FIELDS_TABLE_BOM_SETTINGS & m_cfgBomSettings
static void loadJobBomFmtPreset(const JOB_EXPORT_BOM &aJob, BOM_FMT_PRESET &aPreset)
FIELDS_TABLE_SETTINGS & m_cfgDialogSettings
std::map< wxString, BOM_FMT_PRESET > m_bomFmtPresets
static void loadJobBomPreset(const JOB_EXPORT_BOM &aJob, BOM_PRESET &aPreset)
virtual wxString resolveVariant() const =0
std::set< int > GetSelectedGridRows() const
Return the explicitly selected grid rows, or the cursor row if the selection is empty.
void OnGridMouseWheel(wxMouseEvent &aEvent)
void OnSidebarToggle(wxCommandEvent &event) override
void OnAddField(wxCommandEvent &aEvent) override
std::vector< BOM_PRESET > GetUserBomPresets() const
void onBomPresetChanged(wxCommandEvent &aEvent)
virtual void onBomSettingsChanged()
void SetReadOnly(bool aReadOnly)
std::set< KIID_PATH > SaveGridSelection()
Save the grid selection by stable item identity so it can survive a row rebuild.
void ApplyBomPreset(const wxString &aPresetName)
void OnFilterMouseMoved(wxMouseEvent &event) override
void OnRegroupSymbols(wxCommandEvent &aEvent) override
void OnOutputFileBrowseClicked(wxCommandEvent &aEvent) override
void OnTableValueChanged(wxGridEvent &event) override
virtual FIELDS_TABLE_DATA_MODEL_BASE * getDataModel() const =0
VIEW_CONTROLS_GRID_DATA_MODEL * m_viewControlsDataModel
FIELDS_TABLE_BOM_SETTINGS m_loadedSettings
static wxString GetDefaultBomFileName(const wxString &aInputFileName)
Derive the default BOM output file name from the input file name by swapping the extension to CSV.
std::vector< BOM_FMT_PRESET > GetUserBomFmtPresets() const
void OnTableLabelClick(wxGridEvent &event) override
void setSideBarButtonLook(bool aIsLeftPanelCollapsed)
void AddField(const wxString &aFieldName, const wxString &aLabelValue, bool aShow, bool aGroupBy, bool aAddedByUser=false)
void OnRemoveField(wxCommandEvent &aEvent) override
void OptOut(wxWindow *aWindow)
Opt out of control state saving.
EDA_BASE_FRAME * m_parentFrame
int ShowModal() override
A dialog which shows:
wxString GetTextSelection(int aColumn=0)
Return the selected text from aColumn in the wxListCtrl in the dialog.
void SetListLabel(const wxString &aLabel)
Contains everything completly generic to fields tables data models, as well as column functionality t...
virtual void SetCurrentVariant(const wxString &aVariantName)=0
Select the displayed variant, retaining un-applied edits in every variant.
void SetSorting(int aCol, bool aAscending)
void MoveColumn(int aCol, int aNewPos)
void SetShowColumn(int aCol, bool aShow)
void SetIncludeExcludedFromBOM(bool aInclude)
virtual void AddColumn(const wxString &aFieldName, const wxString &aLabel, bool aAddedByUser)=0
void SetColLabelValue(int aCol, const wxString &aLabel) override
void SetFilterScope(BOM_FILTER_SCOPE aScope)
int GetFieldNameCol(const wxString &aFieldName) const
virtual void ExpandCollapseRow(int aRow)=0
void RenameColumn(int aCol, const wxString &newName)
void SetGroupColumn(int aCol, bool aGroup)
void SetFilter(const wxString &aFilter)
wxString GetColLabelValue(int aCol) override
void ApplyBomPreset(const BOM_PRESET &aPreset)
virtual void RebuildRows()=0
DIALOG_FIELDS_TABLE * m_dialog
FIELDS_TABLE_GRID_TRICKS(DIALOG_FIELDS_TABLE *aDialog, WX_GRID *aGrid, FIELDS_TABLE_DATA_MODEL_BASE *aDataModel)
virtual void showFieldsTablePopupMenu(wxMenu &aMenu, wxGridEvent &aEvent)
void appendPopupMenuItems(wxMenu &aMenu) override
void copyFromVariant(const wxString &aVariant, const std::vector< wxGridCellCoords > &aCells)
FIELDS_TABLE_DATA_MODEL_BASE * m_dataModel
void doPopupSelection(wxCommandEvent &aEvent) override
void showPopupMenu(wxMenu &aMenu, wxGridEvent &aEvent) override
virtual void doFieldsTablePopupSelection(wxCommandEvent &aEvent)
A text control validator used for validating the text allowed in fields.
Definition validators.h:137
This class works around a bug in wxGrid where the first keystroke doesn't get sent through the valida...
Add mouse and command handling (such as cut, copy, and paste) to a WX_GRID instance.
Definition grid_tricks.h:61
GRID_TRICKS(WX_GRID *aGrid)
virtual void doPopupSelection(wxCommandEvent &event)
virtual void showPopupMenu(wxMenu &menu, wxGridEvent &aEvent)
WX_GRID * m_grid
I don't own the grid, but he owns me.
wxString m_stringDelimiter
wxString m_fieldDelimiter
bool m_includeByteOrderMark
wxString m_filterString
std::vector< wxString > m_fieldsOrdered
wxString m_refRangeDelimiter
std::vector< wxString > m_fieldsLabels
wxString m_refDelimiter
void SetSelectedVariant(const wxString &aVariant)
std::vector< wxString > m_fieldsGroupBy
wxString m_bomFmtPresetName
wxString m_sortField
wxString m_bomPresetName
BOM_FILTER_SCOPE m_filterScope
void SetConfiguredOutputPath(const wxString &aPath)
Sets the configured output path for the job, this path is always saved to file.
Definition job.cpp:181
PROJECT & Prj() const
Return a reference to the PROJECT associated with this KIWAY.
static REPORTER & GetInstance()
Definition reporter.cpp:207
virtual ROW_STATE GetRowState(int aRow) const
Definition wx_grid.h:109
void SetColAttr(wxGridCellAttr *aAttr, int aCol) override
Definition wx_grid.h:90
wxString GetGeneratedFieldDisplayName(const wxString &aSource)
Returns any variables unexpanded, e.g.
Definition common.cpp:481
const wxString ExpandEnvVarSubstitutions(const wxString &aString, const PROJECT *aProject, bool aAllowEscapes)
Replace any environment variable & text variable references with their values.
Definition common.cpp:777
wxString ExpandTextVars(const wxString &aSource, const PROJECT *aProject, RESOLUTION_CONTEXT aContext)
Definition common.cpp:60
wxString ResolveProjectPath(const wxString &aPath, const PROJECT *aProject, const std::function< bool(wxString *)> *aTextResolver)
Expand a user-entered file path as ExpandPathVariables() does, then anchor a relative result at the p...
Definition common.cpp:817
wxString NormalizeFilePathForTextVars(const wxString &aPath)
Normalize a file path so its text variables survive ExpandTextVars.
Definition common.cpp:72
bool EnsureFileDirectoryExists(wxFileName *aTargetFullFileName, const wxString &aBaseFilename, REPORTER *aReporter)
Make aTargetFullFileName absolute and create the path of this file if it doesn't yet exist.
Definition common.cpp:829
bool IsGeneratedField(const wxString &aFieldName)
Returns true if the entire string is generated, e.g is a single text var reference.
Definition common.cpp:494
@ INTERNAL
Definition common.h:96
int OKOrCancelDialog(wxWindow *aParent, const wxString &aWarning, const wxString &aMessage, const wxString &aDetailedMessage, const wxString &aOKLabel, const wxString &aCancelLabel, bool *aApplyToAll)
Display a warning dialog with aMessage and returns the user response.
Definition confirm.cpp:165
bool IsOK(wxWindow *aParent, const wxString &aMessage)
Display a yes/no dialog with aMessage and returns the user response.
Definition confirm.cpp:274
void DisplayInfoMessage(wxWindow *aParent, const wxString &aMessage, const wxString &aExtraInfo)
Display an informational message box with aMessage.
Definition confirm.cpp:245
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
void DisplayError(wxWindow *aParent, const wxString &aText)
Display an error or warning message box with aMessage.
Definition confirm.cpp:192
This file is part of the common library.
#define COLUMN_MARGIN
static bool isValidColumnWidth(int aWidth)
static constexpr int MAX_COL_WIDTH
#define _(s)
Base window classes and related definitions.
@ GRIDTRICKS_FIRST_SHOWHIDE
Definition grid_tricks.h:49
@ GRIDTRICKS_FIRST_CLIENT_ID
Definition grid_tricks.h:46
static const std::string CsvFileExtension
static wxString CsvFileWildcard()
void AllowNetworkFileSystems(wxDialog *aDialog)
Configure a file dialog to show network and virtual file systems.
Definition wxgtk/ui.cpp:741
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
bool contains(const _Container &__container, _Value __value)
Returns true if the container contains the given value.
Definition kicad_algo.h:96
std::vector< FAB_LAYER_COLOR > dummy
wxString GetDefaultVariantName()
wxString label
wxString name
wxString fieldDelimiter
bool includeByteOrderMark
static BOM_FMT_PRESET CSV()
static std::vector< BOM_FMT_PRESET > BuiltInPresets()
wxString stringDelimiter
wxString refRangeDelimiter
wxString refDelimiter
Dialog settings for the lib/symbol/footprint table editors across the various editors.
bool FieldNamesAreDuplicates(const wxString &aLhs, const wxString &aRhs, std::initializer_list< FIELD_T > aMandatoryFields)
Test whether two field names should be treated as duplicates for the purposes of field name uniquenes...
wxString GetDefaultFieldName(FIELD_T aFieldId, TRANSLATION aTranslation)
Return a default symbol field name for a mandatory field type.
#define MANDATORY_FIELDS
FIELD_T
The set of all field indices assuming an array like sequence that a SCH_COMPONENT or LIB_PART can hol...
@ FOOTPRINT
Field Name Module PCB, i.e. "16DIP300".
@ DATASHEET
name of datasheet
@ REFERENCE
Field Reference of part, i.e. "IC21".
@ UNTRANSLATED
std::string path
Functions to provide common constants and other functions to assist in making a consistent UI.
Custom text control validator definitions.
Definition of file extensions used in Kicad.
bool IsRowCollapsed(ROW_STATE aState)
Definition wx_grid.h:69
enum KICOMMON_API ROW_STATE
Used primarily by the fields tables to collapse multiple grouped symbols, etc.
Definition wx_grid.h:44
bool IsRowExpanded(ROW_STATE aState)
Definition wx_grid.h:75