KiCad PCB EDA Suite
Loading...
Searching...
No Matches
margin_offset_binder.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 2
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, see <https://www.gnu.org/licenses/>.
18 */
19
21
22#include <wx/dcclient.h>
23#include <wx/stattext.h>
24#include <wx/textentry.h>
25#include <wx/regex.h>
26#include <eda_units.h>
27#include <eda_draw_frame.h>
28
29using namespace EDA_UNIT_UTILS::UI;
30
31
32MARGIN_OFFSET_BINDER::MARGIN_OFFSET_BINDER( EDA_DRAW_FRAME* aParent, wxStaticText* aLabel, wxWindow* aValueCtrl,
33 wxStaticText* aUnitLabel ) :
34 MARGIN_OFFSET_BINDER( aParent, aParent, aLabel, aValueCtrl, aUnitLabel )
35{
36}
37
38
39MARGIN_OFFSET_BINDER::MARGIN_OFFSET_BINDER( UNITS_PROVIDER* aUnitsProvider, wxWindow* aEventSource,
40 wxStaticText* aLabel, wxWindow* aValueCtrl, wxStaticText* aUnitLabel ) :
41 m_label( aLabel ),
42 m_valueCtrl( aValueCtrl ),
43 m_eventSource( aEventSource ),
44 m_unitLabel( aUnitLabel ),
45 m_iuScale( &aUnitsProvider->GetIuScale() ),
46 m_units( aUnitsProvider->GetUserUnits() ),
47 m_eval( aUnitsProvider->GetUserUnits() ),
48 m_cachedOffset( std::nullopt ),
49 m_cachedRatio( std::nullopt ),
50 m_needsParsing( true )
51{
52 if( m_valueCtrl )
53 {
54 m_valueCtrl->Connect( wxEVT_SET_FOCUS, wxFocusEventHandler( MARGIN_OFFSET_BINDER::onSetFocus ),
55 nullptr, this );
56 m_valueCtrl->Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( MARGIN_OFFSET_BINDER::onKillFocus ),
57 nullptr, this );
58 m_valueCtrl->Connect( wxEVT_TEXT, wxCommandEventHandler( MARGIN_OFFSET_BINDER::onTextChanged ),
59 nullptr, this );
60 }
61
62 if( m_eventSource )
63 {
64 m_eventSource->Connect( EDA_EVT_UNITS_CHANGED, wxCommandEventHandler( MARGIN_OFFSET_BINDER::onUnitsChanged ),
65 nullptr, this );
66 }
67
68 // UNIT_BINDER sizes the field it binds, which is why the forms leave its size unset. This
69 // field holds an offset and a ratio together, so it is sized for that combined value.
70 if( m_valueCtrl && dynamic_cast<wxTextEntry*>( m_valueCtrl ) )
71 {
72 wxClientDC dc( m_valueCtrl );
73
74 wxSize minSize = m_valueCtrl->GetMinSize();
75 int minWidth = dc.GetTextExtent( wxT( "-XX.XXXXmm - XX%" ) ).GetWidth();
76
77 if( minSize.GetWidth() < minWidth )
78 m_valueCtrl->SetMinSize( wxSize( minWidth, minSize.GetHeight() ) );
79 }
80
81 // Update the unit label to indicate combined format
82 if( m_unitLabel )
83 m_unitLabel->SetLabel( wxEmptyString );
84}
85
86
88{
89 if( m_valueCtrl )
90 {
91 m_valueCtrl->Disconnect( wxEVT_SET_FOCUS, wxFocusEventHandler( MARGIN_OFFSET_BINDER::onSetFocus ),
92 nullptr, this );
93 m_valueCtrl->Disconnect( wxEVT_KILL_FOCUS, wxFocusEventHandler( MARGIN_OFFSET_BINDER::onKillFocus ),
94 nullptr, this );
95 m_valueCtrl->Disconnect( wxEVT_TEXT, wxCommandEventHandler( MARGIN_OFFSET_BINDER::onTextChanged ),
96 nullptr, this );
97 }
98
99 if( m_eventSource )
100 {
101 m_eventSource->Disconnect( EDA_EVT_UNITS_CHANGED, wxCommandEventHandler( MARGIN_OFFSET_BINDER::onUnitsChanged ),
102 nullptr, this );
103 }
104}
105
106
107void MARGIN_OFFSET_BINDER::SetOffsetValue( std::optional<int> aValue )
108{
109 m_cachedOffset = aValue;
110 m_needsParsing = false;
112}
113
114
115void MARGIN_OFFSET_BINDER::SetRatioValue( std::optional<double> aRatio )
116{
117 m_cachedRatio = aRatio;
118 m_needsParsing = false;
120}
121
122
123std::optional<int> MARGIN_OFFSET_BINDER::GetOffsetValue() const
124{
125 if( m_needsParsing )
126 {
127 wxString input = getTextValue();
129 m_needsParsing = false;
130 }
131
132 return m_cachedOffset;
133}
134
135
136std::optional<double> MARGIN_OFFSET_BINDER::GetRatioValue() const
137{
138 if( m_needsParsing )
139 {
140 wxString input = getTextValue();
142 m_needsParsing = false;
143 }
144
145 return m_cachedRatio;
146}
147
148
150{
151 wxString text = getTextValue();
152 text.Trim( true ).Trim( false );
153 return text.IsEmpty();
154}
155
156
158{
159 if( m_label )
160 m_label->Enable( aEnable );
161
162 if( m_valueCtrl )
163 m_valueCtrl->Enable( aEnable );
164
165 if( m_unitLabel )
166 m_unitLabel->Enable( aEnable );
167}
168
169
170void MARGIN_OFFSET_BINDER::Show( bool aShow, bool aResize )
171{
172 if( m_label )
173 {
174 m_label->Show( aShow );
175
176 if( aResize )
177 {
178 if( aShow )
179 m_label->SetSize( -1, -1 );
180 else
181 m_label->SetSize( 0, 0 );
182 }
183 }
184
185 if( m_valueCtrl )
186 {
187 m_valueCtrl->Show( aShow );
188
189 if( aResize )
190 {
191 if( aShow )
192 m_valueCtrl->SetSize( -1, -1 );
193 else
194 m_valueCtrl->SetSize( 0, 0 );
195 }
196 }
197
198 if( m_unitLabel )
199 {
200 m_unitLabel->Show( aShow );
201
202 if( aResize )
203 {
204 if( aShow )
205 m_unitLabel->SetSize( -1, -1 );
206 else
207 m_unitLabel->SetSize( 0, 0 );
208 }
209 }
210}
211
212
213void MARGIN_OFFSET_BINDER::onSetFocus( wxFocusEvent& aEvent )
214{
215 m_needsParsing = true;
216 aEvent.Skip();
217}
218
219
220void MARGIN_OFFSET_BINDER::onTextChanged( wxCommandEvent& aEvent )
221{
222 // GetOffsetValue/GetRatioValue clear m_needsParsing after each parse, so any subsequent
223 // text edit within the same focus session must re-arm it.
224 m_needsParsing = true;
225 aEvent.Skip();
226}
227
228
229static wxString valueDescriptionFromLabel( wxStaticText* aLabel )
230{
231 wxString desc = aLabel->GetLabel();
232
233 desc.EndsWith( wxT( ":" ), &desc );
234 return desc;
235}
236
237
239{
240 std::optional<int> offset;
241 std::optional<double> ratio;
242
243 if( !parseInput( getTextValue(), offset, ratio ) )
244 {
245 return wxString::Format( _( "%s could not be parsed as a distance and/or percentage offset." ),
247 }
248
249 return wxEmptyString;
250}
251
252
253void MARGIN_OFFSET_BINDER::onKillFocus( wxFocusEvent& aEvent )
254{
255 // Parse and reformat the value on focus loss
256 wxString input = getTextValue();
257 std::optional<int> offset;
258 std::optional<double> ratio;
259
260 if( parseInput( input, offset, ratio ) )
261 {
262 m_cachedOffset = offset;
263 m_cachedRatio = ratio;
264 m_needsParsing = false;
266 }
267
268 aEvent.Skip();
269}
270
271
272void MARGIN_OFFSET_BINDER::onUnitsChanged( wxCommandEvent& aEvent )
273{
274 if( EDA_BASE_FRAME* provider = static_cast<EDA_BASE_FRAME*>( aEvent.GetClientData() ) )
275 {
276 // Preserve current values
277 std::optional<int> offset = GetOffsetValue();
278 std::optional<double> ratio = GetRatioValue();
279
280 // Update units
281 m_units = provider->GetUserUnits();
282 m_iuScale = &provider->GetIuScale();
283 m_eval.SetDefaultUnits( m_units );
284
285 // Reformat with new units
286 setTextValue( formatValue( offset, ratio ) );
287 }
288
289 aEvent.Skip();
290}
291
292
293bool MARGIN_OFFSET_BINDER::parseInput( const wxString& aInput, std::optional<int>& aOffset,
294 std::optional<double>& aRatio ) const
295{
296 aOffset = std::nullopt;
297 aRatio = std::nullopt;
298
299 wxString input = aInput;
300 input.Trim( true ).Trim( false );
301
302 if( input.IsEmpty() )
303 return true;
304
305 // Strategy: find all terms separated by + and - operators
306 // Each term is either a distance value (with optional unit) or a percentage
307
308 // First, normalize the input by adding spaces around operators
309 wxString normalized;
310 bool lastWasOperator = true; // Start as true to handle leading negative
311
312 for( size_t i = 0; i < input.Length(); ++i )
313 {
314 wxChar ch = input[i];
315
316 if( ( ch == '+' || ch == '-' ) && !lastWasOperator )
317 {
318 // This is an operator between terms
319 normalized += ' ';
320 normalized += ch;
321 normalized += ' ';
322 lastWasOperator = true;
323 }
324 else
325 {
326 normalized += ch;
327 lastWasOperator = ( ch == '+' || ch == '-' );
328 }
329 }
330
331 // Split into terms
332 wxArrayString terms;
333 wxString currentTerm;
334
335 for( size_t i = 0; i < normalized.Length(); ++i )
336 {
337 wxChar ch = normalized[i];
338
339 if( ch == ' ' )
340 {
341 if( !currentTerm.IsEmpty() )
342 {
343 currentTerm.Trim( true ).Trim( false );
344 terms.Add( currentTerm );
345 currentTerm.Clear();
346 }
347 }
348 else
349 {
350 currentTerm += ch;
351 }
352 }
353
354 if( !currentTerm.IsEmpty() )
355 {
356 currentTerm.Trim( true ).Trim( false );
357 terms.Add( currentTerm );
358 }
359
360 // Process each term
361 double totalOffset = 0.0;
362 double totalRatio = 0.0;
363 bool hasOffset = false;
364 bool hasRatio = false;
365 double sign = 1.0;
366
367 for( const wxString& term : terms )
368 {
369 if( term == "+" )
370 {
371 sign = 1.0;
372 continue;
373 }
374 else if( term == "-" )
375 {
376 sign = -1.0;
377 continue;
378 }
379
380 bool invalidTerm = true;
381
382 // Check if this term is a percentage
383 if( term.EndsWith( "%" ) )
384 {
385 wxString numPart = term.Left( term.Length() - 1 );
386 numPart.Trim( true ).Trim( false );
387 double value;
388
389 if( numPart.ToDouble( &value ) )
390 {
391 totalRatio += sign * value / 100.0;
392 hasRatio = true;
393 invalidTerm = false;
394 }
395 }
396 else
397 {
398 // Try to parse as a distance value using the evaluator
400
401 if( eval.Process( term ) )
402 {
403 wxString result = eval.Result();
404 double value;
405
406 if( result.ToDouble( &value ) )
407 {
408 // Convert from user units to internal units
410 totalOffset += sign * iuValue;
411 hasOffset = true;
412 invalidTerm = false;
413 }
414 }
415 }
416
417 if( invalidTerm )
418 return false;
419
420 sign = 1.0; // Reset sign for next term
421 }
422
423 if( hasOffset )
424 aOffset = static_cast<int>( totalOffset );
425
426 if( hasRatio )
427 aRatio = totalRatio;
428
429 return hasOffset || hasRatio;
430}
431
432
433wxString MARGIN_OFFSET_BINDER::formatValue( std::optional<int> aOffset, std::optional<double> aRatio ) const
434{
435 wxString result;
436
437 // Format offset value
438 if( aOffset.has_value() && aOffset.value() != 0 )
439 {
441 }
442
443 // Format ratio value
444 if( aRatio.has_value() && std::abs( aRatio.value() ) > 1e-9 )
445 {
446 double percent = aRatio.value() * 100.0;
447
448 if( !result.IsEmpty() )
449 {
450 // Add the ratio with appropriate sign
451 if( percent >= 0 )
452 result += wxString::Format( " + %.4g%%", percent );
453 else
454 result += wxString::Format( " - %.4g%%", -percent );
455 }
456 else
457 {
458 result = wxString::Format( "%.4g%%", percent );
459 }
460 }
461 else if( aOffset.has_value() && aOffset.value() == 0 )
462 {
463 // No value formats as empty string; a value of 0 must format as "0"
464 result = wxT( "0" );
465 }
466
467 return result;
468}
469
470
472{
473 wxTextEntry* textEntry = dynamic_cast<wxTextEntry*>( m_valueCtrl );
474
475 if( textEntry )
476 return textEntry->GetValue();
477
478 return wxEmptyString;
479}
480
481
482void MARGIN_OFFSET_BINDER::setTextValue( const wxString& aValue )
483{
484 wxTextEntry* textEntry = dynamic_cast<wxTextEntry*>( m_valueCtrl );
485
486 if( textEntry )
487 textEntry->ChangeValue( aValue );
488}
static std::optional< VECTOR2D > normalized(const VECTOR2D &aVec)
The base frame for deriving all KiCad main window classes.
The base class for create windows for drawing purpose.
bool IsNull() const
Return true if the control holds no value (ie: empty string).
std::optional< int > GetOffsetValue() const
Get the absolute offset value (in Internal Units).
void onTextChanged(wxCommandEvent &aEvent)
MARGIN_OFFSET_BINDER(EDA_DRAW_FRAME *aParent, wxStaticText *aLabel, wxWindow *aValueCtrl, wxStaticText *aUnitLabel)
std::optional< double > GetRatioValue() const
Get the ratio value as a fraction (e.g., -0.05 for -5%).
const EDA_IU_SCALE * m_iuScale
virtual ~MARGIN_OFFSET_BINDER() override
void Enable(bool aEnable)
Enable/disable the label, widget and units label.
void onSetFocus(wxFocusEvent &aEvent)
bool parseInput(const wxString &aInput, std::optional< int > &aOffset, std::optional< double > &aRatio) const
Parse the input string and extract offset and ratio values.
wxStaticText * m_unitLabel
Can be nullptr.
void SetRatioValue(std::optional< double > aRatio)
Set the ratio value as a fraction (e.g., -0.05 for -5%).
std::optional< int > m_cachedOffset
void Show(bool aShow, bool aResize=false)
Show/hide the label, widget and units label.
std::optional< double > m_cachedRatio
wxString getTextValue() const
Get the current text from the control.
void onKillFocus(wxFocusEvent &aEvent)
void setTextValue(const wxString &aValue)
Set the text in the control without triggering events.
wxString formatValue(std::optional< int > aOffset, std::optional< double > aRatio) const
Format the offset and ratio values into a display string.
void onUnitsChanged(wxCommandEvent &aEvent)
void SetOffsetValue(std::optional< int > aValue)
Set the absolute offset value (in Internal Units).
wxString Result() const
bool Process(const wxString &aString)
const int minSize
Push and Shove router track width and via size dialog.
#define _(s)
static wxString valueDescriptionFromLabel(wxStaticText *aLabel)
KICOMMON_API long long int ValueFromString(const EDA_IU_SCALE &aIuScale, EDA_UNITS aUnits, const wxString &aTextValue, EDA_DATA_TYPE aType=EDA_DATA_TYPE::DISTANCE)
Convert aTextValue in aUnits to internal units used by the application.
KICOMMON_API wxString StringFromValue(const EDA_IU_SCALE &aIuScale, EDA_UNITS aUnits, double aValue, bool aAddUnitsText=false, EDA_DATA_TYPE aType=EDA_DATA_TYPE::DISTANCE)
Return the string from aValue according to aUnits (inch, mm ...) for display.
STL namespace.
EDA_ANGLE abs(const EDA_ANGLE &aAngle)
Definition eda_angle.h:461
DATABASE_CONNECTION dc(odbcBackend(cs))
wxString result
Test unit parsing edge cases and error handling.
constexpr int sign(T val)
Definition util.h:167