55#include <wx/display.h>
70 const wxPoint& aPosition,
const wxSize& aSize,
72 wxScrolledCanvas( aParentWindow, aWindowId, aPosition, aSize ),
96 SetDoubleBuffered(
false );
100 if(
Pgm().GetCommonSettings()->m_Appearance.show_scrollbars )
101 ShowScrollbars( wxSHOW_SB_ALWAYS, wxSHOW_SB_ALWAYS );
103 ShowScrollbars( wxSHOW_SB_NEVER, wxSHOW_SB_NEVER );
105 SetLayoutDirection( wxLayout_LeftToRight );
112 wxWindow* ancestor = aParentWindow->GetParent();
115 ancestor = ancestor->GetParent();
122 SetBackgroundStyle( wxBG_STYLE_CUSTOM );
124 EnableScrolling(
false,
false );
132 const wxEventType events[] = {
160 for( wxEventType eventType : events )
192 wxScrolledCanvas::SetFocus();
244 showMessageLater(
_(
"The graphics driver was reset and OpenGL could not be restored" ),
245 _(
"Restart KiCad to use accelerated graphics again." ),
false );
249 showMessageLater(
_(
"Could not use OpenGL, falling back to software rendering" ),
250 wxString( aError.what() ),
false );
259 catch( std::exception& recoveryErr )
261 showMessageLater(
_(
"Graphics error during recovery" ), wxString( recoveryErr.what() ),
true );
265 showMessageLater(
_(
"Graphics error during recovery" ),
_(
"Unknown exception during backend switch" ),
281 if(
m_gal->IsContextLocked() )
285 if( !IsShownOnScreen() )
289 if( !
m_gal->IsResetSettled() )
295 wxLogTrace(
traceGalContext, wxS(
"Rebuilding canvas %p after GPU reset, repeated %d" ),
this,
298 bool rebuilt =
false;
313 static bool s_notified =
false;
315 wxLogTrace(
traceGalContext, wxS(
"Canvas %p falling back to software rendering" ),
this );
322 showMessageLater(
_(
"The graphics driver keeps resetting, falling back to software rendering" ),
323 wxEmptyString,
false );
337 [parent, aTitle, aDetail, aError]()
356 std::lock_guard<std::mutex> lock(
m_refreshMutex, std::adopt_lock );
364 if( !
m_gal->IsInitialized() || !
m_gal->IsVisible() ||
m_gal->IsContextLocked() )
385 if(
Pgm().GetCommonSettings()->m_Appearance.show_scrollbars )
388#ifdef KICAD_GAL_PROFILE
389 latencyProbeZoomToRender.Checkpoint(
"do-repaint-start");
394 ( *m_PaintEventCounter )++;
403 PROF_TIMER cntCtx(
"view-context-create",
false);
404 PROF_TIMER cntCtxDestroy(
"view-context-destroy",
false);
405 PROF_TIMER cntRedraw(
"view-redraw-rects",
false);
407 bool isDirty =
false;
414 bool viewDirty =
m_view->IsDirty();
416 bool hasPendingItemUpdates =
m_view->HasPendingItemUpdates();
421 if( aAllowSkip && !viewDirty && !cursorMoved && !hasPendingItemUpdates )
427 if( hasPendingItemUpdates )
435 catch( std::out_of_range& err )
439 wxLogTrace(
traceDrawPanel, wxS(
"Out of Range error: %s" ), err.what() );
441 catch( std::runtime_error& err )
446 wxLogTrace(
traceDrawPanel, wxS(
"Runtime error during UpdateItems: %s" ),
452 viewDirty =
m_view->IsDirty();
457 if( aAllowSkip && !viewDirty && !cursorMoved )
478 throw std::runtime_error(
"Could not make the OpenGL context current" );
498 m_gal->ClearScreen();
505 m_gal->ClearScreen();
523 m_gal->DrawCursor( cursorPos );
525 #ifdef KICAD_GAL_PROFILE
526 latencyProbeZoomToRender.Checkpoint(
"do-repaint-pre-ctx-destroy");
530 cntCtxDestroy.
Start();
534 cntCtxDestroy.
Stop();
536#ifdef KICAD_GAL_PROFILE
537 latencyProbeZoomToRender.Checkpoint(
"do-repaint-ctx-done");
545 catch( std::exception& err )
547 wxLogTrace(
traceDrawPanel, wxS(
"DoRePaint exception: %s" ), err.what() );
562#ifdef KICAD_GAL_PROFILE
575#ifdef KICAD_GAL_PROFILE
576 wxLogTrace(
traceGalProfile,
"%s", latencyProbeZoomToRender.to_string() );
577 latencyProbeRepaintToMotion.Reset();
578 latencyProbeRepaintToMotion.Checkpoint(
"repaint-done");
594 if(
m_gal->IsContextLocked() )
600 if( !
m_gal->IsContextValid() )
611 wxSize clientSize = GetClientSize();
613 if( !aForce &&
ToVECTOR2I( clientSize ) ==
m_gal->GetScreenPixelSize() )
617 clientSize.x = std::max( 10, clientSize.x + 1 );
618 clientSize.y = std::max( 10, clientSize.y + 1 );
620 m_gal->ResizeScreen( clientSize.GetX(), clientSize.GetY() );
638 std::vector<wxRect> rects;
640 for( wxWindow* child : GetChildren() )
642 if(
dynamic_cast<WX_INFOBAR*
>( child ) && child->IsShown() )
643 rects.push_back( child->GetRect() );
658 auto now = std::chrono::steady_clock::now();
660 bool galInitialized =
m_gal &&
m_gal->IsInitialized();
668 if( galInitialized &&
m_gal->GetSwapInterval() == 0 )
674 int reported = wxDisplay(
this ).GetCurrentMode().refresh;
676 if( reported >= 24 && reported <= 1000 )
677 refreshHz = reported;
681 minPeriodMs = 1000 / refreshHz;
684 if(
delta >= minPeriodMs )
767 m_view->UpdateAllLayersColor();
774 m_view->SetTopLayer( aLayer );
775 m_view->UpdateAllLayersOrder();
797 bool grid_visibility =
m_gal ?
m_gal->GetGridVisibility() :
true;
816 if( errormsg.empty() )
825 showMessageLater(
_(
"Could not use OpenGL, falling back to software rendering" ), errormsg,
858 catch( std::runtime_error& err )
868 showMessageLater(
_(
"Could not use OpenGL, falling back to software rendering" ),
869 wxString( err.what() ),
false );
871 catch( std::runtime_error& )
882 showMessageLater(
_(
"Error switching GAL backend" ), wxString( err.what() ),
true );
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() );
901 if( grid_size.
x > 0 && grid_size.
y > 0 )
902 m_gal->SetGridSize( grid_size );
904 m_gal->SetGridVisibility( grid_visibility );
922 for( wxWindow* child : GetChildren() )
943 if( wxWindow* inputWindow =
dynamic_cast<wxWindow*
>(
m_gal ) )
1053 m_gal->SetNativeCursorStyle( aCursor, hidpi );
BASE_SCREEN class implementation.
VECTOR2D m_ScrollCenter
Current scroll center point in logical units.
Class to handle configuration and automatic determination of the DPI scale to use for canvases.
double GetContentScaleFactor() const override
Get the content scale factor, which may be different from the scale factor on some platforms.
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.
bool IsDialogPreview() const
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 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.
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.
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).
static const wxEventType EVT_REFRESH_MOUSE
Event that forces mouse move event in the dispatcher (eg.
virtual COMMON_SETTINGS * GetCommonSettings() const
A small class to help profiling.
void Stop()
Save the time when this function was called, and set the counter stane to stop.
void Start()
Start or restart the counter.
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:
void DisplayInfoMessage(wxWindow *aParent, const wxString &aMessage, const wxString &aExtraInfo)
Display an informational message box with aMessage.
void DisplayErrorMessage(wxWindow *aParent, const wxString &aText, const wxString &aExtraInfo)
Display an error message with aMessage.
This file is part of the common library.
static constexpr int MAX_CONTEXT_BIND_RETRIES
Frames to drop before giving up on the GL context and letting the backend recover.
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 ...
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)
@ TARGET_OVERLAY
Items that may change while the view stays the same (noncached)
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.
Structure to keep VIEW_CONTROLS settings for easy store/restore operations.
MOUSE_DRAG_ACTION m_dragLeft
bool m_horizontalPan
Enable horizontal panning with the horizontal scroll/trackpad input.
bool m_scrollReversePanH
Whether to invert the scroll wheel movement for horizontal pan.
bool m_autoPanSettingEnabled
Flag for turning on autopanning.
bool m_focusFollowSchPcb
Flag for automatic focus switching between Schematic and PCB editors.
float m_autoPanAcceleration
How fast does panning accelerate when approaching the window boundary.
MOUSE_DRAG_ACTION m_dragMiddle
int m_zoomSpeed
Zoom speed for the non-accelerating zoom controller.
int m_scrollModifierZoom
What modifier key to enable zoom with the (vertical) scroll wheel.
int m_scrollModifierPanH
What modifier key to enable horizontal pan with the (vertical) scroll wheel.
bool m_warpCursor
If the cursor is allowed to be warped.
MOUSE_DRAG_ACTION m_dragRight
bool m_scrollReverseZoom
Whether to invert the scroll wheel movement for zoom.
int m_motionPanModifier
What modifier key pans the view when the mouse moves with it held.
bool m_zoomAcceleration
Enable the accelerating zoom controller.
bool m_zoomSpeedAuto
When true, ignore zoom_speed and pick a platform-specific default.
int m_scrollModifierPanV
What modifier key to enable vertical with the (vertical) scroll wheel.
wxString result
Test unit parsing edge cases and error handling.
wxLogTrace helper definitions.
VECTOR2< double > VECTOR2D
VECTOR2I ToVECTOR2I(const wxSize &aSize)
WX_VIEW_CONTROLS class definition.