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 <wx/dcclient.h>
24
25#include <chrono>
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>
43#include <gal/cairo/cairo_gal.h>
44#include <gal/gal_modern.h>
45#include <rhi/render_thread.h>
48#include <rhi/frame_mailbox.h>
49#include <rhi/frame_packet.h>
50#include <rhi/rhi_surface.h>
51#ifdef __WXMAC__
52#include <rhi/rhi_metal_view.h>
53#endif
54#include <advanced_config.h>
55#include <frame_type.h>
56#include <math/vector2wx.h>
57
58
60#include <tool/tool_manager.h>
61
62#include <widgets/wx_infobar.h>
63
64#include <kiplatform/touchpad.h>
65#include <kiplatform/ui.h>
66
67#include <atomic>
68#include <stdexcept>
69
70#include <core/profile.h>
71
72#include <wx/display.h>
73#include <wx/utils.h>
74
75#include <pgm_base.h>
76#include <confirm.h>
77
78
84[[maybe_unused]] static const wxChar traceDrawPanel[] = wxT( "KICAD_DRAW_PANEL" );
85
86// Counts inputs to any canvas so the render thread never holds back a frame that answers one
87static std::atomic<uint64_t> s_inputSerial{ 0 };
88
89
91{
92 if( !aFrame )
94
95 switch( aFrame->GetFrameType() )
96 {
97 case FRAME_SCH:
100 case FRAME_SCH_DIFF:
102
103 default:
105 }
106}
107
108
110{
111 static_assert( static_cast<int>( RHI_DISPLAY_TYPE::COCOA ) == KIPLATFORM::UI::DISPLAY_COCOA );
112
114 int displayType = KIPLATFORM::UI::DISPLAY_UNKNOWN;
115
116 KIPLATFORM::UI::GetNativeWindowHandles( aWindow, &handle.nativeHandle, &handle.nativeDisplay, &displayType );
117 handle.displayType = static_cast<RHI_DISPLAY_TYPE>( displayType );
118 return handle;
119}
120
121
124{
125 // Fast relies on the shaders' analytic edge coverage, High Quality supersamples the layer FBOs
127}
128
129
131{
133 {
135
136#ifdef __WXMAC__
138 && m_cachedNativeHandle.nativeHandle )
139 {
141 m_cachedNativeHandle.nativeHandle = host.view;
142 m_cachedNativeHandle.nativeDisplay = host.layer;
143 }
144#endif
145
146 // A paint before the window is realized gets an invalid handle, so retry next frame
148 }
149
151}
152
153
155{
156#ifdef __WXMAC__
159#endif
160
162 m_nativeHandleValid = false;
163}
164
165
167{
168 if( !m_swapchainCtrl )
169 return;
170
171 const wxSize cs = backendScreenSize();
172 float dpiScale = static_cast<float>( GetContentScaleFactor() );
174
175 // An unrealized window's handle would fail surface creation on the render thread
176 if( nativeHandle.IsValid() )
177 {
178 // GTK drawing suppression needs the realized widget at its final layout size
180 {
181 wxLogTrace( traceRhi, wxS( "DrawPanel: deferred PrepareForExternalRendering "
182 "windowId=%u" ), m_windowId );
185 }
186
187 // Caps a window that presents without vsync at one frame per display refresh
188 m_swapchainCtrl->SetRefreshRate( displayRefreshRate() );
189 m_swapchainCtrl->OnPaint( nativeHandle,
190 static_cast<uint32_t>( cs.x ),
191 static_cast<uint32_t>( cs.y ),
192 dpiScale );
193 }
194 else if( IsShown() && !m_refreshTimer.IsRunning() )
195 {
196 // A timer rather than an idle refresh, so a surface that never maps cannot spin
197 m_refreshTimer.StartOnce( 100 );
198 }
199}
200
201
202EDA_DRAW_PANEL_GAL::EDA_DRAW_PANEL_GAL( wxWindow* aParentWindow, wxWindowID aWindowId, const wxPoint& aPosition,
203 const wxSize& aSize, KIGFX::GAL_DISPLAY_OPTIONS& aOptions, GAL_TYPE aGalType ) :
204 wxScrolledCanvas( aParentWindow, aWindowId, aPosition, aSize ),
205 m_MouseCapturedLost( false ),
206 m_parent( aParentWindow ),
207 m_edaFrame( nullptr ),
208 m_drawing( false ),
209 m_drawingEnabled( false ),
210 m_needIdleRefresh( false ),
211 m_cursorInCanvas( false ),
213 m_gal( nullptr ),
214 m_view( nullptr ),
215 m_painter( nullptr ),
216 m_viewControls( nullptr ),
218 m_options( aOptions ),
219 m_eventDispatcher( nullptr ),
220 m_lostFocus( false ),
221 m_recoveryAttempted( false ),
223 m_rebuiltAfterReset( false ),
224 m_pendingResize( false ),
225 m_stealsFocus( true ),
226 m_statusPopup( nullptr )
227{
228#ifdef _WIN32
229 // need to fix broken cairo rendering on Windows with wx 3.3
230 SetDoubleBuffered( false );
231#endif
232 m_PaintEventCounter = std::make_unique<PROF_COUNTER>( "Draw panel paint events" );
233
234 if( Pgm().GetCommonSettings()->m_Appearance.show_scrollbars )
235 ShowScrollbars( wxSHOW_SB_ALWAYS, wxSHOW_SB_ALWAYS );
236 else
237 ShowScrollbars( wxSHOW_SB_NEVER, wxSHOW_SB_NEVER );
238
239 SetLayoutDirection( wxLayout_LeftToRight );
240
241 m_edaFrame = dynamic_cast<EDA_DRAW_FRAME*>( m_parent );
242
243 // If we're in a dialog, we have to go looking for our parent frame
244 if( !m_edaFrame )
245 {
246 wxWindow* ancestor = aParentWindow->GetParent();
247
248 while( ancestor && !dynamic_cast<EDA_DRAW_FRAME*>( ancestor ) )
249 ancestor = ancestor->GetParent();
250
251 if( ancestor )
252 m_edaFrame = dynamic_cast<EDA_DRAW_FRAME*>( ancestor );
253 }
254
256
257 // Callers ask for the modern canvas before the saved choice is known. Starting it only to
258 // switch away costs a GPU device, so other choices start on the fallback and the frame applies them.
259 if( aGalType == GAL_TYPE_MODERN )
260 {
262
264 aGalType = GAL_FALLBACK;
265 }
266
267 SwitchBackend( aGalType );
268 SetBackgroundStyle( wxBG_STYLE_CUSTOM );
269
270 EnableScrolling( false, false ); // otherwise Zoom Auto disables GAL canvas
271 KIPLATFORM::UI::SetOverlayScrolling( this, false ); // Prevent excessive repaint on GTK
272 KIPLATFORM::UI::ImmControl( this, false ); // Ensure our panel can't suck in IME events
273
274 Connect( wxEVT_SIZE, wxSizeEventHandler( EDA_DRAW_PANEL_GAL::onSize ), nullptr, this );
275 Connect( wxEVT_ENTER_WINDOW, wxMouseEventHandler( EDA_DRAW_PANEL_GAL::onEnter ), nullptr, this );
276 Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( EDA_DRAW_PANEL_GAL::onLostFocus ), nullptr, this );
277
278 const wxEventType events[] = {
279 // Binding both EVT_CHAR and EVT_CHAR_HOOK ensures that all key events,
280 // especially special key like arrow keys, are handled by the GAL event dispatcher,
281 // and not sent to GUI without filtering, because they have a default action (scroll)
282 // that must not be called.
283 wxEVT_LEFT_UP,
284 wxEVT_LEFT_DOWN,
285 wxEVT_LEFT_DCLICK,
286 wxEVT_RIGHT_UP,
287 wxEVT_RIGHT_DOWN,
288 wxEVT_RIGHT_DCLICK,
289 wxEVT_MIDDLE_UP,
290 wxEVT_MIDDLE_DOWN,
291 wxEVT_MIDDLE_DCLICK,
292 wxEVT_AUX1_UP,
293 wxEVT_AUX1_DOWN,
294 wxEVT_AUX1_DCLICK,
295 wxEVT_AUX2_UP,
296 wxEVT_AUX2_DOWN,
297 wxEVT_AUX2_DCLICK,
298 wxEVT_MOTION,
299 wxEVT_MOUSEWHEEL,
300 wxEVT_CHAR,
301 wxEVT_CHAR_HOOK,
302 wxEVT_MAGNIFY,
304 };
305
306 for( wxEventType eventType : events )
307 Connect( eventType, wxEventHandler( EDA_DRAW_PANEL_GAL::OnEvent ), nullptr, m_eventDispatcher );
308
309 // Set up timer to detect when drawing starts
310 m_refreshTimer.SetOwner( this );
311 Connect( m_refreshTimer.GetId(), wxEVT_TIMER, wxTimerEventHandler( EDA_DRAW_PANEL_GAL::onRefreshTimer ),
312 nullptr, this );
313
314 Connect( wxEVT_SHOW, wxShowEventHandler( EDA_DRAW_PANEL_GAL::onShowEvent ), nullptr, this );
315
317}
318
319
321{
322 wxLogTrace( traceRhi, wxS( "DrawPanel: destructor windowId=%u backend=%d" ),
323 m_windowId, static_cast<int>( m_backend ) );
324
327
328 // Ensure EDA_DRAW_PANEL_GAL::onShowEvent is not fired during Dtor process
329 Disconnect( wxEVT_SHOW, wxShowEventHandler( EDA_DRAW_PANEL_GAL::onShowEvent ) );
330 StopDrawing();
331
332 wxASSERT( !m_drawing );
333
334 // Deleting the view can retire GAL groups, which needs the device proxy
335 delete m_viewControls;
336 delete m_view;
337
339
340 delete m_gal;
341 m_gal = nullptr;
342}
343
344
346{
348 wxScrolledCanvas::SetFocus();
349 m_lostFocus = false;
350}
351
352
353void EDA_DRAW_PANEL_GAL::SetCursorInCanvas( bool aCursorInCanvas )
354{
355 if( m_cursorInCanvas == aCursorInCanvas )
356 return;
357
358 m_cursorInCanvas = aCursorInCanvas;
360
361 if( m_gal )
362 m_gal->SetCursorInCanvas( m_cursorInCanvas );
363
364 if( m_cursorInCanvas )
366
367 // Not ForceRefresh(), which would restart drawing on a canvas stopped for teardown
368 Refresh();
369}
370
371
372void EDA_DRAW_PANEL_GAL::onPaint( wxPaintEvent& WXUNUSED( aEvent ) )
373{
374 // Consuming the paint region stops GTK3 clearing the modern canvas between presents. The other
375 // backends repost their child's paint event here with no native paint context, where a wxPaintDC asserts.
376 std::optional<wxPaintDC> dc;
377
379 dc.emplace( this );
380
381 DoRePaint( false );
382}
383
384
386{
387 if( IsAccelerated( aFailedCanvasType ) && aFailedCanvasType != GAL_FALLBACK )
388 return GAL_FALLBACK;
389
390 return GAL_TYPE_NONE;
391}
392
393
394bool EDA_DRAW_PANEL_GAL::abandonRhiCanvas( const wxString& aDetail )
395{
397 {
399
400#ifdef __WXMAC__
401 showMessageLater( _( "Could not use Metal, switching to OpenGL" ), aDetail, false );
402#else
403 showMessageLater( _( "Could not use Vulkan, falling back to software rendering" ), aDetail, false );
404#endif
405 }
406
407 wxLogTrace( traceRhi, wxS( "DrawPanel: leaving the RHI canvas for backend %d" ), static_cast<int>( GAL_FALLBACK ) );
408
409 return SwitchBackend( GAL_FALLBACK );
410}
411
412
414{
415 if( m_swapchainCtrl )
416 {
417 m_swapchainCtrl->OnCloseSync();
418 m_swapchainCtrl.reset();
419 }
420
421 if( auto* galModern = dynamic_cast<KIGFX::GAL_MODERN*>( m_gal ) )
422 galModern->DestroyBuffers();
423
424 // The proxy references the render thread. DestroyBuffers() left no proxy call outstanding.
425 m_deviceProxy.reset();
426
427 if( m_renderThread )
428 {
429 m_renderThread->RemoveDeviceLostListener( this );
430
431 // Other canvases keep the thread running, so the uploads still queued from this one are applied
432 // before its GAL and geometry go. A thread that stopped will not read them.
433 while( !m_renderThread->WaitForFence() && m_renderThread->IsRunning() )
434 {
435 }
436
437 m_renderThread.reset();
438 }
439
440 m_frameMailbox.reset();
441 m_hasLastFullDrawDesc = false;
442
444}
445
446
447bool EDA_DRAW_PANEL_GAL::recoverFromGalError( const std::exception& aError )
448{
449 // Reinitializing would hit the same VRAM ceiling, so out-of-memory goes straight to the fallback
450 const bool gpuOutOfMemory = dynamic_cast<const KIGFX::GPU_OOM_ERROR*>( &aError ) != nullptr;
451
452 // The reinit below rewrites m_backend
453 const GAL_TYPE failedBackend = m_backend;
454
455 try
456 {
457 // Reset detection only runs inside LockContext, and this frame's lock came before the reset
458 if( m_gal && !m_gal->IsContextLocked() )
460
461 // A reset seen mid-frame surfaces as a GL error; rebuild rather than spend the one-shot recovery
462 if( handleContextLoss() )
463 return true;
464
465 // Sleep/wake and GPU resets can invalidate the entire GL/device context.
466 // Try a full reinit of the current backend before falling back.
467 if( !gpuOutOfMemory && !m_recoveryAttempted )
468 {
469 m_recoveryAttempted = true;
471
472 if( SwitchBackend( failedBackend ) )
473 {
474 StartDrawing();
475 return true;
476 }
477 }
478
479 if( failedBackend == GAL_TYPE_MODERN )
480 {
481 m_recoveryAttempted = false;
482 abandonRhiCanvas( wxString( aError.what() ) );
483 StartDrawing();
484 return true;
485 }
486
487 if( CanvasAfterFailure( failedBackend ) != GAL_TYPE_NONE )
488 {
489 m_recoveryAttempted = false;
491
493 {
494 // Some drivers refuse new framebuffers to a process for the rest of its life after a reset
495 m_rebuiltAfterReset = false;
497 showMessageLater( _( "The graphics driver was reset and OpenGL could not be restored" ),
498 _( "Restart KiCad to use accelerated graphics again." ), false );
499 }
500 else
501 {
502 showMessageLater( _( "Could not use OpenGL, falling back to software rendering" ),
503 wxString( aError.what() ), false );
504 }
505
506 StartDrawing();
507 return true;
508 }
509
510 showMessageLater( _( "Graphics error" ), wxString( aError.what() ), true );
511 }
512 catch( std::exception& recoveryErr )
513 {
514 showMessageLater( _( "Graphics error during recovery" ), wxString( recoveryErr.what() ), true );
515 }
516 catch( ... )
517 {
518 showMessageLater( _( "Graphics error during recovery" ), _( "Unknown exception during backend switch" ),
519 true );
520 }
521
522 return false;
523}
524
525
527{
529
531 return false;
532
533 // Deleting a GAL that someone still holds locked would leave them unlocking freed memory
534 if( m_gal->IsContextLocked() )
535 return true;
536
537 // Hidden canvases rebuild when next shown, since a new GAL cannot initialize off screen
538 if( !IsShownOnScreen() )
539 return true;
540
541 // Rebuilding while the driver is still resetting can fail or hang, so poll until it finishes
542 if( !m_gal->IsResetSettled() )
543 {
544 m_refreshTimer.StartOnce( 20 );
545 return true;
546 }
547
548 wxLogTrace( traceGalContext, wxS( "Rebuilding canvas %p after GPU reset, repeated %d" ), this,
549 loss == KIGFX::GAL_CONTEXT_LOSS::REPEATED ? 1 : 0 );
550
551 bool rebuilt = false;
552
554 {
555 GAL_TYPE backend = m_backend;
556
557 // Forces SwitchBackend to build a new GAL of the same type
559 rebuilt = SwitchBackend( backend );
560 m_rebuiltAfterReset = rebuilt;
561 }
562
563 // SwitchBackend already reported a failed rebuild, so only a repeated loss needs the notice
564 if( !rebuilt && GAL_FALLBACK_AVAILABLE )
565 {
566 static bool s_notified = false;
567
568 wxLogTrace( traceGalContext, wxS( "Canvas %p falling back to software rendering" ), this );
571
572 if( loss == KIGFX::GAL_CONTEXT_LOSS::REPEATED && !s_notified )
573 {
574 s_notified = true;
575 showMessageLater( _( "The graphics driver keeps resetting, falling back to software rendering" ),
576 wxEmptyString, false );
577 }
578 }
579
580 StartDrawing();
581 return true;
582}
583
584
585void EDA_DRAW_PANEL_GAL::showMessageLater( const wxString& aTitle, const wxString& aDetail, bool aError )
586{
587 wxWindow* parent = m_parent;
588
589 CallAfter(
590 [parent, aTitle, aDetail, aError]()
591 {
592 if( aError )
593 DisplayErrorMessage( parent, aTitle, aDetail );
594 else
595 DisplayInfoMessage( parent, aTitle, aDetail );
596 } );
597}
598
599
601static constexpr int MAX_CONTEXT_BIND_RETRIES = 2;
602
603
605{
606 auto* galModern = static_cast<KIGFX::GAL_MODERN*>( m_gal );
607 auto packet = std::make_unique<KIGFX::FRAME_PACKET>();
608
609 packet->drawDesc = m_lastFullStaticDesc;
610 packet->drawDesc.reuseStaticFBO = true;
611
612 // The cached desc holds the camera of the last full render, which would snap a pan or zoom back
613 galModern->PopulateCameraUBOs( packet->drawDesc );
614 galModern->PopulateCursorUBO( packet->drawDesc );
615
616 // Unchanged epochs tell the render thread to keep both geometry FBOs
617 packet->staticDrawDesc = m_lastFullStaticDesc;
618 packet->dynamicDrawDesc = m_lastFullDynamicDesc;
619 packet->staticChanged = true;
620 packet->dynamicChanged = true;
621 packet->staticEpoch = m_staticEpoch;
622 packet->dynamicEpoch = m_dynamicEpoch;
623
624 packet->inputSerial = s_inputSerial.load( std::memory_order_relaxed );
625 m_frameMailbox->Submit( std::move( packet ) );
626}
627
628
629bool EDA_DRAW_PANEL_GAL::DoRePaint( bool aAllowSkip )
630{
631 if( !m_refreshMutex.try_lock() )
632 {
633 wxLogTrace( traceRhi, wxS( "DrawPanel: DoRePaint SKIP (mutex locked)" ) );
634 return false;
635 }
636
637 std::lock_guard<std::mutex> lock( m_refreshMutex, std::adopt_lock );
638
639 if( !m_drawingEnabled )
640 return false;
641
642 // No surface may be created on an unmapped window. The other backends check visibility below.
643 if( m_backend == GAL_TYPE_MODERN && !IsShown() )
644 {
645 wxLogTrace( traceRhi, wxS( "DrawPanel: DoRePaint SKIP (hidden) windowId=%u" ), m_windowId );
646 return false;
647 }
648
649 if( handleContextLoss() )
650 return false;
651
652 if( m_backend == GAL_TYPE_MODERN && m_renderThread && m_renderThread->IsDeviceLost() )
653 {
654 // A device lost before it ever presented this canvas gives way to the fallback rather than retrying forever
655 if( m_renderThread->HasPresented( m_windowId ) )
656 {
658
660 {
661 StartDrawing();
662 return false;
663 }
664 }
665
666 abandonRhiCanvas( _( "The graphics device was lost and could not be restored." ) );
667 StartDrawing();
668 return false;
669 }
670
671 if( !m_gal->IsInitialized() || !m_gal->IsVisible() || m_gal->IsContextLocked() )
672 {
673 wxLogTrace( traceRhi, wxS( "DrawPanel: DoRePaint SKIP (init=%d vis=%d locked=%d)" ),
674 m_gal->IsInitialized(), m_gal->IsVisible(), m_gal->IsContextLocked() );
675 return false;
676 }
677
678 if( m_drawing )
679 {
680 wxLogTrace( traceRhi, wxS( "DrawPanel: DoRePaint SKIP (already drawing)" ) );
681 return false;
682 }
683
684 // The context may have become current since the size change was deferred
685 if( m_pendingResize )
686 ResizeGal();
687
688 m_lastRepaintStart = std::chrono::steady_clock::now();
689
690 // Update current zoom settings if the canvas is managed by a EDA frame
691 // (i.e. not by a preview panel in a dialog)
692 if( !IsDialogPreview() && GetParentEDAFrame() && GetParentEDAFrame()->GetScreen() )
694
695 if( Pgm().GetCommonSettings()->m_Appearance.show_scrollbars )
696 m_viewControls->UpdateScrollbars();
697
698#ifdef KICAD_GAL_PROFILE
699 latencyProbeZoomToRender.Checkpoint("do-repaint-start");
700#endif
701
702 SCOPED_SET_RESET<bool> drawing( m_drawing, true );
703
704 ( *m_PaintEventCounter )++;
705
706 wxASSERT( m_painter );
707
708 KIGFX::RENDER_SETTINGS* settings =
709 static_cast<KIGFX::RENDER_SETTINGS*>( m_painter->GetSettings() );
710
711 PROF_TIMER cntUpd("view-upd-items", false);
712 PROF_TIMER cntTotal("view-total", false);
713 PROF_TIMER cntCtx("view-context-create", false);
714 PROF_TIMER cntCtxDestroy("view-context-destroy", false);
715 PROF_TIMER cntRedraw("view-redraw-rects", false);
716
717 bool isDirty = false;
718
720 {
721 static_cast<KIGFX::GAL_MODERN*>( m_gal )->ReleaseRetiredBuffers(
722 m_frameMailbox->ConsumedBufferGeneration() );
723 }
724
725 cntTotal.Start();
726
727 try
728 {
729 beforeRedraw();
730
731 VECTOR2D cursorPos = m_viewControls->GetCursorPosition();
732 bool viewDirty = m_view->IsDirty();
733 bool cursorMoved = cursorPos != m_lastCursorPosition || m_cursorVisibilityDirty;
734 bool hasPendingItemUpdates = m_view->HasPendingItemUpdates();
735
736 // Skip all update work when nothing has changed since the previous frame.
737 // Never skip when responding to a native paint event or explicit ForceRefresh
738 // because the window content may have been invalidated by the OS.
739 if( aAllowSkip && !viewDirty && !cursorMoved && !hasPendingItemUpdates )
740 {
741 m_lastRepaintEnd = std::chrono::steady_clock::now();
742 return true;
743 }
744
745 if( hasPendingItemUpdates )
746 {
747 cntUpd.Start();
748
749 try
750 {
751 m_view->UpdateItems();
752 }
753 catch( std::out_of_range& err )
754 {
755 // Don't do anything here but don't fail
756 // This can happen when we don't catch `at()` calls
757 wxLogTrace( traceDrawPanel, wxS( "Out of Range error: %s" ), err.what() );
758 }
759 catch( std::runtime_error& err )
760 {
761 // Handle GL errors (e.g. glMapBuffer failure) that surface during UpdateItems().
762 // These can occur on macOS under memory pressure when embedding large 3D models.
763 // Log and continue so the outer handler can decide whether to switch backends.
764 wxLogTrace( traceDrawPanel, wxS( "Runtime error during UpdateItems: %s" ),
765 err.what() );
766 throw;
767 }
768
769 cntUpd.Stop();
770 viewDirty = m_view->IsDirty();
771 }
772
773 // After processing item updates, skip the GL cycle when neither the
774 // view targets nor the cursor position have changed.
775 if( aAllowSkip && !viewDirty && !cursorMoved )
776 {
777 m_lastRepaintEnd = std::chrono::steady_clock::now();
778 return true;
779 }
780
781 m_lastCursorPosition = cursorPos;
783
784 // A cursor move alone reuses the cached scene and skips the view traversal and upload
785 const bool useOverlayFastPath = m_backend == GAL_TYPE_MODERN
787 && !viewDirty
788 && cursorMoved;
789
790 // A zoom can carry groups across their level of detail
792 m_view->SyncRetainedScene();
793
794 // Grid items are thinned and sized for the zoom they were made at, so they need a full redraw
795 const bool useCameraFastPath = m_backend == GAL_TYPE_MODERN
797 && viewDirty
798 && m_view->IsCameraDirtyOnly()
799 && !m_gal->HasStaticRebuildPending()
800 && m_gal->GetGridSources().empty();
801
802 if( useOverlayFastPath && m_frameMailbox && m_swapchainCtrl )
803 {
804 m_gal->SetCursorColor( settings->GetCursorColor() );
805 m_gal->DrawCursor( cursorPos );
807 presentFrame();
808
809 m_lastRepaintEnd = std::chrono::steady_clock::now();
810
811 m_recoveryAttempted = false;
812 return true;
813 }
814
815 if( useCameraFastPath && m_frameMailbox && m_swapchainCtrl )
816 {
817 // GetDrawDesc() is unusable here because reused-scene frames overwrite the ring-buffered state
818 auto* galModern = static_cast<KIGFX::GAL_MODERN*>( m_gal );
819
820 m_gal->SetClearColor( settings->GetBackgroundColor() );
821 m_gal->SetGridColor( settings->GetGridColor() );
822 m_gal->SetCursorColor( settings->GetCursorColor() );
823 m_gal->DrawCursor( cursorPos );
824
825 if( galModern->SyncScene() )
826 {
827 KIGFX::FRAME_DRAW_DESC patched = galModern->GetStaticDrawDesc();
828 patched.linePipelineKind = m_lastFullStaticDesc.linePipelineKind;
829 patched.supersampleFactor = m_lastFullStaticDesc.supersampleFactor;
830 m_lastFullStaticDesc = patched;
832 }
833
834 auto packet = std::make_unique<KIGFX::FRAME_PACKET>();
835 packet->drawDesc = m_lastFullStaticDesc;
836 packet->drawDesc.reuseStaticFBO = false;
837 packet->drawDesc.linePipelineKind = m_linePipelineKind;
838 ApplyAntialiasingMode( packet->drawDesc, m_options.antialiasing_mode );
839
840 galModern->PopulateCameraUBOs( packet->drawDesc );
841 galModern->PopulateCursorUBO( packet->drawDesc );
842
843 packet->staticDrawDesc = m_lastFullStaticDesc;
844 packet->dynamicDrawDesc = m_lastFullDynamicDesc;
845
846 // The render thread decides reuse from each target desc's own flag and camera, not
847 // drawDesc's, so stale ones would revert the canvas to the old zoom
848 packet->staticDrawDesc.reuseStaticFBO = false;
849 packet->dynamicDrawDesc.reuseDynamicFBO = false;
850 galModern->PopulateCameraUBOs( packet->staticDrawDesc );
851 galModern->PopulateCameraUBOs( packet->dynamicDrawDesc );
852
853 packet->staticChanged = true;
854 packet->dynamicChanged = true;
855 packet->staticEpoch = m_staticEpoch;
856 packet->dynamicEpoch = m_dynamicEpoch;
857
858 // A following cursor-only frame reuses these descs, which must not keep the old view
859 m_lastFullStaticDesc.frameUBO = packet->staticDrawDesc.frameUBO;
860 m_lastFullStaticDesc.gridUBO = packet->staticDrawDesc.gridUBO;
861 m_lastFullStaticDesc.cursorUBO = packet->staticDrawDesc.cursorUBO;
862 m_lastFullDynamicDesc.frameUBO = packet->dynamicDrawDesc.frameUBO;
863 m_lastFullDynamicDesc.gridUBO = packet->dynamicDrawDesc.gridUBO;
864 m_lastFullDynamicDesc.cursorUBO = packet->dynamicDrawDesc.cursorUBO;
865
866 m_view->MarkClean();
867
868 packet->inputSerial = s_inputSerial.load( std::memory_order_relaxed );
869 m_frameMailbox->Submit( std::move( packet ) );
870
871 presentFrame();
872
873 m_lastRepaintEnd = std::chrono::steady_clock::now();
874 m_recoveryAttempted = false;
875 return true;
876 }
877
878 // GAL_DRAWING_CONTEXT can throw in the dtor, so we need to scope
879 // the full lifetime inside the try block
880 {
881 // Cairo clears the screen as drawing begins, so a canvas's first frame needs its colours first
882 m_gal->SetClearColor( settings->GetBackgroundColor() );
883 m_gal->SetGridColor( settings->GetGridColor() );
884 m_gal->SetCursorColor( settings->GetCursorColor() );
885
886 cntCtx.Start();
888 cntCtx.Stop();
889
890 if( !ctx.IsDrawing() )
891 {
892 // A canvas being torn down never reaches here; DoRePaint returns above once
893 // the window stops being visible. So repeated failures mean a live canvas
894 // whose context is gone for good, and retrying forever would leave it blank
896 throw std::runtime_error( "Could not make the OpenGL context current" );
897
899 return false;
900 }
901
902 if( m_view->IsTargetDirty( KIGFX::TARGET_OVERLAY )
903 && !m_gal->HasTarget( KIGFX::TARGET_OVERLAY ) )
904 {
905 m_view->MarkDirty();
906 }
907
908 // The OpenGL back buffer is undefined after SwapBuffers, even on a cursor-only repaint
910 m_gal->ClearScreen();
911
912 if( m_view->IsDirty() )
913 {
914 // Cairo composites all targets into one surface, so a dirty NONCACHED needs a full clear
915 if( !IsAccelerated( m_backend ) && m_view->IsTargetDirty( KIGFX::TARGET_NONCACHED ) )
916 {
917 m_gal->ClearScreen();
918 }
919
920 // A rebuild the backend asked for itself also redraws the whole non-cached target
921 if( m_gal->HasStaticRebuildPending() )
922 {
923 m_view->MarkTargetDirty( KIGFX::TARGET_NONCACHED );
924 m_view->MarkTargetDirty( KIGFX::TARGET_OVERLAY );
925 }
926
927 // A retained scene keeps NONCACHED through a pan or zoom, but the grid is clipped to the old view
928 const bool viewMoved = m_view->IsTargetDirty( KIGFX::TARGET_NONCACHED );
929
930 m_view->ClearTargets();
931
932 // Grid has to be redrawn only when the NONCACHED target is redrawn
933 if( viewMoved || m_view->IsTargetDirty( KIGFX::TARGET_NONCACHED )
934 || m_gal->RefillsNonCachedTargets() )
935 {
937 m_gal->DrawGrid();
938 }
939
940 cntRedraw.Start();
941 m_view->Redraw();
942 cntRedraw.Stop();
943 isDirty = true;
944 }
945
946 m_gal->DrawCursor( cursorPos );
947
948 #ifdef KICAD_GAL_PROFILE
949 latencyProbeZoomToRender.Checkpoint("do-repaint-pre-ctx-destroy");
950 #endif
951
952
953 cntCtxDestroy.Start();
954 }
955
956 // ctx goes out of scope here so destructor would be called
957 cntCtxDestroy.Stop();
958
959#ifdef KICAD_GAL_PROFILE
960 latencyProbeZoomToRender.Checkpoint("do-repaint-ctx-done");
961#endif
962
963 // A clean view leaves GetDrawDesc() empty, which would blank the static FBO
965 {
966 auto* galModern = static_cast<KIGFX::GAL_MODERN*>( m_gal );
967
968 if( !isDirty && m_hasLastFullDrawDesc && m_backend == GAL_TYPE_MODERN )
969 {
971 }
972 else if( isDirty )
973 {
974 auto packet = std::make_unique<KIGFX::FRAME_PACKET>();
975
976 packet->drawDesc = galModern->GetDrawDesc();
977 packet->drawDesc.linePipelineKind = m_linePipelineKind;
978 ApplyAntialiasingMode( packet->drawDesc, m_options.antialiasing_mode );
979
980 // Lets the first frame show the cursor without waiting for a move
981 galModern->PopulateCursorUBO( packet->drawDesc );
982
983 packet->staticDrawDesc = galModern->GetStaticDrawDesc();
984 packet->dynamicDrawDesc = galModern->GetDynamicDrawDesc();
985 packet->staticDrawDesc.linePipelineKind = m_linePipelineKind;
986 packet->dynamicDrawDesc.linePipelineKind = m_linePipelineKind;
987 packet->staticDrawDesc.supersampleFactor = packet->drawDesc.supersampleFactor;
988 packet->dynamicDrawDesc.supersampleFactor = packet->drawDesc.supersampleFactor;
989
990 packet->staticChanged = galModern->TakeStaticChanged();
991 packet->dynamicChanged = true;
992
993 if( packet->staticChanged )
995
997 packet->staticEpoch = m_staticEpoch;
998 packet->dynamicEpoch = m_dynamicEpoch;
999
1000 m_lastFullStaticDesc = packet->staticDrawDesc;
1001 m_lastFullDynamicDesc = packet->dynamicDrawDesc;
1002 m_hasLastFullDrawDesc = true;
1003
1004 packet->inputSerial = s_inputSerial.load( std::memory_order_relaxed );
1005 m_frameMailbox->Submit( std::move( packet ) );
1006 }
1007
1008 presentFrame();
1009 }
1010
1011 m_recoveryAttempted = false;
1013 m_rebuiltAfterReset = false;
1014 }
1015 catch( std::exception& err )
1016 {
1017 wxLogTrace( traceDrawPanel, wxS( "DoRePaint exception: %s" ), err.what() );
1018
1019 if( recoverFromGalError( err ) )
1020 return true;
1021
1022 StopDrawing();
1023 }
1024 catch( ... )
1025 {
1026 showMessageLater( _( "Graphics error" ), _( "Unknown exception" ), true );
1027 StopDrawing();
1028 }
1029
1030 if( isDirty )
1031 {
1032#ifdef KICAD_GAL_PROFILE
1033 wxLogTrace( traceGalProfile, "View timing: %s %s %s %s %s",
1034 cntTotal.to_string(),
1035 cntUpd.to_string(),
1036 cntRedraw.to_string(),
1037 cntCtx.to_string(),
1038 cntCtxDestroy.to_string()
1039 );
1040#endif
1041 }
1042
1043 m_lastRepaintEnd = std::chrono::steady_clock::now();
1044
1045#ifdef KICAD_GAL_PROFILE
1046 wxLogTrace( traceGalProfile, "%s", latencyProbeZoomToRender.to_string() );
1047 latencyProbeRepaintToMotion.Reset();
1048 latencyProbeRepaintToMotion.Checkpoint("repaint-done");
1049#endif
1050
1051 return true;
1052}
1053
1054
1055void EDA_DRAW_PANEL_GAL::onSize( wxSizeEvent& aEvent )
1056{
1057 ResizeGal();
1058
1059 // The first fit often runs before the frame has its final layout, and window managers,
1060 // infobars and panels resize the canvas later. Until someone zooms or pans, fit again.
1061 wxSize clientSize = GetClientSize();
1062
1063 if( clientSize.x > 0 && clientSize.y > 0 && m_view
1064 && m_automaticFit.Holds( m_view->GetScale(), m_view->GetCenter() ) )
1065 {
1066 ZoomToFit( m_automaticFit.GetBox(), m_automaticFit.GetMarginScale() );
1067 }
1068}
1069
1070
1071void EDA_DRAW_PANEL_GAL::ZoomToFit( const BOX2I& aBox, std::optional<double> aMarginScale )
1072{
1073 KIGFX::VIEW* view = m_view;
1074 BOX2I bBox = aBox;
1075
1076 // The GAL's world units may have changed since the view was attached.
1077 m_gal->ComputeWorldScreenMatrix();
1078
1079 // Avoid a temporary zoom that dirties retained targets before the fitted scale is known.
1080 VECTOR2D screenSize = view->ToWorld( ToVECTOR2I( GetClientSize() ), false ) * view->GetScale();
1081
1082 // A box with no extent (an empty screen or a lone point) has nothing to fit
1083 if( bBox.GetWidth() == 0 && bBox.GetHeight() == 0 )
1084 bBox = GetDefaultViewBBox();
1085
1086 VECTOR2D vsize = bBox.GetSize();
1087 double scale = 1.0 / std::max( fabs( vsize.x / screenSize.x ),
1088 fabs( vsize.y / screenSize.y ) );
1089
1090 // if the scale isn't finite (most likely due to an empty canvas)
1091 // simply just make sure we are centered and quit out of trying to zoom to fit
1092 if( !std::isfinite( scale ) )
1093 {
1094 view->SetCenter( VECTOR2D( 0, 0 ) );
1095 m_automaticFit.Clear();
1096 Refresh();
1097 return;
1098 }
1099
1100 // Reserve enough margin to limit the amount of the view that might be obscured behind the
1101 // infobar.
1102 double margin_scale_factor = aMarginScale.value_or( GetClientSize().y < 768 ? 1.10 : 1.04 );
1103
1104 view->SetScale( scale / margin_scale_factor );
1105 view->SetCenter( bBox.Centre() );
1106 m_automaticFit.Record( aBox, aMarginScale, view->GetScale(), view->GetCenter() );
1107 Refresh();
1108}
1109
1110
1112{
1113 // A swapchain that does not match its surface rescales and blurs every frame
1114 if( aBackend == GAL_TYPE_MODERN )
1115 return 0;
1116
1117#ifdef __WXMAC__
1118 // The aligned GL child covers the client area without the offset pixel
1119 if( aBackend == GAL_TYPE_OPENGL )
1120 return 0;
1121#endif
1122
1123 // The ( +1, +1 ) prevents an ugly black line on right and bottom on Mac
1124 return 1;
1125}
1126
1127
1129{
1130 const int pad = ScreenSizePad( m_backend );
1131 wxSize size = GetClientSize();
1132
1133 // The backend window starts below what cannot be drawn over it
1134 size.y -= m_overlayInsetTop;
1135
1136 return wxSize( std::max( 10, size.x + pad ), std::max( 10, size.y + pad ) );
1137}
1138
1139
1141{
1142 // If we get a second wx update call before the first finishes, don't crash
1143 if( m_gal->IsContextLocked() )
1144 return;
1145
1147
1148 // Resizing reallocates the framebuffer, which only exists in this canvas' own context
1149 if( !m_gal->IsContextValid() )
1150 {
1151 // wx reports a given size once, so dropping it here would leave the canvas stuck at
1152 // whatever size the GAL was built with until something else resizes the window
1153 m_pendingResize = true;
1155 return;
1156 }
1157
1158 m_pendingResize = false;
1159
1160 const wxSize clientSize = backendScreenSize();
1161
1162 // A client area that grew by exactly the pad would otherwise match the old GAL size
1163 if( !aForce && ToVECTOR2I( clientSize ) == m_gal->GetScreenPixelSize() )
1164 return;
1165
1166 m_gal->ResizeScreen( clientSize.GetX(), clientSize.GetY() );
1167
1168 wxWindow* backendWindow = dynamic_cast<wxWindow*>( m_gal );
1169
1170 if( backendWindow && backendWindow->GetPosition().y != m_overlayInsetTop )
1171 backendWindow->Move( 0, m_overlayInsetTop );
1172
1173 if( m_backend == GAL_TYPE_MODERN )
1174 {
1175 static_cast<KIGFX::GAL_MODERN*>( m_gal )->SetDpiScale(
1176 static_cast<float>( GetContentScaleFactor() ) );
1177 }
1178
1179 if( m_swapchainCtrl )
1180 {
1181 float dpiScale = static_cast<float>( GetContentScaleFactor() );
1182 m_swapchainCtrl->OnResize( static_cast<uint32_t>( clientSize.x ),
1183 static_cast<uint32_t>( clientSize.y ),
1184 dpiScale );
1185 }
1186
1187 if( m_view )
1188 {
1189 // ResizeScreen reallocates every compositor buffer, so nothing survives the resize
1190 m_view->MarkDirty();
1191
1192 // New FBO sizes need a fresh upload, which the camera fast path would skip
1193 m_view->MarkGeometryDirty();
1194 }
1195
1196 if( m_backend == GAL_TYPE_MODERN )
1197 Refresh();
1198}
1199
1200
1202{
1203 std::vector<wxRect> rects;
1204 int infobarsBottom = 0;
1205
1206 for( wxWindow* child : GetChildren() )
1207 {
1208 if( dynamic_cast<WX_INFOBAR*>( child ) && child->IsShown() )
1209 {
1210 rects.push_back( child->GetRect() );
1211 infobarsBottom = std::max( infobarsBottom, child->GetRect().GetBottom() + 1 );
1212 }
1213 }
1214
1215 // On Wayland the OpenGL canvas is a subsurface stacked above everything the toolkit draws
1216 // in the frame, so an infobar overlaid on it cannot show. The canvas makes room instead.
1217 int inset = 0;
1218
1219#ifdef __WXGTK__
1220 if( m_backend == GAL_TYPE_OPENGL && wxGetDisplayInfo().type == wxDisplayType::wxDisplayWayland )
1221 inset = infobarsBottom;
1222#endif
1223
1224 if( inset != m_overlayInsetTop )
1225 {
1226 m_overlayInsetTop = inset;
1227 ResizeGal( true );
1228 Refresh();
1229 }
1230
1231 // Only the Cairo backend presents frames outside the paint cycle
1232 if( KIGFX::CAIRO_GAL* cairoGal = dynamic_cast<KIGFX::CAIRO_GAL*>( m_gal ) )
1233 cairoGal->SetOverlayExclusions( rects );
1234}
1235
1236
1241
1242
1244{
1245 const auto now = std::chrono::steady_clock::now();
1246
1247 // The window can move to another display
1248 if( now - m_refreshRateAsked >= std::chrono::seconds( 1 ) )
1249 {
1250 const double reported = KIPLATFORM::UI::GetDisplayRefreshRate( this );
1251
1252 // Headless, virtualized and some driver setups report 0 or nonsense
1253 m_refreshRate = reported >= 24.0 && reported <= 1000.0 ? static_cast<float>( reported ) : 0.0f;
1254 m_refreshRateAsked = now;
1255 }
1256
1257 return m_refreshRate;
1258}
1259
1260
1261void EDA_DRAW_PANEL_GAL::Refresh( bool aEraseBackground, const wxRect* aRect )
1262{
1263 auto now = std::chrono::steady_clock::now();
1264 auto delta = std::chrono::duration_cast<std::chrono::milliseconds>( now - m_lastRepaintStart ).count();
1265 bool galInitialized = m_gal && m_gal->IsInitialized();
1266
1267 // When vsync is available the driver throttles SwapBuffers, so we only need
1268 // a small guard to avoid queueing work faster than the GPU can consume it.
1269 // Without vsync, cap the render rate at the monitor refresh rate so the
1270 // GPU is not saturated producing frames that will never be shown.
1271 int minPeriodMs = 3;
1272
1273 if( galInitialized && m_gal->GetSwapInterval() == 0 )
1274 {
1275 const float displayHz = displayRefreshRate();
1276 int refreshHz = displayHz > 0.0f ? KiROUND( displayHz ) : 60;
1277
1278 refreshHz += 5; // Repaint slightly faster to avoid adding latency
1279
1280 minPeriodMs = 1000 / refreshHz;
1281 }
1282
1283 if( delta >= minPeriodMs )
1284 {
1285 if( !DoRePaint() && IsShownOnScreen() )
1287 }
1288 else if( !m_refreshTimer.IsRunning() )
1289 {
1290 m_refreshDeferred = true;
1291 m_refreshTimer.StartOnce( static_cast<int>( minPeriodMs - delta ) );
1292 }
1293}
1294
1295
1297{
1298 wxLogTrace( traceRhi, wxS( "DrawPanel: ForceRefresh windowId=%u drawEnabled=%d "
1299 "IsShown=%d IsShownOnScreen=%d galInit=%d" ),
1300 m_windowId, m_drawingEnabled, IsShown(), IsShownOnScreen(),
1301 m_gal ? m_gal->IsInitialized() : -1 );
1302
1303 if( !m_drawingEnabled )
1304 {
1305 if( m_gal && m_gal->IsInitialized() )
1306 {
1307 Connect( wxEVT_PAINT, wxPaintEventHandler( EDA_DRAW_PANEL_GAL::onPaint ), nullptr, this );
1308 Connect( wxEVT_IDLE, wxIdleEventHandler( EDA_DRAW_PANEL_GAL::onIdle ), nullptr, this );
1309
1310 m_drawingEnabled = true;
1311 DoRePaint( false );
1312
1313 // A freshly mapped GL drawable can drop its first frame, and a refresh skips an unchanged view
1314 if( m_drawingEnabled )
1315 m_refreshTimer.StartOnce( 50 );
1316
1317 return;
1318 }
1319 else if( IsShownOnScreen() )
1320 {
1321 // Try again soon
1322 m_refreshTimer.StartOnce( 100 );
1323 return;
1324 }
1325 else
1326 {
1327 // Polling a canvas nobody can see wakes the app ten times a second for as long as it stays hidden
1328 if( !m_awaitingShow )
1329 {
1330 m_awaitingShow = true;
1331 Bind( wxEVT_IDLE, &EDA_DRAW_PANEL_GAL::onIdleAwaitShow, this );
1332 }
1333
1334 return;
1335 }
1336 }
1337
1338 DoRePaint( false );
1339}
1340
1341
1342void EDA_DRAW_PANEL_GAL::onIdleAwaitShow( wxIdleEvent& aEvent )
1343{
1344 aEvent.Skip();
1345
1346 if( !m_drawingEnabled && !IsShownOnScreen() )
1347 return;
1348
1349 m_awaitingShow = false;
1350 Unbind( wxEVT_IDLE, &EDA_DRAW_PANEL_GAL::onIdleAwaitShow, this );
1351
1352 if( !m_drawingEnabled )
1353 ForceRefresh();
1354}
1355
1356
1357bool EDA_DRAW_PANEL_GAL::GetScreenshot( wxImage& aDstImage )
1358{
1359 if( !m_gal )
1360 return false;
1361
1362 if( m_backend == GAL_TYPE_OPENGL )
1363 {
1364 DoRePaint( false );
1365
1366 // The repaint may have replaced a GAL lost to a GPU reset
1367 if( m_backend != GAL_TYPE_OPENGL || !m_gal )
1368 return false;
1369
1370 return static_cast<KIGFX::OPENGL_GAL*>( m_gal )->GetScreenshot( aDstImage );
1371 }
1372
1374 {
1375 DoRePaint( false );
1376
1377 // The repaint may have torn down the render thread while recovering from an error
1379 return false;
1380
1381 return m_renderThread->ReadbackWindowPixels( m_windowId, aDstImage );
1382 }
1383
1384 // The caller falls back to a wxClientDC capture
1385 return false;
1386}
1387
1388
1390{
1391 m_eventDispatcher = aEventDispatcher;
1392}
1393
1394
1396{
1397 wxLogTrace( traceRhi, wxS( "DrawPanel: StartDrawing windowId=%u" ), m_windowId );
1398
1399 // Start querying GAL if it is ready
1400 m_refreshTimer.StartOnce( 100 );
1401}
1402
1403
1405{
1406 m_refreshTimer.Stop();
1407 m_drawingEnabled = false;
1408
1409 if( m_awaitingShow )
1410 {
1411 m_awaitingShow = false;
1412 Unbind( wxEVT_IDLE, &EDA_DRAW_PANEL_GAL::onIdleAwaitShow, this );
1413 }
1414
1415 Disconnect( wxEVT_PAINT, wxPaintEventHandler( EDA_DRAW_PANEL_GAL::onPaint ), nullptr, this );
1416 Disconnect( wxEVT_IDLE, wxIdleEventHandler( EDA_DRAW_PANEL_GAL::onIdle ), nullptr, this );
1417}
1418
1419
1421{
1422 // Set display settings for high contrast mode
1423 KIGFX::RENDER_SETTINGS* rSettings = m_view->GetPainter()->GetSettings();
1424
1425 SetTopLayer( aLayer );
1426
1427 rSettings->ClearHighContrastLayers();
1428 rSettings->SetLayerIsHighContrast( aLayer );
1429
1430 m_view->UpdateAllLayersColor();
1431}
1432
1433
1435{
1436 m_view->ClearTopLayers();
1437 m_view->SetTopLayer( aLayer );
1438 m_view->UpdateAllLayersOrder();
1439}
1440
1441
1443{
1444 if( aStoredCanvasType == GAL_TYPE_CAIRO || aStoredCanvasType == GAL_TYPE_MODERN )
1445 return static_cast<GAL_TYPE>( aStoredCanvasType );
1446
1447 // The retired wxDC canvas, and any value another KiCad version may have written, leave the
1448 // user with the accelerated canvas rather than the do-nothing stub GAL
1449 return GAL_TYPE_OPENGL;
1450}
1451
1452
1454{
1455 // Do not do anything if the currently used GAL is correct
1456 if( aGalType == m_backend && m_gal != nullptr )
1457 return true;
1458
1459 VECTOR2D grid_origin = m_gal ? m_gal->GetGridOrigin() : VECTOR2D();
1460 VECTOR2D grid_size = m_gal ? m_gal->GetGridSize() : VECTOR2D();
1461 bool grid_visibility = m_gal ? m_gal->GetGridVisibility() : true;
1462 double worldUnitLength = m_gal ? m_gal->GetWorldUnitLength() : 0.0;
1463 bool result = true; // assume everything will be fine
1464
1465 // Prevent refreshing canvas during backend switch
1466 StopDrawing();
1467
1469 m_pendingResize = false;
1470
1471 KIGFX::GAL* new_gal = nullptr;
1472
1473 try
1474 {
1475 switch( aGalType )
1476 {
1477 case GAL_TYPE_OPENGL:
1478 {
1479 wxString errormsg = KIGFX::OPENGL_GAL::CheckFeatures( m_options );
1480
1481 if( errormsg.empty() )
1482 {
1483 new_gal = new KIGFX::OPENGL_GAL( GetVcSettings(), m_options, this, this, this );
1484 }
1485 else
1486 {
1487 if( GAL_FALLBACK != aGalType )
1488 {
1489 aGalType = GAL_FALLBACK;
1490 showMessageLater( _( "Could not use OpenGL, falling back to software rendering" ), errormsg,
1491 false );
1492 new_gal = new KIGFX::CAIRO_GAL( m_options, this, this, this );
1493 }
1494 else
1495 {
1496 // We're well and truly banjaxed if we get here without a fallback.
1497 showMessageLater( _( "Could not use OpenGL" ), errormsg, false );
1498 new_gal = new KIGFX::GAL( m_options );
1499 aGalType = GAL_TYPE_NONE;
1500 result = false;
1501 }
1502 }
1503
1504 break;
1505 }
1506
1507 case GAL_TYPE_CAIRO:
1508 new_gal = new KIGFX::CAIRO_GAL( m_options, this, this, this );
1509 break;
1510
1511 case GAL_TYPE_MODERN:
1512 {
1514
1515 // A device that failed once is not retried, so the user is told only once
1517 return abandonRhiCanvas( wxEmptyString );
1518
1520
1521 if( m_renderThread )
1522 {
1523 wxLogTrace( traceRhi, wxS( "DrawPanel: render thread acquired" ) );
1524
1525 // A repaint sees the loss and rebuilds the canvas. The listener is removed before the panel
1526 // is destroyed, and wx drops anything still queued for it.
1527 m_renderThread->AddDeviceLostListener( this,
1528 [this]()
1529 {
1530 CallAfter(
1531 [this]()
1532 {
1533 Refresh();
1534 } );
1535 } );
1536
1537 // The render thread owns the device, so the UI thread reaches it only through the proxy
1538 m_deviceProxy = std::make_unique<KIGFX::RHI_DEVICE_PROXY>( *m_renderThread );
1539
1540 new_gal = new KIGFX::GAL_MODERN( m_options, *m_deviceProxy );
1541
1542 auto* galModern = static_cast<KIGFX::GAL_MODERN*>( new_gal );
1543 galModern->SetRenderThread( m_renderThread.get() );
1544 galModern->SetPersistentTargets( true );
1545
1546 // Only the track shader draws the glyphs of the font atlas
1547 galModern->SetBitmapGlyphs( m_linePipelineKind == KIGFX::RHI_LINE_PIPELINE_KIND::PCB_TRACKS );
1548
1550 m_frameMailbox = std::make_unique<KIGFX::FRAME_MAILBOX>();
1551 m_swapchainCtrl = std::make_unique<KIGFX::SWAPCHAIN_CONTROLLER>( *m_renderThread, m_windowId );
1552 m_swapchainCtrl->SetFrameMailbox( m_frameMailbox.get() );
1553
1554 wxLogTrace( traceRhi, wxS( "DrawPanel: windowId=%u swapchainCtrl created" ), m_windowId );
1555
1556 // The GDK background is set on the first paint, once the widget is laid out
1559
1560 // The native surface is being recreated
1561 m_nativeHandleValid = false;
1562 }
1563 else
1564 {
1565 return abandonRhiCanvas( wxEmptyString );
1566 }
1567
1568 break;
1569 }
1570
1571 default:
1572 wxASSERT( false );
1574
1575 case GAL_TYPE_NONE:
1576 // KIGFX::GAL is a stub that prevents code relying on GAL canvas
1577 // existence from crashing, but cannot display anything
1578 new_gal = new KIGFX::GAL( m_options );
1579 break;
1580 }
1581 }
1582 catch( std::runtime_error& err )
1583 {
1584 // The GAL is deleted while the device proxy it releases its buffers through is still alive
1585 if( aGalType == GAL_TYPE_MODERN )
1586 {
1587 delete new_gal;
1589
1590 return abandonRhiCanvas( wxString( err.what() ) );
1591 }
1592
1593 // A context the driver refuses to create would otherwise leave every frame on the blank stub
1594 if( aGalType == GAL_TYPE_OPENGL && GAL_FALLBACK_AVAILABLE )
1595 {
1596 try
1597 {
1598 new_gal = new KIGFX::CAIRO_GAL( m_options, this, this, this );
1599 aGalType = GAL_FALLBACK;
1601 showMessageLater( _( "Could not use OpenGL, falling back to software rendering" ),
1602 wxString( err.what() ), false );
1603 }
1604 catch( std::runtime_error& )
1605 {
1606 new_gal = nullptr;
1607 }
1608 }
1609
1610 if( !new_gal )
1611 {
1612 // Create a dummy GAL
1613 new_gal = new KIGFX::GAL( m_options );
1614 aGalType = GAL_TYPE_NONE;
1615 showMessageLater( _( "Error switching GAL backend" ), wxString( err.what() ), true );
1616 result = false;
1617 }
1618 }
1619
1620 // trigger update of the gal options in case they differ from the defaults
1621 m_options.NotifyChanged();
1622
1623 // The native touchpad hook is attached to the window that takes the backend's input
1625
1626 // Queued uploads must not outlive the GAL_MODERN geometry they point at
1627 if( m_backend == GAL_TYPE_MODERN && aGalType != GAL_TYPE_MODERN )
1629
1630 delete m_gal;
1631 m_gal = nullptr;
1632
1633 m_gal = new_gal;
1634 m_gal->SetCursorInCanvas( m_cursorInCanvas );
1635
1636 // The view lays itself out in the editor's world units as it attaches
1637 if( worldUnitLength > 0.0 )
1638 m_gal->SetWorldUnitLength( worldUnitLength );
1639
1640 if( aGalType == GAL_TYPE_MODERN )
1641 {
1642 KIGFX::GAL_MODERN* galModern = static_cast<KIGFX::GAL_MODERN*>( m_gal );
1643
1644 galModern->SetDpiScale( static_cast<float>( GetContentScaleFactor() ) );
1646 }
1647
1648 // Matches ResizeGal() so the picture does not move at the next resize
1649 wxSize clientSize = GetClientSize();
1650 int pad = ScreenSizePad( aGalType );
1651
1652 clientSize.x = std::max( 10, clientSize.x + pad );
1653 clientSize.y = std::max( 10, clientSize.y + pad );
1654 m_gal->ResizeScreen( clientSize.GetX(), clientSize.GetY() );
1655
1656 if( grid_origin != VECTOR2D() )
1657 m_gal->SetGridOrigin( grid_origin );
1658
1659 if( grid_size.x > 0 && grid_size.y > 0 )
1660 m_gal->SetGridSize( grid_size );
1661
1662 m_gal->SetGridVisibility( grid_visibility );
1663
1664 // Make sure the cursor is set on the new canvas
1666
1667 if( m_painter )
1668 m_painter->SetGAL( m_gal );
1669
1670 if( m_view )
1671 {
1672 m_view->SetGAL( m_gal );
1673 // OpenGL requires reverse draw order when draw priority is enabled.
1674 m_view->ReverseDrawOrder( aGalType == GAL_TYPE_OPENGL );
1675
1676 // The new GAL starts with empty geometry caches
1677 m_view->UpdateAllItems( KIGFX::ALL );
1678 }
1679
1680 m_backend = aGalType;
1681
1682 // A shown backend window raises itself, which would bury what is overlaid on this canvas
1683 for( wxWindow* child : GetChildren() )
1684 {
1685 if( child != dynamic_cast<wxWindow*>( m_gal ) )
1686 child->Raise();
1687 }
1688
1690
1692
1693 if( m_view )
1694 {
1695 wxLogTrace( traceRhi, wxS( "DrawPanel: backend %d view centre (%.17g, %.17g) scale %.17g screen %dx%d" ),
1696 static_cast<int>( m_backend ), m_view->GetCenter().x, m_view->GetCenter().y, m_view->GetScale(),
1697 m_gal->GetScreenPixelSize().x, m_gal->GetScreenPixelSize().y );
1698 }
1699
1700 return result;
1701}
1702
1703
1705{
1707
1708 if( Pgm().GetCommonSettings()->m_Input.touchpad_mode != TOUCHPAD_MODE::NATIVE_GESTURES )
1709 return;
1710
1711 // The modern canvas has no child window, so this panel receives the native pointer input
1712 wxWindow* inputWindow = m_backend == GAL_TYPE_MODERN ? static_cast<wxWindow*>( this )
1713 : dynamic_cast<wxWindow*>( m_gal );
1714
1715 if( inputWindow )
1716 {
1718 inputWindow,
1719 [this]( const KIPLATFORM::UI::TOUCHPAD_GESTURE& aGesture )
1720 {
1721 if( !m_viewControls )
1722 return;
1723
1724 m_viewControls->ApplyPanAndZoomGesture(
1725 VECTOR2D( aGesture.panX, aGesture.panY ), aGesture.zoomFactor,
1726 VECTOR2D( aGesture.zoomAnchor.x, aGesture.zoomAnchor.y ) );
1727 } );
1728 }
1729}
1730
1731
1733{
1734 try
1735 {
1736 // Check if the current rendering backend can be properly initialized
1737 m_view->UpdateItems();
1738 }
1739 catch( const std::runtime_error& e )
1740 {
1741 // recoverFromGalError() tells the user the outcome either way
1742 if( !recoverFromGalError( e ) )
1743 {
1744 StopDrawing();
1745 }
1746 else if( m_edaFrame && m_edaFrame->GetCanvas() == this )
1747 {
1748 // The frame's tools and view settings must follow the new GAL
1749 m_edaFrame->ActivateGalCanvas();
1750 }
1751 }
1752}
1753
1754
1756{
1757 s_inputSerial.fetch_add( 1, std::memory_order_relaxed );
1758}
1759
1760
1761void EDA_DRAW_PANEL_GAL::OnEvent( wxEvent& aEvent )
1762{
1763 if( aEvent.GetEventType() != KIGFX::WX_VIEW_CONTROLS::EVT_REFRESH_MOUSE )
1764 NoteInput();
1765
1766 bool shouldSetFocus = m_lostFocus && m_stealsFocus
1767 && !KIUI::IsInputControlFocused() // Don't steal from input controls
1768 && !KIUI::IsModalDialogFocused() // Don't steal from dialogs
1769 && KIPLATFORM::UI::IsWindowActive( m_edaFrame ); // Don't steal from other windows
1770
1771 if( shouldSetFocus )
1772 SetFocus();
1773
1774 if( !m_eventDispatcher )
1775 aEvent.Skip();
1776 else
1777 m_eventDispatcher->DispatchWxEvent( aEvent );
1778
1779 Refresh();
1780}
1781
1782
1783void EDA_DRAW_PANEL_GAL::onEnter( wxMouseEvent& aEvent )
1784{
1785 bool shouldSetFocus = m_stealsFocus
1786 && !KIUI::IsInputControlFocused() // Don't steal from input controls
1787 && !KIUI::IsModalDialogFocused() // Don't steal from dialogs
1788 && KIPLATFORM::UI::IsWindowActive( m_edaFrame ); // Don't steal from other windows
1789
1790 // Getting focus is necessary in order to receive key events properly
1791 if( shouldSetFocus )
1792 SetFocus();
1793
1794 aEvent.Skip();
1795}
1796
1797
1798void EDA_DRAW_PANEL_GAL::onLostFocus( wxFocusEvent& aEvent )
1799{
1800 m_lostFocus = true;
1801
1802 m_viewControls->CancelDrag();
1803
1804 // Reset the tool dispatcher's button state when focus is lost. This prevents
1805 // the dispatcher from thinking the button is still pressed when focus returns,
1806 // which can cause selection and drag operations to stop working.
1807 if( m_eventDispatcher )
1808 m_eventDispatcher->ResetState();
1809
1810 aEvent.Skip();
1811}
1812
1813
1814void EDA_DRAW_PANEL_GAL::onIdle( wxIdleEvent& aEvent )
1815{
1816 if( m_needIdleRefresh )
1817 {
1818 wxLogTrace( traceRhi, wxS( "DrawPanel: onIdle refresh windowId=%u IsShown=%d "
1819 "IsShownOnScreen=%d" ),
1820 m_windowId, IsShown(), IsShownOnScreen() );
1821
1822 m_needIdleRefresh = false;
1823 Refresh();
1824 }
1825
1826 aEvent.Skip();
1827}
1828
1829
1830void EDA_DRAW_PANEL_GAL::onRefreshTimer( wxTimerEvent& aEvent )
1831{
1832 const bool deferred = m_refreshDeferred;
1833
1834 m_refreshDeferred = false;
1835
1836 // A postponed Refresh() is not an expose and must not present the frame already on screen
1837 if( deferred && m_backend == GAL_TYPE_MODERN && m_drawingEnabled )
1838 {
1839 if( !DoRePaint() && IsShownOnScreen() )
1841
1842 return;
1843 }
1844
1845 ForceRefresh();
1846}
1847
1848
1849void EDA_DRAW_PANEL_GAL::onShowEvent( wxShowEvent& aEvent )
1850{
1851 wxLogTrace( traceRhi, wxS( "DrawPanel: onShowEvent windowId=%u show=%d IsShown=%d "
1852 "IsShownOnScreen=%d galInit=%d" ),
1853 m_windowId, aEvent.IsShown(), IsShown(), IsShownOnScreen(),
1854 m_gal ? m_gal->IsInitialized() : -1 );
1855
1856 // A hidden canvas gets no leave event. Only an enter event sets the state again.
1857 if( !IsShownOnScreen() )
1858 SetCursorInCanvas( false );
1859
1860 if( m_gal && m_gal->IsInitialized() && m_gal->IsVisible() )
1861 {
1862 OnShow();
1863 }
1864
1865}
1866
1867
1869{
1870 if( !m_gal )
1871 return;
1872
1873 DPI_SCALING_COMMON dpi( nullptr, m_parent );
1874
1875 bool hidpi = false;
1876
1877 // Cursor scaling factor cannot be set for a wxCursor on GTK and OSX (at least before wx 3.3),
1878 // resulting in 4x rendered size on 2x window scale.
1879 // MSW renders the bitmap as-is, without scaling, so this works here.
1880#ifdef __WXMSW__
1881 hidpi = dpi.GetContentScaleFactor() >= 2.0;
1882#endif
1883
1884 m_gal->SetNativeCursorStyle( aCursor, hidpi );
1885
1886 // The RHI canvas draws into the panel itself, and a new canvas window inherits the panel's cursor
1887#if wxCHECK_VERSION( 3, 3, 0 )
1888 SetCursorBundle( CURSOR_STORE::GetCursor( aCursor, hidpi ) );
1889#else
1890 SetCursor( CURSOR_STORE::GetCursor( aCursor, hidpi ) );
1891#endif
1892}
1893
1894
1895std::shared_ptr<KIGFX::VIEW_OVERLAY> EDA_DRAW_PANEL_GAL::DebugOverlay()
1896{
1897 if( !m_debugOverlay )
1898 {
1899 m_debugOverlay.reset( new KIGFX::VIEW_OVERLAY() );
1900 m_view->Add( m_debugOverlay.get() );
1901 }
1902
1903 return m_debugOverlay;
1904}
1905
1906
1908{
1909 if( m_debugOverlay )
1910 {
1911 m_view->Remove( m_debugOverlay.get() );
1912 m_debugOverlay = nullptr;
1913 }
1914}
1915
1916
1918{
1920
1921 KIGFX::VC_SETTINGS vcSettings;
1922 vcSettings.m_warpCursor = cfg->m_Input.center_on_zoom;
1924 vcSettings.m_autoPanSettingEnabled = cfg->m_Input.auto_pan;
1925 vcSettings.m_autoPanAcceleration = static_cast<float>( cfg->m_Input.auto_pan_acceleration );
1926 vcSettings.m_horizontalPan = cfg->m_Input.horizontal_pan;
1928 vcSettings.m_zoomSpeed = cfg->m_Input.zoom_speed;
1929 vcSettings.m_zoomSpeedAuto = cfg->m_Input.zoom_speed_auto;
1934 vcSettings.m_dragLeft = cfg->m_Input.drag_left;
1935 vcSettings.m_dragMiddle = cfg->m_Input.drag_middle;
1936 vcSettings.m_dragRight = cfg->m_Input.drag_right;
1939
1940 return vcSettings;
1941}
BASE_SCREEN class implementation.
BOX2< VECTOR2I > BOX2I
Definition box2.h:917
constexpr BOX2I KiROUND(const BOX2D &aBoxD)
Definition box2.h:985
static const ADVANCED_CFG & GetCfg()
Get the singleton instance's config, which is shared by all consumers.
VECTOR2D m_ScrollCenter
Current scroll center point in logical units.
Definition base_screen.h:96
constexpr size_type GetWidth() const
Definition box2.h:217
constexpr Vec Centre() const
Definition box2.h:100
constexpr size_type GetHeight() const
Definition box2.h:218
constexpr const SizeVec & GetSize() const
Definition box2.h:209
static const WX_CURSOR_TYPE GetCursor(KICURSOR aCursorType, bool aHiDPI=false)
Get a cursor bundle (wx 3.3+) or appropriate cursor (older versions)
Definition cursors.cpp:399
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.
FRAME_T GetFrameType() const
void Unregister(EDA_CURSOR_OWNER *aOwner)
static EDA_CURSOR_BROADCASTER & Instance()
void NotifyCursorEntered(EDA_CURSOR_OWNER *aEnteredOwner)
Hide the cursor in every registered owner other than aEnteredOwner.
void Register(EDA_CURSOR_OWNER *aOwner)
The base class for create windows for drawing purpose.
static bool CanvasFailed(EDA_DRAW_PANEL_GAL::GAL_TYPE aCanvas)
virtual BASE_SCREEN * GetScreen() const
Return a pointer to a BASE_SCREEN or one of its derivatives.
static void SetCanvasFailed(EDA_DRAW_PANEL_GAL::GAL_TYPE aCanvas)
Keep every frame off a canvas for this session without changing the saved preference.
std::unique_ptr< PROF_COUNTER > m_PaintEventCounter
bool m_cursorVisibilityDirty
The cursor was shown or hidden since the last repaint.
void onIdleAwaitShow(wxIdleEvent &aEvent)
EDA_DRAW_FRAME * m_edaFrame
Parent EDA_DRAW_FRAME (if available)
static GAL_TYPE CanvasAfterFailure(GAL_TYPE aFailedCanvasType)
Return the canvas that takes over from one that could not be used.
virtual void OnShow()
Called when the window is shown for the first time.
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.
RHI_NATIVE_WINDOW_HANDLE m_cachedNativeHandle
Fetching the handle forces a display-server flush, so it is cached between realizations and fetched a...
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.
std::unique_ptr< KIGFX::SWAPCHAIN_CONTROLLER > m_swapchainCtrl
bool abandonRhiCanvas(const wxString &aDetail)
Leave the RHI canvas for GAL_FALLBACK after its device could not be created or restored.
virtual void SetHighContrastLayer(int aLayer)
Take care of display settings for the given layer to be displayed in high contrast mode.
void SetCursorInCanvas(bool aCursorInCanvas)
Set whether the mouse cursor is inside the drawing canvas.
int m_overlayInsetTop
Rows at the top of the panel left to the infobars where the backend window would hide them.
bool m_stealsFocus
Flag to indicate whether the panel should take focus at certain times (when moused over,...
virtual BOX2I GetDefaultViewBBox() const
Return the bounding box of the view that should be used if model is not valid.
KIGFX::GAL_DISPLAY_OPTIONS & m_options
void StopDrawing()
Prevent the GAL canvas from further drawing until it is recreated or StartDrawing() is called.
KIGFX::RHI_LINE_PIPELINE_KIND m_linePipelineKind
Fixed in the constructor from the parent frame's editor.
static KIGFX::VC_SETTINGS GetVcSettings()
Gets a populated View Controls settings object dervived from our program settings.
static void NoteInput()
Count an input so the frame that answers it is never held back by the display-rate limit.
std::unique_ptr< KIGFX::FRAME_MAILBOX > m_frameMailbox
Delivers frame packets to the render thread.
virtual void SetTopLayer(int aLayer)
Move the selected layer to the top, so it is displayed above all others.
KIGFX::FRAME_DRAW_DESC m_lastFullStaticDesc
Draw descriptors of the last full redraw, reused by frames that need no new geometry.
void presentFrame()
Present the most recently submitted frame packet.
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.
static int ScreenSizePad(GAL_TYPE aBackend)
Return how many pixels larger than the client area a backend's GAL is made.
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)
float displayRefreshRate()
Refresh rate in Hz of the display showing the canvas, or 0 when unknown.
void releaseCachedNativeWindowHandle()
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.
std::unique_ptr< KIGFX::RHI_DEVICE_PROXY > m_deviceProxy
The UI thread's access to the device.
static bool IsAccelerated(GAL_TYPE aCanvasType)
True for a canvas drawn on the GPU, which keeps cached layers between frames.
wxSize backendScreenSize() const
The padded size of the backend window, which sits below the top overlay inset.
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
bool m_needsExternalRenderingSetup
True until the first paint completes the deferred GTK drawing suppression.
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_MODERN
RHI implementation, Vulkan or Metal on macOS.
@ GAL_TYPE_CAIRO
Cairo implementation.
@ GAL_TYPE_NONE
GAL not used (the legacy wxDC engine is used)
virtual void beforeRedraw()
Hook for subclasses to update view items whose inputs nothing else tracks.
bool m_awaitingShow
A hidden canvas whose GAL is not ready yet waits for idle instead of polling.
KIGFX::FRAME_DRAW_DESC m_lastFullDynamicDesc
void teardownModernRenderInfra()
Stop the RHI render thread and release its swapchain, mailbox and buffers.
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.)
bool m_cursorInCanvas
True while the mouse cursor is inside the drawing canvas.
const RHI_NATIVE_WINDOW_HANDLE & getCachedNativeWindowHandle()
Return the native window handle for RHI surface creation, or an invalid handle until the window is re...
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.
float m_refreshRate
What displayRefreshRate() last asked the window system.
void onEnter(wxMouseEvent &aEvent)
void submitCachedScene()
Submit the last full scene again with the current camera and cursor, keeping all targets.
uint32_t m_windowId
Routes this window's work on the render thread.
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
uint64_t m_staticEpoch
Content generations of the static and dynamic pools last submitted, see FRAME_PACKET.
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::shared_ptr< KIGFX::RENDER_THREAD > m_renderThread
The render thread that owns the RHI device, shared by every canvas, see GAL_MODERN::AcquireRenderThre...
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_recoveryAttempted
Set after a GPU recovery attempt to prevent infinite retry loops.
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.
KIGFX::AUTOMATIC_FIT m_automaticFit
What the last ZoomToFit() left, refitted on a resize until the view is zoomed or panned.
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.
std::chrono::steady_clock::time_point m_refreshRateAsked
void ZoomToFit(const BOX2I &aBox, std::optional< double > aMarginScale=std::nullopt)
Scale and centre the view on aBox, and fit it again whenever the canvas changes size until something ...
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.
bool m_refreshDeferred
The refresh timer was armed by Refresh() for a repaint it postponed.
GAL that turns drawing commands into instanced primitives for the RHI device.
Definition gal_modern.h:50
void SetCentringPad(int aPad)
The other canvases lay the view out this many pixels larger than the client area.
Definition gal_modern.h:155
void SetRenderThread(RENDER_THREAD *aThread)
Render thread used for fence-based synchronization.
Definition gal_modern.h:143
static uint32_t AllocateWindowId()
static std::shared_ptr< RENDER_THREAD > AcquireRenderThread(bool aEnableValidation)
Return the render thread every RHI canvas in the process shares, starting it on first use and replaci...
void SetDpiScale(float aScale)
Backing-store scale factor, 2.0 on Retina.
Definition gal_modern.h:149
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:69
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.
Hold a (potentially large) number of VIEW_ITEMs and renders them on a graphics device provided by the...
Definition view.h:68
double GetScale() const
Definition view.h:298
const VECTOR2D & GetCenter() const
Return the center point of this VIEW (in world space coordinates).
Definition view.h:377
virtual void SetScale(double aScale, VECTOR2D aAnchor={ 0, 0 })
Set the scaling factor, zooming around a given anchor point.
Definition view.cpp:900
VECTOR2D ToWorld(const VECTOR2D &aCoord, bool aAbsolute=true) const
Converts a screen space point/vector to a point/vector in world space coordinates.
Definition view.cpp:790
void SetCenter(const VECTOR2D &aCenter)
Set the center point of the VIEW (i.e.
Definition view.cpp:970
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:576
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:41
@ ARROW
Definition cursors.h:43
static RHI_NATIVE_WINDOW_HANDLE GetNativeWindowHandle(wxWindow *aWindow)
static constexpr int MAX_CONTEXT_BIND_RETRIES
Frames to drop before giving up on the GL context and letting the backend recover.
static void ApplyAntialiasingMode(KIGFX::FRAME_DRAW_DESC &aDesc, KIGFX::GAL_ANTIALIASING_MODE aMode)
static std::atomic< uint64_t > s_inputSerial
static KIGFX::RHI_LINE_PIPELINE_KIND DetermineLinePipelineKind(const EDA_DRAW_FRAME *aFrame)
#define _(s)
@ FRAME_SCH_SYMBOL_EDITOR
Definition frame_type.h:31
@ FRAME_SCH_VIEWER
Definition frame_type.h:32
@ FRAME_SCH
Definition frame_type.h:30
@ FRAME_SCH_DIFF
Definition frame_type.h:35
const wxChar *const traceGalContext
Flag to enable debug output of GAL context binding.
const wxChar *const traceRhi
Flag to enable debug output of the RHI rendering backend.
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.
RHI_LINE_PIPELINE_KIND
@ ALL
All except INITIAL_ADD.
Definition view_item.h:55
@ 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
double GetDisplayRefreshRate(const wxWindow *aWindow)
Return the refresh rate in Hz of the display showing most of the window, or 0 if unknown.
Definition wxgtk/ui.cpp:483
void GetNativeWindowHandles(wxWindow *aWindow, void **aHandle, void **aDisplay, int *aDisplayType=nullptr)
Get the native handles needed to create a GPU surface for aWindow.
void PrepareForExternalRendering(wxWindow *aWindow)
Prepare a realized widget for Vulkan or Metal rendering, before its first present.
void SetOverlayScrolling(const wxWindow *aWindow, bool overlay)
Used to set overlay/non-overlay scrolling mode in a window.
Definition wxgtk/ui.cpp:509
void ImmControl(wxWindow *aWindow, bool aEnable)
Configures the IME mode of a given control handle.
Definition wxgtk/ui.cpp:717
@ DISPLAY_UNKNOWN
Definition ui.h:291
@ DISPLAY_COCOA
Definition ui.h:295
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:722
bool IsWindowActive(wxWindow *aWindow)
Check to see if the given window is the currently active window (e.g.
Definition wxgtk/ui.cpp:233
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
KICOMMON_API RHI_METAL_HOST_VIEW RhiMetalAttachHostView(void *aCanvasView)
KICOMMON_API void RhiMetalDetachHostView(void *aHostView)
RHI_DISPLAY_TYPE
Matches KIPLATFORM::UI::NATIVE_DISPLAY_TYPE as reported by GetNativeWindowHandles().
Definition rhi_surface.h:30
const int scale
int canvas_type
EDA_DRAW_PANEL_GAL::GAL_TYPE_* value, see gal_options_panel.cpp.
MOUSE_DRAG_ACTION drag_right
MOUSE_DRAG_ACTION drag_middle
MOUSE_DRAG_ACTION drag_left
GPU geometry of one frame, built by GAL_MODERN after EndDrawing() and passed through the FRAME_MAILBO...
RHI_LINE_PIPELINE_KIND linePipelineKind
uint32_t supersampleFactor
Layer FBO scale that the present blit downsamples.
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
Platform-agnostic wrapper for a native window handle.
Definition rhi_surface.h:45
RHI_DISPLAY_TYPE displayType
Definition rhi_surface.h:48
bool IsValid() const
A handle is usable only once the window is realized.
Definition rhi_surface.h:54
DATABASE_CONNECTION dc(odbcBackend(cs))
struct DROP_TABLE cs
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.