KiCad PCB EDA Suite
Loading...
Searching...
No Matches
dialog_kicad_merge_3way.cpp
Go to the documentation of this file.
1/*
2 * This program source code file is part of KiCad, a free EDA CAD application.
3 *
4 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
5 *
6 * This program is free software; you can redistribute it and/or
7 * modify it under the terms of the GNU General Public License
8 * as published by the Free Software Foundation; either version 3
9 * of the License, or (at your option) any later version.
10 *
11 * This program is distributed in the hope that it will be useful,
12 * but WITHOUT ANY WARRANTY; without even the implied warranty of
13 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
14 * GNU General Public License for more details.
15 *
16 * You should have received a copy of the GNU General Public License
17 * along with this program; if not, you may find one here:
18 * http://www.gnu.org/licenses/gpl-3.0.html
19 * or you may search the http://www.gnu.org website for the version 3 license,
20 * or you may write to the Free Software Foundation, Inc.,
21 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
22 */
23
25
28#include <pgm_base.h>
29#include <reporter.h>
30#include <trace_helpers.h>
32
33#include <wx/ffile.h>
34#include <wx/log.h>
35#include <wx/msgdlg.h>
36#include <wx/sizer.h>
37#include <wx/utils.h>
38
39
40namespace
41{
42
46const KIGFX::COLOR4D& highlightColor()
47{
48 static const KICAD_DIFF::DIFF_COLOR_THEME theme;
49 return theme.conflict;
50}
51
52
57enum class AUTO_MODE
58{
59 NOT_SET, // KICAD_MERGETOOL_AUTO env var absent — use the dialog
60 LOADED, // env set, file valid, aOut populated
61 LOAD_FAILED // env set but file missing / unparseable / malformed
62};
63
64
68AUTO_MODE loadAutoResolutionFile( std::map<wxString, KICAD_DIFF::ITEM_RES>& aOut )
69{
70 wxString path;
71
72 if( !wxGetEnv( wxT( "KICAD_MERGETOOL_AUTO" ), &path ) || path.IsEmpty() )
73 return AUTO_MODE::NOT_SET;
74
75 wxFFile file( path, wxT( "rb" ) );
76 wxString contents;
77
78 if( !file.IsOpened() || !file.ReadAll( &contents, wxConvUTF8 ) )
79 {
80 wxLogTrace( traceDiffMerge,
81 wxT( "KICAD_MERGETOOL_AUTO points at unreadable path '%s'" ), path );
82 return AUTO_MODE::LOAD_FAILED;
83 }
84
87 std::string( contents.utf8_str().data(), contents.utf8_str().length() ) );
88
90 {
91 wxLogTrace( traceDiffMerge,
92 wxT( "KICAD_MERGETOOL_AUTO parse failed (status=%d, context=%s)" ),
93 static_cast<int>( parsed.status ), parsed.errorContext );
94 return AUTO_MODE::LOAD_FAILED;
95 }
96
97 aOut = std::move( parsed.resolutions );
98 return AUTO_MODE::LOADED;
99}
100
101} // namespace
102
103
105DIALOG_KICAD_MERGE_3WAY::LibraryContext( const std::set<wxString>& aNames, LIBRARY_ITEM_DRAWER aDraw )
106{
107 std::map<KIID_PATH, wxString> names;
108
109 for( const wxString& name : aNames )
110 names.emplace( KICAD_DIFF::LibraryItemKiidPath( name ), name );
111
112 auto nameOf = [names = std::move( names )]( const KIID_PATH& aId ) -> wxString
113 {
114 auto it = names.find( aId );
115 return it != names.end() ? it->second : wxString();
116 };
117
119
120 ctx.describeItem = nameOf;
121 ctx.drawSide = [nameOf, draw = std::move( aDraw )]( WIDGET_DIFF_CANVAS& aCanvas, SIDE aSide,
122 const std::optional<KIID_PATH>& aId )
123 {
124 draw( aCanvas, aSide, aId ? nameOf( *aId ) : wxString() );
125 };
126
127 return ctx;
128}
129
130
132{
133 if( Pgm().IsGUI() )
134 return true;
135
136 aReporter.Report( _( "--interactive requires a GUI KiCad process; the console "
137 "kicad-cli cannot open dialogs.\n" ),
139 return false;
140}
141
142
144 const KICAD_DIFF::MERGE_PLAN& aPlan,
145 CONFLICT_CONTEXT aContext ) :
147 m_plan( aPlan ),
148 m_context( std::move( aContext ) )
149{
150 // Choices belong to this merge, so do not restore them from another dialog.
151 OptOut( this );
152
153 // Splice a GAL-backed conflict viewer into the resolution panel's sizer
154 // when one is present. The original .fbp emits a text-only layout; we
155 // augment it programmatically here rather than re-authoring the .fbp.
156 if( wxSizer* resolutionSizer = m_panelResolution->GetSizer() )
157 {
159 m_canvas->SetMinSize( wxSize( -1, 200 ) );
160
161 // Insert just above the text detail (which sits at index 1 after
162 // the label). Keep the existing layout otherwise intact.
163 const size_t insertAt = std::min<size_t>( 1, resolutionSizer->GetItemCount() );
164 resolutionSizer->Insert( insertAt, m_canvas,
165 wxSizerFlags( 1 ).Expand().Border( wxALL, 4 ) );
166 m_panelResolution->Layout();
167 }
168
169 if( !m_context.formatNotice.IsEmpty() )
170 m_labelIntro->SetLabel( m_labelIntro->GetLabel() + wxS( "\n\n" ) + m_context.formatNotice );
171
172 buildList();
173
174 if( m_conflictActionIndex.empty() )
175 {
176 m_labelDetail->SetLabel( _( "No conflicts to resolve." ) );
177 m_sdbSizerApply->Enable( true );
178 }
179 else
180 {
181 m_listConflicts->SetSelection( 0 );
182 showConflict( 0 );
183 }
184
186
187 Layout();
188
189 // The first conflict is drawn before the canvas has a surface, so draw it again once shown
190 CallAfter(
191 [this]()
192 {
193 if( m_canvas )
194 m_canvas->ForceRefresh();
195 } );
196
197 // Headless / scripted mode: if KICAD_MERGETOOL_AUTO is set, apply the
198 // pre-recorded resolutions and close the dialog immediately. The
199 // EndModal is deferred via CallAfter so it runs after ShowModal has
200 // started its event loop. Used by CI test runners that exercise the
201 // full git mergetool → kicad-cli → kicad --mergetool → applier flow
202 // without a human at the keyboard.
203 //
204 // Bad-env paths (missing file, parse error, partial coverage, unknown
205 // resolution kind) explicitly EndModal( wxID_CANCEL ) so the caller's
206 // exit code is non-zero. Silently falling back to the interactive
207 // dialog would hang a CI run forever.
208 std::map<wxString, KICAD_DIFF::ITEM_RES> autoResolutions;
209
210 switch( loadAutoResolutionFile( autoResolutions ) )
211 {
212 case AUTO_MODE::NOT_SET:
213 break;
214
215 case AUTO_MODE::LOAD_FAILED:
216 wxLogTrace( traceDiffMerge,
217 wxT( "KICAD_MERGETOOL_AUTO load failed; closing dialog as cancelled" ) );
218 CallAfter( [this]() { EndModal( wxID_CANCEL ); } );
219 break;
220
221 case AUTO_MODE::LOADED:
222 {
225 autoResolutions );
226
227 switch( applied.status )
228 {
230 wxLogTrace( traceDiffMerge,
231 wxT( "KICAD_MERGETOOL_AUTO missing resolution for %s" ),
232 applied.firstMissingId.AsString() );
233 CallAfter( [this]() { EndModal( wxID_CANCEL ); } );
234 break;
235
238 CallAfter( [this]() { EndModal( wxID_APPLY ); } );
239 wxLogTrace( traceDiffMerge,
240 wxT( "KICAD_MERGETOOL_AUTO applied %zu auto-resolutions" ),
241 applied.appliedCount );
242 break;
243 }
244
245 break;
246 }
247 }
248}
249
250
251void DIALOG_KICAD_MERGE_3WAY::OnClose( wxCloseEvent& aEvent )
252{
253 EndModal( wxID_CANCEL );
254}
255
256
257void DIALOG_KICAD_MERGE_3WAY::OnCancel( wxCommandEvent& aEvent )
258{
259 EndModal( wxID_CANCEL );
260}
261
262
263void DIALOG_KICAD_MERGE_3WAY::OnApply( wxCommandEvent& aEvent )
264{
265 // Every conflict needs an explicit choice before the plan can be applied.
266 const std::vector<KIID_PATH> stillUnresolved =
268
269 if( !stillUnresolved.empty() )
270 {
271 wxMessageBox( wxString::Format( wxPLURAL( "%zu conflict still needs a resolution. "
272 "Pick Ours, Theirs, or Ancestor for each one.",
273 "%zu conflicts still need a resolution. "
274 "Pick Ours, Theirs, or Ancestor for each one.",
275 stillUnresolved.size() ),
276 stillUnresolved.size() ),
277 _( "Resolve Merge Conflicts" ),
278 wxOK | wxICON_INFORMATION, this );
279 return;
280 }
281
282 m_plan.unresolved.clear();
283 EndModal( wxID_APPLY );
284}
285
286
288{
289 showConflict( m_listConflicts->GetSelection() );
290}
291
292
294{
295 if( m_currentConflict < 0
296 || m_currentConflict >= static_cast<int>( m_conflictActionIndex.size() ) )
297 {
298 return;
299 }
300
301 std::size_t actionIdx = m_conflictActionIndex[m_currentConflict];
302 KICAD_DIFF::ITEM_RESOLUTION& action = m_plan.actions[actionIdx];
303
304 if( m_radioOurs->GetValue() )
306 else if( m_radioTheirs->GetValue() )
308 else if( m_radioAncestor->GetValue() )
312
315}
316
317
319{
320 if( m_radioTheirs->GetValue() )
321 return SIDE::THEIRS;
322
323 if( m_radioAncestor->GetValue() )
324 return SIDE::ANCESTOR;
325
326 return SIDE::OURS;
327}
328
329
331{
332 if( !m_canvas )
333 return;
334
336 const std::map<KIID_PATH, BOX2I>* primaryBBoxes = nullptr;
337
338 switch( activeSide() )
339 {
340 case SIDE::OURS:
341 scene.referenceGeometry = m_context.oursGeometry;
342 primaryBBoxes = &m_context.oursBBoxes;
343 break;
344 case SIDE::THEIRS:
345 scene.referenceGeometry = m_context.theirsGeometry;
346 primaryBBoxes = &m_context.theirsBBoxes;
347 break;
348 case SIDE::ANCESTOR:
349 scene.referenceGeometry = m_context.ancestorGeometry;
350 primaryBBoxes = &m_context.ancestorBBoxes;
351 break;
352 }
353
354 static const std::map<KIID_PATH, BOX2I> emptyBBoxMap;
355
356 BOX2I conflictBBox;
357
358 if( m_currentConflict >= 0
359 && m_currentConflict < static_cast<int>( m_conflictActionIndex.size() ) )
360 {
361 const KICAD_DIFF::ITEM_RESOLUTION& action =
363
364 const std::optional<BOX2I> resolved =
366 action.id,
367 primaryBBoxes ? *primaryBBoxes : emptyBBoxMap,
368 m_context.oursBBoxes, m_context.theirsBBoxes,
369 m_context.ancestorBBoxes );
370
371 if( resolved.has_value() )
372 {
373 conflictBBox = *resolved;
374
376 shape.bbox = conflictBBox;
377 shape.color = highlightColor();
378 shape.changeId = action.id;
379 scene.conflictShapes.push_back( shape );
380 }
381 }
382
383 // documentBBox covers the side's geometry so the user can pan/zoom out
384 // to see context; the explicit ZoomToBBox below focuses the initial view
385 // on the conflict so it isn't lost in the wide-area auto-fit.
387
388 std::optional<KIID_PATH> highlight;
389
390 if( m_currentConflict >= 0 )
391 highlight = m_plan.actions[m_conflictActionIndex[m_currentConflict]].id;
392
393 m_canvas->SetScene( std::move( scene ) );
394
395 // The editor's painter draws the real items, so text reads as text. The canvas drops the
396 // flattened geometry once it has them, and keeps the conflict highlight from the scene.
397 if( m_context.drawSide )
398 m_context.drawSide( *m_canvas, activeSide(), highlight );
399
400 m_canvas->HighlightChange( highlight );
401
402 if( conflictBBox.GetWidth() > 0 || conflictBBox.GetHeight() > 0 )
403 {
404 // Pad the focus a bit so the highlight isn't flush with the edges
405 // and the user sees some surrounding context.
406 BOX2I focus = conflictBBox;
407 focus.Inflate( std::max( conflictBBox.GetWidth(), conflictBBox.GetHeight() ) );
408 m_canvas->ZoomToBBox( focus );
409 }
410}
411
412
413wxString DIALOG_KICAD_MERGE_3WAY::describe( const KIID_PATH& aId, const wxString& aFallback ) const
414{
415 if( m_context.describeItem )
416 {
417 wxString named = m_context.describeItem( aId );
418
419 if( !named.IsEmpty() )
420 return named;
421 }
422
423 return aFallback;
424}
425
426
428{
429 m_listConflicts->Clear();
430 m_conflictActionIndex.clear();
431 m_hasMergedEdit.clear();
432
433 for( const KICAD_DIFF::CONFLICT_LIST_ENTRY& entry
435 {
436 m_listConflicts->Append( describe( entry.id, entry.label ) );
437 m_conflictActionIndex.push_back( entry.actionIndex );
438 m_hasMergedEdit.push_back( m_plan.actions[entry.actionIndex].kind == KICAD_DIFF::ITEM_RES::MERGE_PROPS );
439 }
440}
441
442
444{
445 m_currentConflict = aIndex;
446
447 if( aIndex < 0 || aIndex >= static_cast<int>( m_conflictActionIndex.size() ) )
448 {
449 m_labelDetail->SetLabel( _( "Select a conflict on the left to see details." ) );
450 m_textDetail->SetValue( wxEmptyString );
451 return;
452 }
453
454 std::size_t actionIdx = m_conflictActionIndex[aIndex];
455 const KICAD_DIFF::ITEM_RESOLUTION& action = m_plan.actions[actionIdx];
456
457 const bool offersMerge = m_hasMergedEdit[aIndex];
458
459 // A native radio group cannot clear every button, so the fourth one holds whatever is
460 // not a side.
461 m_radioUnresolved->SetLabel( offersMerge ? _( "Merge both changes" ) : _( "Not decided yet" ) );
462 m_radioUnresolved->Enable( offersMerge );
463 m_panelResolution->Layout();
464
465 switch( action.kind )
466 {
467 case KICAD_DIFF::ITEM_RES::TAKE_OURS: m_radioOurs->SetValue( true ); break;
468 case KICAD_DIFF::ITEM_RES::TAKE_THEIRS: m_radioTheirs->SetValue( true ); break;
469 case KICAD_DIFF::ITEM_RES::TAKE_ANCESTOR: m_radioAncestor->SetValue( true ); break;
470 default: m_radioUnresolved->SetValue( true ); break;
471 }
472
473 // The canvas never draws the combined result, so say which document it is showing.
474 wxString shown;
475
476 switch( activeSide() )
477 {
478 case SIDE::OURS: shown = _( "showing your version" ); break;
479 case SIDE::THEIRS: shown = _( "showing their version" ); break;
480 case SIDE::ANCESTOR: shown = _( "showing the common version" ); break;
481 }
482
483 m_labelDetail->SetLabel(
484 wxString::Format( _( "Conflict on %s, %s" ), describe( action.id, action.id.AsString() ), shown ) );
485
487 {
488 // The detail box does not wrap, so the lines are broken here.
490 + _( "\n\nBoth sides changed this item, and their edits are combined.\n"
491 "Where both changed the same thing, your version is kept.\n"
492 "Pick a side to take that version whole instead." ) );
493 }
494 else if( m_radioUnresolved->GetValue() )
495 {
496 m_textDetail->SetValue( _( "Pick Ours, Theirs, or Ancestor to preview and keep that version." ) );
497 }
498 else
499 {
501 }
502
504}
const char * name
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
constexpr BOX2< Vec > & Inflate(coord_type dx, coord_type dy)
Inflates the rectangle horizontally by dx and vertically by dy.
Definition box2.h:556
constexpr size_type GetWidth() const
Definition box2.h:217
constexpr size_type GetHeight() const
Definition box2.h:218
DIALOG_KICAD_MERGE_3WAY_BASE(wxWindow *parent, wxWindowID id=wxID_ANY, const wxString &title=_("Resolve Merge Conflicts"), const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxSize(950, 700), long style=wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER)
void OnConflictSelected(wxCommandEvent &aEvent) override
SIDE activeSide() const
The side the canvas previews.
DIALOG_KICAD_MERGE_3WAY(wxWindow *aParent, const KICAD_DIFF::MERGE_PLAN &aPlan, CONFLICT_CONTEXT aContext={})
static CONFLICT_CONTEXT LibraryContext(const std::set< wxString > &aNames, LIBRARY_ITEM_DRAWER aDraw)
Context for merging a library, whose items are known by the names in aNames.
static bool CanOpen(REPORTER &aReporter)
Report to aReporter and return false when this process cannot open a dialog.
void OnApply(wxCommandEvent &aEvent) override
wxString describe(const KIID_PATH &aId, const wxString &aFallback) const
The item's name from the editor, or aFallback when there is none.
void OnCancel(wxCommandEvent &aEvent) override
void rebuildCanvas()
Rebuild the canvas scene from the current side (per radio) and the active conflict's bbox.
void OnClose(wxCloseEvent &aEvent) override
WIDGET_DIFF_CANVAS * m_canvas
GAL-backed conflict viewer injected into the resolution panel.
KICAD_DIFF::MERGE_PLAN m_plan
int m_currentConflict
Currently-displayed conflict (index into m_conflictActionIndex), -1 if none.
std::function< void(WIDGET_DIFF_CANVAS &, SIDE, const wxString &aName)> LIBRARY_ITEM_DRAWER
void showConflict(int aIndex)
Update the detail panel for the selected conflict.
void buildList()
Populate the conflict list from the plan's unresolved items.
SIDE
Which side's version the canvas should currently display.
std::vector< bool > m_hasMergedEdit
True where the engine combined both sides' edits, in the order of m_conflictActionIndex.
void OnResolutionChanged(wxCommandEvent &aEvent) override
std::vector< std::size_t > m_conflictActionIndex
Indices into m_plan.actions matching the order of m_listConflicts.
void OptOut(wxWindow *aWindow)
Opt out of control state saving.
A color representation with 4 components: red, green, blue, alpha.
Definition color4d.h:101
wxString AsString() const
Definition kiid.cpp:423
A pure virtual class used to derive REPORTER objects from.
Definition reporter.h:73
virtual REPORTER & Report(const wxString &aText, SEVERITY aSeverity=RPT_SEVERITY_UNDEFINED)
Report a string with a given severity.
Definition reporter.h:102
GAL-backed canvas for visualizing a KICAD_DIFF::DIFF_SCENE.
static bool empty(const wxTextEntryBase *aCtrl)
#define _(s)
const wxChar *const traceDiffMerge
Flag to enable diff/merge engine and renderer debugging output.
wxString BuildConflictDetailText(const ITEM_RESOLUTION &aResolution)
Build the human-readable detail text shown in the merge dialog's resolution panel for a given ITEM_RE...
AUTO_RESOLUTION_PARSE_RESULT ParseAutoResolutionJson(const std::string &aJsonContent)
Parse a KICAD_MERGETOOL_AUTO-format JSON object mapping item IDs (KIID_PATH strings) to ITEM_RES spel...
@ OK
parsed cleanly; resolutions is populated
std::vector< CONFLICT_LIST_ENTRY > BuildConflictList(const MERGE_PLAN &aPlan)
std::optional< BOX2I > ResolveConflictBBox(const KIID_PATH &aId, const std::map< KIID_PATH, BOX2I > &aPrimary, const std::map< KIID_PATH, BOX2I > &aOurs, const std::map< KIID_PATH, BOX2I > &aTheirs, const std::map< KIID_PATH, BOX2I > &aAncestor)
Resolve the best bounding box for a conflicted item across the three sides of a 3-way merge.
KIID_PATH LibraryItemKiidPath(const wxString &aName)
Build a deterministic synthetic KIID_PATH from a library item name (symbol name or footprint name).
APPLY_AUTO_RESOLUTIONS_RESULT ApplyAutoResolutions(MERGE_PLAN &aPlan, const std::vector< std::size_t > &aConflictActionIndices, const std::map< wxString, ITEM_RES > &aResolutions)
Apply a parsed auto-resolution map to a MERGE_PLAN's conflicts.
void ExpandBBoxToGeometry(DIFF_SCENE &aScene)
Grow the scene's documentBBox to also include the extent of any background geometry.
std::vector< KIID_PATH > CollectUnresolvedConflicts(const MERGE_PLAN &aPlan, const std::vector< std::size_t > &aConflictActionIndices)
Return the conflict actions that still have no decision.
STL namespace.
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
@ LOAD_FAILED
@ RPT_SEVERITY_ERROR
Phase 8 context for the conflict canvas.
std::function< void(WIDGET_DIFF_CANVAS &, SIDE, const std::optional< KIID_PATH > &)> drawSide
Draw a side on the canvas with the editor's own painter.
std::function< wxString(const KIID_PATH &)> describeItem
Name an item the way the editor would, so a conflict can be told from its neighbours.
APPLY_AUTO_RESOLUTIONS_STATUS status
KIID_PATH firstMissingId
Set only when status == PARTIAL AND the partial result was caused by a missing entry in the auto-reso...
Result of ParseAutoResolutionJson.
std::map< wxString, ITEM_RES > resolutions
Build the list of conflict-action indices the dialog walks: the positions in plan....
Diff colors with defaults for light backgrounds.
Definition diff_scene.h:278
DOCUMENT_GEOMETRY referenceGeometry
Background geometry from the two source documents.
Definition diff_scene.h:242
std::vector< SCENE_SHAPE > conflictShapes
Definition diff_scene.h:236
Result of planning a 3-way merge.
Shared rendering model consumed by both the GAL renderer (interactive widget) and the plotter rendere...
Definition diff_scene.h:90
KIGFX::COLOR4D color
Definition diff_scene.h:92
KIID_PATH changeId
Stable identifier of the ITEM_CHANGE that produced this shape.
Definition diff_scene.h:99
std::string path
wxLogTrace helper definitions.