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, see <https://www.gnu.org/licenses/>.
22 */
23#include <eda_draw_frame.h>
24#include <kiface_base.h>
25#include <macros.h>
26#include <scoped_set_reset.h>
28#include <trace_helpers.h>
29
31#include <view/view.h>
33#include <gal/painter.h>
34#include <base_screen.h>
35#include <gal/cursors.h>
39#include <gal/cairo/cairo_gal.h>
40#include <math/vector2wx.h>
41
42
44#include <tool/tool_manager.h>
45
46#include <widgets/wx_infobar.h>
47
48#include <kiplatform/touchpad.h>
49#include <kiplatform/ui.h>
50
51#include <stdexcept>
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 ),
76 m_drawing( false ),
77 m_drawingEnabled( false ),
78 m_needIdleRefresh( false ),
79 m_gal( nullptr ),
80 m_view( nullptr ),
81 m_painter( nullptr ),
82 m_viewControls( nullptr ),
84 m_options( aOptions ),
85 m_eventDispatcher( nullptr ),
86 m_lostFocus( false ),
87 m_glRecoveryAttempted( false ),
89 m_rebuiltAfterReset( false ),
90 m_pendingResize( false ),
91 m_stealsFocus( true ),
92 m_statusPopup( nullptr )
93{
94#ifdef _WIN32
95 // need to fix broken cairo rendering on Windows with wx 3.3
96 SetDoubleBuffered( false );
97#endif
98 m_PaintEventCounter = std::make_unique<PROF_COUNTER>( "Draw panel paint events" );
99
100 if( Pgm().GetCommonSettings()->m_Appearance.show_scrollbars )
101 ShowScrollbars( wxSHOW_SB_ALWAYS, wxSHOW_SB_ALWAYS );
102 else
103 ShowScrollbars( wxSHOW_SB_NEVER, wxSHOW_SB_NEVER );
104
105 SetLayoutDirection( wxLayout_LeftToRight );
106
107 m_edaFrame = dynamic_cast<EDA_DRAW_FRAME*>( m_parent );
108
109 // If we're in a dialog, we have to go looking for our parent frame
110 if( !m_edaFrame )
111 {
112 wxWindow* ancestor = aParentWindow->GetParent();
113
114 while( ancestor && !dynamic_cast<EDA_DRAW_FRAME*>( ancestor ) )
115 ancestor = ancestor->GetParent();
116
117 if( ancestor )
118 m_edaFrame = dynamic_cast<EDA_DRAW_FRAME*>( ancestor );
119 }
120
121 SwitchBackend( aGalType );
122 SetBackgroundStyle( wxBG_STYLE_CUSTOM );
123
124 EnableScrolling( false, false ); // otherwise Zoom Auto disables GAL canvas
125 KIPLATFORM::UI::SetOverlayScrolling( this, false ); // Prevent excessive repaint on GTK
126 KIPLATFORM::UI::ImmControl( this, false ); // Ensure our panel can't suck in IME events
127
128 Connect( wxEVT_SIZE, wxSizeEventHandler( EDA_DRAW_PANEL_GAL::onSize ), nullptr, this );
129 Connect( wxEVT_ENTER_WINDOW, wxMouseEventHandler( EDA_DRAW_PANEL_GAL::onEnter ), nullptr, this );
130 Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( EDA_DRAW_PANEL_GAL::onLostFocus ), nullptr, this );
131
132 const wxEventType events[] = {
133 // Binding both EVT_CHAR and EVT_CHAR_HOOK ensures that all key events,
134 // especially special key like arrow keys, are handled by the GAL event dispatcher,
135 // and not sent to GUI without filtering, because they have a default action (scroll)
136 // that must not be called.
137 wxEVT_LEFT_UP,
138 wxEVT_LEFT_DOWN,
139 wxEVT_LEFT_DCLICK,
140 wxEVT_RIGHT_UP,
141 wxEVT_RIGHT_DOWN,
142 wxEVT_RIGHT_DCLICK,
143 wxEVT_MIDDLE_UP,
144 wxEVT_MIDDLE_DOWN,
145 wxEVT_MIDDLE_DCLICK,
146 wxEVT_AUX1_UP,
147 wxEVT_AUX1_DOWN,
148 wxEVT_AUX1_DCLICK,
149 wxEVT_AUX2_UP,
150 wxEVT_AUX2_DOWN,
151 wxEVT_AUX2_DCLICK,
152 wxEVT_MOTION,
153 wxEVT_MOUSEWHEEL,
154 wxEVT_CHAR,
155 wxEVT_CHAR_HOOK,
156 wxEVT_MAGNIFY,
158 };
159
160 for( wxEventType eventType : events )
161 Connect( eventType, wxEventHandler( EDA_DRAW_PANEL_GAL::OnEvent ), nullptr, m_eventDispatcher );
162
163 // Set up timer to detect when drawing starts
164 m_refreshTimer.SetOwner( this );
165 Connect( m_refreshTimer.GetId(), wxEVT_TIMER, wxTimerEventHandler( EDA_DRAW_PANEL_GAL::onRefreshTimer ),
166 nullptr, this );
167
168 Connect( wxEVT_SHOW, wxShowEventHandler( EDA_DRAW_PANEL_GAL::onShowEvent ), nullptr, this );
169}
170
171
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 // A predicted GPU out-of-memory cannot be cured by reinitializing OpenGL; it would just
206 // hit the same VRAM ceiling. Skip straight to the software fallback.
207 const bool gpuOutOfMemory = dynamic_cast<const KIGFX::GPU_OOM_ERROR*>( &aError ) != nullptr;
208
209 try
210 {
211 // Reset detection only runs inside LockContext, and this frame's lock came before the reset
212 if( m_gal && !m_gal->IsContextLocked() )
214
215 // A reset seen mid-frame surfaces as a GL error; rebuild rather than spend the one-shot recovery
216 if( handleContextLoss() )
217 return true;
218
219 // Sleep/wake and GPU resets can invalidate the entire GL context.
220 // Try a full reinit of the current backend before falling back.
221 if( !gpuOutOfMemory && !m_glRecoveryAttempted )
222 {
224 GAL_TYPE prevBackend = m_backend;
226
227 if( SwitchBackend( prevBackend ) )
228 {
229 StartDrawing();
230 return true;
231 }
232 }
233
235 {
236 m_glRecoveryAttempted = false;
238
240 {
241 // Some drivers refuse new framebuffers to a process for the rest of its life after a reset
242 m_rebuiltAfterReset = false;
244 showMessageLater( _( "The graphics driver was reset and OpenGL could not be restored" ),
245 _( "Restart KiCad to use accelerated graphics again." ), false );
246 }
247 else
248 {
249 showMessageLater( _( "Could not use OpenGL, falling back to software rendering" ),
250 wxString( aError.what() ), false );
251 }
252
253 StartDrawing();
254 return true;
255 }
256
257 showMessageLater( _( "Graphics error" ), wxString( aError.what() ), true );
258 }
259 catch( std::exception& recoveryErr )
260 {
261 showMessageLater( _( "Graphics error during recovery" ), wxString( recoveryErr.what() ), true );
262 }
263 catch( ... )
264 {
265 showMessageLater( _( "Graphics error during recovery" ), _( "Unknown exception during backend switch" ),
266 true );
267 }
268
269 return false;
270}
271
272
274{
276
278 return false;
279
280 // Deleting a GAL that someone still holds locked would leave them unlocking freed memory
281 if( m_gal->IsContextLocked() )
282 return true;
283
284 // Hidden canvases rebuild when next shown, since a new GAL cannot initialize off screen
285 if( !IsShownOnScreen() )
286 return true;
287
288 // Rebuilding while the driver is still resetting can fail or hang, so poll until it finishes
289 if( !m_gal->IsResetSettled() )
290 {
291 m_refreshTimer.StartOnce( 20 );
292 return true;
293 }
294
295 wxLogTrace( traceGalContext, wxS( "Rebuilding canvas %p after GPU reset, repeated %d" ), this,
296 loss == KIGFX::GAL_CONTEXT_LOSS::REPEATED ? 1 : 0 );
297
298 bool rebuilt = false;
299
301 {
302 GAL_TYPE backend = m_backend;
303
304 // Forces SwitchBackend to build a new GAL of the same type
306 rebuilt = SwitchBackend( backend );
307 m_rebuiltAfterReset = rebuilt;
308 }
309
310 // SwitchBackend already reported a failed rebuild, so only a repeated loss needs the notice
311 if( !rebuilt && GAL_FALLBACK_AVAILABLE )
312 {
313 static bool s_notified = false;
314
315 wxLogTrace( traceGalContext, wxS( "Canvas %p falling back to software rendering" ), this );
318
319 if( loss == KIGFX::GAL_CONTEXT_LOSS::REPEATED && !s_notified )
320 {
321 s_notified = true;
322 showMessageLater( _( "The graphics driver keeps resetting, falling back to software rendering" ),
323 wxEmptyString, false );
324 }
325 }
326
327 StartDrawing();
328 return true;
329}
330
331
332void EDA_DRAW_PANEL_GAL::showMessageLater( const wxString& aTitle, const wxString& aDetail, bool aError )
333{
334 wxWindow* parent = m_parent;
335
336 CallAfter(
337 [parent, aTitle, aDetail, aError]()
338 {
339 if( aError )
340 DisplayErrorMessage( parent, aTitle, aDetail );
341 else
342 DisplayInfoMessage( parent, aTitle, aDetail );
343 } );
344}
345
346
348static constexpr int MAX_CONTEXT_BIND_RETRIES = 2;
349
350
351bool EDA_DRAW_PANEL_GAL::DoRePaint( bool aAllowSkip )
352{
353 if( !m_refreshMutex.try_lock() )
354 return false;
355
356 std::lock_guard<std::mutex> lock( m_refreshMutex, std::adopt_lock );
357
358 if( !m_drawingEnabled )
359 return false;
360
361 if( handleContextLoss() )
362 return false;
363
364 if( !m_gal->IsInitialized() || !m_gal->IsVisible() || m_gal->IsContextLocked() )
365 return false;
366
367 if( m_drawing )
368 return false;
369
370 // The context may have become current since the size change was deferred
371 if( m_pendingResize )
372 ResizeGal();
373
374 m_lastRepaintStart = std::chrono::steady_clock::now();
375
376 // Repaint the canvas, and fix scrollbar cursors
377 // Usually called by a OnPaint event, but because it does not use a wxPaintDC,
378 // it can be called outside a wxPaintEvent.
379
380 // Update current zoom settings if the canvas is managed by a EDA frame
381 // (i.e. not by a preview panel in a dialog)
382 if( !IsDialogPreview() && GetParentEDAFrame() && GetParentEDAFrame()->GetScreen() )
384
385 if( Pgm().GetCommonSettings()->m_Appearance.show_scrollbars )
386 m_viewControls->UpdateScrollbars();
387
388#ifdef KICAD_GAL_PROFILE
389 latencyProbeZoomToRender.Checkpoint("do-repaint-start");
390#endif
391
392 SCOPED_SET_RESET<bool> drawing( m_drawing, true );
393
394 ( *m_PaintEventCounter )++;
395
396 wxASSERT( m_painter );
397
398 KIGFX::RENDER_SETTINGS* settings =
399 static_cast<KIGFX::RENDER_SETTINGS*>( m_painter->GetSettings() );
400
401 PROF_TIMER cntUpd("view-upd-items", false);
402 PROF_TIMER cntTotal("view-total", false);
403 PROF_TIMER cntCtx("view-context-create", false);
404 PROF_TIMER cntCtxDestroy("view-context-destroy", false);
405 PROF_TIMER cntRedraw("view-redraw-rects", false);
406
407 bool isDirty = false;
408
409 cntTotal.Start();
410
411 try
412 {
413 VECTOR2D cursorPos = m_viewControls->GetCursorPosition();
414 bool viewDirty = m_view->IsDirty();
415 bool cursorMoved = ( cursorPos != m_lastCursorPosition );
416 bool hasPendingItemUpdates = m_view->HasPendingItemUpdates();
417
418 // Skip all update work when nothing has changed since the previous frame.
419 // Never skip when responding to a native paint event or explicit ForceRefresh
420 // because the window content may have been invalidated by the OS.
421 if( aAllowSkip && !viewDirty && !cursorMoved && !hasPendingItemUpdates )
422 {
423 m_lastRepaintEnd = std::chrono::steady_clock::now();
424 return true;
425 }
426
427 if( hasPendingItemUpdates )
428 {
429 cntUpd.Start();
430
431 try
432 {
433 m_view->UpdateItems();
434 }
435 catch( std::out_of_range& err )
436 {
437 // Don't do anything here but don't fail
438 // This can happen when we don't catch `at()` calls
439 wxLogTrace( traceDrawPanel, wxS( "Out of Range error: %s" ), err.what() );
440 }
441 catch( std::runtime_error& err )
442 {
443 // Handle GL errors (e.g. glMapBuffer failure) that surface during UpdateItems().
444 // These can occur on macOS under memory pressure when embedding large 3D models.
445 // Log and continue so the outer handler can decide whether to switch backends.
446 wxLogTrace( traceDrawPanel, wxS( "Runtime error during UpdateItems: %s" ),
447 err.what() );
448 throw;
449 }
450
451 cntUpd.Stop();
452 viewDirty = m_view->IsDirty();
453 }
454
455 // After processing item updates, skip the GL cycle when neither the
456 // view targets nor the cursor position have changed.
457 if( aAllowSkip && !viewDirty && !cursorMoved )
458 {
459 m_lastRepaintEnd = std::chrono::steady_clock::now();
460 return true;
461 }
462
463 m_lastCursorPosition = cursorPos;
464
465 // GAL_DRAWING_CONTEXT can throw in the dtor, so we need to scope
466 // the full lifetime inside the try block
467 {
468 cntCtx.Start();
470 cntCtx.Stop();
471
472 if( !ctx.IsDrawing() )
473 {
474 // A canvas being torn down never reaches here; DoRePaint returns above once
475 // the window stops being visible. So repeated failures mean a live canvas
476 // whose context is gone for good, and retrying forever would leave it blank
478 throw std::runtime_error( "Could not make the OpenGL context current" );
479
481 return false;
482 }
483
484 if( m_view->IsTargetDirty( KIGFX::TARGET_OVERLAY )
485 && !m_gal->HasTarget( KIGFX::TARGET_OVERLAY ) )
486 {
487 m_view->MarkDirty();
488 }
489
490 m_gal->SetClearColor( settings->GetBackgroundColor() );
491 m_gal->SetGridColor( settings->GetGridColor() );
492 m_gal->SetCursorColor( settings->GetCursorColor() );
493
494 // OpenGL double-buffering leaves the back buffer undefined after
495 // SwapBuffers, so a full clear is always required before compositing.
496 // Cairo only needs to clear when NONCACHED content changed.
498 m_gal->ClearScreen();
499
500 if( m_view->IsDirty() )
501 {
502 if( m_backend != GAL_TYPE_OPENGL // Already called in opengl
503 && m_view->IsTargetDirty( KIGFX::TARGET_NONCACHED ) )
504 {
505 m_gal->ClearScreen();
506 }
507
508 m_view->ClearTargets();
509
510 // Grid has to be redrawn only when the NONCACHED target is redrawn
511 if( m_view->IsTargetDirty( KIGFX::TARGET_NONCACHED ) )
512 {
514 m_gal->DrawGrid();
515 }
516
517 cntRedraw.Start();
518 m_view->Redraw();
519 cntRedraw.Stop();
520 isDirty = true;
521 }
522
523 m_gal->DrawCursor( cursorPos );
524
525 #ifdef KICAD_GAL_PROFILE
526 latencyProbeZoomToRender.Checkpoint("do-repaint-pre-ctx-destroy");
527 #endif
528
529
530 cntCtxDestroy.Start();
531 }
532
533 // ctx goes out of scope here so destructor would be called
534 cntCtxDestroy.Stop();
535
536#ifdef KICAD_GAL_PROFILE
537 latencyProbeZoomToRender.Checkpoint("do-repaint-ctx-done");
538#endif
539
540 // OpenGL frame completed successfully, allow future recovery attempts
541 m_glRecoveryAttempted = false;
543 m_rebuiltAfterReset = false;
544 }
545 catch( std::exception& err )
546 {
547 wxLogTrace( traceDrawPanel, wxS( "DoRePaint exception: %s" ), err.what() );
548
549 if( recoverFromGalError( err ) )
550 return true;
551
552 StopDrawing();
553 }
554 catch( ... )
555 {
556 showMessageLater( _( "Graphics error" ), _( "Unknown exception" ), true );
557 StopDrawing();
558 }
559
560 if( isDirty )
561 {
562#ifdef KICAD_GAL_PROFILE
563 wxLogTrace( traceGalProfile, "View timing: %s %s %s %s %s",
564 cntTotal.to_string(),
565 cntUpd.to_string(),
566 cntRedraw.to_string(),
567 cntCtx.to_string(),
568 cntCtxDestroy.to_string()
569 );
570#endif
571 }
572
573 m_lastRepaintEnd = std::chrono::steady_clock::now();
574
575#ifdef KICAD_GAL_PROFILE
576 wxLogTrace( traceGalProfile, "%s", latencyProbeZoomToRender.to_string() );
577 latencyProbeRepaintToMotion.Reset();
578 latencyProbeRepaintToMotion.Checkpoint("repaint-done");
579#endif
580
581 return true;
582}
583
584
585void EDA_DRAW_PANEL_GAL::onSize( wxSizeEvent& aEvent )
586{
587 ResizeGal();
588}
589
590
592{
593 // If we get a second wx update call before the first finishes, don't crash
594 if( m_gal->IsContextLocked() )
595 return;
596
598
599 // Resizing reallocates the framebuffer, which only exists in this canvas' own context
600 if( !m_gal->IsContextValid() )
601 {
602 // wx reports a given size once, so dropping it here would leave the canvas stuck at
603 // whatever size the GAL was built with until something else resizes the window
604 m_pendingResize = true;
606 return;
607 }
608
609 m_pendingResize = false;
610
611 wxSize clientSize = GetClientSize();
612
613 if( !aForce && ToVECTOR2I( clientSize ) == m_gal->GetScreenPixelSize() )
614 return;
615
616 // Note: ( +1, +1 ) prevents an ugly black line on right and bottom on Mac
617 clientSize.x = std::max( 10, clientSize.x + 1 );
618 clientSize.y = std::max( 10, clientSize.y + 1 );
619
620 m_gal->ResizeScreen( clientSize.GetX(), clientSize.GetY() );
621
622 if( m_view )
623 {
624 // ResizeScreen reallocates every compositor buffer, so nothing survives the resize
625 m_view->MarkDirty();
626 }
627}
628
629
631{
632 KIGFX::CAIRO_GAL* cairoGal = dynamic_cast<KIGFX::CAIRO_GAL*>( m_gal );
633
634 // Only the Cairo backend presents frames outside the paint cycle
635 if( !cairoGal )
636 return;
637
638 std::vector<wxRect> rects;
639
640 for( wxWindow* child : GetChildren() )
641 {
642 if( dynamic_cast<WX_INFOBAR*>( child ) && child->IsShown() )
643 rects.push_back( child->GetRect() );
644 }
645
646 cairoGal->SetOverlayExclusions( rects );
647}
648
649
654
655
656void EDA_DRAW_PANEL_GAL::Refresh( bool aEraseBackground, const wxRect* aRect )
657{
658 auto now = std::chrono::steady_clock::now();
659 auto delta = std::chrono::duration_cast<std::chrono::milliseconds>( now - m_lastRepaintStart ).count();
660 bool galInitialized = m_gal && m_gal->IsInitialized();
661
662 // When vsync is available the driver throttles SwapBuffers, so we only need
663 // a small guard to avoid queueing work faster than the GPU can consume it.
664 // Without vsync, cap the render rate at the monitor refresh rate so the
665 // GPU is not saturated producing frames that will never be shown.
666 int minPeriodMs = 3;
667
668 if( galInitialized && m_gal->GetSwapInterval() == 0 )
669 {
670 // wxDisplay reports 0 on headless, some virtualized, and a few driver
671 // combinations. Clamp to a plausible monitor range before trusting it
672 // and fall back to 60 Hz otherwise.
673 int refreshHz = 60;
674 int reported = wxDisplay( this ).GetCurrentMode().refresh;
675
676 if( reported >= 24 && reported <= 1000 )
677 refreshHz = reported;
678
679 refreshHz += 5; // Repaint slightly faster to avoid adding latency
680
681 minPeriodMs = 1000 / refreshHz;
682 }
683
684 if( delta >= minPeriodMs )
685 {
686 if( !DoRePaint() )
688 }
689 else if( !m_refreshTimer.IsRunning() )
690 {
691 m_refreshTimer.StartOnce( static_cast<int>( minPeriodMs - delta ) );
692 }
693}
694
695
697{
698 if( !m_drawingEnabled )
699 {
700 if( m_gal && m_gal->IsInitialized() )
701 {
702 Connect( wxEVT_PAINT, wxPaintEventHandler( EDA_DRAW_PANEL_GAL::onPaint ), nullptr, this );
703 Connect( wxEVT_IDLE, wxIdleEventHandler( EDA_DRAW_PANEL_GAL::onIdle ), nullptr, this );
704
705 m_drawingEnabled = true;
706 }
707 else
708 {
709 // Try again soon
710 m_refreshTimer.StartOnce( 100 );
711 return;
712 }
713 }
714
715 DoRePaint( false );
716}
717
718
719bool EDA_DRAW_PANEL_GAL::GetScreenshot( wxImage& aDstImage )
720{
721 if( m_backend != GAL_TYPE_OPENGL || !m_gal )
722 return false;
723
724 DoRePaint( false );
725
726 // The repaint may have replaced a GAL lost to a GPU reset
727 if( m_backend != GAL_TYPE_OPENGL || !m_gal )
728 return false;
729
730 return static_cast<KIGFX::OPENGL_GAL*>( m_gal )->GetScreenshot( aDstImage );
731}
732
733
735{
736 m_eventDispatcher = aEventDispatcher;
737}
738
739
741{
742 // Start querying GAL if it is ready
743 m_refreshTimer.StartOnce( 100 );
744}
745
746
748{
749 m_refreshTimer.Stop();
750 m_drawingEnabled = false;
751
752 Disconnect( wxEVT_PAINT, wxPaintEventHandler( EDA_DRAW_PANEL_GAL::onPaint ), nullptr, this );
753 Disconnect( wxEVT_IDLE, wxIdleEventHandler( EDA_DRAW_PANEL_GAL::onIdle ), nullptr, this );
754}
755
756
758{
759 // Set display settings for high contrast mode
760 KIGFX::RENDER_SETTINGS* rSettings = m_view->GetPainter()->GetSettings();
761
762 SetTopLayer( aLayer );
763
764 rSettings->ClearHighContrastLayers();
765 rSettings->SetLayerIsHighContrast( aLayer );
766
767 m_view->UpdateAllLayersColor();
768}
769
770
772{
773 m_view->ClearTopLayers();
774 m_view->SetTopLayer( aLayer );
775 m_view->UpdateAllLayersOrder();
776}
777
778
780{
781 if( aStoredCanvasType == GAL_TYPE_CAIRO )
782 return GAL_TYPE_CAIRO;
783
784 // The retired wxDC canvas, and any value another KiCad version may have written, leave the
785 // user with the accelerated canvas rather than the do-nothing stub GAL
786 return GAL_TYPE_OPENGL;
787}
788
789
791{
792 // Do not do anything if the currently used GAL is correct
793 if( aGalType == m_backend && m_gal != nullptr )
794 return true;
795
796 VECTOR2D grid_size = m_gal ? m_gal->GetGridSize() : VECTOR2D();
797 bool grid_visibility = m_gal ? m_gal->GetGridVisibility() : true;
798 bool result = true; // assume everything will be fine
799
800 // Prevent refreshing canvas during backend switch
801 StopDrawing();
802
804 m_pendingResize = false;
805
806 KIGFX::GAL* new_gal = nullptr;
807
808 try
809 {
810 switch( aGalType )
811 {
812 case GAL_TYPE_OPENGL:
813 {
814 wxString errormsg = KIGFX::OPENGL_GAL::CheckFeatures( m_options );
815
816 if( errormsg.empty() )
817 {
818 new_gal = new KIGFX::OPENGL_GAL( GetVcSettings(), m_options, this, this, this );
819 }
820 else
821 {
822 if( GAL_FALLBACK != aGalType )
823 {
824 aGalType = GAL_FALLBACK;
825 showMessageLater( _( "Could not use OpenGL, falling back to software rendering" ), errormsg,
826 false );
827 new_gal = new KIGFX::CAIRO_GAL( m_options, this, this, this );
828 }
829 else
830 {
831 // We're well and truly banjaxed if we get here without a fallback.
832 showMessageLater( _( "Could not use OpenGL" ), errormsg, false );
833 new_gal = new KIGFX::GAL( m_options );
834 aGalType = GAL_TYPE_NONE;
835 result = false;
836 }
837 }
838
839 break;
840 }
841
842 case GAL_TYPE_CAIRO:
843 new_gal = new KIGFX::CAIRO_GAL( m_options, this, this, this );
844 break;
845
846 default:
847 wxASSERT( false );
849 // warn about unhandled GAL canvas type, but continue with the fallback option
850
851 case GAL_TYPE_NONE:
852 // KIGFX::GAL is a stub - it actually does cannot display anything,
853 // but prevents code relying on GAL canvas existence from crashing
854 new_gal = new KIGFX::GAL( m_options );
855 break;
856 }
857 }
858 catch( std::runtime_error& err )
859 {
860 // A context the driver refuses to create would otherwise leave every frame on the blank stub
861 if( aGalType == GAL_TYPE_OPENGL && GAL_FALLBACK_AVAILABLE )
862 {
863 try
864 {
865 new_gal = new KIGFX::CAIRO_GAL( m_options, this, this, this );
866 aGalType = GAL_FALLBACK;
868 showMessageLater( _( "Could not use OpenGL, falling back to software rendering" ),
869 wxString( err.what() ), false );
870 }
871 catch( std::runtime_error& )
872 {
873 new_gal = nullptr;
874 }
875 }
876
877 if( !new_gal )
878 {
879 // Create a dummy GAL
880 new_gal = new KIGFX::GAL( m_options );
881 aGalType = GAL_TYPE_NONE;
882 showMessageLater( _( "Error switching GAL backend" ), wxString( err.what() ), true );
883 result = false;
884 }
885 }
886
887 // trigger update of the gal options in case they differ from the defaults
888 m_options.NotifyChanged();
889
890 // The native touchpad hook is attached to the backend's child window.
892
893 delete m_gal;
894 m_gal = new_gal;
895
896 wxSize clientSize = GetClientSize();
897 clientSize.x = std::max( 10, clientSize.x );
898 clientSize.y = std::max( 10, clientSize.y );
899 m_gal->ResizeScreen( clientSize.GetX(), clientSize.GetY() );
900
901 if( grid_size.x > 0 && grid_size.y > 0 )
902 m_gal->SetGridSize( grid_size );
903
904 m_gal->SetGridVisibility( grid_visibility );
905
906 // Make sure the cursor is set on the new canvas
908
909 if( m_painter )
910 m_painter->SetGAL( m_gal );
911
912 if( m_view )
913 {
914 m_view->SetGAL( m_gal );
915 // Note: OpenGL requires reverse draw order when draw priority is enabled
916 m_view->ReverseDrawOrder( aGalType == GAL_TYPE_OPENGL );
917 }
918
919 m_backend = aGalType;
920
921 // A shown backend window raises itself, which would bury an infobar overlaid on this canvas
922 for( wxWindow* child : GetChildren() )
923 {
924 if( dynamic_cast<WX_INFOBAR*>( child ) )
925 child->Raise();
926 }
927
929
931
932 return result;
933}
934
935
937{
939
940 if( Pgm().GetCommonSettings()->m_Input.touchpad_mode != TOUCHPAD_MODE::NATIVE_GESTURES )
941 return;
942
943 if( wxWindow* inputWindow = dynamic_cast<wxWindow*>( m_gal ) )
944 {
946 inputWindow,
947 [this]( const KIPLATFORM::UI::TOUCHPAD_GESTURE& aGesture )
948 {
949 if( !m_viewControls )
950 return;
951
952 m_viewControls->ApplyPanAndZoomGesture(
953 VECTOR2D( aGesture.panX, aGesture.panY ), aGesture.zoomFactor,
954 VECTOR2D( aGesture.zoomAnchor.x, aGesture.zoomAnchor.y ) );
955 } );
956 }
957}
958
959
960void EDA_DRAW_PANEL_GAL::OnEvent( wxEvent& aEvent )
961{
962 bool shouldSetFocus = m_lostFocus && m_stealsFocus
963 && !KIUI::IsInputControlFocused() // Don't steal from input controls
964 && !KIUI::IsModalDialogFocused() // Don't steal from dialogs
965 && KIPLATFORM::UI::IsWindowActive( m_edaFrame ); // Don't steal from other windows
966
967 if( shouldSetFocus )
968 SetFocus();
969
970 if( !m_eventDispatcher )
971 aEvent.Skip();
972 else
973 m_eventDispatcher->DispatchWxEvent( aEvent );
974
975 Refresh();
976}
977
978
979void EDA_DRAW_PANEL_GAL::onEnter( wxMouseEvent& aEvent )
980{
981 bool shouldSetFocus = m_stealsFocus
982 && !KIUI::IsInputControlFocused() // Don't steal from input controls
983 && !KIUI::IsModalDialogFocused() // Don't steal from dialogs
984 && KIPLATFORM::UI::IsWindowActive( m_edaFrame ); // Don't steal from other windows
985
986 // Getting focus is necessary in order to receive key events properly
987 if( shouldSetFocus )
988 SetFocus();
989
990 aEvent.Skip();
991}
992
993
994void EDA_DRAW_PANEL_GAL::onLostFocus( wxFocusEvent& aEvent )
995{
996 m_lostFocus = true;
997
998 m_viewControls->CancelDrag();
999
1000 // Reset the tool dispatcher's button state when focus is lost. This prevents
1001 // the dispatcher from thinking the button is still pressed when focus returns,
1002 // which can cause selection and drag operations to stop working.
1003 if( m_eventDispatcher )
1004 m_eventDispatcher->ResetState();
1005
1006 aEvent.Skip();
1007}
1008
1009
1010void EDA_DRAW_PANEL_GAL::onIdle( wxIdleEvent& aEvent )
1011{
1012 if( m_needIdleRefresh )
1013 {
1014 m_needIdleRefresh = false;
1015 Refresh();
1016 }
1017
1018 aEvent.Skip();
1019}
1020
1021
1022void EDA_DRAW_PANEL_GAL::onRefreshTimer( wxTimerEvent& aEvent )
1023{
1024 ForceRefresh();
1025}
1026
1027
1028void EDA_DRAW_PANEL_GAL::onShowEvent( wxShowEvent& aEvent )
1029{
1030 if( m_gal && m_gal->IsInitialized() && m_gal->IsVisible() )
1031 {
1032 OnShow();
1033 }
1034}
1035
1036
1038{
1039 if( !m_gal )
1040 return;
1041
1042 DPI_SCALING_COMMON dpi( nullptr, m_parent );
1043
1044 bool hidpi = false;
1045
1046 // Cursor scaling factor cannot be set for a wxCursor on GTK and OSX (at least before wx 3.3),
1047 // resulting in 4x rendered size on 2x window scale.
1048 // MSW renders the bitmap as-is, without scaling, so this works here.
1049#ifdef __WXMSW__
1050 hidpi = dpi.GetContentScaleFactor() >= 2.0;
1051#endif
1052
1053 m_gal->SetNativeCursorStyle( aCursor, hidpi );
1054}
1055
1056
1057std::shared_ptr<KIGFX::VIEW_OVERLAY> EDA_DRAW_PANEL_GAL::DebugOverlay()
1058{
1059 if( !m_debugOverlay )
1060 {
1061 m_debugOverlay.reset( new KIGFX::VIEW_OVERLAY() );
1062 m_view->Add( m_debugOverlay.get() );
1063 }
1064
1065 return m_debugOverlay;
1066}
1067
1068
1070{
1071 if( m_debugOverlay )
1072 {
1073 m_view->Remove( m_debugOverlay.get() );
1074 m_debugOverlay = nullptr;
1075 }
1076}
1077
1078
1080{
1082
1083 KIGFX::VC_SETTINGS vcSettings;
1084 vcSettings.m_warpCursor = cfg->m_Input.center_on_zoom;
1086 vcSettings.m_autoPanSettingEnabled = cfg->m_Input.auto_pan;
1088 vcSettings.m_horizontalPan = cfg->m_Input.horizontal_pan;
1090 vcSettings.m_zoomSpeed = cfg->m_Input.zoom_speed;
1091 vcSettings.m_zoomSpeedAuto = cfg->m_Input.zoom_speed_auto;
1096 vcSettings.m_dragLeft = cfg->m_Input.drag_left;
1097 vcSettings.m_dragMiddle = cfg->m_Input.drag_middle;
1098 vcSettings.m_dragRight = cfg->m_Input.drag_right;
1101
1102 return vcSettings;
1103}
BASE_SCREEN class implementation.
VECTOR2D m_ScrollCenter
Current scroll center point in logical units.
Definition base_screen.h:96
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.
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.
static void SetOpenGLFailureOccurred()
Keep every frame on the fallback canvas for this session without changing the saved preference.
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.
bool m_rebuiltAfterReset
The GAL was rebuilt after a GPU reset and has not completed a frame yet.
void onSize(wxSizeEvent &aEvent)
bool m_pendingResize
Set when a size change could not be applied because the GL context was unavailable.
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 KIGFX::VIEW instance used in the panel.
void ForceRefresh()
Force a redraw.
bool recoverFromGalError(const std::exception &aErr)
void ResizeGal(bool aForce=false)
Resize the GAL to the current client size of this panel.
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.
std::chrono::steady_clock::time_point m_lastRepaintStart
Timestamp of the last repaint start.
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::chrono::steady_clock::time_point m_lastRepaintEnd
Timestamp of the last repaint end.
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.
@ GAL_TYPE_OPENGL
OpenGL implementation.
@ GAL_TYPE_CAIRO
Cairo implementation.
@ GAL_TYPE_NONE
GAL not used (the legacy wxDC engine is used)
virtual void prepareGridSources()
Hook for subclasses to push per-frame grid sources onto the GAL.
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 UpdateTouchpadGestureHandler()
Apply the current native touchpad gesture preference to the active backend window.
void SetEventDispatcher(TOOL_DISPATCHER *aEventDispatcher)
Set a dispatcher that processes events and forwards them to tools.
void UpdateOverlayExclusions()
Tell the backend which areas of this panel are covered by an overlaid infobar.
void onEnter(wxMouseEvent &aEvent)
void showMessageLater(const wxString &aTitle, const wxString &aDetail, bool aError)
Show a recovery message once the current event finishes.
std::unique_ptr< KIPLATFORM::UI::TOUCHPAD_GESTURE_HANDLER > m_touchpadGestureHandler
void RequestRefresh()
Make sure a refresh gets done on the next idle event if it hasn't already.
int m_contextBindFailures
Consecutive frames dropped because the GL context could not be made current.
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.
static GAL_TYPE ResolveStoredCanvasType(int aStoredCanvasType)
Convert a stored canvas type setting into a backend that can actually be used.
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)
bool handleContextLoss()
Replace a GAL whose context was destroyed by a GPU reset.
static constexpr bool GAL_FALLBACK_AVAILABLE
GAL_TYPE m_backend
Currently used GAL.
VECTOR2D m_lastCursorPosition
Last cursor position sent to GAL for drawing.
bool GetScreenshot(wxImage &aDstImage)
Capture the current canvas contents into aDstImage.
EDA_DRAW_FRAME * GetParentEDAFrame() const
Returns parent EDA_DRAW_FRAME, if available or NULL otherwise.
void SetOverlayExclusions(const std::vector< wxRect > &aRects)
Set areas, in canvas coordinates, that the frame blit must leave alone.
Definition cairo_gal.h:441
Abstract interface for drawing on a 2D-surface.
Raised when a GPU buffer allocation is predicted to exceed the available video memory.
OpenGL implementation of the Graphics Abstraction Layer.
Definition opengl_gal.h:72
static wxString CheckFeatures(GAL_DISPLAY_OPTIONS &aOptions)
Check 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:353
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:546
A small class to help profiling.
Definition profile.h:46
void Stop()
Save the time when this function was called, and set the counter stane to stop.
Definition profile.h:86
void Start()
Start or restart the counter.
Definition profile.h:74
std::string to_string()
Definition profile.h:154
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:76
void DisplayInfoMessage(wxWindow *aParent, const wxString &aMessage, const wxString &aExtraInfo)
Display an informational message box with aMessage.
Definition confirm.cpp:245
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
Definition confirm.cpp:217
This file is part of the common library.
KICURSOR
Definition cursors.h:40
@ ARROW
Definition cursors.h:42
static constexpr int MAX_CONTEXT_BIND_RETRIES
Frames to drop before giving up on the GL context and letting the backend recover.
#define _(s)
const wxChar *const traceGalContext
Flag to enable debug output of GAL context binding.
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:79
GAL_CONTEXT_LOSS
State of a canvas' rendering context after a GPU reset.
@ REPEATED
Contexts keep being lost; stop using this backend.
@ RECOVERABLE
Context was lost; rebuild the canvas.
@ TARGET_NONCACHED
Auxiliary rendering target (noncached)
Definition definitions.h:34
@ TARGET_OVERLAY
Items that may change while the view stays the same (noncached)
Definition definitions.h:35
void SetOverlayScrolling(const wxWindow *aWindow, bool overlay)
Used to set overlay/non-overlay scrolling mode in a window.
Definition wxgtk/ui.cpp:374
void ImmControl(wxWindow *aWindow, bool aEnable)
Configures the IME mode of a given control handle.
Definition wxgtk/ui.cpp:503
std::unique_ptr< TOUCHPAD_GESTURE_HANDLER > CreateTouchpadGestureHandler(wxWindow *aInputWindow, TOUCHPAD_GESTURE_CALLBACK aCallback)
Register a window for native touchpad pan and pinch gestures when the port supports it.
void ImeNotifyCancelComposition(wxWindow *aWindow)
Asks the IME to cancel.
Definition wxgtk/ui.cpp:508
bool IsWindowActive(wxWindow *aWindow)
Check to see if the given window is the currently active window (e.g.
Definition wxgtk/ui.cpp:149
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.
A pan and zoom update produced by a native touchpad gesture recognizer.
Definition touchpad.h:38
wxString result
Test unit parsing edge cases and error handling.
int delta
wxLogTrace helper definitions.
VECTOR2< double > VECTOR2D
Definition vector2d.h:707
VECTOR2I ToVECTOR2I(const wxSize &aSize)
Definition vector2wx.h:26
WX_VIEW_CONTROLS class definition.