KiCad PCB EDA Suite
Loading...
Searching...
No Matches
draw_panel_gal.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) 2013-2017 CERN
5 * Copyright The KiCad Developers, see AUTHORS.txt for contributors.
6 *
7 * @author Tomasz Wlostowski <[email protected]>
8 * @author Maciej Suminski <[email protected]>
9 *
10 * This program is free software; you can redistribute it and/or
11 * modify it under the terms of the GNU General Public License
12 * as published by the Free Software Foundation; either version 2
13 * of the License, or (at your option) any later version.
14 *
15 * This program is distributed in the hope that it will be useful,
16 * but WITHOUT ANY WARRANTY; without even the implied warranty of
17 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
18 * GNU General Public License for more details.
19 *
20 * You should have received a copy of the GNU General Public License
21 * along with this program; if not, you may find one here:
22 * http://www.gnu.org/licenses/old-licenses/gpl-2.0.html
23 * or you may search the http://www.gnu.org website for the version 2 license,
24 * or you may write to the Free Software Foundation, Inc.,
25 * 51 Franklin Street, Fifth Floor, Boston, MA 02110-1301, USA
26 */
27#include <eda_draw_frame.h>
28#include <kiface_base.h>
29#include <macros.h>
30#include <scoped_set_reset.h>
32#include <trace_helpers.h>
33
35#include <view/view.h>
37#include <gal/painter.h>
38#include <base_screen.h>
39#include <gal/cursors.h>
42#include <gal/cairo/cairo_gal.h>
43#include <math/vector2wx.h>
44
45
47#include <tool/tool_manager.h>
48
49#include <widgets/wx_infobar.h>
50
51#include <kiplatform/ui.h>
52
53#include <core/profile.h>
54
55#include <wx/display.h>
56
57#include <pgm_base.h>
58#include <confirm.h>
59
60
66static const wxChar traceDrawPanel[] = wxT( "KICAD_DRAW_PANEL" );
67
68
69EDA_DRAW_PANEL_GAL::EDA_DRAW_PANEL_GAL( wxWindow* aParentWindow, wxWindowID aWindowId,
70 const wxPoint& aPosition, const wxSize& aSize,
71 KIGFX::GAL_DISPLAY_OPTIONS& aOptions, GAL_TYPE aGalType ) :
72 wxScrolledCanvas( aParentWindow, aWindowId, aPosition, aSize ),
73 m_MouseCapturedLost( false ),
74 m_parent( aParentWindow ),
75 m_edaFrame( nullptr ),
78 m_drawing( false ),
79 m_drawingEnabled( false ),
80 m_needIdleRefresh( false ),
81 m_gal( nullptr ),
82 m_view( nullptr ),
83 m_painter( nullptr ),
84 m_viewControls( nullptr ),
86 m_options( aOptions ),
87 m_eventDispatcher( nullptr ),
88 m_lostFocus( false ),
89 m_glRecoveryAttempted( false ),
90 m_stealsFocus( true ),
91 m_statusPopup( nullptr )
92{
93#ifdef _WIN32
94 // need to fix broken cairo rendering on Windows with wx 3.3
95 SetDoubleBuffered( false );
96#endif
97 m_PaintEventCounter = std::make_unique<PROF_COUNTER>( "Draw panel paint events" );
98
99 if( Pgm().GetCommonSettings()->m_Appearance.show_scrollbars )
100 ShowScrollbars( wxSHOW_SB_ALWAYS, wxSHOW_SB_ALWAYS );
101 else
102 ShowScrollbars( wxSHOW_SB_NEVER, wxSHOW_SB_NEVER );
103
104 SetLayoutDirection( wxLayout_LeftToRight );
105
106 m_edaFrame = dynamic_cast<EDA_DRAW_FRAME*>( m_parent );
107
108 // If we're in a dialog, we have to go looking for our parent frame
109 if( !m_edaFrame )
110 {
111 wxWindow* ancestor = aParentWindow->GetParent();
112
113 while( ancestor && !dynamic_cast<EDA_DRAW_FRAME*>( ancestor ) )
114 ancestor = ancestor->GetParent();
115
116 if( ancestor )
117 m_edaFrame = dynamic_cast<EDA_DRAW_FRAME*>( ancestor );
118 }
119
120 SwitchBackend( aGalType );
121 SetBackgroundStyle( wxBG_STYLE_CUSTOM );
122
123 EnableScrolling( false, false ); // otherwise Zoom Auto disables GAL canvas
124 KIPLATFORM::UI::SetOverlayScrolling( this, false ); // Prevent excessive repaint on GTK
125 KIPLATFORM::UI::ImmControl( this, false ); // Ensure our panel can't suck in IME events
126
127 Connect( wxEVT_SIZE, wxSizeEventHandler( EDA_DRAW_PANEL_GAL::onSize ), nullptr, this );
128 Connect( wxEVT_ENTER_WINDOW, wxMouseEventHandler( EDA_DRAW_PANEL_GAL::onEnter ), nullptr,
129 this );
130 Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( EDA_DRAW_PANEL_GAL::onLostFocus ), nullptr,
131 this );
132
133 const wxEventType events[] = {
134 // Binding both EVT_CHAR and EVT_CHAR_HOOK ensures that all key events,
135 // especially special key like arrow keys, are handled by the GAL event dispatcher,
136 // and not sent to GUI without filtering, because they have a default action (scroll)
137 // that must not be called.
138 wxEVT_LEFT_UP,
139 wxEVT_LEFT_DOWN,
140 wxEVT_LEFT_DCLICK,
141 wxEVT_RIGHT_UP,
142 wxEVT_RIGHT_DOWN,
143 wxEVT_RIGHT_DCLICK,
144 wxEVT_MIDDLE_UP,
145 wxEVT_MIDDLE_DOWN,
146 wxEVT_MIDDLE_DCLICK,
147 wxEVT_AUX1_UP,
148 wxEVT_AUX1_DOWN,
149 wxEVT_AUX1_DCLICK,
150 wxEVT_AUX2_UP,
151 wxEVT_AUX2_DOWN,
152 wxEVT_AUX2_DCLICK,
153 wxEVT_MOTION,
154 wxEVT_MOUSEWHEEL,
155 wxEVT_CHAR,
156 wxEVT_CHAR_HOOK,
157 wxEVT_MAGNIFY,
159 };
160
161 for( wxEventType eventType : events )
162 Connect( eventType, wxEventHandler( EDA_DRAW_PANEL_GAL::OnEvent ), nullptr,
164
165 // Set up timer to detect when drawing starts
166 m_refreshTimer.SetOwner( this );
167 Connect( m_refreshTimer.GetId(), wxEVT_TIMER,
168 wxTimerEventHandler( EDA_DRAW_PANEL_GAL::onRefreshTimer ), nullptr, this );
169
170 Connect( wxEVT_SHOW, wxShowEventHandler( EDA_DRAW_PANEL_GAL::onShowEvent ), nullptr, this );
171}
172
173
175{
176 // Ensure EDA_DRAW_PANEL_GAL::onShowEvent is not fired during Dtor process
177 Disconnect( wxEVT_SHOW, wxShowEventHandler( EDA_DRAW_PANEL_GAL::onShowEvent ) );
178 StopDrawing();
179
180 wxASSERT( !m_drawing );
181
182 delete m_viewControls;
183 delete m_view;
184 delete m_gal;
185 m_gal = nullptr; // Ensure OnShow is not called
186}
187
188
190{
192 wxScrolledCanvas::SetFocus();
193 m_lostFocus = false;
194}
195
196
197void EDA_DRAW_PANEL_GAL::onPaint( wxPaintEvent& WXUNUSED( aEvent ) )
198{
199 DoRePaint( false );
200}
201
202
203bool EDA_DRAW_PANEL_GAL::recoverFromGalError( const std::exception& aError )
204{
205 try
206 {
207 // Sleep/wake and GPU resets can invalidate the entire GL context.
208 // Try a full reinit of the current backend before falling back.
210 {
212 GAL_TYPE prevBackend = m_backend;
214
215 if( SwitchBackend( prevBackend ) )
216 {
217 StartDrawing();
218 return true;
219 }
220 }
221
223 {
224 m_glRecoveryAttempted = false;
226
227 DisplayInfoMessage( m_parent, _( "Could not use OpenGL, falling back to software rendering" ),
228 wxString( aError.what() ) );
229
230 StartDrawing();
231 return true;
232 }
233
234 DisplayErrorMessage( m_parent, _( "Graphics error" ), wxString( aError.what() ) );
235 }
236 catch( std::exception& recoveryErr )
237 {
238 DisplayErrorMessage( m_parent, _( "Graphics error during recovery" ), wxString( recoveryErr.what() ) );
239 }
240 catch( ... )
241 {
242 DisplayErrorMessage( m_parent, _( "Graphics error during recovery" ),
243 _( "Unknown exception during backend switch" ) );
244 }
245
246 return false;
247}
248
249
250bool EDA_DRAW_PANEL_GAL::DoRePaint( bool aAllowSkip )
251{
252 if( !m_refreshMutex.try_lock() )
253 return false;
254
255 std::lock_guard<std::mutex> lock( m_refreshMutex, std::adopt_lock );
256
257 if( !m_drawingEnabled )
258 return false;
259
260 if( !m_gal->IsInitialized() || !m_gal->IsVisible() || m_gal->IsContextLocked() )
261 return false;
262
263 if( m_drawing )
264 return false;
265
266 m_lastRepaintStart = wxGetLocalTimeMillis();
267
268 // Repaint the canvas, and fix scrollbar cursors
269 // Usually called by a OnPaint event, but because it does not use a wxPaintDC,
270 // it can be called outside a wxPaintEvent.
271
272 // Update current zoom settings if the canvas is managed by a EDA frame
273 // (i.e. not by a preview panel in a dialog)
274 if( !IsDialogPreview() && GetParentEDAFrame() && GetParentEDAFrame()->GetScreen() )
276
277 if( Pgm().GetCommonSettings()->m_Appearance.show_scrollbars )
278 m_viewControls->UpdateScrollbars();
279
280 SCOPED_SET_RESET<bool> drawing( m_drawing, true );
281
282 ( *m_PaintEventCounter )++;
283
284 wxASSERT( m_painter );
285
286 KIGFX::RENDER_SETTINGS* settings =
287 static_cast<KIGFX::RENDER_SETTINGS*>( m_painter->GetSettings() );
288
289 PROF_TIMER cntUpd("view-upd-items");
290 PROF_TIMER cntTotal("view-total");
291 PROF_TIMER cntCtx("view-context-create");
292 PROF_TIMER cntCtxDestroy("view-context-destroy");
293 PROF_TIMER cntRedraw("view-redraw-rects");
294
295 bool isDirty = false;
296
297 cntTotal.Start();
298
299 try
300 {
301 VECTOR2D cursorPos = m_viewControls->GetCursorPosition();
302 bool viewDirty = m_view->IsDirty();
303 bool cursorMoved = ( cursorPos != m_lastCursorPosition );
304 bool hasPendingItemUpdates = m_view->HasPendingItemUpdates();
305
306 // Skip all update work when nothing has changed since the previous frame.
307 // Never skip when responding to a native paint event or explicit ForceRefresh
308 // because the window content may have been invalidated by the OS.
309 if( aAllowSkip && !viewDirty && !cursorMoved && !hasPendingItemUpdates )
310 {
311 m_lastRepaintEnd = wxGetLocalTimeMillis();
312 return true;
313 }
314
315 if( hasPendingItemUpdates )
316 {
317 cntUpd.Start();
318
319 try
320 {
321 m_view->UpdateItems();
322 }
323 catch( std::out_of_range& err )
324 {
325 // Don't do anything here but don't fail
326 // This can happen when we don't catch `at()` calls
327 wxLogTrace( traceDrawPanel, wxS( "Out of Range error: %s" ), err.what() );
328 }
329 catch( std::runtime_error& err )
330 {
331 // Handle GL errors (e.g. glMapBuffer failure) that surface during UpdateItems().
332 // These can occur on macOS under memory pressure when embedding large 3D models.
333 // Log and continue so the outer handler can decide whether to switch backends.
334 wxLogTrace( traceDrawPanel, wxS( "Runtime error during UpdateItems: %s" ),
335 err.what() );
336 throw;
337 }
338
339 cntUpd.Stop();
340 viewDirty = m_view->IsDirty();
341 }
342
343 // After processing item updates, skip the GL cycle when neither the
344 // view targets nor the cursor position have changed.
345 if( aAllowSkip && !viewDirty && !cursorMoved )
346 {
347 m_lastRepaintEnd = wxGetLocalTimeMillis();
348 return true;
349 }
350
351 m_lastCursorPosition = cursorPos;
352
353 // GAL_DRAWING_CONTEXT can throw in the dtor, so we need to scope
354 // the full lifetime inside the try block
355 {
356 cntCtx.Start();
358 cntCtx.Stop();
359
360 if( m_view->IsTargetDirty( KIGFX::TARGET_OVERLAY )
361 && !m_gal->HasTarget( KIGFX::TARGET_OVERLAY ) )
362 {
363 m_view->MarkDirty();
364 }
365
366 m_gal->SetClearColor( settings->GetBackgroundColor() );
367 m_gal->SetGridColor( settings->GetGridColor() );
368 m_gal->SetCursorColor( settings->GetCursorColor() );
369
370 // OpenGL double-buffering leaves the back buffer undefined after
371 // SwapBuffers, so a full clear is always required before compositing.
372 // Cairo only needs to clear when NONCACHED content changed.
374 m_gal->ClearScreen();
375
376 if( m_view->IsDirty() )
377 {
378 if( m_backend != GAL_TYPE_OPENGL // Already called in opengl
379 && m_view->IsTargetDirty( KIGFX::TARGET_NONCACHED ) )
380 {
381 m_gal->ClearScreen();
382 }
383
384 m_view->ClearTargets();
385
386 // Grid has to be redrawn only when the NONCACHED target is redrawn
387 if( m_view->IsTargetDirty( KIGFX::TARGET_NONCACHED ) )
388 m_gal->DrawGrid();
389
390 cntRedraw.Start();
391 m_view->Redraw();
392 cntRedraw.Stop();
393 isDirty = true;
394 }
395
396 m_gal->DrawCursor( cursorPos );
397
398 cntCtxDestroy.Start();
399 }
400
401 // ctx goes out of scope here so destructor would be called
402 cntCtxDestroy.Stop();
403
404 // OpenGL frame completed successfully, allow future recovery attempts
405 m_glRecoveryAttempted = false;
406 }
407 catch( std::exception& err )
408 {
409 wxLogTrace( traceDrawPanel, wxS( "DoRePaint exception: %s" ), err.what() );
410
411 if( recoverFromGalError( err ) )
412 return true;
413
414 StopDrawing();
415 }
416 catch( ... )
417 {
418 DisplayErrorMessage( m_parent, _( "Graphics error" ), _( "Unknown exception" ) );
419 StopDrawing();
420 }
421
422 if( isDirty )
423 {
424 wxLogTrace( traceGalProfile, "View timing: %s %s %s %s %s",
425 cntTotal.to_string(),
426 cntUpd.to_string(),
427 cntRedraw.to_string(),
428 cntCtx.to_string(),
429 cntCtxDestroy.to_string()
430 );
431 }
432
433 m_lastRepaintEnd = wxGetLocalTimeMillis();
434
435 return true;
436}
437
438
439void EDA_DRAW_PANEL_GAL::onSize( wxSizeEvent& aEvent )
440{
441 // If we get a second wx update call before the first finishes, don't crash
442 if( m_gal->IsContextLocked() )
443 return;
444
446 wxSize clientSize = GetClientSize();
447 WX_INFOBAR* infobar = GetParentEDAFrame() ? GetParentEDAFrame()->GetInfoBar() : nullptr;
448
449 if( ToVECTOR2I( clientSize ) == m_gal->GetScreenPixelSize() )
450 return;
451
452 // Note: ( +1, +1 ) prevents an ugly black line on right and bottom on Mac
453 clientSize.x = std::max( 10, clientSize.x + 1 );
454 clientSize.y = std::max( 10, clientSize.y + 1 );
455
456 VECTOR2D bottom( 0, 0 );
457
458 if( m_view )
459 bottom = m_view->ToWorld( m_gal->GetScreenPixelSize(), true );
460
461 m_gal->ResizeScreen( clientSize.GetX(), clientSize.GetY() );
462
463 if( m_view )
464 {
465 if( infobar && infobar->IsLocked() )
466 {
467 VECTOR2D halfScreen( std::ceil( 0.5 * clientSize.x ), std::ceil( 0.5 * clientSize.y ) );
468 m_view->SetCenter( bottom - m_view->ToWorld( halfScreen, false ) );
469 }
470
471 m_view->MarkTargetDirty( KIGFX::TARGET_CACHED );
472 m_view->MarkTargetDirty( KIGFX::TARGET_NONCACHED );
473 }
474}
475
476
481
482
483void EDA_DRAW_PANEL_GAL::Refresh( bool aEraseBackground, const wxRect* aRect )
484{
485 wxLongLong now = wxGetLocalTimeMillis();
486 wxLongLong delta = now - m_lastRepaintEnd;
487 bool galInitialized = m_gal && m_gal->IsInitialized();
488
489 // wxGetLocalTimeMillis is wall clock, so an NTP correction or manual
490 // clock change can make delta negative. Treat that as "long enough".
491 if( delta < 0 )
492 delta = 0;
493
494 // When vsync is available the driver throttles SwapBuffers, so we only need
495 // a small guard to avoid queueing work faster than the GPU can consume it.
496 // Without vsync, cap the render rate at the monitor refresh rate so the
497 // GPU is not saturated producing frames that will never be shown.
498 int minPeriodMs = 3;
499
500 if( galInitialized && m_gal->GetSwapInterval() == 0 )
501 {
502 // wxDisplay reports 0 on headless, some virtualized, and a few driver
503 // combinations. Clamp to a plausible monitor range before trusting it
504 // and fall back to 60 Hz otherwise.
505 int refreshHz = 60;
506 int reported = wxDisplay( this ).GetCurrentMode().refresh;
507
508 if( reported >= 24 && reported <= 1000 )
509 refreshHz = reported;
510
511 minPeriodMs = 1000 / refreshHz;
512 }
513
514 if( delta >= minPeriodMs )
515 {
516 if( !DoRePaint() )
518 }
519 else if( !m_refreshTimer.IsRunning() )
520 {
521 m_refreshTimer.StartOnce( static_cast<int>( ( minPeriodMs - delta ).GetValue() ) );
522 }
523}
524
525
527{
528 if( !m_drawingEnabled )
529 {
530 if( m_gal && m_gal->IsInitialized() )
531 {
532 Connect( wxEVT_PAINT, wxPaintEventHandler( EDA_DRAW_PANEL_GAL::onPaint ), nullptr,
533 this );
534
535 Connect( wxEVT_IDLE, wxIdleEventHandler( EDA_DRAW_PANEL_GAL::onIdle ), nullptr, this );
536
537 m_drawingEnabled = true;
538 }
539 else
540 {
541 // Try again soon
542 m_refreshTimer.StartOnce( 100 );
543 return;
544 }
545 }
546
547 DoRePaint( false );
548}
549
550
552{
553 m_eventDispatcher = aEventDispatcher;
554}
555
556
558{
559 // Start querying GAL if it is ready
560 m_refreshTimer.StartOnce( 100 );
561}
562
563
565{
566 m_refreshTimer.Stop();
567 m_drawingEnabled = false;
568
569 Disconnect( wxEVT_PAINT, wxPaintEventHandler( EDA_DRAW_PANEL_GAL::onPaint ), nullptr, this );
570
571 Disconnect( wxEVT_IDLE, wxIdleEventHandler( EDA_DRAW_PANEL_GAL::onIdle ), nullptr, this );
572}
573
574
576{
577 // Set display settings for high contrast mode
578 KIGFX::RENDER_SETTINGS* rSettings = m_view->GetPainter()->GetSettings();
579
580 SetTopLayer( aLayer );
581
582 rSettings->ClearHighContrastLayers();
583 rSettings->SetLayerIsHighContrast( aLayer );
584
585 m_view->UpdateAllLayersColor();
586}
587
588
590{
591 m_view->ClearTopLayers();
592 m_view->SetTopLayer( aLayer );
593 m_view->UpdateAllLayersOrder();
594}
595
596
598{
599 // Do not do anything if the currently used GAL is correct
600 if( aGalType == m_backend && m_gal != nullptr )
601 return true;
602
603 VECTOR2D grid_size = m_gal ? m_gal->GetGridSize() : VECTOR2D();
604 bool grid_visibility = m_gal ? m_gal->GetGridVisibility() : true;
605 bool result = true; // assume everything will be fine
606
607 // Prevent refreshing canvas during backend switch
608 StopDrawing();
609
610 KIGFX::GAL* new_gal = nullptr;
611
612 try
613 {
614 switch( aGalType )
615 {
616 case GAL_TYPE_OPENGL:
617 {
618 wxString errormsg = KIGFX::OPENGL_GAL::CheckFeatures( m_options );
619
620 if( errormsg.empty() )
621 {
622 new_gal = new KIGFX::OPENGL_GAL( GetVcSettings(), m_options, this, this, this );
623 }
624 else
625 {
626 if( GAL_FALLBACK != aGalType )
627 {
628 aGalType = GAL_FALLBACK;
630 m_parent,
631 _( "Could not use OpenGL, falling back to software rendering" ),
632 errormsg );
633 new_gal = new KIGFX::CAIRO_GAL( m_options, this, this, this );
634 }
635 else
636 {
637 // We're well and truly banjaxed if we get here without a fallback.
638 DisplayInfoMessage( m_parent, _( "Could not use OpenGL" ), errormsg );
639 }
640 }
641
642 break;
643 }
644
645 case GAL_TYPE_CAIRO:
646 new_gal = new KIGFX::CAIRO_GAL( m_options, this, this, this );
647 break;
648
649 default:
650 wxASSERT( false );
652 // warn about unhandled GAL canvas type, but continue with the fallback option
653
654 case GAL_TYPE_NONE:
655 // KIGFX::GAL is a stub - it actually does cannot display anything,
656 // but prevents code relying on GAL canvas existence from crashing
657 new_gal = new KIGFX::GAL( m_options );
658 break;
659 }
660 }
661 catch( std::runtime_error& err )
662 {
663 // Create a dummy GAL
664 new_gal = new KIGFX::GAL( m_options );
665 aGalType = GAL_TYPE_NONE;
666 DisplayErrorMessage( m_parent, _( "Error switching GAL backend" ), wxString( err.what() ) );
667 result = false;
668 }
669
670 // trigger update of the gal options in case they differ from the defaults
671 m_options.NotifyChanged();
672
673 delete m_gal;
674 m_gal = new_gal;
675
676 wxSize clientSize = GetClientSize();
677 clientSize.x = std::max( 10, clientSize.x );
678 clientSize.y = std::max( 10, clientSize.y );
679 m_gal->ResizeScreen( clientSize.GetX(), clientSize.GetY() );
680
681 if( grid_size.x > 0 && grid_size.y > 0 )
682 m_gal->SetGridSize( grid_size );
683
684 m_gal->SetGridVisibility( grid_visibility );
685
686 // Make sure the cursor is set on the new canvas
688
689 if( m_painter )
690 m_painter->SetGAL( m_gal );
691
692 if( m_view )
693 {
694 m_view->SetGAL( m_gal );
695 // Note: OpenGL requires reverse draw order when draw priority is enabled
696 m_view->ReverseDrawOrder( aGalType == GAL_TYPE_OPENGL );
697 }
698
699 m_backend = aGalType;
700
701 return result;
702}
703
704
705void EDA_DRAW_PANEL_GAL::OnEvent( wxEvent& aEvent )
706{
707 bool shouldSetFocus = m_lostFocus && m_stealsFocus
708 && !KIUI::IsInputControlFocused() // Don't steal from input controls
709 && !KIUI::IsModalDialogFocused() // Don't steal from dialogs
710 && KIPLATFORM::UI::IsWindowActive( m_edaFrame ); // Don't steal from other windows
711
712 if( shouldSetFocus )
713 SetFocus();
714
715 if( !m_eventDispatcher )
716 aEvent.Skip();
717 else
718 m_eventDispatcher->DispatchWxEvent( aEvent );
719
720 Refresh();
721}
722
723
724void EDA_DRAW_PANEL_GAL::onEnter( wxMouseEvent& aEvent )
725{
726 bool shouldSetFocus = m_stealsFocus
727 && !KIUI::IsInputControlFocused() // Don't steal from input controls
728 && !KIUI::IsModalDialogFocused() // Don't steal from dialogs
729 && KIPLATFORM::UI::IsWindowActive( m_edaFrame ); // Don't steal from other windows
730
731 // Getting focus is necessary in order to receive key events properly
732 if( shouldSetFocus )
733 SetFocus();
734
735 aEvent.Skip();
736}
737
738
739void EDA_DRAW_PANEL_GAL::onLostFocus( wxFocusEvent& aEvent )
740{
741 m_lostFocus = true;
742
743 m_viewControls->CancelDrag();
744
745 // Reset the tool dispatcher's button state when focus is lost. This prevents
746 // the dispatcher from thinking the button is still pressed when focus returns,
747 // which can cause selection and drag operations to stop working.
749 m_eventDispatcher->ResetState();
750
751 aEvent.Skip();
752}
753
754
755void EDA_DRAW_PANEL_GAL::onIdle( wxIdleEvent& aEvent )
756{
758 {
759 m_needIdleRefresh = false;
760 Refresh();
761 }
762
763 aEvent.Skip();
764}
765
766
767void EDA_DRAW_PANEL_GAL::onRefreshTimer( wxTimerEvent& aEvent )
768{
769 ForceRefresh();
770}
771
772
773void EDA_DRAW_PANEL_GAL::onShowEvent( wxShowEvent& aEvent )
774{
775 if( m_gal && m_gal->IsInitialized() && m_gal->IsVisible() )
776 {
777 OnShow();
778 }
779}
780
781
783{
784 if( !m_gal )
785 return;
786
787 DPI_SCALING_COMMON dpi( nullptr, m_parent );
788
789 bool hidpi = false;
790
791 // Cursor scaling factor cannot be set for a wxCursor on GTK and OSX (at least before wx 3.3),
792 // resulting in 4x rendered size on 2x window scale.
793 // MSW renders the bitmap as-is, without scaling, so this works here.
794#ifdef __WXMSW__
795 hidpi = dpi.GetContentScaleFactor() >= 2.0;
796#endif
797
798 m_gal->SetNativeCursorStyle( aCursor, hidpi );
799}
800
801
802std::shared_ptr<KIGFX::VIEW_OVERLAY> EDA_DRAW_PANEL_GAL::DebugOverlay()
803{
804 if( !m_debugOverlay )
805 {
806 m_debugOverlay.reset( new KIGFX::VIEW_OVERLAY() );
807 m_view->Add( m_debugOverlay.get() );
808 }
809
810 return m_debugOverlay;
811}
812
813
815{
816 if( m_debugOverlay )
817 {
818 m_view->Remove( m_debugOverlay.get() );
819 m_debugOverlay = nullptr;
820 }
821}
822
823
825{
827
828 KIGFX::VC_SETTINGS vcSettings;
829 vcSettings.m_warpCursor = cfg->m_Input.center_on_zoom;
831 vcSettings.m_autoPanSettingEnabled = cfg->m_Input.auto_pan;
833 vcSettings.m_horizontalPan = cfg->m_Input.horizontal_pan;
835 vcSettings.m_zoomSpeed = cfg->m_Input.zoom_speed;
836 vcSettings.m_zoomSpeedAuto = cfg->m_Input.zoom_speed_auto;
841 vcSettings.m_dragLeft = cfg->m_Input.drag_left;
842 vcSettings.m_dragMiddle = cfg->m_Input.drag_middle;
843 vcSettings.m_dragRight = cfg->m_Input.drag_right;
846
847 return vcSettings;
848}
BASE_SCREEN class implementation.
VECTOR2D m_ScrollCenter
Current scroll center point in logical units.
Class to handle configuration and automatic determination of the DPI scale to use for canvases.
double GetContentScaleFactor() const override
Get the content scale factor, which may be different from the scale factor on some platforms.
WX_INFOBAR * GetInfoBar()
The base class for create windows for drawing purpose.
virtual BASE_SCREEN * GetScreen() const
Return a pointer to a BASE_SCREEN or one of its derivatives.
std::unique_ptr< PROF_COUNTER > m_PaintEventCounter
bool m_glRecoveryAttempted
Set after an OpenGL recovery attempt to prevent infinite retry loops.
EDA_DRAW_FRAME * m_edaFrame
Parent EDA_DRAW_FRAME (if available)
void onLostFocus(wxFocusEvent &aEvent)
static constexpr GAL_TYPE GAL_FALLBACK
std::unique_ptr< KIGFX::PAINTER > m_painter
Contains information about how to draw items using GAL.
void onSize(wxSizeEvent &aEvent)
bool m_needIdleRefresh
True when canvas needs to be refreshed from idle handler.
virtual void SetHighContrastLayer(int aLayer)
Take care of display settings for the given layer to be displayed in high contrast mode.
bool m_stealsFocus
Flag to indicate whether the panel should take focus at certain times (when moused over,...
KIGFX::GAL_DISPLAY_OPTIONS & m_options
void StopDrawing()
Prevent the GAL canvas from further drawing until it is recreated or StartDrawing() is called.
static KIGFX::VC_SETTINGS GetVcSettings()
Gets a populated View Controls settings object dervived from our program settings.
virtual void SetTopLayer(int aLayer)
Move the selected layer to the top, so it is displayed above all others.
void ClearDebugOverlay()
Clear the contents of the debug overlay and removes it from the VIEW.
virtual KIGFX::VIEW * GetView() const
Return a pointer to the #VIEW instance used in the panel.
void ForceRefresh()
Force a redraw.
bool recoverFromGalError(const std::exception &aErr)
bool m_drawing
True if GAL is currently redrawing the view.
KIGFX::GAL * m_gal
Interface for drawing objects on a 2D-surface.
EDA_DRAW_PANEL_GAL(wxWindow *aParentWindow, wxWindowID aWindowId, const wxPoint &aPosition, const wxSize &aSize, KIGFX::GAL_DISPLAY_OPTIONS &aOptions, GAL_TYPE aGalType=GAL_TYPE_OPENGL)
Create a drawing panel that is contained inside aParentWindow.
void onRefreshTimer(wxTimerEvent &aEvent)
void SetCurrentCursor(KICURSOR aCursor)
Set the current cursor shape for this panel.
virtual void onPaint(wxPaintEvent &WXUNUSED(aEvent))
bool m_lostFocus
Flag to indicate that focus should be regained on the next mouse event.
virtual void OnShow()
Called when the window is shown for the first time.
std::shared_ptr< KIGFX::VIEW_OVERLAY > m_debugOverlay
Optional overlay for drawing transient debug objects.
virtual void Refresh(bool aEraseBackground=true, const wxRect *aRect=nullptr) override
wxTimer m_refreshTimer
Timer to prevent too-frequent refreshing.
TOOL_DISPATCHER * m_eventDispatcher
Processes and forwards events to tools.
wxWindow * m_parent
Pointer to the parent window.
wxLongLong m_lastRepaintStart
Timestamp of the last repaint start.
@ GAL_TYPE_OPENGL
OpenGL implementation.
@ GAL_TYPE_CAIRO
Cairo implementation.
@ GAL_TYPE_NONE
GAL not used (the legacy wxDC engine is used)
KIGFX::VIEW * m_view
Stores view settings (scale, center, etc.) and items to be drawn.
bool m_MouseCapturedLost
used on wxMSW: true after a wxEVT_MOUSE_CAPTURE_LOST was received false after the mouse is recaptured...
KIGFX::WX_VIEW_CONTROLS * m_viewControls
Control for VIEW (moving, zooming, etc.)
void SetFocus() override
void onIdle(wxIdleEvent &aEvent)
void SetEventDispatcher(TOOL_DISPATCHER *aEventDispatcher)
Set a dispatcher that processes events and forwards them to tools.
void onEnter(wxMouseEvent &aEvent)
void RequestRefresh()
Make sure a refresh gets done on the next idle event if it hasn't already.
std::mutex m_refreshMutex
Blocks multiple calls to the draw.
virtual bool SwitchBackend(GAL_TYPE aGalType)
Switch method of rendering graphics.
void StartDrawing()
Begin drawing if it was stopped previously.
wxLongLong m_lastRepaintEnd
Timestamp of the last repaint end.
bool DoRePaint(bool aAllowSkip=true)
Repaint the canvas, and fix scrollbar cursors.
void OnEvent(wxEvent &aEvent)
Used to forward events to the canvas from popups, etc.
bool m_drawingEnabled
Flag that determines if VIEW may use GAL for redrawing the screen.
std::shared_ptr< KIGFX::VIEW_OVERLAY > DebugOverlay()
Create an overlay for rendering debug graphics.
void onShowEvent(wxShowEvent &aEvent)
static constexpr bool GAL_FALLBACK_AVAILABLE
GAL_TYPE m_backend
Currently used GAL.
VECTOR2D m_lastCursorPosition
Last cursor position sent to GAL for drawing.
EDA_DRAW_FRAME * GetParentEDAFrame() const
Returns parent EDA_DRAW_FRAME, if available or NULL otherwise.
Abstract interface for drawing on a 2D-surface.
OpenGL implementation of the Graphics Abstraction Layer.
Definition opengl_gal.h:73
static wxString CheckFeatures(GAL_DISPLAY_OPTIONS &aOptions)
Checks OpenGL features.
Container for all the knowledge about how graphical objects are drawn on any output surface/device.
void ClearHighContrastLayers()
Clear the list of active layers.
virtual const COLOR4D & GetGridColor()=0
Return current grid color settings.
virtual const COLOR4D & GetBackgroundColor() const =0
Return current background color settings.
void SetLayerIsHighContrast(int aLayerId, bool aEnabled=true)
Set the specified layer as high-contrast.
virtual const COLOR4D & GetCursorColor()=0
Return current cursor color settings.
const VECTOR2D & GetCenter() const
Return the center point of this VIEW (in world space coordinates).
Definition view.h:355
static const wxEventType EVT_REFRESH_MOUSE
Event that forces mouse move event in the dispatcher (eg.
virtual COMMON_SETTINGS * GetCommonSettings() const
Definition pgm_base.cpp:541
A small class to help profiling.
Definition profile.h:49
void Stop()
Save the time when this function was called, and set the counter stane to stop.
Definition profile.h:88
void Start()
Start or restart the counter.
Definition profile.h:77
std::string to_string()
Definition profile.h:155
RAII class that sets an value at construction and resets it to the original value at destruction.
A modified version of the wxInfoBar class that allows us to:
Definition wx_infobar.h:77
bool IsLocked()
Returns true if the infobar is being updated.
Definition wx_infobar.h:207
void DisplayInfoMessage(wxWindow *aParent, const wxString &aMessage, const wxString &aExtraInfo)
Display an informational message box with aMessage.
Definition confirm.cpp:249
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:221
This file is part of the common library.
KICURSOR
Definition cursors.h:44
@ ARROW
Definition cursors.h:46
#define _(s)
static const wxChar traceDrawPanel[]
Flag to enable drawing panel debugging output.
const wxChar *const traceGalProfile
Flag to enable debug output of GAL performance profiling.
This file contains miscellaneous commonly used macros and functions.
#define KI_FALLTHROUGH
The KI_FALLTHROUGH macro is to be used when switch statement cases should purposely fallthrough from ...
Definition macros.h:83
@ TARGET_NONCACHED
Auxiliary rendering target (noncached)
Definition definitions.h:38
@ TARGET_CACHED
Main rendering target (cached)
Definition definitions.h:37
@ TARGET_OVERLAY
Items that may change while the view stays the same (noncached)
Definition definitions.h:39
void SetOverlayScrolling(const wxWindow *aWindow, bool overlay)
Used to set overlay/non-overlay scrolling mode in a window.
Definition wxgtk/ui.cpp:288
void ImmControl(wxWindow *aWindow, bool aEnable)
Configures the IME mode of a given control handle.
Definition wxgtk/ui.cpp:405
void ImeNotifyCancelComposition(wxWindow *aWindow)
Asks the IME to cancel.
Definition wxgtk/ui.cpp:410
bool IsWindowActive(wxWindow *aWindow)
Check to see if the given window is the currently active window (e.g.
Definition wxgtk/ui.cpp:147
KICOMMON_API bool IsInputControlFocused(wxWindow *aFocus=nullptr)
Check if a input control has focus.
KICOMMON_API bool IsModalDialogFocused()
PGM_BASE & Pgm()
The global program "get" accessor.
see class PGM_BASE
MOUSE_DRAG_ACTION drag_right
MOUSE_DRAG_ACTION drag_middle
MOUSE_DRAG_ACTION drag_left
Structure to keep VIEW_CONTROLS settings for easy store/restore operations.
MOUSE_DRAG_ACTION m_dragLeft
bool m_horizontalPan
Enable horizontal panning with the horizontal scroll/trackpad input.
bool m_scrollReversePanH
Whether to invert the scroll wheel movement for horizontal pan.
bool m_autoPanSettingEnabled
Flag for turning on autopanning.
bool m_focusFollowSchPcb
Flag for automatic focus switching between Schematic and PCB editors.
float m_autoPanAcceleration
How fast does panning accelerate when approaching the window boundary.
MOUSE_DRAG_ACTION m_dragMiddle
int m_zoomSpeed
Zoom speed for the non-accelerating zoom controller.
int m_scrollModifierZoom
What modifier key to enable zoom with the (vertical) scroll wheel.
int m_scrollModifierPanH
What modifier key to enable horizontal pan with the (vertical) scroll wheel.
bool m_warpCursor
If the cursor is allowed to be warped.
MOUSE_DRAG_ACTION m_dragRight
bool m_scrollReverseZoom
Whether to invert the scroll wheel movement for zoom.
int m_motionPanModifier
What modifier key pans the view when the mouse moves with it held.
bool m_zoomAcceleration
Enable the accelerating zoom controller.
bool m_zoomSpeedAuto
When true, ignore zoom_speed and pick a platform-specific default.
int m_scrollModifierPanV
What modifier key to enable vertical with the (vertical) scroll wheel.
wxString result
Test unit parsing edge cases and error handling.
int delta
wxLogTrace helper definitions.
VECTOR2< double > VECTOR2D
Definition vector2d.h:686
VECTOR2I ToVECTOR2I(const wxSize &aSize)
Definition vector2wx.h:30
WX_VIEW_CONTROLS class definition.