KiCad PCB EDA Suite
Loading...
Searching...
No Matches
match_properties_tool.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
22#include <board.h>
23#include <board_commit.h>
24#include <collectors.h>
25#include <dialog_shim.h>
26#include <pgm_base.h>
27#include <pcb_generated_table.h>
28#include <pcbnew_settings.h>
32#include <tool/tool_manager.h>
33#include <kiplatform/ui.h>
35#include <status_popup.h>
36#include <tools/hover_picker.h>
38#include <tools/pcb_actions.h>
41#include <view/view_controls.h>
42
43#include <algorithm>
44
45#include <wx/checklst.h>
46#include <wx/clntdata.h>
47#include <wx/dialog.h>
48#include <wx/menu.h>
49#include <wx/sizer.h>
50#include <wx/stattext.h>
51
52
56{
57public:
58 MATCH_PROPERTIES_DIALOG( wxWindow* aParent, std::set<wxString>& aEnabled, const wxString& aFamily ) :
59 DIALOG_SHIM( aParent, wxID_ANY, _( "Match Properties Settings" ), wxDefaultPosition, wxDefaultSize,
60 wxDEFAULT_DIALOG_STYLE | wxRESIZE_BORDER ),
61 m_enabled( aEnabled )
62 {
63 wxBoxSizer* sizer = new wxBoxSizer( wxVERTICAL );
64
65 sizer->Add( new wxStaticText( this, wxID_ANY,
66 wxString::Format( _( "Properties copied from %s:" ),
68 0, wxALL, 10 );
69
70 m_properties = new wxCheckListBox( this, wxID_ANY );
71 m_properties->SetMinSize( FromDIP( wxSize( 380, 320 ) ) );
72
73 std::vector<std::pair<wxString, wxString>> rows;
74
75 for( const wxString& key : MATCH_PROPERTIES_CATALOG::AllSafeKeys() )
76 {
77 if( MATCH_PROPERTIES_CATALOG::FamiliesFor( key ).contains( aFamily ) )
78 rows.emplace_back( MATCH_PROPERTIES_CATALOG::PropertyLabel( key ), key );
79 }
80
81 std::ranges::sort( rows );
82
83 for( const auto& [label, key] : rows )
84 {
85 const unsigned int index = m_properties->Append( label, new wxStringClientData( key ) );
86
87 m_properties->Check( index, m_enabled.contains( key ) );
88 }
89
90 sizer->Add( m_properties, 1, wxEXPAND | wxLEFT | wxRIGHT, 10 );
91 sizer->Add( CreateStdDialogButtonSizer( wxOK | wxCANCEL ), 0, wxEXPAND | wxALL, 10 );
92 SetSizer( sizer );
93
94 m_properties->Bind( wxEVT_CONTEXT_MENU, &MATCH_PROPERTIES_DIALOG::onContextMenu, this );
95
98 }
99
101 {
102 // Only the rows on screen are answered for. Another kind's properties were never shown,
103 // so clearing the set wholesale would silently turn them all off.
104 for( unsigned int ii = 0; ii < m_properties->GetCount(); ++ii )
105 {
106 const wxString key = keyAt( ii );
107
108 if( m_properties->IsChecked( ii ) )
109 m_enabled.insert( key );
110 else
111 m_enabled.erase( key );
112 }
113
114 return true;
115 }
116
117private:
118 wxString keyAt( unsigned int aIndex ) const
119 {
120 auto* data = static_cast<wxStringClientData*>( m_properties->GetClientObject( aIndex ) );
121
122 return data ? data->GetData() : wxString();
123 }
124
125 void checkAll( bool aChecked )
126 {
127 for( unsigned int ii = 0; ii < m_properties->GetCount(); ++ii )
128 m_properties->Check( ii, aChecked );
129 }
130
131 void onContextMenu( wxContextMenuEvent& aEvent )
132 {
133 wxMenu menu;
134
135 enum
136 {
137 ID_CHECK_ALL = wxID_HIGHEST + 1,
138 ID_UNCHECK_ALL
139 };
140
141 menu.Append( ID_CHECK_ALL, _( "Check All" ) );
142 menu.Append( ID_UNCHECK_ALL, _( "Uncheck All" ) );
143
144 switch( GetPopupMenuSelectionFromUser( menu ) )
145 {
146 case ID_CHECK_ALL: checkAll( true ); break;
147 case ID_UNCHECK_ALL: checkAll( false ); break;
148 default: break;
149 }
150 }
151
152 wxCheckListBox* m_properties;
153 std::set<wxString>& m_enabled;
154};
155
156
158static bool hasMatchableSource( const SELECTION& aSelection )
159{
160 if( aSelection.Size() != 1 )
161 return false;
162
163 return !MATCH_PROPERTIES_CATALOG::Family( *aSelection.Front() ).IsEmpty();
164}
165
166
168 PCB_TOOL_BASE( "pcbnew.MatchProperties" )
169{
170}
171
172
174{
176
177 // Settings live in the Edit menu only, like every other tool.
178 CONDITIONAL_MENU& menu = m_selectionTool->GetToolMenu().GetMenu();
179
181
182 return true;
183}
184
185
186const std::set<wxString>& MATCH_PROPERTIES_TOOL::enabledKeys()
187{
188 PCB_VIEWERS_SETTINGS_BASE* settings = frame()->GetViewerSettingsBase();
189
190 return settings ? settings->m_MatchProperties : MATCH_PROPERTIES_CATALOG::DefaultKeys();
191}
192
193
194bool MATCH_PROPERTIES_TOOL::applyToTargets( const EDA_ITEM& aSource, const std::vector<EDA_ITEM*>& aTargets )
195{
196 if( aTargets.empty() )
197 return false;
198
199 const std::set<wxString>& enabled = enabledKeys();
200 BOARD_COMMIT commit( this );
201 PROPERTY_COMMIT_HANDLER handler( &commit );
202 wxString error;
203 int changed = 0;
204
205 // CompatibleTargets() already reduced this to board items of the source family.
206 for( EDA_ITEM* target : aTargets )
207 {
208 wxCHECK2( target->IsBOARD_ITEM(), continue );
209
210 commit.Modify( static_cast<BOARD_ITEM*>( target ) );
211
212 // Copy() stages on a clone and writes only if every value validates. A refusal leaves
213 // this target untouched. Revert() undoes the earlier ones.
215
216 if( !result )
217 {
218 error = result.m_Error;
219 break;
220 }
221
222 changed += result.m_Changed;
223
224 // A generated table is laid out from its cells' formatting, so relayout what was copied
225 if( BOARD* board = static_cast<BOARD_ITEM*>( target )->GetBoard(); result.m_Changed && board )
226 {
227 if( IsGeneratedTableType( target->Type() ) )
228 static_cast<PCB_GENERATED_TABLE*>( target )->RebuildCells( *board );
229 else if( IsGeneratedTableCell( target ) )
230 static_cast<PCB_GENERATED_TABLE*>( target->GetParent() )->RebuildCells( *board );
231 }
232 }
233
234 if( !error.IsEmpty() )
235 frame()->ShowInfoBarError( error );
236 else if( changed == 0 )
237 frame()->ShowInfoBarMsg( _( "Nothing to copy. The target already matches the source." ) );
238
239 if( !error.IsEmpty() || changed == 0 )
240 {
241 commit.Revert();
242 return false;
243 }
244
245 commit.Push( _( "Match Properties" ) );
246 return true;
247}
248
249
251{
252 PCB_SELECTION& selection = m_selectionTool->GetSelection();
253
254 // The tool copies from one item to many, so the one it copies from has to be settled before
255 // it starts. The context menu says the same, but the hotkey can arrive any time.
256 if( selection.Size() != 1 )
257 {
258 frame()->ShowInfoBarError( _( "Select one item to copy properties from." ) );
259 return 0;
260 }
261
262 EDA_ITEM* source = selection.Front();
263
264 if( MATCH_PROPERTIES_CATALOG::Family( *source ).IsEmpty() )
265 {
266 frame()->ShowInfoBarError( _( "The selected source item has no properties to match." ) );
267 return 0;
268 }
269
270 // Not a reason to refuse. The settings only open from inside the tool, so there would
271 // be no way left to turn anything on.
273 {
274 frame()->ShowInfoBarMsg( _( "No properties are enabled for this kind of item. Press <ctrl>+<,> to "
275 "choose some." ) );
276 }
277
278 return runInteractive( aEvent, source->m_Uuid );
279}
280
281
282int MATCH_PROPERTIES_TOOL::runInteractive( const TOOL_EVENT& aEvent, const KIID& aSourceId )
283{
284 BOARD* board = frame()->GetBoard();
285 PCB_PICKER_TOOL* picker = m_toolMgr->GetTool<PCB_PICKER_TOOL>();
286 HOVER_PICKER hover( m_toolMgr );
287 STATUS_TEXT_POPUP statusPopup( frame() );
288 const KIID sourceId = aSourceId;
289 bool done = false;
290
291 // Settled before the run started, so it can only go missing under a commit or an undo.
292 auto currentSource = [&]() -> BOARD_ITEM*
293 {
294 return board->ResolveItem( sourceId, true );
295 };
296
297 // How much of the enabled set this kind of source can actually offer. Saying the number
298 // beats making the user open the dialog to find out nothing is turned on.
299 auto enabledCount = [&]( const EDA_ITEM& aItem )
300 {
301 const wxString family = MATCH_PROPERTIES_CATALOG::Family( aItem );
302 int count = 0;
303
304 for( const wxString& key : enabledKeys() )
305 {
306 if( MATCH_PROPERTIES_CATALOG::FamiliesFor( key ).contains( family ) )
307 count++;
308 }
309
310 return count;
311 };
312
313 auto prompt = [&]()
314 {
315 if( BOARD_ITEM* source = currentSource() )
316 {
317 statusPopup.SetText( wxString::Format( _( "Click or drag over the items to copy to.\n"
318 "%d properties enabled; <ctrl>+<,> for settings." ),
319 enabledCount( *source ) ) );
320 }
321 };
322
324 auto accepts = [&]( BOARD_ITEM* aSource )
325 {
326 return [aSource]( BOARD_ITEM& aItem )
327 {
328 return &aItem != aSource && MATCH_PROPERTIES_CATALOG::Compatible( *aSource, aItem );
329 };
330 };
331
332 // The source keeps a mark of its own for the whole run. Without it there is nothing on
333 // screen saying what the properties are being copied from.
334 auto updateHover = [&]( const VECTOR2I& aPointer )
335 {
336 BOARD_ITEM* source = currentSource();
337
338 hover.ClearBrightening();
339 statusPopup.Move( KIPLATFORM::UI::GetMousePosition() + wxPoint( 20, 20 ) );
340
341 // An undo can take the source out from under the run. Nothing is a target without one
342 // to compare against.
343 if( !source )
344 return;
345
346 hover.Brighten( source );
347
348 if( BOARD_ITEM* target = hover.Pick( aPointer, accepts( source ) ) )
349 hover.Brighten( target );
350 };
351
352 Activate();
353
354 // The selection tool arms its disambiguation on button-down unless a tool owns the stack.
355 // Without this the applying click also selects, which cancels the picker.
356 frame()->PushTool( aEvent );
357
358 m_selectionTool->ClearSelection();
359 prompt();
360 statusPopup.Popup();
361 statusPopup.Move( KIPLATFORM::UI::GetMousePosition() + wxPoint( 20, 20 ) );
362 canvas()->SetStatusPopup( statusPopup.GetPanel() );
363
364 picker->SetCursor( KICURSOR::BULLSEYE );
365
366 // Snapping on is what makes the picker honour the modifiers that turn it off again, so
367 // <shift> and <ctrl> give a finer aim among crowded items.
368 picker->SetSnapping( true );
369
370 // The pointer only names an item, so the lines the snap system draws are just noise.
371 picker->SetConstructionGeometry( false );
372 picker->ClearHandlers();
373 picker->SetMotionHandler(
374 [&]( const VECTOR2D& aPointer )
375 {
376 updateHover( aPointer );
377 } );
378 picker->SetClickHandler(
379 [&]( const VECTOR2D& aPointer ) -> bool
380 {
381 BOARD_ITEM* source = currentSource();
382
383 if( !source )
384 {
385 frame()->ShowInfoBarError( _( "The Match Properties source no longer exists." ) );
386 return false;
387 }
388
389 // The click takes what the hover lit, so what was shown is what is changed.
390 BOARD_ITEM* target = hover.Pick( aPointer, accepts( source ) );
391
392 if( !target )
393 return true;
394
395 // The commit may replace either item, so let go of every highlight first.
396 hover.ClearBrightening();
398 updateHover( aPointer );
399 return true;
400 } );
401
402 // Light the items the box has caught so far, so a drag shows its reach as it grows.
403 picker->SetAreaPreviewHandler(
405 {
406 BOARD_ITEM* source = currentSource();
407
408 if( !source )
409 return;
410
411 std::vector<BOARD_ITEM*> lit{ source };
412
413 for( BOARD_ITEM* item : m_selectionTool->CollectMultiple( aArea ) )
414 {
415 if( item != source && MATCH_PROPERTIES_CATALOG::Compatible( *source, *item ) )
416 lit.push_back( item );
417 }
418
419 // The box grows by a little on every motion event, so most of this set was
420 // already lit a moment ago.
421 hover.BrightenOnly( lit );
422 } );
423 picker->SetAreaHandler(
424 [&]() -> bool
425 {
426 BOARD_ITEM* source = currentSource();
427
428 if( !source )
429 return false;
430
431 const PCB_SELECTION& selected = m_selectionTool->GetSelection();
432 std::vector<EDA_ITEM*> candidates( selected.begin(), selected.end() );
433
434 hover.ClearBrightening();
436 m_selectionTool->ClearSelection();
437 return true;
438 } );
439 picker->SetCancelHandler(
440 [&]()
441 {
442 hover.ClearBrightening();
443 } );
444 picker->SetFinalizeHandler(
445 [&]( const int& )
446 {
447 hover.ClearBrightening();
448 done = true;
449 } );
450 m_toolMgr->RunAction( ACTIONS::pickerSubTool );
451
452 while( !done )
453 {
454 TOOL_EVENT* event = Wait();
455
456 if( !event )
457 break;
458
459 // Handled here rather than passed on. The tool is already inside this coroutine,
460 // and letting the action dispatch to it would tear the picker down.
461 if( event->IsAction( &PCB_ACTIONS::matchPropertiesSettings ) )
462 {
463 if( BOARD_ITEM* source = currentSource() )
465
466 prompt();
467
468 // The enabled set decides what a click would copy, so the mark under the pointer
469 // may mean something different now.
470 updateHover( getViewControls()->GetMousePosition() );
471 continue;
472 }
473
474 event->SetPassEvent();
475 }
476
477 picker->ClearHandlers();
478 hover.ClearBrightening();
479 statusPopup.Hide();
480 canvas()->SetStatusPopup( nullptr );
482
483 if( EDA_ITEM* remaining = board->ResolveItem( sourceId, true ) )
484 m_selectionTool->AddItemToSel( remaining, true );
485
486 frame()->PopTool( aEvent );
487 return 0;
488}
489
490
492{
493 PCB_VIEWERS_SETTINGS_BASE* settings = frame()->GetViewerSettingsBase();
494
495 if( !settings )
496 return;
497
498 std::set<wxString> enabled = settings->m_MatchProperties;
499 MATCH_PROPERTIES_DIALOG dialog( frame(), enabled, MATCH_PROPERTIES_CATALOG::Family( aSource ) );
500
501 if( dialog.ShowModal() == wxID_OK )
502 {
503 settings->m_MatchProperties = std::move( enabled );
504 Pgm().GetSettingsManager().Save( settings );
505 }
506}
507
508
int index
static TOOL_ACTION pickerSubTool
Definition actions.h:251
static TOOL_ACTION selectionClear
Clear the current selection.
Definition actions.h:221
void Push(const wxString &aMessage=wxEmptyString, int aCommitFlags=0) override
Execute the changes.
void Revert() override
Revert the commit by restoring the modified items state.
A base class for any item which can be embedded within the BOARD container class, and therefore insta...
Definition board_item.h:99
Information pertinent to a Pcbnew printed circuit board.
Definition board.h:411
COMMIT & Modify(EDA_ITEM *aItem, BASE_SCREEN *aScreen=nullptr, RECURSE_MODE aRecurse=RECURSE_MODE::NO_RECURSE)
Modify a given item in the model.
Definition commit.h:102
void SetupStandardButtons(std::map< int, wxString > aLabels={})
void finishDialogSettings()
In all dialogs, we must call the same functions to fix minimal dlg size, the default position and per...
DIALOG_SHIM(wxWindow *aParent, wxWindowID id, const wxString &title, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxDefaultSize, long style=wxDEFAULT_FRAME_STYLE|wxRESIZE_BORDER, const wxString &name=wxDialogNameStr)
int ShowModal() override
void SetStatusPopup(wxWindow *aPopup)
A base class for most all the KiCad significant classes used in schematics and boards.
Definition eda_item.h:98
The board item under the pointer, and the highlight that follows it.
Represent a selection area (currently a rectangle) in a VIEW, drawn corner-to-corner between two poin...
Definition kiid.h:46
The properties this kind of source can offer.
std::set< wxString > & m_enabled
MATCH_PROPERTIES_DIALOG(wxWindow *aParent, std::set< wxString > &aEnabled, const wxString &aFamily)
wxString keyAt(unsigned int aIndex) const
void onContextMenu(wxContextMenuEvent &aEvent)
void showSettingsDialog(const EDA_ITEM &aSource)
Only the running tool opens this, and only for the source it is copying from.
bool Init() override
Init() is called once upon a registration of the tool.
int Match(const TOOL_EVENT &aEvent)
void setTransitions() override
This method is meant to be overridden in order to specify handlers for events.
PCB_SELECTION_TOOL * m_selectionTool
bool applyToTargets(const EDA_ITEM &aSource, const std::vector< EDA_ITEM * > &aTargets)
int runInteractive(const TOOL_EVENT &aEvent, const KIID &aSourceId)
The picker session. aSourceId is niluuid when the first click still has to name it.
const std::set< wxString > & enabledKeys()
static TOOL_ACTION matchPropertiesSettings
static TOOL_ACTION matchProperties
A table whose cell text is derived from the board and rebuilt whenever it goes stale.
void RebuildCells(const BOARD &aBoard, GENERATED_TABLE_REFRESH *aRefresh=nullptr)
Regenerate the cells from the board.
Generic tool for picking an item.
void SetAreaPreviewHandler(PCB_SELECTION_TOOL::AREA_PREVIEW aHandler)
Set a handler called with the drag box each time it changes, before anything is selected.
void SetConstructionGeometry(bool aEnable)
Whether the snap system may draw its explanatory geometry over the board this run.
void ClearHandlers()
Handlers only.
The selection tool: currently supports:
T * frame() const
PCB_TOOL_BASE(TOOL_ID aId, const std::string &aName)
Constructor.
BOARD * board() const
PCB_DRAW_PANEL_GAL * canvas() const
const PCB_SELECTION & selection() const
std::set< wxString > m_MatchProperties
Keyed as "family/Property Name"; see MATCH_PROPERTIES_CATALOG.
virtual SETTINGS_MANAGER & GetSettingsManager() const
Definition pgm_base.h:124
void SetAreaHandler(AREA_HANDLER aHandler)
Set a handler for a rubber-band drag.
void SetMotionHandler(MOTION_HANDLER aHandler)
Set a handler for mouse motion.
Definition picker_tool.h:92
void SetClickHandler(CLICK_HANDLER aHandler)
Set a handler for mouse click event.
Definition picker_tool.h:81
void SetSnapping(bool aSnap)
Definition picker_tool.h:65
void SetCursor(KICURSOR aCursor)
Definition picker_tool.h:63
void SetCancelHandler(CANCEL_HANDLER aHandler)
Set a handler for cancel events (ESC or context-menu Cancel).
void SetFinalizeHandler(FINALIZE_HANDLER aHandler)
Set a handler for the finalize event.
ITER end()
Definition selection.h:76
ITER begin()
Definition selection.h:75
EDA_ITEM * Front() const
Definition selection.h:176
int Size() const
Returns the number of selected parts.
Definition selection.h:120
wxWindow * GetPanel()
virtual void Popup(wxWindow *aFocus=nullptr)
virtual void Move(const wxPoint &aWhere)
Extension of STATUS_POPUP for displaying a single line text.
void SetText(const wxString &aText)
Display a text.
KIGFX::VIEW_CONTROLS * getViewControls() const
Return the instance of VIEW_CONTROLS object used in the application.
Definition tool_base.cpp:40
TOOL_MANAGER * m_toolMgr
Definition tool_base.h:220
Generic, UI-independent tool event.
Definition tool_event.h:167
void Go(int(T::*aStateFunc)(const TOOL_EVENT &), const TOOL_EVENT_LIST &aConditions=TOOL_EVENT(TC_ANY, TA_ANY))
Define which state (aStateFunc) to go when a certain event arrives (aConditions).
TOOL_EVENT * Wait(const TOOL_EVENT_LIST &aEventList=TOOL_EVENT(TC_ANY, TA_ANY))
Suspend execution of the tool until an event specified in aEventList arrives.
void Activate()
Run the tool.
@ BULLSEYE
Definition cursors.h:55
#define _(s)
std::string source
static bool hasMatchableSource(const SELECTION &aSelection)
One item, and one the catalog can read. With several there is no saying which one leads.
wxPoint GetMousePosition()
Returns the mouse position in screen coordinates.
MATCH_PROPERTIES_RESULT Copy(const EDA_ITEM &aSource, EDA_ITEM &aTarget, const std::set< wxString > &aEnabledKeys)
bool Compatible(const EDA_ITEM &aSource, const EDA_ITEM &aTarget)
const std::set< wxString > & AllSafeKeys()
Every property Match Properties may copy, keyed as "family/Property Name".
wxString PropertyLabel(const wxString &aKey)
The translated property name alone, without the family it belongs to.
const std::set< wxString > & DefaultKeys()
The subset enabled until the user says otherwise.
bool AnyEnabledFor(const EDA_ITEM &aItem, const std::set< wxString > &aEnabledKeys)
True if any enabled key names a property of this item's family.
std::vector< EDA_ITEM * > CompatibleTargets(const EDA_ITEM &aSource, const std::vector< EDA_ITEM * > &aCandidates)
wxString FamilyLabel(const wxString &aFamily)
The translated name of a family, for the heading of its group.
std::set< wxString > FamiliesFor(const wxString &aKey)
The families a key reaches. One for a family key, several for a common one.
wxString Family(const EDA_ITEM &aItem)
bool IsGeneratedTableCell(const EDA_ITEM *aItem)
True for a cell whose text is generated from the board, so only its formatting is the user's.
Definition pcb_table.h:355
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
std::vector< DATABASE_CONNECTION::ROW > rows
static std::vector< int > candidates(const SEGMENT_INDEX &aIndex, const SEG &aQuery, int aPadding)
wxString result
Test unit parsing edge cases and error handling.
constexpr bool IsGeneratedTableType(const KICAD_T aType)
A PCB_TABLE subclass whose cells are generated from the board rather than typed by the user.
Definition typeinfo.h:328
VECTOR2< int32_t > VECTOR2I
Definition vector2d.h:708
VECTOR2< double > VECTOR2D
Definition vector2d.h:707