KiCad PCB EDA Suite
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 <dick@softplc.com>
5  * Copyright (C) 2012-2018 KiCad Developers, see AUTHORS.txt for contributors.
6  *
7  * This program is free software; you can redistribute it and/or
8  * modify it under the terms of the GNU General Public License
9  * as published by the Free Software Foundation; either version 2
10  * of the License, or (at your option) any later version.
11  *
12  * This program is distributed in the hope that it will be useful,
13  * but WITHOUT ANY WARRANTY; without even the implied warranty of
14  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
15  * GNU General Public License for more details.
16  *
17  * You should have received a copy of the GNU General Public License
18  * along with this program; if not, you may find one here:
19  * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
20  * or you may search the http://www.gnu.org website for the version 2 license,
21  * or you may write to the Free Software Foundation, Inc.,
22  * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
23  */
24 
25 #include <dialog_shim.h>
26 #include <kiway_player.h>
27 #include <wx/evtloop.h>
28 #include <pgm_base.h>
29 #include <eda_rect.h>
30 #include <wx/display.h>
31 
34 {
35  wxWindow* m_win;
36 
37 public:
38 
39  WDO_ENABLE_DISABLE( wxWindow* aWindow ) :
40  m_win( aWindow )
41  {
42  if( m_win )
43  m_win->Disable();
44  }
45 
47  {
48  if( m_win )
49  {
50  m_win->Enable();
51  m_win->SetFocus(); // let's focus back on the parent window
52  }
53  }
54 };
55 
56 
57 DIALOG_SHIM::DIALOG_SHIM( wxWindow* aParent, wxWindowID id, const wxString& title,
58  const wxPoint& pos, const wxSize& size, long style, const wxString& name ) :
59  wxDialog( aParent, id, title, pos, size, style, name ),
60  KIWAY_HOLDER( nullptr ),
61  m_units( MILLIMETRES ),
62  m_firstPaintEvent( true ),
63  m_initialFocusTarget( nullptr ),
64  m_qmodal_loop( nullptr ),
65  m_qmodal_showing( false ),
66  m_qmodal_parent_disabler( nullptr )
67 {
68  KIWAY_HOLDER* kiwayHolder = nullptr;
69 
70  if( aParent )
71  {
72  kiwayHolder = dynamic_cast<KIWAY_HOLDER*>( aParent );
73 
74  while( !kiwayHolder && aParent->GetParent() )
75  {
76  aParent = aParent->GetParent();
77  kiwayHolder = dynamic_cast<KIWAY_HOLDER*>( aParent );
78  }
79  }
80 
81  if( kiwayHolder )
82  {
83  // Inherit units from parent
84  m_units = kiwayHolder->GetUserUnits();
85 
86  // Set up the message bus
87  SetKiway( this, &kiwayHolder->Kiway() );
88  }
89 
90  Bind( wxEVT_CLOSE_WINDOW, &DIALOG_SHIM::OnCloseWindow, this );
91  Bind( wxEVT_BUTTON, &DIALOG_SHIM::OnButton, this );
92 
93 #ifdef __WINDOWS__
94  // On Windows, the app top windows can be brought to the foreground
95  // (at least temporary) in certain circumstances,
96  // for instance when calling an external tool in Eeschema BOM generation.
97  // So set the parent KIWAY_PLAYER kicad frame (if exists) to top window
98  // to avoid this annoying behavior
99  KIWAY_PLAYER* parent_kiwayplayer = dynamic_cast<KIWAY_PLAYER*>( aParent );
100 
101  if( parent_kiwayplayer )
102  Pgm().App().SetTopWindow( parent_kiwayplayer );
103 #endif
104 
105  Connect( wxEVT_PAINT, wxPaintEventHandler( DIALOG_SHIM::OnPaint ) );
106 }
107 
108 
110 {
111  // if the dialog is quasi-modal, this will end its event loop
112  if( IsQuasiModal() )
113  EndQuasiModal( wxID_CANCEL );
114 
116  delete m_qmodal_parent_disabler; // usually NULL by now
117 }
118 
119 
121 {
122  // must be called from the constructor of derived classes,
123  // when all widgets are initialized, and therefore their size fixed
124 
125  // SetSizeHints fixes the minimal size of sizers in the dialog
126  // (SetSizeHints calls Fit(), so no need to call it)
127  GetSizer()->SetSizeHints( this );
128 
129  // the default position, when calling the first time the dlg
130  Center();
131 }
132 
133 
134 void DIALOG_SHIM::SetSizeInDU( int x, int y )
135 {
136  wxSize sz( x, y );
137  SetSize( ConvertDialogToPixels( sz ) );
138 }
139 
140 
142 {
143  wxSize sz( x, 0 );
144  return ConvertDialogToPixels( sz ).x;
145 }
146 
147 
149 {
150  wxSize sz( 0, y );
151  return ConvertDialogToPixels( sz ).y;
152 }
153 
154 
155 // our hashtable is an implementation secret, don't need or want it in a header file
156 #include <hashtables.h>
157 #include <base_struct.h> // EDA_RECT
158 #include <typeinfo>
159 
161 
162 bool DIALOG_SHIM::Show( bool show )
163 {
164  bool ret;
165  const char* hash_key;
166 
167  if( m_hash_key.size() )
168  {
169  // a special case like EDA_LIST_DIALOG, which has multiple uses.
170  hash_key = m_hash_key.c_str();
171  }
172  else
173  {
174  hash_key = typeid(*this).name();
175  }
176 
177  // Show or hide the window. If hiding, save current position and size.
178  // If showing, use previous position and size.
179  if( show )
180  {
181 #ifndef __WINDOWS__
182  wxDialog::Raise(); // Needed on OS X and some other window managers (i.e. Unity)
183 #endif
184  ret = wxDialog::Show( show );
185 
186  // classname is key, returns a zeroed out default EDA_RECT if none existed before.
187  EDA_RECT savedDialogRect = class_map[ hash_key ];
188 
189  if( savedDialogRect.GetSize().x != 0 && savedDialogRect.GetSize().y != 0 )
190  {
191  SetSize( savedDialogRect.GetPosition().x,
192  savedDialogRect.GetPosition().y,
193  std::max( wxDialog::GetSize().x, savedDialogRect.GetSize().x ),
194  std::max( wxDialog::GetSize().y, savedDialogRect.GetSize().y ),
195  0 );
196  }
197 
198  // Be sure that the dialog appears in a visible area
199  // (the dialog position might have been stored at the time when it was
200  // shown on another display)
201  if( wxDisplay::GetFromWindow( this ) == wxNOT_FOUND )
202  Centre();
203  }
204  else
205  {
206  // Save the dialog's position & size before hiding, using classname as key
207  class_map[ hash_key ] = EDA_RECT( wxDialog::GetPosition(), wxDialog::GetSize() );
208 
209 #ifdef __WXMAC__
210  if ( m_eventLoop )
211  m_eventLoop->Exit( GetReturnCode() ); // Needed for APP-MODAL dlgs on OSX
212 #endif
213 
214  ret = wxDialog::Show( show );
215  }
216 
217  return ret;
218 }
219 
220 
221 bool DIALOG_SHIM::Enable( bool enable )
222 {
223  // so we can do logging of this state change:
224 
225 #if defined(DEBUG)
226  const char* type_id = typeid( *this ).name();
227  printf( "wxDialog %s: %s\n", type_id, enable ? "enabled" : "disabled" );
228 #endif
229 
230  return wxDialog::Enable( enable );
231 }
232 
233 
234 #ifdef __WXMAC__
235 // Recursive descent doing a SelectAll() in wxTextCtrls.
236 // MacOS User Interface Guidelines state that when tabbing to a text control all its
237 // text should be selected. Since wxWidgets fails to implement this, we do it here.
238 static void selectAllInTextCtrls( wxWindowList& children )
239 {
240  for( wxWindow* child : children )
241  {
242  wxTextCtrl* childTextCtrl = dynamic_cast<wxTextCtrl*>( child );
243  if( childTextCtrl )
244  {
245  wxTextEntry* asTextEntry = dynamic_cast<wxTextEntry*>( childTextCtrl );
246 
247  // Respect an existing selection
248  if( asTextEntry->GetStringSelection().IsEmpty() )
249  asTextEntry->SelectAll();
250  }
251  else
252  selectAllInTextCtrls( child->GetChildren() );
253  }
254 }
255 #endif
256 
257 
258 #ifdef __WXMAC__
259 static void fixOSXCancelButtonIssue( wxWindow *aWindow )
260 {
261  // A ugly hack to fix an issue on OSX: cmd+c closes the dialog instead of
262  // copying the text if a button with wxID_CANCEL is used in a
263  // wxStdDialogButtonSizer created by wxFormBuilder: the label is &Cancel, and
264  // this accelerator key has priority over the standard copy accelerator.
265  // Note: problem also exists in other languages; for instance cmd+a closes
266  // dialogs in German because the button is &Abbrechen.
267  wxButton* button = dynamic_cast<wxButton*>( wxWindow::FindWindowById( wxID_CANCEL, aWindow ) );
268 
269  if( button )
270  {
271  static const wxString placeholder = wxT( "{amp}" );
272 
273  wxString buttonLabel = button->GetLabel();
274  buttonLabel.Replace( wxT( "&&" ), placeholder );
275  buttonLabel.Replace( wxT( "&" ), wxEmptyString );
276  buttonLabel.Replace( placeholder, wxT( "&" ) );
277  button->SetLabel( buttonLabel );
278  }
279 }
280 #endif
281 
282 
283 void DIALOG_SHIM::OnPaint( wxPaintEvent &event )
284 {
285  if( m_firstPaintEvent )
286  {
287 #ifdef __WXMAC__
288  fixOSXCancelButtonIssue( this );
289  selectAllInTextCtrls( GetChildren() );
290 #endif
291 
293  m_initialFocusTarget->SetFocus();
294  else
295  SetFocus(); // Focus the dialog itself
296 
297  m_firstPaintEvent = false;
298  }
299 
300  event.Skip();
301 }
302 
303 
304 /*
305  Quasi-Modal Mode Explained:
306 
307  The gtk calls in wxDialog::ShowModal() cause event routing problems if that
308  modal dialog then tries to use KIWAY_PLAYER::ShowModal(). The latter shows up
309  and mostly works but does not respond to the window decoration close button.
310  There is no way to get around this without reversing the gtk calls temporarily.
311 
312  Quasi-Modal mode is our own almost modal mode which disables only the parent
313  of the DIALOG_SHIM, leaving other frames operable and while staying captured in the
314  nested event loop. This avoids the gtk calls and leaves event routing pure
315  and sufficient to operate the KIWAY_PLAYER::ShowModal() properly. When using
316  ShowQuasiModal() you have to use EndQuasiModal() in your dialogs and not
317  EndModal(). There is also IsQuasiModal() but its value can only be true
318  when the nested event loop is active. Do not mix the modal and quasi-modal
319  functions. Use one set or the other.
320 
321  You might find this behavior preferable over a pure modal mode, and it was said
322  that only the Mac has this natively, but now other platforms have something
323  similar. You CAN use it anywhere for any dialog. But you MUST use it when
324  you want to use KIWAY_PLAYER::ShowModal() from a dialog event.
325 */
326 
328 {
329  // This is an exception safe way to zero a pointer before returning.
330  // Yes, even though DismissModal() clears this first normally, this is
331  // here in case there's an exception before the dialog is dismissed.
332  struct NULLER
333  {
334  void*& m_what;
335  NULLER( void*& aPtr ) : m_what( aPtr ) {}
336  ~NULLER() { m_what = 0; } // indeed, set it to NULL on destruction
337  } clear_this( (void*&) m_qmodal_loop );
338 
339  // release the mouse if it's currently captured as the window having it
340  // will be disabled when this dialog is shown -- but will still keep the
341  // capture making it impossible to do anything in the modal dialog itself
342  wxWindow* win = wxWindow::GetCapture();
343  if( win )
344  win->ReleaseMouse();
345 
346  // Get the optimal parent
347  wxWindow* parent = GetParentForModalDialog( GetParent(), GetWindowStyle() );
348 
349  // Show the optimal parent
350  DBG( if( parent ) printf( "%s: optimal parent: %s\n", __func__, typeid(*parent).name() );)
351 
352  wxASSERT_MSG( !m_qmodal_parent_disabler,
353  wxT( "Caller using ShowQuasiModal() twice on same window?" ) );
354 
355  // quasi-modal: disable only my "optimal" parent
357 
358 #ifdef __WXMAC__
359  // Apple in its infinite wisdom will raise a disabled window before even passing
360  // us the event, so we have no way to stop it. Instead, we must set an order on
361  // the windows so that the quasi-modal will be pushed in front of the disabled
362  // window when it is raised.
363  ReparentQuasiModal();
364 #endif
365  Show( true );
366 
367  m_qmodal_showing = true;
368 
369  WX_EVENT_LOOP event_loop;
370 
371  m_qmodal_loop = &event_loop;
372 
373  event_loop.Run();
374 
375  m_qmodal_showing = false;
376 
377  return GetReturnCode();
378 }
379 
380 
381 void DIALOG_SHIM::EndQuasiModal( int retCode )
382 {
383  // Hook up validator and transfer data from controls handling so quasi-modal dialogs
384  // handle validation in the same way as other dialogs.
385  if( ( retCode == wxID_OK ) && ( !Validate() || !TransferDataFromWindow() ) )
386  return;
387 
388  SetReturnCode( retCode );
389 
390  if( !IsQuasiModal() )
391  {
392  wxFAIL_MSG( wxT( "either DIALOG_SHIM::EndQuasiModal called twice or ShowQuasiModal wasn't called" ) );
393  return;
394  }
395 
396  if( m_qmodal_loop )
397  {
398  if( m_qmodal_loop->IsRunning() )
399  m_qmodal_loop->Exit( 0 );
400  else
401  m_qmodal_loop->ScheduleExit( 0 );
402 
403  m_qmodal_loop = NULL;
404  }
405 
408 
409  Show( false );
410 }
411 
412 
413 void DIALOG_SHIM::OnCloseWindow( wxCloseEvent& aEvent )
414 {
415  if( IsQuasiModal() )
416  {
417  EndQuasiModal( wxID_CANCEL );
418  return;
419  }
420 
421  // This is mandatory to allow wxDialogBase::OnCloseWindow() to be called.
422  aEvent.Skip();
423 }
424 
425 
426 void DIALOG_SHIM::OnButton( wxCommandEvent& aEvent )
427 {
428  if( IsQuasiModal() )
429  {
430  const int id = aEvent.GetId();
431 
432  if( id == GetAffirmativeId() )
433  {
434  EndQuasiModal( id );
435  }
436  else if( id == wxID_APPLY )
437  {
438  // Dialogs that provide Apply buttons should make sure data is valid before
439  // allowing a transfer, as there is no other way to indicate failure
440  // (i.e. the dialog can't refuse to close as it might with OK, because it
441  // isn't closing anyway)
442  if( Validate() )
443  {
444  bool success = TransferDataFromWindow();
445  (void) success;
446  }
447  }
448  else if( id == GetEscapeId() ||
449  (id == wxID_CANCEL && GetEscapeId() == wxID_ANY) )
450  {
451  EndQuasiModal( wxID_CANCEL );
452  }
453  else // not a standard button
454  {
455  aEvent.Skip();
456  }
457 
458  return;
459  }
460 
461  // This is mandatory to allow wxDialogBase::OnButton() to be called.
462  aEvent.Skip();
463 }
bool m_qmodal_showing
Definition: dialog_shim.h:183
Class KIWAY_HOLDER is a mix in class which holds the location of a wxWindow&#39;s KIWAY.
Definition: kiway_player.h:48
Class KIWAY_PLAYER is a wxFrame capable of the OpenProjectFiles function, meaning it can load a porti...
Definition: kiway_player.h:120
void SetKiway(wxWindow *aDest, KIWAY *aKiway)
Function SetKiway.
#define WX_EVENT_LOOP
Definition: kiway_player.h:100
KIWAY & Kiway() const
Function Kiway returns a reference to the KIWAY that this object has an opportunity to participate in...
Definition: kiway_player.h:60
void OnButton(wxCommandEvent &aEvent)
Function OnCloseWindow.
const wxSize GetSize() const
Definition: eda_rect.h:101
std::string m_hash_key
Definition: dialog_shim.h:173
void FinishDialogSettings()
In all dialogs, we must call the same functions to fix minimal dlg size, the default position and per...
VTBL_ENTRY wxApp & App()
Function App returns a bare naked wxApp, which may come from wxPython, SINGLE_TOP, or kicad.exe.
Definition: pgm_base.cpp:188
PGM_BASE & Pgm()
The global Program "get" accessor.
Definition: kicad.cpp:66
wxWindow * m_initialFocusTarget
Definition: dialog_shim.h:179
bool m_firstPaintEvent
Definition: dialog_shim.h:178
WX_EVENT_LOOP * m_qmodal_loop
Definition: dialog_shim.h:182
void OnCloseWindow(wxCloseEvent &aEvent)
Function OnCloseWindow.
int ShowQuasiModal()
static RECT_MAP class_map
void SetSizeInDU(int x, int y)
Set the dialog to the given dimensions in "dialog units".
bool IsQuasiModal()
Definition: dialog_shim.h:124
void OnPaint(wxPaintEvent &event)
const wxPoint GetPosition() const
Definition: eda_rect.h:113
bool Show(bool show) override
int VertPixelsFromDU(int y)
Convert an integer number of dialog units to pixels, vertically.
WDO_ENABLE_DISABLE * m_qmodal_parent_disabler
Definition: dialog_shim.h:184
void EndQuasiModal(int retCode)
see class PGM_BASE
DIALOG_SHIM(wxWindow *aParent, wxWindowID id, const wxString &title, const wxPoint &pos=wxDefaultPosition, const wxSize &size=wxDefaultSize, long style=wxDEFAULT_DIALOG_STYLE|wxRESIZE_BORDER, const wxString &name=wxDialogNameStr)
Definition: dialog_shim.cpp:57
const char * name
Definition: DXF_plotter.cpp:61
#define max(a, b)
Definition: auxiliary.h:86
Class EDA_RECT handles the component boundary box.
Definition: eda_rect.h:44
Toggle a window&#39;s "enable" status to disabled, then enabled on destruction.
Definition: dialog_shim.cpp:33
VTBL_ENTRY EDA_UNITS_T GetUserUnits() const
Function GetUserUnits Allows participation in KEYWAY_PLAYER/DIALOG_SHIM userUnits inheritance...
int HorizPixelsFromDU(int x)
Convert an integer number of dialog units to pixels, horizontally.
bool Enable(bool enable) override
#define DBG(x)
Definition: fctsys.h:33
Basic classes for most KiCad items.
EDA_UNITS_T m_units
Definition: dialog_shim.h:172
WDO_ENABLE_DISABLE(wxWindow *aWindow)
Definition: dialog_shim.cpp:39
std::unordered_map< std::string, EDA_RECT > RECT_MAP
Map a C string to an EDA_RECT.
Definition: hashtables.h:136