KiCad PCB EDA Suite
Loading...
Searching...
No Matches
lib_table_grid_tricks.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 modify it
7 * under the terms of the GNU General Public License as published by the
8 * Free Software Foundation, either version 3 of the License, or (at your
9 * option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful, but
12 * WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the GNU
14 * 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, see <https://www.gnu.org/licenses/>.
18 */
19
21#include "confirm.h"
24#include <wx/clipbrd.h>
25#include <wx/log.h>
26#include <wx/msgdlg.h>
27#include <lib_id.h>
28
29
30static bool isGridReadOnly( WX_GRID* aGrid )
31{
32 LIB_TABLE_GRID_DATA_MODEL* model = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( aGrid->GetTable() );
33 return model && model->Table().IsReadOnly();
34}
35
36
41
42
44 std::function<void( wxCommandEvent& )> aAddHandler ) :
45 GRID_TRICKS( aGrid, aAddHandler )
46{
47}
48
49
51{
52 if( aEvent.GetCol() == COL_STATUS )
53 {
54 // Status column button action depends on row:
55 // Normal rows should have no button, so they are a no-op
56 // Errored rows should have the warning button, so we show their error
57 // Configurable libraries will have the options button, so we launch the config
58 // Chained tables will have the open button, so we request the table be opened
60 const LIBRARY_TABLE_ROW& row = model->at( aEvent.GetRow() );
61 LIBRARY_MANAGER_ADAPTER* adapter = model->Adapter();
62
63 wxString title = row.Type() == "Table"
64 ? wxString::Format( _( "Error loading library table '%s'" ), row.Nickname() )
65 : wxString::Format( _( "Error loading library '%s'" ), row.Nickname() );
66
67 // The settings dialog reports load errors itself and is where they get fixed
68 if( adapter->SupportsConfigurationDialog( row ) && !isGridReadOnly( m_grid ) )
69 {
70 if( adapter->ShowConfigurationDialog( row, model->Table().Scope(), wxGetTopLevelParent( m_grid ) )
71 != wxID_CANCEL )
72 {
73 model->OnModify();
74 }
75 }
76 else if( !row.IsOk() )
77 {
79 }
80 else if( std::optional<LIBRARY_ERROR> e = adapter->LibraryError( row.Nickname() ) )
81 {
82 DisplayErrorMessage( m_grid, title, e->message );
83 }
85 {
86 openTable( row );
87 }
88
89 aEvent.Skip();
90 }
91 else
92 {
94 }
95}
96
97
98void LIB_TABLE_GRID_TRICKS::showPopupMenu( wxMenu& menu, wxGridEvent& aEvent )
99{
100 // Ensure selection parameters are up to date
102
103 LIB_TABLE_GRID_DATA_MODEL* model = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( m_grid->GetTable() );
104 const LIBRARY_TABLE_ROW& firstRow = model->at( m_sel_row_start );
105 bool readOnly = model->Table().IsReadOnly();
106
107 bool showSettings = false;
108 bool showOpen = false;
109
110 if( !readOnly )
111 {
112 if( LIBRARY_MANAGER_ADAPTER* adapter = model->Adapter() )
113 {
114 if( m_sel_row_count == 1 && adapter->SupportsConfigurationDialog( firstRow ) )
115 {
116 showSettings = true;
117 menu.Append( LIB_TABLE_GRID_TRICKS_LIBRARY_SETTINGS, _( "Edit Settings..." ) );
118 }
119 }
120 }
121
122 if( firstRow.Type() == LIBRARY_TABLE_ROW::TABLE_TYPE_NAME )
123 {
124 showOpen = true;
125 menu.Append( LIB_TABLE_GRID_TRICKS_OPEN_TABLE, _( "Open Library Table" ) );
126 }
127
128 if( showSettings || showOpen )
129 menu.AppendSeparator();
130
131 bool showActivate = false;
132 bool showDeactivate = false;
133 bool showSetVisible = false;
134 bool showUnsetVisible = false;
135 bool showOptions = false;
136
137 for( int row = m_sel_row_start; row < m_sel_row_start + m_sel_row_count; ++row )
138 {
139 if( model->GetValueAsBool( row, COL_ENABLED ) )
140 showDeactivate = true;
141 else
142 showActivate = true;
143
144 if( model->GetValueAsBool( row, COL_VISIBLE ) )
145 showUnsetVisible = true;
146 else
147 showSetVisible = true;
148
149 if( showActivate && showDeactivate && showSetVisible && showUnsetVisible )
150 break;
151 }
152
153 if( showActivate )
154 menu.Append( LIB_TABLE_GRID_TRICKS_ACTIVATE_SELECTED, _( "Activate Selected" ) );
155
156 if( showDeactivate )
157 menu.Append( LIB_TABLE_GRID_TRICKS_DEACTIVATE_SELECTED, _( "Deactivate Selected" ) );
158
160 {
161 if( showSetVisible )
162 menu.Append( LIB_TABLE_GRID_TRICKS_SET_VISIBLE, _( "Set Visible Flag" ) );
163
164 if( showUnsetVisible )
165 menu.Append( LIB_TABLE_GRID_TRICKS_UNSET_VISIBLE, _( "Unset Visible Flag" ) );
166 }
167
168 if( !readOnly && m_sel_row_count == 1 && firstRow.Type() != LIBRARY_TABLE_ROW::TABLE_TYPE_NAME )
169 {
170 showOptions = true;
171 menu.Append( LIB_TABLE_GRID_TRICKS_OPTIONS_EDITOR, _( "Edit Options..." ),
172 _( "Edit options for this library entry" ) );
173 }
174
175 if( showActivate || showDeactivate || showSetVisible || showUnsetVisible || showOptions )
176 menu.AppendSeparator();
177
178 // For read-only tables, only show activate/deactivate and visible options (no cut/paste/delete)
179 if( !readOnly )
180 GRID_TRICKS::showPopupMenu( menu, aEvent );
181}
182
183
184void LIB_TABLE_GRID_TRICKS::doPopupSelection( wxCommandEvent& event )
185{
186 int menu_id = event.GetId();
187 LIB_TABLE_GRID_DATA_MODEL* model = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( m_grid->GetTable() );
188
190 {
191 optionsEditor( m_grid->GetGridCursorRow() );
192 }
195 {
196 bool selected_state = menu_id == LIB_TABLE_GRID_TRICKS_ACTIVATE_SELECTED;
197
198 for( int row = m_sel_row_start; row < m_sel_row_start + m_sel_row_count; ++row )
199 model->SetValueAsBool( row, COL_ENABLED, selected_state );
200
201 // Ensure the new state (on/off) of the widgets is immediately shown:
202 m_grid->Refresh();
203 }
204 else if( menu_id == LIB_TABLE_GRID_TRICKS_SET_VISIBLE
206 {
207 bool selected_state = menu_id == LIB_TABLE_GRID_TRICKS_SET_VISIBLE;
208
209 for( int row = m_sel_row_start; row < m_sel_row_start + m_sel_row_count; ++row )
210 model->SetValueAsBool( row, COL_VISIBLE, selected_state );
211
212 // Ensure the new state (on/off) of the widgets is immediately shown:
213 m_grid->Refresh();
214 }
215 else if( menu_id == LIB_TABLE_GRID_TRICKS_LIBRARY_SETTINGS )
216 {
217 LIBRARY_MANAGER_ADAPTER* adapter = model->Adapter();
219
220 if( adapter->ShowConfigurationDialog( row, model->Table().Scope(), wxGetTopLevelParent( m_grid ) )
221 != wxID_CANCEL )
222 {
223 model->OnModify();
224 }
225 }
226 else if( menu_id == LIB_TABLE_GRID_TRICKS_OPEN_TABLE )
227 {
229 }
230 else
231 {
233 }
234}
235
236
238{
239 if( ev.GetModifiers() == wxMOD_CONTROL && ev.GetKeyCode() == 'V' && m_grid->IsCellEditControlShown() )
240 {
241 wxLogNull doNotLog;
242
243 if( wxTheClipboard->Open() )
244 {
245 if( wxTheClipboard->IsSupported( wxDF_TEXT ) || wxTheClipboard->IsSupported( wxDF_UNICODETEXT ) )
246 {
247 wxTextDataObject data;
248 wxTheClipboard->GetData( data );
249
250 wxString text = data.GetText();
251
252 if( !text.Contains( '\t' ) && text.Contains( ',' ) )
253 text.Replace( ',', '\t' );
254
255 if( text.Contains( '\t' ) || text.Contains( '\n' ) || text.Contains( '\r' ) )
256 {
257 m_grid->CancelPendingChanges();
258 int row = m_grid->GetGridCursorRow();
259
260 // Check if the current row already has data (has a nickname)
261 wxGridTableBase* table = m_grid->GetTable();
262
263 if( table && row >= 0 && row < table->GetNumberRows() )
264 {
265 // Check if the row has a nickname (indicating it has existing data)
266 wxString nickname = table->GetValue( row, COL_NICKNAME );
267
268 if( !nickname.IsEmpty() )
269 {
270 // Row already has data, don't allow pasting over it
271 wxTheClipboard->Close();
272 wxBell(); // Provide audio feedback
273 return;
274 }
275 }
276
277 m_grid->ClearSelection();
278 m_grid->SelectRow( row );
279 m_grid->SetGridCursor( row, 0 );
281 paste_text( text );
282 wxTheClipboard->Close();
283 m_grid->ForceRefresh();
284 return;
285 }
286 }
287
288 wxTheClipboard->Close();
289 }
290 }
291
293}
294
295
296/*
297 * Handle specialized clipboard text, either s-expr syntax starting with a lib table preamble
298 * (such as "(fp_lib_table"), or spreadsheet formatted text.
299 */
300void LIB_TABLE_GRID_TRICKS::paste_text( const wxString& cb_text )
301{
302 LIB_TABLE_GRID_DATA_MODEL* model = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( m_grid->GetTable() );
303
304 if( model->Table().IsReadOnly() )
305 {
306 wxBell();
307 return;
308 }
309
310 if( size_t ndx = cb_text.find( getTablePreamble() ); ndx != std::string::npos )
311 {
312 // paste the LIB_TABLE_ROWs of s-expr, starting at column 0 regardless of current cursor column.
313
314 if( LIBRARY_TABLE tempTable( true, cb_text, model->Table().Scope() ); tempTable.IsOk() )
315 {
316 std::ranges::copy( tempTable.Rows(),
317 std::inserter( model->Table().Rows(), model->Table().Rows().begin() ) );
318
319 if( model->GetView() )
320 {
321 wxGridTableMessage msg( model, wxGRIDTABLE_NOTIFY_ROWS_INSERTED, 0, 0 );
322 model->GetView()->ProcessTableMessage( msg );
323 model->OnModify();
324 }
325 }
326 else
327 {
328 DisplayError( wxGetTopLevelParent( m_grid ), tempTable.ErrorDescription() );
329 }
330 }
331 else
332 {
333 wxString text = cb_text;
334
335 if( !text.Contains( '\t' ) && text.Contains( ',' ) )
336 text.Replace( ',', '\t' );
337
338 if( text.Contains( '\t' ) )
339 {
340 int row = m_grid->GetGridCursorRow();
341 m_grid->ClearSelection();
342 m_grid->SelectRow( row );
343 m_grid->SetGridCursor( row, 0 );
345 }
346
348 model->OnModify();
349
350 m_grid->AutoSizeColumns( false );
351 }
352
353 m_grid->AutoSizeColumns( false );
354}
355
356
358{
359 if( aEvent.GetCol() == COL_OPTIONS )
360 {
361 if( isGridReadOnly( m_grid ) )
362 {
363 wxBell();
364 return true;
365 }
366
367 optionsEditor( aEvent.GetRow() );
368 return true;
369 }
370
371 return false;
372}
373
374
375void LIB_TABLE_GRID_TRICKS::AppendRowHandler( WX_GRID* aGrid, const wxString& aType )
376{
377 if( isGridReadOnly( aGrid ) )
378 {
379 wxBell();
380 return;
381 }
382
383 aGrid->OnAddRow(
384 [&]() -> std::pair<int, int>
385 {
386 LIB_TABLE_GRID_DATA_MODEL* model = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( aGrid->GetTable() );
387
388 aGrid->AppendRows( 1 );
389 aGrid->SetCellValue( aGrid->GetNumberRows() - 1, COL_TYPE, aType );
390 model->OnModify();
391 return { aGrid->GetNumberRows() - 1, COL_NICKNAME };
392 } );
393}
394
395
397{
398 if( isGridReadOnly( aGrid ) )
399 {
400 wxBell();
401 return;
402 }
403
404 if( !aGrid->CommitPendingChanges() )
405 return;
406
407 wxGridUpdateLocker noUpdates( aGrid );
408
409 int curRow = aGrid->GetGridCursorRow();
410 int curCol = aGrid->GetGridCursorCol();
411
412 // In a wxGrid, collect rows that have a selected cell, or are selected
413 // It is not so easy: it depends on the way the selection was made.
414 // Here, we collect rows selected by clicking on a row label, and rows that contain
415 // previously-selected cells.
416 // If no candidate, just delete the row with the grid cursor.
417 wxArrayInt selectedRows = aGrid->GetSelectedRows();
418 wxGridCellCoordsArray cells = aGrid->GetSelectedCells();
419 wxGridCellCoordsArray blockTopLeft = aGrid->GetSelectionBlockTopLeft();
420 wxGridCellCoordsArray blockBotRight = aGrid->GetSelectionBlockBottomRight();
421
422 // Add all row having cell selected to list:
423 for( unsigned ii = 0; ii < cells.GetCount(); ii++ )
424 selectedRows.Add( cells[ii].GetRow() );
425
426 // Handle block selection
427 if( !blockTopLeft.IsEmpty() && !blockBotRight.IsEmpty() )
428 {
429 for( int i = blockTopLeft[0].GetRow(); i <= blockBotRight[0].GetRow(); ++i )
430 selectedRows.Add( i );
431 }
432
433 // Use the row having the grid cursor only if we have no candidate:
434 if( selectedRows.size() == 0 && aGrid->GetGridCursorRow() >= 0 )
435 selectedRows.Add( aGrid->GetGridCursorRow() );
436
437 if( selectedRows.size() == 0 )
438 {
439 wxBell();
440 return;
441 }
442
443 std::sort( selectedRows.begin(), selectedRows.end() );
444
445 // Remove selected rows (note: a row can be stored more than once in list)
446 int last_row = -1;
447
448 // Needed to avoid a wxWidgets alert if the row to delete is the last row
449 // at least on wxMSW 3.2
450 aGrid->ClearSelection();
451
452 for( int ii = selectedRows.GetCount()-1; ii >= 0; ii-- )
453 {
454 int row = selectedRows[ii];
455
456 if( row != last_row )
457 {
458 last_row = row;
459 aGrid->DeleteRows( row, 1 );
460 static_cast<LIB_TABLE_GRID_DATA_MODEL*>( aGrid->GetTable() )->OnModify();
461 }
462 }
463
464 if( aGrid->GetNumberRows() > 0 && curRow >= 0 )
465 aGrid->SetGridCursor( std::min( curRow, aGrid->GetNumberRows() - 1 ), curCol );
466}
467
468
470{
471 if( isGridReadOnly( aGrid ) )
472 {
473 wxBell();
474 return;
475 }
476
477 aGrid->OnMoveRowUp(
478 [&]( int row )
479 {
480 LIB_TABLE_GRID_DATA_MODEL* model = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( aGrid->GetTable() );
481 int curRow = aGrid->GetGridCursorRow();
482 std::deque<LIBRARY_TABLE_ROW>& rows = model->Table().Rows();
483
484 auto current = rows.begin() + curRow;
485 auto prev = rows.begin() + curRow - 1;
486
487 std::iter_swap( current, prev );
488
489 // Update the wxGrid
490 wxGridTableMessage msg( model, wxGRIDTABLE_NOTIFY_ROWS_INSERTED, row - 1, 0 );
491 model->GetView()->ProcessTableMessage( msg );
492 model->OnModify();
493 } );
494}
495
496
498{
499 if( isGridReadOnly( aGrid ) )
500 {
501 wxBell();
502 return;
503 }
504
505 aGrid->OnMoveRowDown(
506 [&]( int row )
507 {
508 LIB_TABLE_GRID_DATA_MODEL* model = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( aGrid->GetTable() );
509 int curRow = aGrid->GetGridCursorRow();
510 std::deque<LIBRARY_TABLE_ROW>& rows = model->Table().Rows();
511
512 auto current = rows.begin() + curRow;
513 auto next = rows.begin() + curRow + 1;
514
515 std::iter_swap( current, next );
516
517 // Update the wxGrid
518 wxGridTableMessage msg( model, wxGRIDTABLE_NOTIFY_ROWS_INSERTED, row, 0 );
519 model->GetView()->ProcessTableMessage( msg );
520 model->OnModify();
521 } );
522}
523
524
525bool LIB_TABLE_GRID_TRICKS::VerifyTable( WX_GRID* aGrid, bool aSupportsVisibilityColumn,
526 std::function<void( int aRow, int aCol )> aErrorHandler )
527{
528 wxWindow* topLevelParent = wxGetTopLevelParent( aGrid );
529 LIB_TABLE_GRID_DATA_MODEL* model = static_cast<LIB_TABLE_GRID_DATA_MODEL*>( aGrid->GetTable() );
530 wxString msg;
531
532 for( int r = 0; r < model->GetNumberRows(); )
533 {
534 wxString nick = model->GetValue( r, COL_NICKNAME ).Trim( false ).Trim();
535 wxString uri = model->GetValue( r, COL_URI ).Trim( false ).Trim();
536 unsigned illegalCh = 0;
537
538 if( !uri )
539 {
540 // Silently nuke rows that have no libraray URI
541 model->DeleteRows( r, 1 );
542 }
543 else if( !nick || ( illegalCh = LIB_ID::FindIllegalLibraryNameChar( nick ) ) )
544 {
545 if( !nick )
546 msg = _( "Library must have a nickname." );
547 else
548 msg = wxString::Format( _( "Illegal character '%c' in nickname '%s'." ), illegalCh, nick );
549
550 aErrorHandler( r, COL_NICKNAME );
551
552 KICAD_MESSAGE_DIALOG errdlg( topLevelParent, msg, _( "Library Nickname Error" ) );
553 errdlg.ShowModal();
554 return false;
555 }
556 else
557 {
558 // set the trimmed values back into the table so they get saved to disk.
559 model->SetValue( r, COL_NICKNAME, nick );
560 model->SetValue( r, COL_URI, uri );
561
562 if( !aSupportsVisibilityColumn )
563 {
564 // Make sure to not save an inappropriate hidden flag
565 model->SetValue( r, COL_VISIBLE, wxS( "1" ) );
566 }
567
568 ++r; // this row was OK.
569 }
570 }
571
572 // check for duplicate nickNames
573 for( int r1 = 0; r1 < model->GetNumberRows() - 1; ++r1 )
574 {
575 wxString nick1 = model->GetValue( r1, COL_NICKNAME );
576
577 for( int r2 = r1 + 1; r2 < model->GetNumberRows(); ++r2 )
578 {
579 wxString nick2 = model->GetValue( r2, COL_NICKNAME );
580
581 if( nick1 == nick2 )
582 {
583 msg = wxString::Format( _( "Multiple libraries cannot share the same nickname ('%s')." ), nick1 );
584
585 // go to the lower of the two rows, it is technically the duplicate:
586 aErrorHandler( r2, 1 );
587
588 KICAD_MESSAGE_DIALOG errdlg( topLevelParent, msg, _( "Library Nickname Error" ) );
589 errdlg.ShowModal();
590 return false;
591 }
592 }
593 }
594
595 return true;
596}
virtual void paste_text(const wxString &cb_text)
void getSelectedArea()
Puts the selected area into a sensible rectangle of m_sel_{row,col}_{start,count} above.
GRID_TRICKS(WX_GRID *aGrid)
virtual void doPopupSelection(wxCommandEvent &event)
virtual void showPopupMenu(wxMenu &menu, wxGridEvent &aEvent)
int m_sel_row_start
WX_GRID * m_grid
I don't own the grid, but he owns me.
int m_sel_row_count
virtual void onGridCellLeftClick(wxGridEvent &event)
virtual void onCharHook(wxKeyEvent &event)
The interface used by the classes that actually can load IO plugins for the different parts of KiCad ...
virtual std::optional< LIBRARY_ERROR > LibraryError(const wxString &aNickname) const
virtual bool SupportsConfigurationDialog(const LIBRARY_TABLE_ROW &aRow) const
Configuration works from the row itself, so libraries that failed to load or are not yet committed to...
virtual int ShowConfigurationDialog(const LIBRARY_TABLE_ROW &aRow, LIBRARY_TABLE_SCOPE aScope, wxWindow *aParent)
Shows the plugin's configuration dialog for a library table row.
const wxString & ErrorDescription() const
const wxString & Type() const
static const wxString TABLE_TYPE_NAME
bool IsOk() const
const wxString & Nickname() const
bool IsOk() const
static unsigned FindIllegalLibraryNameChar(const UTF8 &aLibraryName)
Looks for characters that are illegal in library nicknames.
Definition lib_id.cpp:228
This abstract base class mixes any object derived from LIBRARY_TABLE into wxGridTableBase so the resu...
void onGridCellLeftClick(wxGridEvent &aEvent) override
virtual void openTable(const LIBRARY_TABLE_ROW &aRow)=0
virtual wxString getTablePreamble()=0
static void MoveUpHandler(WX_GRID *aGrid)
virtual bool supportsVisibilityColumn()=0
void paste_text(const wxString &cb_text) override
bool handleDoubleClick(wxGridEvent &aEvent) override
LIB_TABLE_GRID_TRICKS(WX_GRID *aGrid)
static void DeleteRowHandler(WX_GRID *aGrid)
virtual void optionsEditor(int aRow)=0
static void AppendRowHandler(WX_GRID *aGrid, const wxString &aType)
void doPopupSelection(wxCommandEvent &event) override
static bool VerifyTable(WX_GRID *aGrid, bool aSupportsVisibilityColumn, std::function< void(int aRow, int aCol)> aErrorHandler)
static void MoveDownHandler(WX_GRID *aGrid)
void onCharHook(wxKeyEvent &ev) override
void showPopupMenu(wxMenu &menu, wxGridEvent &aEvent) override
void OnMoveRowUp(const std::function< void(int row)> &aMover)
Definition wx_grid.cpp:957
void OnMoveRowDown(const std::function< void(int row)> &aMover)
Definition wx_grid.cpp:990
void OnAddRow(const std::function< std::pair< int, int >()> &aAdder)
Definition wx_grid.cpp:857
bool CommitPendingChanges(bool aQuietMode=false)
Close any open cell edit controls.
Definition wx_grid.cpp:805
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 KICAD_MESSAGE_DIALOG
Definition confirm.h:48
#define _(s)
static bool isGridReadOnly(WX_GRID *aGrid)
CITER next(CITER it)
Definition ptree.cpp:120
const std::string table
std::vector< DATABASE_CONNECTION::ROW > rows
KIBIS_MODEL * model