KiCad PCB EDA Suite
Loading...
Searching...
No Matches
dialog_shim.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) 2012 SoftPLC Corporation, Dick Hollenbeck <[email protected]>
5 * Copyright (C) 2023 CERN
6 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
7 *
8 * This program is free software; you can redistribute it and/or
9 * modify it under the terms of the GNU General Public License
10 * as published by the Free Software Foundation; either version 2
11 * of the License, or (at your option) any later version.
12 *
13 * This program is distributed in the hope that it will be useful,
14 * but WITHOUT ANY WARRANTY; without even the implied warranty of
15 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
16 * GNU General Public License for more details.
17 *
18 * You should have received a copy of the GNU General Public License
19 * along with this program. If not, see <https://www.gnu.org/licenses/>.
20 */
21
22#include "dialog_shim.h"
23
24#include <app_monitor.h>
27#include <core/ignore.h>
28#include <kiway_player.h>
29#include <kiway.h>
30#include <pgm_base.h>
32#include <property_holder.h>
34#include <tool/tool_manager.h>
35#include <kiplatform/ui.h>
37#include <widgets/unit_binder.h>
38
39#include <wx/display.h>
40#include <wx/evtloop.h>
41#include <wx/app.h>
42#include <wx/event.h>
43#include <wx/grid.h>
44#include <widgets/wx_grid.h>
45#include <wx/propgrid/propgrid.h>
46#include <wx/checklst.h>
47#include <wx/dataview.h>
48#include <wx/bmpbuttn.h>
49#include <wx/textctrl.h>
50#include <wx/stc/stc.h>
51#include <wx/combobox.h>
52#include <wx/odcombo.h>
53#include <wx/choice.h>
54#include <wx/checkbox.h>
55#include <wx/spinctrl.h>
56#include <wx/splitter.h>
57#include <wx/radiobox.h>
58#include <wx/radiobut.h>
59#include <wx/datectrl.h>
60#if wxUSE_TIMEPICKCTRL
61#include <wx/timectrl.h>
62#endif
63#include <wx/variant.h>
64#include <wx/weakref.h>
65
66#include <algorithm>
67#include <functional>
68#include <nlohmann/json.hpp>
69#include <utility>
70
71BEGIN_EVENT_TABLE( DIALOG_SHIM, wxDialog )
72 EVT_CHAR_HOOK( DIALOG_SHIM::OnCharHook )
73 EVT_ACTIVATE( DIALOG_SHIM::OnActivate )
74END_EVENT_TABLE()
75
76
77
83static std::string getDialogKeyFromTitle( const wxString& aTitle )
84{
85 std::string title = aTitle.ToStdString();
86 size_t parenPos = title.rfind( '(' );
87
88 if( parenPos != std::string::npos && parenPos > 0 )
89 {
90 size_t end = parenPos;
91
92 while( end > 0 && title[end - 1] == ' ' )
93 end--;
94
95 return title.substr( 0, end );
96 }
97
98 return title;
99}
100
101
111static bool isCompoundDateTimePicker( const wxWindow* aWin )
112{
113#if wxUSE_DATEPICKCTRL
114 if( dynamic_cast<const wxDatePickerCtrl*>( aWin ) != nullptr )
115 return true;
116#endif
117
118#if wxUSE_TIMEPICKCTRL
119 if( dynamic_cast<const wxTimePickerCtrl*>( aWin ) != nullptr )
120 return true;
121#endif
122
123 return false;
124}
125
126
127DIALOG_SHIM::DIALOG_SHIM( wxWindow* aParent, wxWindowID id, const wxString& title, const wxPoint& pos,
128 const wxSize& size, long style, const wxString& name ) :
129 wxDialog( aParent, id, title, pos, size, style, name ),
130 KIWAY_HOLDER( nullptr, KIWAY_HOLDER::DIALOG ),
131 m_units( EDA_UNITS::MM ),
132 m_useCalculatedSize( false ),
133 m_firstPaintEvent( true ),
134 m_initialFocusTarget( nullptr ),
135 m_isClosing( false ),
136 m_qmodal_loop( nullptr ),
137 m_qmodal_showing( false ),
138 m_qmodal_parent_disabler( nullptr ),
139 m_parentFrame( nullptr ),
140 m_userPositioned( false ),
141 m_userResized( false ),
142 m_handlingUndoRedo( false ),
143 m_childReleased( false )
144{
145 KIWAY_HOLDER* kiwayHolder = nullptr;
146 m_initialSize = size;
147
148 if( aParent )
149 {
150 kiwayHolder = dynamic_cast<KIWAY_HOLDER*>( aParent );
151
152 while( !kiwayHolder && aParent->GetParent() )
153 {
154 aParent = aParent->GetParent();
155 kiwayHolder = dynamic_cast<KIWAY_HOLDER*>( aParent );
156 }
157 }
158
159 // Inherit units from parent
160 if( kiwayHolder && kiwayHolder->GetType() == KIWAY_HOLDER::FRAME )
161 m_units = static_cast<EDA_BASE_FRAME*>( kiwayHolder )->GetUserUnits();
162 else if( kiwayHolder && kiwayHolder->GetType() == KIWAY_HOLDER::DIALOG )
163 m_units = static_cast<DIALOG_SHIM*>( kiwayHolder )->GetUserUnits();
164
165 // Don't mouse-warp after a dialog run from the context menu
166 if( kiwayHolder && kiwayHolder->GetType() == KIWAY_HOLDER::FRAME )
167 {
168 m_parentFrame = static_cast<EDA_BASE_FRAME*>( kiwayHolder );
169 TOOL_MANAGER* toolMgr = m_parentFrame->GetToolManager();
170
171 if( toolMgr && toolMgr->IsContextMenuActive() )
172 toolMgr->VetoContextMenuMouseWarp();
173 }
174
175 // Set up the message bus
176 if( kiwayHolder )
177 SetKiway( this, &kiwayHolder->Kiway() );
178
179 if( HasKiway() )
180 Kiway().SetBlockingDialog( this );
181
182 Bind( wxEVT_CLOSE_WINDOW, &DIALOG_SHIM::OnCloseWindow, this );
183 Bind( wxEVT_BUTTON, &DIALOG_SHIM::OnButton, this );
184 Bind( wxEVT_SIZE, &DIALOG_SHIM::OnSize, this );
185 Bind( wxEVT_MOVE, &DIALOG_SHIM::OnMove, this );
186 Bind( wxEVT_INIT_DIALOG, &DIALOG_SHIM::onInitDialog, this );
187
188#ifdef __WINDOWS__
189 // On Windows, the app top windows can be brought to the foreground (at least temporarily)
190 // in certain circumstances such as when calling an external tool in Eeschema BOM generation.
191 // So set the parent frame (if exists) to top window to avoid this annoying behavior.
192 if( kiwayHolder && kiwayHolder->GetType() == KIWAY_HOLDER::FRAME )
193 Pgm().App().SetTopWindow( (EDA_BASE_FRAME*) kiwayHolder );
194#endif
195
196 Bind( wxEVT_PAINT, &DIALOG_SHIM::OnPaint, this );
197
198 wxString msg = wxString::Format( "Opening dialog %s", GetTitle() );
199 APP_MONITOR::AddNavigationBreadcrumb( msg, "dialog.open" );
200}
201
202
204{
205 m_isClosing = true;
206
207 Unbind( wxEVT_CLOSE_WINDOW, &DIALOG_SHIM::OnCloseWindow, this );
208 Unbind( wxEVT_BUTTON, &DIALOG_SHIM::OnButton, this );
209 Unbind( wxEVT_PAINT, &DIALOG_SHIM::OnPaint, this );
210 Unbind( wxEVT_SIZE, &DIALOG_SHIM::OnSize, this );
211 Unbind( wxEVT_MOVE, &DIALOG_SHIM::OnMove, this );
212 Unbind( wxEVT_INIT_DIALOG, &DIALOG_SHIM::onInitDialog, this );
213
214 std::function<void( wxWindowList& )> clearOptOuts =
215 [&]( wxWindowList& children )
216 {
217 for( wxWindow* child : children )
218 {
219 delete PROPERTY_HOLDER::SafeCast( child->GetClientData() );
220 child->SetClientData( nullptr );
221 clearOptOuts( child->GetChildren() );
222 }
223 };
224
225 delete PROPERTY_HOLDER::SafeCast( GetClientData() );
226 SetClientData( nullptr );
227 clearOptOuts( GetChildren() );
228
229 std::function<void( wxWindowList& )> disconnectFocusHandlers =
230 [&]( wxWindowList& children )
231 {
232 for( wxWindow* child : children )
233 {
234 if( isCompoundDateTimePicker( child ) )
235 continue;
236
237 if( wxTextCtrl* textCtrl = dynamic_cast<wxTextCtrl*>( child ) )
238 {
239 textCtrl->Disconnect( wxEVT_SET_FOCUS, wxFocusEventHandler( DIALOG_SHIM::onChildSetFocus ),
240 nullptr, this );
241 }
242 else if( wxStyledTextCtrl* scintilla = dynamic_cast<wxStyledTextCtrl*>( child ) )
243 {
244 scintilla->Disconnect( wxEVT_SET_FOCUS, wxFocusEventHandler( DIALOG_SHIM::onChildSetFocus ),
245 nullptr, this );
246 }
247 else
248 {
249 disconnectFocusHandlers( child->GetChildren() );
250 }
251 }
252 };
253
254 disconnectFocusHandlers( GetChildren() );
255
256 std::function<void( wxWindowList& )> disconnectUndoRedoHandlers =
257 [&]( wxWindowList& children )
258 {
259 for( wxWindow* child : children )
260 {
261 if( isCompoundDateTimePicker( child ) )
262 continue;
263
264 if( wxTextCtrl* textCtrl = dynamic_cast<wxTextCtrl*>( child ) )
265 {
266 textCtrl->Unbind( wxEVT_TEXT, &DIALOG_SHIM::onCommandEvent, this );
267 }
268 else if( wxStyledTextCtrl* scintilla = dynamic_cast<wxStyledTextCtrl*>( child ) )
269 {
270 scintilla->Unbind( wxEVT_STC_CHANGE, &DIALOG_SHIM::onStyledTextChanged, this );
271 }
272 else if( wxComboBox* combo = dynamic_cast<wxComboBox*>( child ) )
273 {
274 combo->Unbind( wxEVT_TEXT, &DIALOG_SHIM::onCommandEvent, this );
275 combo->Unbind( wxEVT_COMBOBOX, &DIALOG_SHIM::onCommandEvent, this );
276 }
277 else if( wxChoice* choice = dynamic_cast<wxChoice*>( child ) )
278 {
279 choice->Unbind( wxEVT_CHOICE, &DIALOG_SHIM::onCommandEvent, this );
280 }
281 else if( wxCheckBox* check = dynamic_cast<wxCheckBox*>( child ) )
282 {
283 check->Unbind( wxEVT_CHECKBOX, &DIALOG_SHIM::onCommandEvent, this );
284 }
285 else if( wxSpinCtrl* spin = dynamic_cast<wxSpinCtrl*>( child ) )
286 {
287 spin->Unbind( wxEVT_SPINCTRL, &DIALOG_SHIM::onSpinEvent, this );
288 spin->Unbind( wxEVT_TEXT, &DIALOG_SHIM::onCommandEvent, this );
289 }
290 else if( wxSpinCtrlDouble* spinD = dynamic_cast<wxSpinCtrlDouble*>( child ) )
291 {
292 spinD->Unbind( wxEVT_SPINCTRLDOUBLE, &DIALOG_SHIM::onSpinDoubleEvent, this );
293 spinD->Unbind( wxEVT_TEXT, &DIALOG_SHIM::onCommandEvent, this );
294 }
295 else if( wxRadioButton* radio = dynamic_cast<wxRadioButton*>( child ) )
296 {
297 radio->Unbind( wxEVT_RADIOBUTTON, &DIALOG_SHIM::onCommandEvent, this );
298 }
299 else if( wxRadioBox* radioBox = dynamic_cast<wxRadioBox*>( child ) )
300 {
301 radioBox->Unbind( wxEVT_RADIOBOX, &DIALOG_SHIM::onCommandEvent, this );
302 }
303 else if( wxGrid* grid = dynamic_cast<wxGrid*>( child ) )
304 {
305 grid->Unbind( wxEVT_GRID_CELL_CHANGED, &DIALOG_SHIM::onGridCellChanged, this );
306 }
307 else if( wxPropertyGrid* propGrid = dynamic_cast<wxPropertyGrid*>( child ) )
308 {
309 propGrid->Unbind( wxEVT_PG_CHANGED, &DIALOG_SHIM::onPropertyGridChanged, this );
310 }
311 else if( wxCheckListBox* checkList = dynamic_cast<wxCheckListBox*>( child ) )
312 {
313 checkList->Unbind( wxEVT_CHECKLISTBOX, &DIALOG_SHIM::onCommandEvent, this );
314 }
315 else if( wxDataViewListCtrl* dataList = dynamic_cast<wxDataViewListCtrl*>( child ) )
316 {
317 dataList->Unbind( wxEVT_DATAVIEW_ITEM_VALUE_CHANGED, &DIALOG_SHIM::onDataViewListChanged, this );
318 }
319 else
320 {
321 disconnectUndoRedoHandlers( child->GetChildren() );
322 }
323 }
324 };
325
326 disconnectUndoRedoHandlers( GetChildren() );
327
328 // The child controls (and the UNIT_BINDERs that live alongside them) outlive this dialog's
329 // member teardown, so sever their back-references now while m_unitBinders is still valid.
330 for( const auto& [window, binder] : m_unitBinders )
331 binder->DetachFromDialogShim();
332
333 // if the dialog is quasi-modal, this will end its event loop
334 if( IsQuasiModal() )
335 EndQuasiModal( wxID_CANCEL );
336
337 if( HasKiway() )
338 Kiway().SetBlockingDialog( nullptr );
339
341}
342
343
344void DIALOG_SHIM::onInitDialog( wxInitDialogEvent& aEvent )
345{
346#ifdef __WXMAC__
347 CallAfter(
348 [this]
349 {
350 if( wxSizer* sz = GetSizer() )
351 sz->Layout();
352 } );
353#endif
354
356 aEvent.Skip();
357}
358
359
361{
362 // must be called from the constructor of derived classes,
363 // when all widgets are initialized, and therefore their size fixed
364
365 // SetSizeHints fixes the minimal size of sizers in the dialog
366 // (SetSizeHints calls Fit(), so no need to call it)
367 GetSizer()->SetSizeHints( this );
368}
369
370
371wxRect ClampRectToDisplay( const wxRect& aRect, const wxRect& aClientArea )
372{
373 wxRect rect = aRect;
374
375 // A window can never be larger than the display that holds it.
376 rect.width = std::min( rect.width, aClientArea.width );
377 rect.height = std::min( rect.height, aClientArea.height );
378
379 rect.x = std::clamp( rect.x, aClientArea.x, aClientArea.GetRight() - rect.width + 1 );
380 rect.y = std::clamp( rect.y, aClientArea.y, aClientArea.GetBottom() - rect.height + 1 );
381
382 return rect;
383}
384
385
387{
388 // A dialog not yet mapped onto a monitor reports no display, so fall back to the parent's
389 // monitor rather than blindly clamping against display zero on a multi-head setup.
390 int displayIdx = wxDisplay::GetFromWindow( this );
391
392 if( displayIdx == wxNOT_FOUND && m_parent )
393 displayIdx = wxDisplay::GetFromWindow( m_parent );
394
395 if( displayIdx == wxNOT_FOUND )
396 displayIdx = 0;
397
398 wxRect clientArea = wxDisplay( (unsigned int) displayIdx ).GetClientArea();
399
400 if( clientArea.width <= 0 || clientArea.height <= 0 )
401 return;
402
403 // The minimum size must shrink first, otherwise SetSize() below cannot honour a cap that
404 // is smaller than a stale minimum restored from a larger monitor.
405 wxSize minSize = GetMinSize();
406 wxSize clampedMin( std::min( minSize.x, clientArea.width ),
407 std::min( minSize.y, clientArea.height ) );
408
409 if( clampedMin != minSize )
410 SetMinSize( clampedMin );
411
412 // Cap the size to the work area and pull the whole dialog back on-screen. Geometry restored
413 // from a different (possibly higher-DPI) monitor can otherwise land off-screen or oversized.
414 wxRect current( GetPosition(), GetSize() );
415 wxRect clamped = ClampRectToDisplay( current, clientArea );
416
417 if( clamped != current )
418 SetSize( clamped.x, clamped.y, clamped.width, clamped.height, 0 );
419}
420
421
422void DIALOG_SHIM::setSizeInDU( int x, int y )
423{
424 wxSize sz( x, y );
425 SetSize( ConvertDialogToPixels( sz ) );
426}
427
428
430{
431 wxSize sz( x, 0 );
432 return ConvertDialogToPixels( sz ).x;
433}
434
435
437{
438 wxSize sz( 0, y );
439 return ConvertDialogToPixels( sz ).y;
440}
441
442
443// our hashtable is an implementation secret, don't need or want it in a header file
444#include <hashtables.h>
445#include <typeinfo>
446#include <grid_tricks.h>
447
448
449void DIALOG_SHIM::SetPosition( const wxPoint& aNewPosition )
450{
451 wxDialog::SetPosition( aNewPosition );
452}
453
454
455void DIALOG_SHIM::focusParentCanvas( bool aDeferUntilFrameActive )
456{
457 // A dialog can be hidden while its parent frame is part way through its own destructor,
458 // where the frame's overrides are gone and GetToolCanvas() is pure again.
459 if( m_parentFrame && m_parentFrame->IsBeingDeleted() )
460 return;
461
462 wxWindow* toolCanvas = m_parentFrame ? m_parentFrame->GetToolCanvas() : nullptr;
463 wxWindow* target = toolCanvas ? toolCanvas : m_parent;
464
465 if( !target )
466 return;
467
468 target->SetFocus();
469
470 if( !aDeferUntilFrameActive || !toolCanvas )
471 return;
472
473#ifdef __WXGTK__
474 // A quasi-modal dialog is still the active top-level window when its nested event loop exits,
475 // so the SetFocus() above is undone when the dialog is destroyed and GTK restores the frame's
476 // previously-focused widget. Re-assert focus once the event loop has settled, otherwise
477 // keyboard events keep routing to the stale owner until the mouse re-enters the canvas.
479
480 frame->CallAfter(
481 [frame]()
482 {
483 // Skip if another dialog grabbed the activation in the meantime, otherwise we
484 // would raise the frame from behind a chained modal dialog.
485 if( !KIPLATFORM::UI::IsWindowActive( frame ) )
486 return;
487
488 if( wxWindow* canvas = frame->GetToolCanvas() )
489 canvas->SetFocus();
490 } );
491#endif
492}
493
494
495bool DIALOG_SHIM::Show( bool show )
496{
497 bool ret;
498
499 if( show )
500 {
502
503#ifndef __WINDOWS__
504 wxDialog::Raise(); // Needed on OS X and some other window managers (i.e. Unity)
505#endif
506 ret = wxDialog::Show( show );
507
508 wxRect savedDialogRect;
509 wxSize savedClientSize;
510 std::string key = m_hash_key.empty() ? getDialogKeyFromTitle( GetTitle() ) : m_hash_key;
511
512 if( COMMON_SETTINGS* settings = Pgm().GetCommonSettings() )
513 {
514 auto dlgIt = settings->CsInternals().m_dialogControlValues.find( key );
515
516 if( dlgIt != settings->CsInternals().m_dialogControlValues.end() )
517 {
518 auto geoIt = dlgIt->second.find( "__geometry" );
519
520 if( geoIt != dlgIt->second.end() && geoIt->second.is_object() )
521 {
522 const nlohmann::json& g = geoIt->second;
523 savedDialogRect.SetPosition( wxPoint( g.value( "x", 0 ), g.value( "y", 0 ) ) );
524 savedDialogRect.SetSize( wxSize( g.value( "w", 500 ), g.value( "h", 300 ) ) );
525 savedClientSize = wxSize( g.value( "cw", 0 ), g.value( "ch", 0 ) );
526 }
527 }
528 }
529
530 if( savedDialogRect.GetSize().x != 0 && savedDialogRect.GetSize().y != 0 )
531 {
532 // Convert saved DIP size to logical pixels for the current monitor
533 wxSize restoredSize = FromDIP( savedDialogRect.GetSize() );
534
535 if( m_useCalculatedSize || ( GetWindowStyleFlag() & wxRESIZE_BORDER ) == 0 )
536 {
537 SetSize( savedDialogRect.GetPosition().x, savedDialogRect.GetPosition().y,
538 wxDialog::GetSize().x, wxDialog::GetSize().y, 0 );
539 }
540 else
541 {
542 // GTK may not know the decorations of a process's first window yet, so a frame size
543 // restored there lands as the client size and the dialog grows on every open
544 if( savedClientSize.x > 0 && savedClientSize.y > 0 )
545 {
546 Move( savedDialogRect.GetPosition() );
547
548 wxSize restoredClient = FromDIP( savedClientSize );
549 SetClientSize( std::max( wxDialog::GetClientSize().x, restoredClient.x ),
550 std::max( wxDialog::GetClientSize().y, restoredClient.y ) );
551 }
552 else
553 {
554 SetSize( savedDialogRect.GetPosition().x, savedDialogRect.GetPosition().y,
555 std::max( wxDialog::GetSize().x, restoredSize.x ),
556 std::max( wxDialog::GetSize().y, restoredSize.y ), 0 );
557 }
558
559 // Reset minimum size so the user can resize the dialog smaller than
560 // the saved size. We must clear the current minimum and invalidate
561 // the cached best size so GetBestSize() returns the true sizer
562 // minimum rather than being constrained by the restored size.
563 SetMinSize( wxDefaultSize );
564 InvalidateBestSize();
565 SetMinSize( GetBestSize() );
566 }
567
568#ifdef __WXMAC__
569 if( m_parent != nullptr )
570 {
571 if( wxDisplay::GetFromPoint( m_parent->GetPosition() )
572 != wxDisplay::GetFromPoint( savedDialogRect.GetPosition() ) )
573 {
574 Centre();
575 }
576 }
577#endif
578
580 }
581 else if( m_initialSize != wxDefaultSize )
582 {
583 SetSize( m_initialSize );
584 Centre();
585
587 }
588
589 // Re-center if the title bar would land on no display. Testing a point inside the title
590 // bar (not the window corner) ignores the negative border offset of maximized windows.
591 wxPoint grabPoint = GetPosition();
592 grabPoint.x += GetSize().x / 2;
593 grabPoint.y += FromDIP( 15 );
594
595 if( wxDisplay::GetFromPoint( grabPoint ) == wxNOT_FOUND )
596 Centre();
597
598 m_userPositioned = false;
599 m_userResized = false;
600
601 // Cap size and pull the dialog back on-screen here, after the minimum has been
602 // (re)established above, so the clamp is not overwritten.
604 }
605 else
606 {
607
608#ifdef __WXMAC__
609 if ( m_eventLoop )
610 m_eventLoop->Exit( GetReturnCode() ); // Needed for APP-MODAL dlgs on OSX
611#endif
612
613 // Controls settle on the focus loss that hiding sends, but the restorable position needs a mapped window
614 std::optional<wxPoint> position;
615
616 if( IsShown() )
617 position = KIPLATFORM::UI::GetRestorablePosition( this );
618
619 ret = wxDialog::Show( show );
620
621 SaveControlState( position );
623 }
624
625 return ret;
626}
627
628
630{
631 if( COMMON_SETTINGS* settings = Pgm().GetCommonSettings() )
632 {
633 std::string key = m_hash_key.empty() ? getDialogKeyFromTitle( GetTitle() ) : m_hash_key;
634
635 auto dlgIt = settings->CsInternals().m_dialogControlValues.find( key );
636
637 if( dlgIt == settings->CsInternals().m_dialogControlValues.end() )
638 return;
639
640 dlgIt->second.erase( "__geometry" );
641 }
642}
643
644
645void DIALOG_SHIM::OnSize( wxSizeEvent& aEvent )
646{
647 m_userResized = true;
648 aEvent.Skip();
649}
650
651
652void DIALOG_SHIM::OnMove( wxMoveEvent& aEvent )
653{
654 m_userPositioned = true;
655
656#ifdef __WXMAC__
657 if( m_parent )
658 {
659 int parentDisplay = wxDisplay::GetFromWindow( m_parent );
660 int myDisplay = wxDisplay::GetFromWindow( this );
661
662 if( parentDisplay != wxNOT_FOUND && myDisplay != wxNOT_FOUND )
663 {
664 if( myDisplay != parentDisplay && !m_childReleased )
665 {
666 // Moving to different monitor - release child relationship
668 m_childReleased = true;
669 }
670 else if( myDisplay == parentDisplay && m_childReleased )
671 {
672 // Back on same monitor - restore child relationship
674 m_childReleased = false;
675 }
676 }
677 }
678#endif
679
680 aEvent.Skip();
681}
682
683
684bool DIALOG_SHIM::Enable( bool enable )
685{
686 // so we can do logging of this state change:
687 return wxDialog::Enable( enable );
688}
689
690
691std::string DIALOG_SHIM::generateKey( const wxWindow* aWin ) const
692{
693 auto getSiblingIndex =
694 []( const wxWindow* parent, const wxWindow* child )
695 {
696 wxString childClass = child->GetClassInfo()->GetClassName();
697 int index = 0;
698
699 for( const wxWindow* sibling : parent->GetChildren() )
700 {
701 if( sibling->GetClassInfo()->GetClassName() != childClass )
702 continue;
703
704 if( sibling == child )
705 break;
706
707 index++;
708 }
709
710 return index;
711 };
712
713 auto makeKey =
714 [&]( const wxWindow* window )
715 {
716 std::string key = wxString( window->GetClassInfo()->GetClassName() ).ToStdString();
717
718 if( window->GetParent() )
719 key += "_" + std::to_string( getSiblingIndex( window->GetParent(), window ) );
720
721 return key;
722 };
723
724 std::string key = makeKey( aWin );
725
726 for( const wxWindow* parent = aWin->GetParent(); parent && parent != this; parent = parent->GetParent() )
727 key = makeKey( parent ) + key;
728
729 return key;
730}
731
732
733void DIALOG_SHIM::SaveControlState( const std::optional<wxPoint>& aPosition )
734{
735 COMMON_SETTINGS* settings = Pgm().GetCommonSettings();
736
737 if( !settings )
738 return;
739
740 std::string dialogKey = m_hash_key.empty() ? getDialogKeyFromTitle( GetTitle() ) : m_hash_key;
741 std::map<std::string, nlohmann::json>& dlgMap = settings->CsInternals().m_dialogControlValues[ dialogKey ];
742
743 // A hidden GTK dialog reports its frame origin, which static gravity would restore off by the decorations
744 if( aPosition || IsShown() )
745 {
746 wxPoint pos = aPosition ? *aPosition : KIPLATFORM::UI::GetRestorablePosition( this );
747 wxSize dipSize = ToDIP( GetSize() );
748 wxSize dipClientSize = ToDIP( GetClientSize() );
749 nlohmann::json geom;
750 geom[ "x" ] = pos.x;
751 geom[ "y" ] = pos.y;
752 geom[ "w" ] = dipSize.x;
753 geom[ "h" ] = dipSize.y;
754 geom[ "cw" ] = dipClientSize.x;
755 geom[ "ch" ] = dipClientSize.y;
756 dlgMap[ "__geometry" ] = geom;
757 }
758
759 std::function<void( wxWindow* )> saveFn =
760 [&]( wxWindow* win )
761 {
762 if( PROPERTY_HOLDER* props = PROPERTY_HOLDER::SafeCast( win->GetClientData() ) )
763 {
764 if( !props->GetPropertyOr( "persist", false ) )
765 return;
766 }
767
768 if( isCompoundDateTimePicker( win ) )
769 return;
770
771 std::string key = generateKey( win );
772
773 if( !key.empty() )
774 {
775 UNIT_BINDER* binder = m_unitBinders.contains( win ) ? m_unitBinders[ win ] : nullptr;
776 wxString formula = binder ? binder->GetFormula() : wxString();
777
778 if( binder && !binder->UnitsInvariant() )
779 {
780 // The value survives a change of units while the expression does not, so
781 // the value is always stored and the expression rides along with it.
782 if( formula.IsEmpty() )
783 {
784 dlgMap[ key ] = binder->GetValue();
785 }
786 else
787 {
788 nlohmann::json state;
789 state[ "value" ] = binder->GetValue();
790 state[ "formula" ] = formula;
791 dlgMap[ key ] = state;
792 }
793 }
794 else if( !formula.IsEmpty() )
795 {
796 dlgMap[ key ] = formula;
797 }
798 else if( TEXT_CTRL_EVAL* evalCtrl = binder ? nullptr : dynamic_cast<TEXT_CTRL_EVAL*>( win ) )
799 {
800 dlgMap[ key ] = evalCtrl->GetFormula();
801 }
802 else if( wxComboBox* combo = dynamic_cast<wxComboBox*>( win ) )
803 {
804 dlgMap[ key ] = combo->GetValue();
805 }
806 else if( wxOwnerDrawnComboBox* od_combo = dynamic_cast<wxOwnerDrawnComboBox*>( win ) )
807 {
808 dlgMap[ key ] = od_combo->GetSelection();
809 }
810 else if( wxSpinCtrl* spin = dynamic_cast<wxSpinCtrl*>( win ) )
811 {
812 dlgMap[ key ] = spin->GetValue();
813 }
814 else if( wxSpinCtrlDouble* spinDouble = dynamic_cast<wxSpinCtrlDouble*>( win ) )
815 {
816 dlgMap[ key ] = spinDouble->GetValue();
817 }
818 else if( wxTextEntry* textEntry = dynamic_cast<wxTextEntry*>( win ) )
819 {
820 dlgMap[ key ] = textEntry->GetValue();
821 }
822 else if( wxChoice* choice = dynamic_cast<wxChoice*>( win ) )
823 {
824 dlgMap[ key ] = choice->GetSelection();
825 }
826 else if( wxCheckBox* check = dynamic_cast<wxCheckBox*>( win ) )
827 {
828 dlgMap[ key ] = check->GetValue();
829 }
830 else if( wxRadioButton* radio = dynamic_cast<wxRadioButton*>( win ) )
831 {
832 dlgMap[ key ] = radio->GetValue();
833 }
834 else if( wxRadioBox* radioBox = dynamic_cast<wxRadioBox*>( win ) )
835 {
836 dlgMap[ key ] = radioBox->GetSelection();
837 }
838 else if( wxSplitterWindow* splitter = dynamic_cast<wxSplitterWindow*>( win ) )
839 {
840 // An unsplit sash is meaningless, so keep the one saved while split
841 if( splitter->IsSplit() )
842 dlgMap[ key ] = splitter->GetSashPosition();
843 }
844 else if( wxScrolledWindow* scrolled = dynamic_cast<wxScrolledWindow*>( win ) )
845 {
846 dlgMap[ key ] = scrolled->GetScrollPos( wxVERTICAL );
847 }
848 else if( wxNotebook* notebook = dynamic_cast<wxNotebook*>( win ) )
849 {
850 int index = notebook->GetSelection();
851
852 if( index >= 0 && index < (int) notebook->GetPageCount() )
853 dlgMap[ key ] = notebook->GetPageText( notebook->GetSelection() );
854 }
855 else if( wxAuiNotebook* auiNotebook = dynamic_cast<wxAuiNotebook*>( win ) )
856 {
857 int index = auiNotebook->GetSelection();
858
859 if( index >= 0 && index < (int) auiNotebook->GetPageCount() )
860 dlgMap[ key ] = auiNotebook->GetPageText( auiNotebook->GetSelection() );
861 }
862 else if( WX_GRID* grid = dynamic_cast<WX_GRID*>( win ) )
863 {
864 dlgMap[ key ] = grid->GetShownColumnsAsString();
865 }
866 }
867
868 for( wxWindow* child : win->GetChildren() )
869 saveFn( child );
870 };
871
872 if( PROPERTY_HOLDER* props = PROPERTY_HOLDER::SafeCast( GetClientData() ) )
873 {
874 if( !props->GetPropertyOr( "persist", false ) )
875 return;
876 }
877
878 for( wxWindow* child : GetChildren() )
879 saveFn( child );
880}
881
882
884{
885 COMMON_SETTINGS* settings = Pgm().GetCommonSettings();
886
887 if( !settings )
888 return;
889
890 std::string dialogKey = m_hash_key.empty() ? getDialogKeyFromTitle( GetTitle() ) : m_hash_key;
891 auto dlgIt = settings->CsInternals().m_dialogControlValues.find( dialogKey );
892
893 if( dlgIt == settings->CsInternals().m_dialogControlValues.end() )
894 return;
895
896 const std::map<std::string, nlohmann::json>& dlgMap = dlgIt->second;
897
898 std::function<void( wxWindow* )> loadFn =
899 [&]( wxWindow* win )
900 {
901 if( PROPERTY_HOLDER* props = PROPERTY_HOLDER::SafeCast( win->GetClientData() ) )
902 {
903 if( !props->GetPropertyOr( "persist", false ) )
904 return;
905 }
906
907 if( isCompoundDateTimePicker( win ) )
908 return;
909
910 std::string key = generateKey( win );
911
912 if( !key.empty() )
913 {
914 auto it = dlgMap.find( key );
915
916 if( it != dlgMap.end() )
917 {
918 const nlohmann::json& j = it->second;
919
920 if( m_unitBinders.contains( win ) )
921 {
922 UNIT_BINDER* binder = m_unitBinders[ win ];
923
924 if( j.is_number_integer() )
925 {
926 binder->ChangeValue( j.get<int>() );
927 }
928 else if( j.is_object() && j.contains( "value" ) && j[ "value" ].is_number_integer() )
929 {
930 wxString formula;
931
932 if( j.contains( "formula" ) && j[ "formula" ].is_string() )
933 formula = wxString::FromUTF8( j[ "formula" ].get<std::string>().c_str() );
934
935 binder->RestoreValue( j[ "value" ].get<int>(), formula );
936 }
937 else if( j.is_string() )
938 {
939 wxString text = wxString::FromUTF8( j.get<std::string>().c_str() );
940
941 if( !binder->RestoreFormula( text ) )
942 {
943 if( wxTextEntry* textEntry = dynamic_cast<wxTextEntry*>( win ) )
944 textEntry->ChangeValue( text );
945 }
946 }
947 }
948 else if( TEXT_CTRL_EVAL* evalCtrl = dynamic_cast<TEXT_CTRL_EVAL*>( win ) )
949 {
950 if( j.is_string() )
951 {
952 wxString text = wxString::FromUTF8( j.get<std::string>().c_str() );
953
954 if( !evalCtrl->RestoreFormula( text ) )
955 evalCtrl->ChangeValue( text );
956 }
957 }
958 else if( wxComboBox* combo = dynamic_cast<wxComboBox*>( win ) )
959 {
960 if( j.is_string() )
961 combo->SetValue( wxString::FromUTF8( j.get<std::string>().c_str() ) );
962 }
963 else if( wxOwnerDrawnComboBox* od_combo = dynamic_cast<wxOwnerDrawnComboBox*>( win ) )
964 {
965 if( j.is_number_integer() )
966 {
967 int index = j.get<int>();
968
969 if( index >= 0 && index < (int) od_combo->GetCount() )
970 od_combo->SetSelection( index );
971 }
972 }
973 else if( wxSpinCtrl* spin = dynamic_cast<wxSpinCtrl*>( win ) )
974 {
975 if( j.is_number_integer() )
976 spin->SetValue( j.get<int>() );
977 }
978 else if( wxSpinCtrlDouble* spinDouble = dynamic_cast<wxSpinCtrlDouble*>( win ) )
979 {
980 if( j.is_number() )
981 spinDouble->SetValue( j.get<double>() );
982 }
983 else if( wxTextEntry* textEntry = dynamic_cast<wxTextEntry*>( win ) )
984 {
985 if( j.is_string() )
986 textEntry->ChangeValue( wxString::FromUTF8( j.get<std::string>().c_str() ) );
987 }
988 else if( wxChoice* choice = dynamic_cast<wxChoice*>( win ) )
989 {
990 if( j.is_number_integer() )
991 {
992 int index = j.get<int>();
993
994 if( index >= 0 && index < (int) choice->GetCount() )
995 choice->SetSelection( index );
996 }
997 }
998 else if( wxCheckBox* check = dynamic_cast<wxCheckBox*>( win ) )
999 {
1000 if( j.is_boolean() )
1001 check->SetValue( j.get<bool>() );
1002 }
1003 else if( wxRadioButton* radio = dynamic_cast<wxRadioButton*>( win ) )
1004 {
1005 if( j.is_boolean() )
1006 {
1007 // Only set active radio buttons. Let wxWidgets handle unsetting the inactive
1008 // ones. This prevents all from being unset, which trips up wxWidgets in some
1009 // cases.
1010 if( j.get<bool>() )
1011 radio->SetValue( true );
1012 }
1013 }
1014 else if( wxRadioBox* radioBox = dynamic_cast<wxRadioBox*>( win ) )
1015 {
1016 if( j.is_number_integer() )
1017 {
1018 int index = j.get<int>();
1019
1020 if( index >= 0 && index < (int) radioBox->GetCount() )
1021 radioBox->SetSelection( index );
1022 }
1023 }
1024 else if( wxSplitterWindow* splitter = dynamic_cast<wxSplitterWindow*>( win ) )
1025 {
1026 if( j.is_number_integer() )
1027 splitter->SetSashPosition( j.get<int>() );
1028 }
1029 else if( wxScrolledWindow* scrolled = dynamic_cast<wxScrolledWindow*>( win ) )
1030 {
1031 if( j.is_number_integer() )
1032 scrolled->SetScrollPos( wxVERTICAL, j.get<int>() );
1033 }
1034 else if( wxNotebook* notebook = dynamic_cast<wxNotebook*>( win ) )
1035 {
1036 if( j.is_string() )
1037 {
1038 wxString pageTitle = wxString::FromUTF8( j.get<std::string>().c_str() );
1039
1040 for( int page = 0; page < (int) notebook->GetPageCount(); ++page )
1041 {
1042 if( notebook->GetPageText( page ) == pageTitle )
1043 notebook->ChangeSelection( page );
1044 }
1045 }
1046 }
1047 else if( wxAuiNotebook* auiNotebook = dynamic_cast<wxAuiNotebook*>( win ) )
1048 {
1049 if( j.is_string() )
1050 {
1051 wxString pageTitle = wxString::FromUTF8( j.get<std::string>().c_str() );
1052
1053 for( int page = 0; page < (int) auiNotebook->GetPageCount(); ++page )
1054 {
1055 if( auiNotebook->GetPageText( page ) == pageTitle )
1056 auiNotebook->ChangeSelection( page );
1057 }
1058 }
1059 }
1060 else if( WX_GRID* grid = dynamic_cast<WX_GRID*>( win ) )
1061 {
1062 if( j.is_string() )
1063 grid->ShowHideColumns( wxString::FromUTF8( j.get<std::string>().c_str() ) );
1064 }
1065 }
1066 }
1067
1068 for( wxWindow* child : win->GetChildren() )
1069 loadFn( child );
1070 };
1071
1072 if( PROPERTY_HOLDER* props = PROPERTY_HOLDER::SafeCast( GetClientData() ) )
1073 {
1074 if( !props->GetPropertyOr( "persist", false ) )
1075 return;
1076 }
1077
1078 for( wxWindow* child : GetChildren() )
1079 loadFn( child );
1080}
1081
1082
1084{
1085 COMMON_SETTINGS* settings = Pgm().GetCommonSettings();
1086
1087 if( !settings )
1088 return;
1089
1090 std::string dialogKey = m_hash_key.empty() ? getDialogKeyFromTitle( GetTitle() ) : m_hash_key;
1091 auto dlgIt = settings->CsInternals().m_dialogControlValues.find( dialogKey );
1092
1093 if( dlgIt == settings->CsInternals().m_dialogControlValues.end() )
1094 return;
1095
1096 const std::map<std::string, nlohmann::json>& dlgMap = dlgIt->second;
1097
1098 std::function<void( wxWindow* )> loadFn =
1099 [&]( wxWindow* win )
1100 {
1101 if( PROPERTY_HOLDER* props = PROPERTY_HOLDER::SafeCast( win->GetClientData() ) )
1102 {
1103 if( !props->GetPropertyOr( "persist", false ) )
1104 return;
1105 }
1106
1107 std::string key = generateKey( win );
1108
1109 if( !key.empty() )
1110 {
1111 auto it = dlgMap.find( key );
1112
1113 if( it != dlgMap.end() )
1114 {
1115 const nlohmann::json& j = it->second;
1116
1117 if( wxSplitterWindow* splitter = dynamic_cast<wxSplitterWindow*>( win ) )
1118 {
1119 if( j.is_number_integer() )
1120 splitter->SetSashPosition( j.get<int>() );
1121 }
1122 }
1123 }
1124
1125 for( wxWindow* child : win->GetChildren() )
1126 loadFn( child );
1127 };
1128
1129 if( PROPERTY_HOLDER* props = PROPERTY_HOLDER::SafeCast( GetClientData() ) )
1130 {
1131 if( !props->GetPropertyOr( "persist", false ) )
1132 return;
1133 }
1134
1135 for( wxWindow* child : GetChildren() )
1136 loadFn( child );
1137}
1138
1139
1140void DIALOG_SHIM::OptOut( wxWindow* aWindow )
1141{
1142 PROPERTY_HOLDER* props = new PROPERTY_HOLDER();
1143 props->SetProperty( "persist", false );
1144 aWindow->SetClientData( props );
1145
1146 if( aWindow == this )
1147 {
1148 COMMON_SETTINGS* settings = Pgm().GetCommonSettings();
1149
1150 if( settings )
1151 {
1152 std::string dialogKey = m_hash_key.empty() ? getDialogKeyFromTitle( GetTitle() ) : m_hash_key;
1153 auto dlgIt = settings->CsInternals().m_dialogControlValues.find( dialogKey );
1154
1155 if( dlgIt != settings->CsInternals().m_dialogControlValues.end() )
1156 {
1157 std::erase_if( dlgIt->second,
1158 []( const auto& aEntry )
1159 {
1160 return aEntry.first != "__geometry";
1161 } );
1162 }
1163 }
1164 }
1165}
1166
1167
1169{
1170 m_noControlUndoRedo.insert( aWindow );
1171}
1172
1173
1174void DIALOG_SHIM::RegisterUnitBinder( UNIT_BINDER* aUnitBinder, wxWindow* aWindow )
1175{
1176 m_unitBinders[ aWindow ] = aUnitBinder;
1177}
1178
1179
1181{
1182 // Erase by binder identity rather than window key, so that a stale entry whose window has
1183 // already been reused by a newer binder is left untouched.
1184 std::erase_if( m_unitBinders,
1185 [aUnitBinder]( const auto& aEntry )
1186 {
1187 return aEntry.second == aUnitBinder;
1188 } );
1189}
1190
1191
1192// Recursive descent doing a SelectAll() in wxTextCtrls.
1193// MacOS User Interface Guidelines state that when tabbing to a text control all its
1194// text should be selected. Since wxWidgets fails to implement this, we do it here.
1195void DIALOG_SHIM::SelectAllInTextCtrls( wxWindowList& children )
1196{
1197 for( wxWindow* child : children )
1198 {
1199 if( isCompoundDateTimePicker( child ) )
1200 continue;
1201
1202 if( wxTextCtrl* textCtrl = dynamic_cast<wxTextCtrl*>( child ) )
1203 {
1204 m_beforeEditValues[ textCtrl ] = textCtrl->GetValue();
1205 textCtrl->Connect( wxEVT_SET_FOCUS, wxFocusEventHandler( DIALOG_SHIM::onChildSetFocus ),
1206 nullptr, this );
1207
1208 // We don't currently run this on GTK because some window managers don't hide the
1209 // selection in non-active controls, and other window managers do the selection
1210 // automatically anyway.
1211#if defined( __WXMAC__ ) || defined( __WXMSW__ )
1212 if( !textCtrl->GetStringSelection().IsEmpty() )
1213 {
1214 // Respect an existing selection
1215 }
1216 else if( textCtrl->IsEditable() )
1217 {
1218 textCtrl->SelectAll();
1219 }
1220#else
1221 ignore_unused( textCtrl );
1222#endif
1223 }
1224 else if( wxStyledTextCtrl* scintilla = dynamic_cast<wxStyledTextCtrl*>( child ) )
1225 {
1226 m_beforeEditValues[ scintilla ] = scintilla->GetText();
1227 scintilla->Connect( wxEVT_SET_FOCUS,
1228 wxFocusEventHandler( DIALOG_SHIM::onChildSetFocus ),
1229 nullptr, this );
1230
1231 if( !scintilla->GetSelectedText().IsEmpty() )
1232 {
1233 // Respect an existing selection
1234 }
1235 else if( scintilla->GetMarginWidth( 0 ) > 0 )
1236 {
1237 // Don't select-all in Custom Rules, etc.
1238 }
1239 else if( scintilla->IsEditable() )
1240 {
1241 scintilla->SelectAll();
1242 }
1243 }
1244#ifdef __WXMAC__
1245 // Temp hack for square (looking) buttons on OSX. Will likely be made redundant
1246 // by the image store....
1247 else if( dynamic_cast<wxBitmapButton*>( child ) != nullptr )
1248 {
1249 wxSize minSize( 29, 27 );
1250 wxRect rect = child->GetRect();
1251
1252 child->ConvertDialogToPixels( minSize );
1253
1254 rect.Inflate( std::max( 0, minSize.x - rect.GetWidth() ),
1255 std::max( 0, minSize.y - rect.GetHeight() ) );
1256
1257 child->SetMinSize( rect.GetSize() );
1258 child->SetSize( rect );
1259 }
1260#endif
1261 else
1262 {
1263 SelectAllInTextCtrls( child->GetChildren() );
1264 }
1265 }
1266}
1267
1268
1269void DIALOG_SHIM::registerUndoRedoHandlers( wxWindowList& children )
1270{
1271 for( wxWindow* child : children )
1272 {
1273 if( m_noControlUndoRedo.count( child ) )
1274 continue;
1275
1276 if( isCompoundDateTimePicker( child ) )
1277 continue;
1278
1279 if( wxTextCtrl* textCtrl = dynamic_cast<wxTextCtrl*>( child ) )
1280 {
1281 textCtrl->Bind( wxEVT_TEXT, &DIALOG_SHIM::onCommandEvent, this );
1282 m_currentValues[ textCtrl ] = textCtrl->GetValue();
1283 }
1284 else if( wxStyledTextCtrl* scintilla = dynamic_cast<wxStyledTextCtrl*>( child ) )
1285 {
1286 scintilla->Bind( wxEVT_STC_CHANGE, &DIALOG_SHIM::onStyledTextChanged, this );
1287 m_currentValues[ scintilla ] = scintilla->GetText();
1288 }
1289 else if( wxComboBox* combo = dynamic_cast<wxComboBox*>( child ) )
1290 {
1291 combo->Bind( wxEVT_TEXT, &DIALOG_SHIM::onCommandEvent, this );
1292 combo->Bind( wxEVT_COMBOBOX, &DIALOG_SHIM::onCommandEvent, this );
1293 m_currentValues[ combo ] = combo->GetValue();
1294 }
1295 else if( wxChoice* choice = dynamic_cast<wxChoice*>( child ) )
1296 {
1297 choice->Bind( wxEVT_CHOICE, &DIALOG_SHIM::onCommandEvent, this );
1298 m_currentValues[ choice ] = static_cast<long>( choice->GetSelection() );
1299 }
1300 else if( wxCheckBox* check = dynamic_cast<wxCheckBox*>( child ) )
1301 {
1302 check->Bind( wxEVT_CHECKBOX, &DIALOG_SHIM::onCommandEvent, this );
1303 m_currentValues[ check ] = check->GetValue();
1304 }
1305 else if( wxSpinCtrl* spin = dynamic_cast<wxSpinCtrl*>( child ) )
1306 {
1307 spin->Bind( wxEVT_SPINCTRL, &DIALOG_SHIM::onSpinEvent, this );
1308 spin->Bind( wxEVT_TEXT, &DIALOG_SHIM::onCommandEvent, this );
1309 m_currentValues[ spin ] = static_cast<long>( spin->GetValue() );
1310 }
1311 else if( wxSpinCtrlDouble* spinD = dynamic_cast<wxSpinCtrlDouble*>( child ) )
1312 {
1313 spinD->Bind( wxEVT_SPINCTRLDOUBLE, &DIALOG_SHIM::onSpinDoubleEvent, this );
1314 spinD->Bind( wxEVT_TEXT, &DIALOG_SHIM::onCommandEvent, this );
1315 m_currentValues[ spinD ] = spinD->GetValue();
1316 }
1317 else if( wxRadioButton* radio = dynamic_cast<wxRadioButton*>( child ) )
1318 {
1319 radio->Bind( wxEVT_RADIOBUTTON, &DIALOG_SHIM::onCommandEvent, this );
1320 m_currentValues[ radio ] = radio->GetValue();
1321 }
1322 else if( wxRadioBox* radioBox = dynamic_cast<wxRadioBox*>( child ) )
1323 {
1324 radioBox->Bind( wxEVT_RADIOBOX, &DIALOG_SHIM::onCommandEvent, this );
1325 m_currentValues[ radioBox ] = static_cast<long>( radioBox->GetSelection() );
1326 }
1327 else if( wxGrid* grid = dynamic_cast<wxGrid*>( child ) )
1328 {
1329 grid->Bind( wxEVT_GRID_CELL_CHANGED, &DIALOG_SHIM::onGridCellChanged, this );
1331 }
1332 else if( wxPropertyGrid* propGrid = dynamic_cast<wxPropertyGrid*>( child ) )
1333 {
1334 propGrid->Bind( wxEVT_PG_CHANGED, &DIALOG_SHIM::onPropertyGridChanged, this );
1335 m_currentValues[ propGrid ] = getControlValue( propGrid );
1336 }
1337 else if( wxCheckListBox* checkList = dynamic_cast<wxCheckListBox*>( child ) )
1338 {
1339 checkList->Bind( wxEVT_CHECKLISTBOX, &DIALOG_SHIM::onCommandEvent, this );
1340 m_currentValues[ checkList ] = getControlValue( checkList );
1341 }
1342 else if( wxDataViewListCtrl* dataList = dynamic_cast<wxDataViewListCtrl*>( child ) )
1343 {
1344 dataList->Bind( wxEVT_DATAVIEW_ITEM_VALUE_CHANGED, &DIALOG_SHIM::onDataViewListChanged, this );
1345 m_currentValues[ dataList ] = getControlValue( dataList );
1346 }
1347 else
1348 {
1349 registerUndoRedoHandlers( child->GetChildren() );
1350 }
1351 }
1352}
1353
1354
1356{
1357 // If we are in an event handler that generates lots of events (e.g. cutting
1358 // a range of cells in a grid), we want to coalesce all of those events into a
1359 // single undo commit.
1360 //
1361 // So what we'll do is collect all of the controls that have changes,
1362 // and enqueue a single call to flushPendingControlChanges() to be called after the
1363 // current event handler (which is calling this function) has finished.
1364
1365 const auto [it, inserted] = m_controlsWithPendingChanges.insert( aCtrl );
1366
1367 if( !inserted )
1368 return;
1369
1370 if( m_controlsWithPendingChanges.size() == 1 )
1372}
1373
1374
1376{
1377 for( wxWindow* const ctrl : m_controlsWithPendingChanges )
1378 {
1379 wxVariant before = m_currentValues[ctrl];
1380 wxVariant after = getControlValue( ctrl );
1381
1382 if( before != after )
1383 {
1384 // Note this still produces an undo/redo entry per control,
1385 // even if changed within a control are combined.
1386 // If an event causes a multi-control change, the user will
1387 // still have to hit undo multiple times to get back to the
1388 // original state.`
1389 m_undoStack.push_back( { ctrl, before, after } );
1390 m_redoStack.clear();
1391 m_currentValues[ctrl] = after;
1392 }
1393 }
1394
1396}
1397
1398
1399void DIALOG_SHIM::onCommandEvent( wxCommandEvent& aEvent )
1400{
1401 if( !m_handlingUndoRedo )
1402 recordControlChange( static_cast<wxWindow*>( aEvent.GetEventObject() ) );
1403
1404 aEvent.Skip();
1405}
1406
1407
1408void DIALOG_SHIM::onSpinEvent( wxSpinEvent& aEvent )
1409{
1410 if( !m_handlingUndoRedo )
1411 recordControlChange( static_cast<wxWindow*>( aEvent.GetEventObject() ) );
1412
1413 aEvent.Skip();
1414}
1415
1416
1417void DIALOG_SHIM::onSpinDoubleEvent( wxSpinDoubleEvent& aEvent )
1418{
1419 if( !m_handlingUndoRedo )
1420 recordControlChange( static_cast<wxWindow*>( aEvent.GetEventObject() ) );
1421
1422 aEvent.Skip();
1423}
1424
1425
1426void DIALOG_SHIM::onStyledTextChanged( wxStyledTextEvent& aEvent )
1427{
1428 if( !m_handlingUndoRedo )
1429 recordControlChange( static_cast<wxWindow*>( aEvent.GetEventObject() ) );
1430
1431 aEvent.Skip();
1432}
1433
1434
1435void DIALOG_SHIM::onGridCellChanged( wxGridEvent& aEvent )
1436{
1437 if( !m_handlingUndoRedo )
1438 recordControlChange( static_cast<wxWindow*>( aEvent.GetEventObject() ) );
1439
1440 aEvent.Skip();
1441}
1442
1443void DIALOG_SHIM::onPropertyGridChanged( wxPropertyGridEvent& aEvent )
1444{
1445 if( !m_handlingUndoRedo )
1446 recordControlChange( static_cast<wxWindow*>( aEvent.GetEventObject() ) );
1447
1448 aEvent.Skip();
1449}
1450
1451void DIALOG_SHIM::onDataViewListChanged( wxDataViewEvent& aEvent )
1452{
1453 if( !m_handlingUndoRedo )
1454 recordControlChange( static_cast<wxWindow*>( aEvent.GetEventObject() ) );
1455
1456 aEvent.Skip();
1457}
1458
1459wxVariant DIALOG_SHIM::getControlValue( wxWindow* aCtrl )
1460{
1461 if( wxTextCtrl* textCtrl = dynamic_cast<wxTextCtrl*>( aCtrl ) )
1462 return wxVariant( textCtrl->GetValue() );
1463 else if( wxStyledTextCtrl* scintilla = dynamic_cast<wxStyledTextCtrl*>( aCtrl ) )
1464 return wxVariant( scintilla->GetText() );
1465 else if( wxComboBox* combo = dynamic_cast<wxComboBox*>( aCtrl ) )
1466 return wxVariant( combo->GetValue() );
1467 else if( wxChoice* choice = dynamic_cast<wxChoice*>( aCtrl ) )
1468 return wxVariant( (long) choice->GetSelection() );
1469 else if( wxCheckBox* check = dynamic_cast<wxCheckBox*>( aCtrl ) )
1470 return wxVariant( check->GetValue() );
1471 else if( wxSpinCtrl* spin = dynamic_cast<wxSpinCtrl*>( aCtrl ) )
1472 return wxVariant( (long) spin->GetValue() );
1473 else if( wxSpinCtrlDouble* spinD = dynamic_cast<wxSpinCtrlDouble*>( aCtrl ) )
1474 return wxVariant( spinD->GetValue() );
1475 else if( wxRadioButton* radio = dynamic_cast<wxRadioButton*>( aCtrl ) )
1476 return wxVariant( radio->GetValue() );
1477 else if( wxRadioBox* radioBox = dynamic_cast<wxRadioBox*>( aCtrl ) )
1478 return wxVariant( (long) radioBox->GetSelection() );
1479 else if( wxGrid* grid = dynamic_cast<wxGrid*>( aCtrl ) )
1480 {
1481 // Tables with regroupable/sortable rows serialize by identity instead of row position.
1482 if( auto* table = dynamic_cast<WX_GRID_TABLE_BASE*>( grid->GetTable() );
1483 table && table->HasUndoStateSerialization() )
1484 {
1485 return wxVariant( table->SerializeUndoState() );
1486 }
1487
1488 nlohmann::json j = nlohmann::json::array();
1489 int rows = grid->GetNumberRows();
1490 int cols = grid->GetNumberCols();
1491
1492 for( int r = 0; r < rows; ++r )
1493 {
1494 nlohmann::json row = nlohmann::json::array();
1495
1496 for( int c = 0; c < cols; ++c )
1497 row.push_back( std::string( grid->GetCellValue( r, c ).ToUTF8() ) );
1498
1499 j.push_back( row );
1500 }
1501
1502 return wxVariant( wxString( j.dump() ) );
1503 }
1504 else if( wxPropertyGrid* propGrid = dynamic_cast<wxPropertyGrid*>( aCtrl ) )
1505 {
1506 nlohmann::json j;
1507
1508 for( wxPropertyGridIterator it = propGrid->GetIterator(); !it.AtEnd(); ++it )
1509 {
1510 wxPGProperty* prop = *it;
1511 j[ prop->GetName().ToStdString() ] = prop->GetValueAsString().ToStdString();
1512 }
1513
1514 return wxVariant( wxString( j.dump() ) );
1515 }
1516 else if( wxCheckListBox* checkList = dynamic_cast<wxCheckListBox*>( aCtrl ) )
1517 {
1518 nlohmann::json j = nlohmann::json::array();
1519 unsigned int count = checkList->GetCount();
1520
1521 for( unsigned int i = 0; i < count; ++i )
1522 {
1523 if( checkList->IsChecked( i ) )
1524 j.push_back( i );
1525 }
1526
1527 return wxVariant( wxString( j.dump() ) );
1528 }
1529 else if( wxDataViewListCtrl* dataList = dynamic_cast<wxDataViewListCtrl*>( aCtrl ) )
1530 {
1531 nlohmann::json j = nlohmann::json::array();
1532 unsigned int rows = dataList->GetItemCount();
1533 unsigned int cols = dataList->GetColumnCount();
1534
1535 for( unsigned int r = 0; r < rows; ++r )
1536 {
1537 nlohmann::json row = nlohmann::json::array();
1538
1539 for( unsigned int c = 0; c < cols; ++c )
1540 {
1541 wxVariant val;
1542 dataList->GetValue( val, r, c );
1543 row.push_back( std::string( val.GetString().ToUTF8() ) );
1544 }
1545
1546 j.push_back( row );
1547 }
1548
1549 return wxVariant( wxString( j.dump() ) );
1550 }
1551 else
1552 return wxVariant();
1553}
1554
1555
1556void DIALOG_SHIM::setControlValue( wxWindow* aCtrl, const wxVariant& aValue )
1557{
1558 if( wxTextCtrl* textCtrl = dynamic_cast<wxTextCtrl*>( aCtrl ) )
1559 textCtrl->SetValue( aValue.GetString() );
1560 else if( wxStyledTextCtrl* scintilla = dynamic_cast<wxStyledTextCtrl*>( aCtrl ) )
1561 scintilla->SetText( aValue.GetString() );
1562 else if( wxComboBox* combo = dynamic_cast<wxComboBox*>( aCtrl ) )
1563 combo->SetValue( aValue.GetString() );
1564 else if( wxChoice* choice = dynamic_cast<wxChoice*>( aCtrl ) )
1565 choice->SetSelection( (int) aValue.GetLong() );
1566 else if( wxCheckBox* check = dynamic_cast<wxCheckBox*>( aCtrl ) )
1567 check->SetValue( aValue.GetBool() );
1568 else if( wxSpinCtrl* spin = dynamic_cast<wxSpinCtrl*>( aCtrl ) )
1569 spin->SetValue( (int) aValue.GetLong() );
1570 else if( wxSpinCtrlDouble* spinD = dynamic_cast<wxSpinCtrlDouble*>( aCtrl ) )
1571 spinD->SetValue( aValue.GetDouble() );
1572 else if( wxRadioButton* radio = dynamic_cast<wxRadioButton*>( aCtrl ) )
1573 radio->SetValue( aValue.GetBool() );
1574 else if( wxRadioBox* radioBox = dynamic_cast<wxRadioBox*>( aCtrl ) )
1575 radioBox->SetSelection( (int) aValue.GetLong() );
1576 else if( wxGrid* grid = dynamic_cast<wxGrid*>( aCtrl ) )
1577 {
1578 if( auto* table = dynamic_cast<WX_GRID_TABLE_BASE*>( grid->GetTable() );
1579 table && table->HasUndoStateSerialization() )
1580 {
1581 table->RestoreUndoState( aValue.GetString() );
1582 return;
1583 }
1584
1585 nlohmann::json j = nlohmann::json::parse( aValue.GetString().ToStdString(), nullptr, false );
1586
1587 if( j.is_array() )
1588 {
1589 int rows = std::min( (int) j.size(), grid->GetNumberRows() );
1590
1591 std::vector<std::pair<int, int>> changedCells;
1592
1593 for( int r = 0; r < rows; ++r )
1594 {
1595 nlohmann::json row = j[r];
1596 int cols = std::min( (int) row.size(), grid->GetNumberCols() );
1597
1598 for( int c = 0; c < cols; ++c )
1599 {
1600 wxString value = wxString( row[c].get<std::string>() );
1601
1602 if( grid->GetCellValue( r, c ) != value )
1603 {
1604 grid->SetCellValue( r, c, value );
1605 changedCells.emplace_back( r, c );
1606 }
1607 }
1608 }
1609
1610 for( const auto& [row, col] : changedCells )
1611 {
1612 wxGridEvent evt( grid->GetId(), wxEVT_GRID_CELL_CHANGED, grid, row, col );
1613 evt.SetString( grid->GetCellValue( row, col ) );
1614 grid->GetEventHandler()->ProcessEvent( evt );
1615 }
1616 }
1617 }
1618 else if( wxPropertyGrid* propGrid = dynamic_cast<wxPropertyGrid*>( aCtrl ) )
1619 {
1620 nlohmann::json j = nlohmann::json::parse( aValue.GetString().ToStdString(), nullptr, false );
1621
1622 if( j.is_object() )
1623 {
1624 for( auto it = j.begin(); it != j.end(); ++it )
1625 propGrid->SetPropertyValue( wxString( it.key() ), wxString( it.value().get<std::string>() ) );
1626 }
1627 }
1628 else if( wxCheckListBox* checkList = dynamic_cast<wxCheckListBox*>( aCtrl ) )
1629 {
1630 nlohmann::json j = nlohmann::json::parse( aValue.GetString().ToStdString(), nullptr, false );
1631
1632 if( j.is_array() )
1633 {
1634 unsigned int count = checkList->GetCount();
1635
1636 for( unsigned int i = 0; i < count; ++i )
1637 checkList->Check( i, false );
1638
1639 for( auto& idx : j )
1640 {
1641 unsigned int i = idx.get<unsigned int>();
1642
1643 if( i < count )
1644 checkList->Check( i, true );
1645 }
1646 }
1647 }
1648 else if( wxDataViewListCtrl* dataList = dynamic_cast<wxDataViewListCtrl*>( aCtrl ) )
1649 {
1650 nlohmann::json j = nlohmann::json::parse( aValue.GetString().ToStdString(), nullptr, false );
1651
1652 if( j.is_array() )
1653 {
1654 unsigned int rows = std::min( static_cast<unsigned int>( j.size() ),
1655 static_cast<unsigned int>( dataList->GetItemCount() ) );
1656
1657 for( unsigned int r = 0; r < rows; ++r )
1658 {
1659 nlohmann::json row = j[r];
1660 unsigned int cols = std::min( (unsigned int) row.size(), dataList->GetColumnCount() );
1661
1662 for( unsigned int c = 0; c < cols; ++c )
1663 {
1664 wxVariant val( wxString( row[c].get<std::string>() ) );
1665 dataList->SetValue( val, r, c );
1666 }
1667 }
1668 }
1669 }
1670}
1671
1672
1674{
1676
1677 if( m_undoStack.empty() )
1678 return;
1679
1680 m_handlingUndoRedo = true;
1681 UNDO_STEP step = m_undoStack.back();
1682 m_undoStack.pop_back();
1683 setControlValue( step.ctrl, step.before );
1684 m_currentValues[ step.ctrl ] = step.before;
1685 m_redoStack.push_back( step );
1686 m_handlingUndoRedo = false;
1687}
1688
1689
1691{
1693
1694 if( m_redoStack.empty() )
1695 return;
1696
1697 m_handlingUndoRedo = true;
1698 UNDO_STEP step = m_redoStack.back();
1699 m_redoStack.pop_back();
1700 setControlValue( step.ctrl, step.after );
1701 m_currentValues[ step.ctrl ] = step.after;
1702 m_undoStack.push_back( step );
1703 m_handlingUndoRedo = false;
1704}
1705
1706
1707void DIALOG_SHIM::OnPaint( wxPaintEvent &event )
1708{
1709 if( m_firstPaintEvent )
1710 {
1712
1713 SelectAllInTextCtrls( GetChildren() );
1714 registerUndoRedoHandlers( GetChildren() );
1715
1717
1718 m_firstPaintEvent = false;
1719 }
1720
1721 event.Skip();
1722}
1723
1724
1726{
1727 // Skip targets that can't take focus (e.g. hidden on a notebook page) so ESC still works
1728 if( m_initialFocusTarget && m_initialFocusTarget->IsShownOnScreen()
1729 && m_initialFocusTarget->CanAcceptFocus() )
1730 {
1732 }
1733 else
1734 {
1736 }
1737}
1738
1739
1740void DIALOG_SHIM::OnActivate( wxActivateEvent& aEvent )
1741{
1742 // Null FindFocus() means focus landed on a non-wx element (WM title bar, GTK tab strip)
1743 // where ESC never reaches OnCharHook; defer via CallAfter since GTK reports null transiently
1744 if( aEvent.GetActive() && !m_firstPaintEvent )
1745 {
1746 wxWeakRef<DIALOG_SHIM> self( this );
1747
1748 CallAfter(
1749 [self]()
1750 {
1751 DIALOG_SHIM* dlg = self;
1752
1753 if( dlg && KIPLATFORM::UI::IsWindowActive( dlg )
1754 && wxWindow::FindFocus() == nullptr )
1755 {
1756 dlg->forceInitialFocus();
1757 }
1758 } );
1759 }
1760
1761 aEvent.Skip();
1762}
1763
1764
1766{
1767 if( !GetTitle().StartsWith( wxS( "*" ) ) )
1768 SetTitle( wxS( "*" ) + GetTitle() );
1769}
1770
1771
1773{
1774 if( GetTitle().StartsWith( wxS( "*" ) ) )
1775 SetTitle( GetTitle().AfterFirst( '*' ) );
1776}
1777
1779{
1781
1782 // Apple in its infinite wisdom will raise a disabled window before even passing
1783 // us the event, so we have no way to stop it. Instead, we must set an order on
1784 // the windows so that the modal will be pushed in front of the disabled
1785 // window when it is raised.
1787
1788 // Call the base class ShowModal() method
1789 return wxDialog::ShowModal();
1790}
1791
1792/*
1793 QuasiModal Mode Explained:
1794
1795 The gtk calls in wxDialog::ShowModal() cause event routing problems if that
1796 modal dialog then tries to use KIWAY_PLAYER::ShowModal(). The latter shows up
1797 and mostly works but does not respond to the window decoration close button.
1798 There is no way to get around this without reversing the gtk calls temporarily.
1799
1800 There are also issues with the Scintilla text editor putting up autocomplete
1801 popups, which appear behind the dialog window if QuasiModal is not used.
1802
1803 QuasiModal mode is our own almost modal mode which disables only the parent
1804 of the DIALOG_SHIM, leaving other frames operable and while staying captured in the
1805 nested event loop. This avoids the gtk calls and leaves event routing pure
1806 and sufficient to operate the KIWAY_PLAYER::ShowModal() properly. When using
1807 ShowQuasiModal() you have to use EndQuasiModal() in your dialogs and not
1808 EndModal(). There is also IsQuasiModal() but its value can only be true
1809 when the nested event loop is active. Do not mix the modal and quasi-modal
1810 functions. Use one set or the other.
1811
1812 You might find this behavior preferable over a pure modal mode, and it was said
1813 that only the Mac has this natively, but now other platforms have something
1814 similar. You CAN use it anywhere for any dialog. But you MUST use it when
1815 you want to use KIWAY_PLAYER::ShowModal() from a dialog event.
1816*/
1817
1819{
1820 NULLER raii_nuller( (void*&) m_qmodal_loop );
1821
1822 // release the mouse if it's currently captured as the window having it
1823 // will be disabled when this dialog is shown -- but will still keep the
1824 // capture making it impossible to do anything in the modal dialog itself
1825 if( wxWindow* win = wxWindow::GetCapture() )
1826 win->ReleaseMouse();
1827
1828 // Get the optimal parent
1829 wxWindow* parent = GetParentForModalDialog( GetParent(), GetWindowStyle() );
1830
1831 wxASSERT_MSG( !m_qmodal_parent_disabler, wxT( "Caller using ShowQuasiModal() twice on same window?" ) );
1832
1833 // quasi-modal: disable only my "optimal" parent
1835
1836 // Apple in its infinite wisdom will raise a disabled window before even passing
1837 // us the event, so we have no way to stop it. Instead, we must set an order on
1838 // the windows so that the quasi-modal will be pushed in front of the disabled
1839 // window when it is raised.
1841
1842 Show( true );
1843
1844 m_qmodal_showing = true;
1845
1846 wxGUIEventLoop event_loop;
1847
1848 m_qmodal_loop = &event_loop;
1849
1850 event_loop.Run();
1851
1852 m_qmodal_showing = false;
1853 focusParentCanvas( true );
1854
1855 return GetReturnCode();
1856}
1857
1858
1860{
1862 m_qmodal_parent_disabler->SuspendForTrueModal();
1863}
1864
1865
1867{
1869 m_qmodal_parent_disabler->ResumeAfterTrueModal();
1870}
1871
1872
1874{
1875 // Hook up validator and transfer data from controls handling so quasi-modal dialogs
1876 // handle validation in the same way as other dialogs.
1877 if( ( retCode == wxID_OK ) && ( !Validate() || !TransferDataFromWindow() ) )
1878 return;
1879
1880 SetReturnCode( retCode );
1881
1882 if( !IsQuasiModal() )
1883 {
1884 wxFAIL_MSG( wxT( "Either DIALOG_SHIM::EndQuasiModal was called twice, or ShowQuasiModal wasn't called" ) );
1885 return;
1886 }
1887
1889
1890 if( m_qmodal_loop )
1891 {
1892 if( m_qmodal_loop->IsRunning() )
1893 m_qmodal_loop->Exit( 0 );
1894 else
1895 m_qmodal_loop->ScheduleExit( 0 );
1896 }
1897
1899 m_qmodal_parent_disabler = nullptr;
1900
1901 Show( false );
1902}
1903
1904
1905void DIALOG_SHIM::OnCloseWindow( wxCloseEvent& aEvent )
1906{
1907 wxString msg = wxString::Format( "Closing dialog %s", GetTitle() );
1908 APP_MONITOR::AddNavigationBreadcrumb( msg, "dialog.close" );
1909
1911
1912 if( IsQuasiModal() )
1913 {
1914 EndQuasiModal( wxID_CANCEL );
1915 return;
1916 }
1917
1918 // This is mandatory to allow wxDialogBase::OnCloseWindow() to be called.
1919 aEvent.Skip();
1920}
1921
1922
1923void DIALOG_SHIM::OnButton( wxCommandEvent& aEvent )
1924{
1925 const int id = aEvent.GetId();
1926
1927 if( IsQuasiModal() )
1928 {
1929 if( id == GetAffirmativeId() )
1930 {
1931 EndQuasiModal( id );
1932 }
1933 else if( id == wxID_APPLY )
1934 {
1935 // Dialogs that provide Apply buttons should make sure data is valid before
1936 // allowing a transfer, as there is no other way to indicate failure
1937 // (i.e. the dialog can't refuse to close as it might with OK, because it
1938 // isn't closing anyway)
1939 if( Validate() )
1940 ignore_unused( TransferDataFromWindow() );
1941 }
1942 else if( id == wxID_CANCEL )
1943 {
1944 EndQuasiModal( wxID_CANCEL );
1945 }
1946 else // not a standard button
1947 {
1948 aEvent.Skip();
1949 }
1950
1951 return;
1952 }
1953
1954 // This is mandatory to allow wxDialogBase::OnButton() to be called.
1955 aEvent.Skip();
1956}
1957
1958
1959void DIALOG_SHIM::onChildSetFocus( wxFocusEvent& aEvent )
1960{
1961 // When setting focus to a text control reset the before-edit value.
1962
1963 if( !m_isClosing )
1964 {
1965 if( wxTextCtrl* textCtrl = dynamic_cast<wxTextCtrl*>( aEvent.GetEventObject() ) )
1966 m_beforeEditValues[ textCtrl ] = textCtrl->GetValue();
1967 else if( wxStyledTextCtrl* scintilla = dynamic_cast<wxStyledTextCtrl*>( aEvent.GetEventObject() ) )
1968 m_beforeEditValues[ scintilla ] = scintilla->GetText();
1969 }
1970
1971 aEvent.Skip();
1972}
1973
1974
1975void DIALOG_SHIM::OnCharHook( wxKeyEvent& aEvt )
1976{
1977 int key = aEvt.GetKeyCode();
1978 int mods = 0;
1979
1980 if( aEvt.ControlDown() )
1981 mods |= MD_CTRL;
1982 if( aEvt.ShiftDown() )
1983 mods |= MD_SHIFT;
1984 if( aEvt.AltDown() )
1985 mods |= MD_ALT;
1986
1987 int hotkey = key | mods;
1988
1989 // Check for standard undo/redo hotkeys
1990 if( hotkey == (MD_CTRL + 'Z') )
1991 {
1992 doUndo();
1993 return;
1994 }
1995 else if( hotkey == (MD_CTRL + MD_SHIFT + 'Z') || hotkey == (MD_CTRL + 'Y') )
1996 {
1997 doRedo();
1998 return;
1999 }
2000
2001 if( aEvt.GetKeyCode() == 'U' && aEvt.GetModifiers() == wxMOD_CONTROL )
2002 {
2003 if( m_parentFrame )
2004 {
2005 m_parentFrame->ToggleUserUnits();
2006 return;
2007 }
2008 }
2009 // shift-return (Mac default) or Ctrl-Return (GTK) for new line input
2010 else if( ( aEvt.GetKeyCode() == WXK_RETURN || aEvt.GetKeyCode() == WXK_NUMPAD_ENTER ) && aEvt.ShiftDown() )
2011 {
2012 wxObject* eventSource = aEvt.GetEventObject();
2013
2014 if( wxTextCtrl* textCtrl = dynamic_cast<wxTextCtrl*>( eventSource ) )
2015 {
2016 // If the text control is not multi-line, we want to close the dialog
2017 if( !textCtrl->IsMultiLine() )
2018 {
2019 wxPostEvent( this, wxCommandEvent( wxEVT_COMMAND_BUTTON_CLICKED, wxID_OK ) );
2020 return;
2021 }
2022
2023#if defined( __WXMAC__ ) || defined( __WXMSW__ )
2024 wxString eol = "\r\n";
2025#else
2026 wxString eol = "\n";
2027#endif
2028
2029 long pos = textCtrl->GetInsertionPoint();
2030 textCtrl->WriteText( eol );
2031 textCtrl->SetInsertionPoint( pos + eol.length() );
2032 return;
2033 }
2034 else if( wxStyledTextCtrl* scintilla = dynamic_cast<wxStyledTextCtrl*>( eventSource ) )
2035 {
2036 wxString eol = "\n";
2037
2038 switch( scintilla->GetEOLMode() )
2039 {
2040 case wxSTC_EOL_CRLF: eol = "\r\n"; break;
2041 case wxSTC_EOL_CR: eol = "\r"; break;
2042 case wxSTC_EOL_LF: eol = "\n"; break;
2043 }
2044
2045 long pos = scintilla->GetCurrentPos();
2046 scintilla->InsertText( pos, eol );
2047 scintilla->GotoPos( pos + eol.length() );
2048 return;
2049 }
2050 return;
2051 }
2052 // command-return (Mac default) or Ctrl-Return (GTK) for OK
2053 else if( ( aEvt.GetKeyCode() == WXK_RETURN || aEvt.GetKeyCode() == WXK_NUMPAD_ENTER ) && aEvt.ControlDown() )
2054 {
2055 wxPostEvent( this, wxCommandEvent( wxEVT_COMMAND_BUTTON_CLICKED, wxID_OK ) );
2056 return;
2057 }
2058 else if( aEvt.GetKeyCode() == WXK_TAB && !aEvt.ControlDown() )
2059 {
2060 wxWindow* currentWindow = wxWindow::FindFocus();
2061 int currentIdx = -1;
2062 int delta = aEvt.ShiftDown() ? -1 : 1;
2063
2064 auto advance =
2065 [&]( int& idx )
2066 {
2067 // Wrap-around modulus
2068 int size = (int) m_tabOrder.size();
2069 idx = ( ( idx + delta ) % size + size ) % size;
2070 };
2071
2072 for( size_t i = 0; i < m_tabOrder.size(); ++i )
2073 {
2074 // Check for exact match or if currentWindow is a child of the control
2075 // (e.g., the text entry inside a wxComboBox)
2076 if( m_tabOrder[i] == currentWindow
2077 || ( currentWindow && m_tabOrder[i]->IsDescendant( currentWindow ) ) )
2078 {
2079 currentIdx = (int) i;
2080 break;
2081 }
2082 }
2083
2084 if( currentIdx >= 0 )
2085 {
2086 advance( currentIdx );
2087
2088 // Skip hidden or disabled controls
2089 int startIdx = currentIdx;
2090
2091 while( !m_tabOrder[currentIdx]->IsShown() || !m_tabOrder[currentIdx]->IsEnabled() )
2092 {
2093 advance( currentIdx );
2094
2095 if( currentIdx == startIdx )
2096 break; // Avoid infinite loop if all controls are hidden
2097 }
2098
2099 //todo: We don't currently have non-textentry dialog boxes but this will break if
2100 // we add them.
2101#ifdef __APPLE__
2102 while( dynamic_cast<wxTextEntry*>( m_tabOrder[ currentIdx ] ) == nullptr )
2103 advance( currentIdx );
2104#endif
2105
2106 m_tabOrder[ currentIdx ]->SetFocus();
2107 return;
2108 }
2109 }
2110 else if( aEvt.GetKeyCode() == WXK_ESCAPE )
2111 {
2112 wxObject* eventSource = aEvt.GetEventObject();
2113
2114 if( wxTextCtrl* textCtrl = dynamic_cast<wxTextCtrl*>( eventSource ) )
2115 {
2116 // First escape after an edit cancels edit
2117 if( textCtrl->GetValue() != m_beforeEditValues[ textCtrl ] )
2118 {
2119 textCtrl->SetValue( m_beforeEditValues[ textCtrl ] );
2120 textCtrl->SelectAll();
2121 return;
2122 }
2123 }
2124 else if( wxStyledTextCtrl* scintilla = dynamic_cast<wxStyledTextCtrl*>( eventSource ) )
2125 {
2126 // First escape after an edit cancels edit
2127 if( scintilla->GetText() != m_beforeEditValues[ scintilla ] )
2128 {
2129 scintilla->SetText( m_beforeEditValues[ scintilla ] );
2130 scintilla->SelectAll();
2131 return;
2132 }
2133 }
2134 }
2135
2136 aEvt.Skip();
2137}
2138
2139
2140static void recursiveDescent( wxSizer* aSizer, std::map<int, wxString>& aLabels )
2141{
2142 wxStdDialogButtonSizer* sdbSizer = dynamic_cast<wxStdDialogButtonSizer*>( aSizer );
2143
2144 auto setupButton =
2145 [&]( wxButton* aButton )
2146 {
2147 if( aLabels.count( aButton->GetId() ) > 0 )
2148 {
2149 aButton->SetLabel( aLabels[ aButton->GetId() ] );
2150 }
2151 else
2152 {
2153 // wxWidgets has an uneven track record when the language is changed on
2154 // the fly so we set them even when they don't appear in the label map
2155 switch( aButton->GetId() )
2156 {
2157 case wxID_OK: aButton->SetLabel( _( "&OK" ) ); break;
2158 case wxID_CANCEL: aButton->SetLabel( _( "&Cancel" ) ); break;
2159 case wxID_YES: aButton->SetLabel( _( "&Yes" ) ); break;
2160 case wxID_NO: aButton->SetLabel( _( "&No" ) ); break;
2161 case wxID_APPLY: aButton->SetLabel( _( "&Apply" ) ); break;
2162 case wxID_SAVE: aButton->SetLabel( _( "&Save" ) ); break;
2163 case wxID_HELP: aButton->SetLabel( _( "&Help" ) ); break;
2164 case wxID_CONTEXT_HELP: aButton->SetLabel( _( "&Help" ) ); break;
2165 }
2166 }
2167 };
2168
2169 if( sdbSizer )
2170 {
2171 if( sdbSizer->GetAffirmativeButton() )
2172 setupButton( sdbSizer->GetAffirmativeButton() );
2173
2174 if( sdbSizer->GetApplyButton() )
2175 setupButton( sdbSizer->GetApplyButton() );
2176
2177 if( sdbSizer->GetNegativeButton() )
2178 setupButton( sdbSizer->GetNegativeButton() );
2179
2180 if( sdbSizer->GetCancelButton() )
2181 setupButton( sdbSizer->GetCancelButton() );
2182
2183 if( sdbSizer->GetHelpButton() )
2184 setupButton( sdbSizer->GetHelpButton() );
2185
2186 sdbSizer->Layout();
2187
2188 if( sdbSizer->GetAffirmativeButton() )
2189 sdbSizer->GetAffirmativeButton()->SetDefault();
2190 }
2191
2192 for( wxSizerItem* item : aSizer->GetChildren() )
2193 {
2194 if( item->GetSizer() )
2195 recursiveDescent( item->GetSizer(), aLabels );
2196 }
2197}
2198
2199
2200void DIALOG_SHIM::SetupStandardButtons( std::map<int, wxString> aLabels )
2201{
2202 recursiveDescent( GetSizer(), aLabels );
2203}
2204
2205
2206void DIALOG_SHIM::EndDialogShim( int aReturnCode )
2207{
2208 if( IsQuasiModal() )
2209 EndQuasiModal( aReturnCode );
2210 else
2211 EndDialog( aReturnCode ); // Call the default handler for modal and mode-less dialogs.
2212}
int index
const char * name
COMMON_SETTINGS_INTERNALS & CsInternals()
Dialog helper object to sit in the inheritance tree between wxDialog and any class written by wxFormB...
Definition dialog_shim.h:81
void SelectAllInTextCtrls(wxWindowList &children)
wxVariant getControlValue(wxWindow *aCtrl)
bool m_handlingUndoRedo
void onPropertyGridChanged(wxPropertyGridEvent &aEvent)
std::set< wxWindow * > m_noControlUndoRedo
std::vector< wxWindow * > m_tabOrder
void OnPaint(wxPaintEvent &event)
bool m_qmodal_showing
virtual void TearDownQuasiModal()
Override this method to perform dialog tear down actions not suitable for object dtor.
std::set< wxWindow * > m_controlsWithPendingChanges
void recordControlChange(wxWindow *aCtrl)
Tell the undo mechanism to snapshot the current value of a control and record it as an undo step when...
int vertPixelsFromDU(int y) const
Convert an integer number of dialog units to pixels, vertically.
bool Show(bool show) override
std::vector< UNDO_STEP > m_redoStack
void setControlValue(wxWindow *aCtrl, const wxVariant &aValue)
wxGUIEventLoop * m_qmodal_loop
void onChildSetFocus(wxFocusEvent &aEvent)
EDA_UNITS m_units
void LoadControlState()
Load persisted control values from the current project's local settings.
void ExcludeFromControlUndoRedo(wxWindow *aWindow)
Opt a control out of the dialog's generic Ctrl+Z/Ctrl+Y undo/redo.
void UnregisterUnitBinder(UNIT_BINDER *aUnitBinder)
Remove a UNIT_BINDER from the control-state save/restore map.
void OptOut(wxWindow *aWindow)
Opt out of control state saving.
void SetupStandardButtons(std::map< int, wxString > aLabels={})
WINDOW_DISABLER * m_qmodal_parent_disabler
void clampToWorkArea()
Constrain the dialog's minimum size, size and position to the work area of the display it occupies,...
void onInitDialog(wxInitDialogEvent &aEvent)
std::string m_hash_key
bool m_firstPaintEvent
void OnActivate(wxActivateEvent &aEvent)
bool m_userResized
void onSpinDoubleEvent(wxSpinDoubleEvent &aEvent)
void SaveControlState(const std::optional< wxPoint > &aPosition=std::nullopt)
Save control values and geometry to the current project's local settings.
int horizPixelsFromDU(int x) const
Convert an integer number of dialog units to pixels, horizontally.
void resetSize()
Clear the existing dialog size and position.
std::map< wxWindow *, wxString > m_beforeEditValues
void setSizeInDU(int x, int y)
Set the dialog to the given dimensions in "dialog units".
void onDataViewListChanged(wxDataViewEvent &aEvent)
bool IsQuasiModal() const
bool m_useCalculatedSize
std::map< wxWindow *, UNIT_BINDER * > m_unitBinders
void ReloadSashPositions()
While we did this in LoadControlState(), we need to re-apply if after setting the dialog size.
bool m_childReleased
void EndQuasiModal(int retCode)
void RegisterUnitBinder(UNIT_BINDER *aUnitBinder, wxWindow *aWindow)
Register a UNIT_BINDER so that it can handle units in control-state save/restore.
void OnMove(wxMoveEvent &aEvent)
void EndDialogShim(int aReturnCode)
A mode agnostic way to close a dialog.
void onCommandEvent(wxCommandEvent &aEvent)
void CleanupAfterModalSubDialog()
std::string generateKey(const wxWindow *aWin) const
void PrepareForModalSubDialog()
void OnButton(wxCommandEvent &aEvent)
Properly handle the default button events when in the quasimodal mode when not calling EndQuasiModal ...
void forceInitialFocus()
Focus the requested initial target if it is visible, otherwise focus the dialog itself so keyboard ev...
void onGridCellChanged(wxGridEvent &aEvent)
void finishDialogSettings()
In all dialogs, we must call the same functions to fix minimal dlg size, the default position and per...
void registerUndoRedoHandlers(wxWindowList &aChildren)
wxWindow * m_initialFocusTarget
void OnSize(wxSizeEvent &aEvent)
bool Enable(bool enable) override
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)
void focusParentCanvas(bool aDeferUntilFrameActive=false)
Set focus back to the parent frame's tool canvas if available, otherwise to the parent window.
void SetPosition(const wxPoint &aNewPosition)
Force the position of the dialog to a new position.
void onSpinEvent(wxSpinEvent &aEvent)
bool m_userPositioned
void OnCloseWindow(wxCloseEvent &aEvent)
Properly handle the wxCloseEvent when in the quasimodal mode when not calling EndQuasiModal which is ...
std::map< wxWindow *, wxVariant > m_currentValues
wxSize m_initialSize
EDA_BASE_FRAME * m_parentFrame
virtual void OnCharHook(wxKeyEvent &aEvt)
std::vector< UNDO_STEP > m_undoStack
void onStyledTextChanged(wxStyledTextEvent &aEvent)
void flushPendingControlChanges()
Apply outstanding control changes to the undo stack, and clear the pending list.
int ShowModal() override
The base frame for deriving all KiCad main window classes.
KIWAY_HOLDER(KIWAY *aKiway, HOLDER_TYPE aType)
KIWAY & Kiway() const
Return a reference to the KIWAY that this object has an opportunity to participate in.
void SetKiway(wxWindow *aDest, KIWAY *aKiway)
It is only used for debugging, since "this" is not a wxWindow*.
bool HasKiway() const
Safety check before asking for the Kiway reference.
HOLDER_TYPE GetType() const
void SetBlockingDialog(wxWindow *aWin)
Definition kiway.cpp:711
Definition raii.h:34
virtual COMMON_SETTINGS * GetCommonSettings() const
Definition pgm_base.cpp:600
virtual wxApp & App()
Return a bare naked wxApp which may come from wxPython, SINGLE_TOP, or kicad.exe.
Definition pgm_base.cpp:236
bool SetProperty(const std::string &aKey, T &&aValue)
Set a property with the given key and value.
static PROPERTY_HOLDER * SafeCast(void *aPtr) noexcept
Safely cast a void pointer to PROPERTY_HOLDER*.
wxTextCtrl wrapper to handle math expression evaluation.
virtual wxWindow * GetToolCanvas() const =0
Canvas access.
EDA_UNITS GetUserUnits() const
virtual wxString GetFormula() const
Return the expression the user entered if it is more than a plain number, otherwise an empty string.
virtual long long int GetValue() const
Return the current value in Internal Units.
virtual void RestoreValue(int aValue, const wxString &aFormula)
Set a value (in Internal Units) as ChangeValue() does and reinstate the expression that produced it.
virtual bool RestoreFormula(const wxString &aFormula)
Show the result of an expression returned by GetFormula() and retain the expression so that it reappe...
bool UnitsInvariant() const
Definition unit_binder.h:72
virtual void ChangeValue(int aValue)
Set new value (in Internal Units) for the text field, taking care of units conversion WITHOUT trigger...
Temporarily disable a window, and then re-enable on destruction.
Definition raii.h:89
static std::string getDialogKeyFromTitle(const wxString &aTitle)
Strip parenthetical suffixes from dialog titles to create stable persistence keys.
static void recursiveDescent(wxSizer *aSizer, std::map< int, wxString > &aLabels)
static bool isCompoundDateTimePicker(const wxWindow *aWin)
Return true when the given window is a compound date/time picker whose internal children should be op...
wxRect ClampRectToDisplay(const wxRect &aRect, const wxRect &aClientArea)
Constrain a window rectangle so it fits entirely within a display's client area.
KICOMMON_API wxRect ClampRectToDisplay(const wxRect &aRect, const wxRect &aClientArea)
Constrain a window rectangle so it fits entirely within a display's client area.
const int minSize
Push and Shove router track width and via size dialog.
#define _(s)
EDA_UNITS
Definition eda_units.h:45
void ignore_unused(const T &)
Definition ignore.h:20
void AddNavigationBreadcrumb(const wxString &aMsg, const wxString &aCategory)
Add a navigation breadcrumb.
wxPoint GetRestorablePosition(wxWindow *aWindow)
Return the point that wxWindow::Move() needs to put a stabilized window back where it is.
Definition wxgtk/ui.cpp:260
void ReleaseChildWindow(wxNonOwnedWindow *aWindow)
Release a modal window's parent-child relationship with its parent window.
Definition wxgtk/ui.cpp:735
void FixupCancelButtonCmdKeyCollision(wxWindow *aWindow)
Definition wxgtk/ui.cpp:376
void StabilizeWindowPosition(wxWindow *aWindow)
Prepare a top-level window for reliable position round-tripping.
Definition wxgtk/ui.cpp:248
bool IsWindowActive(wxWindow *aWindow)
Check to see if the given window is the currently active window (e.g.
Definition wxgtk/ui.cpp:233
void ForceFocus(wxWindow *aWindow)
Pass the current focus to the window.
Definition wxgtk/ui.cpp:211
void ReparentModal(wxNonOwnedWindow *aWindow)
Move a window's parent to be the top-level window and force the window to be on top.
Definition wxgtk/ui.cpp:364
STL namespace.
static wxString makeKey(const wxString &aFirst, const wxString &aSecond)
Assemble a two part key as a simple concatenation of aFirst and aSecond parts, using a separator.
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
std::map< std::string, std::map< std::string, nlohmann::json > > m_dialogControlValues
const std::string table
std::vector< DATABASE_CONNECTION::ROW > rows
static const long long MM
VECTOR2I end
int delta
@ MD_ALT
Definition tool_event.h:141
@ MD_CTRL
Definition tool_event.h:140
@ MD_SHIFT
Definition tool_event.h:139
static PIECE rect(double aLeft, double aTop, double aRight, double aBottom, bool aMixed=false)