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 <core/profile.h>
52
53#include <wx/display.h>
54
55#include <pgm_base.h>
56#include <confirm.h>
57
58
64static const wxChar traceDrawPanel[] = wxT( "KICAD_DRAW_PANEL" );
65
66
67EDA_DRAW_PANEL_GAL::EDA_DRAW_PANEL_GAL( wxWindow* aParentWindow, wxWindowID aWindowId,
68 const wxPoint& aPosition, const wxSize& aSize,
69 KIGFX::GAL_DISPLAY_OPTIONS& aOptions, GAL_TYPE aGalType ) :
70 wxScrolledCanvas( aParentWindow, aWindowId, aPosition, aSize ),
71 m_MouseCapturedLost( false ),
72 m_parent( aParentWindow ),
73 m_edaFrame( nullptr ),
74 m_drawing( false ),
75 m_drawingEnabled( false ),
76 m_needIdleRefresh( false ),
77 m_gal( nullptr ),
78 m_view( nullptr ),
79 m_painter( nullptr ),
80 m_viewControls( nullptr ),
82 m_options( aOptions ),
83 m_eventDispatcher( nullptr ),
84 m_lostFocus( false ),
85 m_glRecoveryAttempted( false ),
86 m_stealsFocus( true ),
87 m_statusPopup( nullptr )
88{
89#ifdef _WIN32
90 // need to fix broken cairo rendering on Windows with wx 3.3
91 SetDoubleBuffered( false );
92#endif
93 m_PaintEventCounter = std::make_unique<PROF_COUNTER>( "Draw panel paint events" );
94
95 if( Pgm().GetCommonSettings()->m_Appearance.show_scrollbars )
96 ShowScrollbars( wxSHOW_SB_ALWAYS, wxSHOW_SB_ALWAYS );
97 else
98 ShowScrollbars( wxSHOW_SB_NEVER, wxSHOW_SB_NEVER );
99
100 SetLayoutDirection( wxLayout_LeftToRight );
101
102 m_edaFrame = dynamic_cast<EDA_DRAW_FRAME*>( m_parent );
103
104 // If we're in a dialog, we have to go looking for our parent frame
105 if( !m_edaFrame )
106 {
107 wxWindow* ancestor = aParentWindow->GetParent();
108
109 while( ancestor && !dynamic_cast<EDA_DRAW_FRAME*>( ancestor ) )
110 ancestor = ancestor->GetParent();
111
112 if( ancestor )
113 m_edaFrame = dynamic_cast<EDA_DRAW_FRAME*>( ancestor );
114 }
115
116 SwitchBackend( aGalType );
117 SetBackgroundStyle( wxBG_STYLE_CUSTOM );
118
119 EnableScrolling( false, false ); // otherwise Zoom Auto disables GAL canvas
120 KIPLATFORM::UI::SetOverlayScrolling( this, false ); // Prevent excessive repaint on GTK
121 KIPLATFORM::UI::ImmControl( this, false ); // Ensure our panel can't suck in IME events
122
123 Connect( wxEVT_SIZE, wxSizeEventHandler( EDA_DRAW_PANEL_GAL::onSize ), nullptr, this );
124 Connect( wxEVT_ENTER_WINDOW, wxMouseEventHandler( EDA_DRAW_PANEL_GAL::onEnter ), nullptr, this );
125 Connect( wxEVT_KILL_FOCUS, wxFocusEventHandler( EDA_DRAW_PANEL_GAL::onLostFocus ), nullptr, this );
126
127 const wxEventType events[] = {
128 // Binding both EVT_CHAR and EVT_CHAR_HOOK ensures that all key events,
129 // especially special key like arrow keys, are handled by the GAL event dispatcher,
130 // and not sent to GUI without filtering, because they have a default action (scroll)
131 // that must not be called.
132 wxEVT_LEFT_UP,
133 wxEVT_LEFT_DOWN,
134 wxEVT_LEFT_DCLICK,
135 wxEVT_RIGHT_UP,
136 wxEVT_RIGHT_DOWN,
137 wxEVT_RIGHT_DCLICK,
138 wxEVT_MIDDLE_UP,
139 wxEVT_MIDDLE_DOWN,
140 wxEVT_MIDDLE_DCLICK,
141 wxEVT_AUX1_UP,
142 wxEVT_AUX1_DOWN,
143 wxEVT_AUX1_DCLICK,
144 wxEVT_AUX2_UP,
145 wxEVT_AUX2_DOWN,
146 wxEVT_AUX2_DCLICK,
147 wxEVT_MOTION,
148 wxEVT_MOUSEWHEEL,
149 wxEVT_CHAR,
150 wxEVT_CHAR_HOOK,
151 wxEVT_MAGNIFY,
153 };
154
155 for( wxEventType eventType : events )
156 Connect( eventType, wxEventHandler( EDA_DRAW_PANEL_GAL::OnEvent ), nullptr, m_eventDispatcher );
157
158 // Set up timer to detect when drawing starts
159 m_refreshTimer.SetOwner( this );
160 Connect( m_refreshTimer.GetId(), wxEVT_TIMER, wxTimerEventHandler( EDA_DRAW_PANEL_GAL::onRefreshTimer ),
161 nullptr, this );
162
163 Connect( wxEVT_SHOW, wxShowEventHandler( EDA_DRAW_PANEL_GAL::onShowEvent ), nullptr, this );
164}
165
166
168{
170
171 // Ensure EDA_DRAW_PANEL_GAL::onShowEvent is not fired during Dtor process
172 Disconnect( wxEVT_SHOW, wxShowEventHandler( EDA_DRAW_PANEL_GAL::onShowEvent ) );
173 StopDrawing();
174
175 wxASSERT( !m_drawing );
176
177 delete m_viewControls;
178 delete m_view;
179 delete m_gal;
180 m_gal = nullptr; // Ensure OnShow is not called
181}
182
183
185{
187 wxScrolledCanvas::SetFocus();
188 m_lostFocus = false;
189}
190
191
192void EDA_DRAW_PANEL_GAL::onPaint( wxPaintEvent& WXUNUSED( aEvent ) )
193{
194 DoRePaint( false );
195}
196
197
198bool EDA_DRAW_PANEL_GAL::recoverFromGalError( const std::exception& aError )
199{
200 // A predicted GPU out-of-memory cannot be cured by reinitializing OpenGL; it would just
201 // hit the same VRAM ceiling. Skip straight to the software fallback.
202 const bool gpuOutOfMemory = dynamic_cast<const KIGFX::GPU_OOM_ERROR*>( &aError ) != nullptr;
203
204 try
205 {
206 // Sleep/wake and GPU resets can invalidate the entire GL context.
207 // Try a full reinit of the current backend before falling back.
208 if( !gpuOutOfMemory && !m_glRecoveryAttempted )
209 {
211 GAL_TYPE prevBackend = m_backend;
213
214 if( SwitchBackend( prevBackend ) )
215 {
216 StartDrawing();
217 return true;
218 }
219 }
220
222 {
223 m_glRecoveryAttempted = false;
225
226 DisplayInfoMessage( m_parent, _( "Could not use OpenGL, falling back to software rendering" ),
227 wxString( aError.what() ) );
228
229 StartDrawing();
230 return true;
231 }
232
233 DisplayErrorMessage( m_parent, _( "Graphics error" ), wxString( aError.what() ) );
234 }
235 catch( std::exception& recoveryErr )
236 {
237 DisplayErrorMessage( m_parent, _( "Graphics error during recovery" ), wxString( recoveryErr.what() ) );
238 }
239 catch( ... )
240 {
241 DisplayErrorMessage( m_parent, _( "Graphics error during recovery" ),
242 _( "Unknown exception during backend switch" ) );
243 }
244
245 return false;
246}
247
248
249bool EDA_DRAW_PANEL_GAL::DoRePaint( bool aAllowSkip )
250{
251 if( !m_refreshMutex.try_lock() )
252 return false;
253
254 std::lock_guard<std::mutex> lock( m_refreshMutex, std::adopt_lock );
255
256 if( !m_drawingEnabled )
257 return false;
258
259 if( !m_gal->IsInitialized() || !m_gal->IsVisible() || m_gal->IsContextLocked() )
260 return false;
261
262 if( m_drawing )
263 return false;
264
265 m_lastRepaintStart = std::chrono::steady_clock::now();
266
267 // Repaint the canvas, and fix scrollbar cursors
268 // Usually called by a OnPaint event, but because it does not use a wxPaintDC,
269 // it can be called outside a wxPaintEvent.
270
271 // Update current zoom settings if the canvas is managed by a EDA frame
272 // (i.e. not by a preview panel in a dialog)
273 if( !IsDialogPreview() && GetParentEDAFrame() && GetParentEDAFrame()->GetScreen() )
275
276 if( Pgm().GetCommonSettings()->m_Appearance.show_scrollbars )
277 m_viewControls->UpdateScrollbars();
278
279#ifdef KICAD_GAL_PROFILE
280 latencyProbeZoomToRender.Checkpoint("do-repaint-start");
281#endif
282
283 SCOPED_SET_RESET<bool> drawing( m_drawing, true );
284
285 ( *m_PaintEventCounter )++;
286
287 wxASSERT( m_painter );
288
289 KIGFX::RENDER_SETTINGS* settings =
290 static_cast<KIGFX::RENDER_SETTINGS*>( m_painter->GetSettings() );
291
292 PROF_TIMER cntUpd("view-upd-items", false);
293 PROF_TIMER cntTotal("view-total", false);
294 PROF_TIMER cntCtx("view-context-create", false);
295 PROF_TIMER cntCtxDestroy("view-context-destroy", false);
296 PROF_TIMER cntRedraw("view-redraw-rects", false);
297
298 bool isDirty = false;
299
300 cntTotal.Start();
301
302 try
303 {
304 VECTOR2D cursorPos = m_viewControls->GetCursorPosition();
305 bool viewDirty = m_view->IsDirty();
306 bool cursorMoved = ( cursorPos != m_lastCursorPosition );
307 bool hasPendingItemUpdates = m_view->HasPendingItemUpdates();
308
309 // Skip all update work when nothing has changed since the previous frame.
310 // Never skip when responding to a native paint event or explicit ForceRefresh
311 // because the window content may have been invalidated by the OS.
312 if( aAllowSkip && !viewDirty && !cursorMoved && !hasPendingItemUpdates )
313 {
314 m_lastRepaintEnd = std::chrono::steady_clock::now();
315 return true;
316 }
317
318 if( hasPendingItemUpdates )
319 {
320 cntUpd.Start();
321
322 try
323 {
324 m_view->UpdateItems();
325 }
326 catch( std::out_of_range& err )
327 {
328 // Don't do anything here but don't fail
329 // This can happen when we don't catch `at()` calls
330 wxLogTrace( traceDrawPanel, wxS( "Out of Range error: %s" ), err.what() );
331 }
332 catch( std::runtime_error& err )
333 {
334 // Handle GL errors (e.g. glMapBuffer failure) that surface during UpdateItems().
335 // These can occur on macOS under memory pressure when embedding large 3D models.
336 // Log and continue so the outer handler can decide whether to switch backends.
337 wxLogTrace( traceDrawPanel, wxS( "Runtime error during UpdateItems: %s" ),
338 err.what() );
339 throw;
340 }
341
342 cntUpd.Stop();
343 viewDirty = m_view->IsDirty();
344 }
345
346 // After processing item updates, skip the GL cycle when neither the
347 // view targets nor the cursor position have changed.
348 if( aAllowSkip && !viewDirty && !cursorMoved )
349 {
350 m_lastRepaintEnd = std::chrono::steady_clock::now();
351 return true;
352 }
353
354 m_lastCursorPosition = cursorPos;
355
356 // GAL_DRAWING_CONTEXT can throw in the dtor, so we need to scope
357 // the full lifetime inside the try block
358 {
359 cntCtx.Start();
361 cntCtx.Stop();
362
363 if( m_view->IsTargetDirty( KIGFX::TARGET_OVERLAY )
364 && !m_gal->HasTarget( KIGFX::TARGET_OVERLAY ) )
365 {
366 m_view->MarkDirty();
367 }
368
369 m_gal->SetClearColor( settings->GetBackgroundColor() );
370 m_gal->SetGridColor( settings->GetGridColor() );
371 m_gal->SetCursorColor( settings->GetCursorColor() );
372
373 // OpenGL double-buffering leaves the back buffer undefined after
374 // SwapBuffers, so a full clear is always required before compositing.
375 // Cairo only needs to clear when NONCACHED content changed.
377 m_gal->ClearScreen();
378
379 if( m_view->IsDirty() )
380 {
381 if( m_backend != GAL_TYPE_OPENGL // Already called in opengl
382 && m_view->IsTargetDirty( KIGFX::TARGET_NONCACHED ) )
383 {
384 m_gal->ClearScreen();
385 }
386
387 m_view->ClearTargets();
388
389 // Grid has to be redrawn only when the NONCACHED target is redrawn
390 if( m_view->IsTargetDirty( KIGFX::TARGET_NONCACHED ) )
391 {
393 m_gal->DrawGrid();
394 }
395
396 cntRedraw.Start();
397 m_view->Redraw();
398 cntRedraw.Stop();
399 isDirty = true;
400 }
401
402 m_gal->DrawCursor( cursorPos );
403
404 #ifdef KICAD_GAL_PROFILE
405 latencyProbeZoomToRender.Checkpoint("do-repaint-pre-ctx-destroy");
406 #endif
407
408
409 cntCtxDestroy.Start();
410 }
411
412 // ctx goes out of scope here so destructor would be called
413 cntCtxDestroy.Stop();
414
415#ifdef KICAD_GAL_PROFILE
416 latencyProbeZoomToRender.Checkpoint("do-repaint-ctx-done");
417#endif
418
419 // OpenGL frame completed successfully, allow future recovery attempts
420 m_glRecoveryAttempted = false;
421 }
422 catch( std::exception& err )
423 {
424 wxLogTrace( traceDrawPanel, wxS( "DoRePaint exception: %s" ), err.what() );
425
426 if( recoverFromGalError( err ) )
427 return true;
428
429 StopDrawing();
430 }
431 catch( ... )
432 {
433 DisplayErrorMessage( m_parent, _( "Graphics error" ), _( "Unknown exception" ) );
434 StopDrawing();
435 }
436
437 if( isDirty )
438 {
439#ifdef KICAD_GAL_PROFILE
440 wxLogTrace( traceGalProfile, "View timing: %s %s %s %s %s",
441 cntTotal.to_string(),
442 cntUpd.to_string(),
443 cntRedraw.to_string(),
444 cntCtx.to_string(),
445 cntCtxDestroy.to_string()
446 );
447#endif
448 }
449
450 m_lastRepaintEnd = std::chrono::steady_clock::now();
451
452#ifdef KICAD_GAL_PROFILE
453 wxLogTrace( traceGalProfile, "%s", latencyProbeZoomToRender.to_string() );
454 latencyProbeRepaintToMotion.Reset();
455 latencyProbeRepaintToMotion.Checkpoint("repaint-done");
456#endif
457
458 return true;
459}
460
461
462void EDA_DRAW_PANEL_GAL::onSize( wxSizeEvent& aEvent )
463{
464 ResizeGal();
465}
466
467
469{
470 // If we get a second wx update call before the first finishes, don't crash
471 if( m_gal->IsContextLocked() )
472 return;
473
475 wxSize clientSize = GetClientSize();
476
477 if( !aForce && ToVECTOR2I( clientSize ) == m_gal->GetScreenPixelSize() )
478 return;
479
480 // Note: ( +1, +1 ) prevents an ugly black line on right and bottom on Mac
481 clientSize.x = std::max( 10, clientSize.x + 1 );
482 clientSize.y = std::max( 10, clientSize.y + 1 );
483
484 m_gal->ResizeScreen( clientSize.GetX(), clientSize.GetY() );
485
486 if( m_view )
487 {
488 // ResizeScreen reallocates every compositor buffer, so nothing survives the resize
489 m_view->MarkDirty();
490 }
491}
492
493
495{
496 KIGFX::CAIRO_GAL* cairoGal = dynamic_cast<KIGFX::CAIRO_GAL*>( m_gal );
497
498 // Only the Cairo backend presents frames outside the paint cycle
499 if( !cairoGal )
500 return;
501
502 std::vector<wxRect> rects;
503
504 for( wxWindow* child : GetChildren() )
505 {
506 if( dynamic_cast<WX_INFOBAR*>( child ) && child->IsShown() )
507 rects.push_back( child->GetRect() );
508 }
509
510 cairoGal->SetOverlayExclusions( rects );
511}
512
513
518
519
520void EDA_DRAW_PANEL_GAL::Refresh( bool aEraseBackground, const wxRect* aRect )
521{
522 auto now = std::chrono::steady_clock::now();
523 auto delta = std::chrono::duration_cast<std::chrono::milliseconds>( now - m_lastRepaintStart ).count();
524 bool galInitialized = m_gal && m_gal->IsInitialized();
525
526 // When vsync is available the driver throttles SwapBuffers, so we only need
527 // a small guard to avoid queueing work faster than the GPU can consume it.
528 // Without vsync, cap the render rate at the monitor refresh rate so the
529 // GPU is not saturated producing frames that will never be shown.
530 int minPeriodMs = 3;
531
532 if( galInitialized && m_gal->GetSwapInterval() == 0 )
533 {
534 // wxDisplay reports 0 on headless, some virtualized, and a few driver
535 // combinations. Clamp to a plausible monitor range before trusting it
536 // and fall back to 60 Hz otherwise.
537 int refreshHz = 60;
538 int reported = wxDisplay( this ).GetCurrentMode().refresh;
539
540 if( reported >= 24 && reported <= 1000 )
541 refreshHz = reported;
542
543 refreshHz += 5; // Repaint slightly faster to avoid adding latency
544
545 minPeriodMs = 1000 / refreshHz;
546 }
547
548 if( delta >= minPeriodMs )
549 {
550 if( !DoRePaint() )
552 }
553 else if( !m_refreshTimer.IsRunning() )
554 {
555 m_refreshTimer.StartOnce( static_cast<int>( minPeriodMs - delta ) );
556 }
557}
558
559
561{
562 if( !m_drawingEnabled )
563 {
564 if( m_gal && m_gal->IsInitialized() )
565 {
566 Connect( wxEVT_PAINT, wxPaintEventHandler( EDA_DRAW_PANEL_GAL::onPaint ), nullptr, this );
567 Connect( wxEVT_IDLE, wxIdleEventHandler( EDA_DRAW_PANEL_GAL::onIdle ), nullptr, this );
568
569 m_drawingEnabled = true;
570 }
571 else
572 {
573 // Try again soon
574 m_refreshTimer.StartOnce( 100 );
575 return;
576 }
577 }
578
579 DoRePaint( false );
580}
581
582
583bool EDA_DRAW_PANEL_GAL::GetScreenshot( wxImage& aDstImage )
584{
585 if( m_backend != GAL_TYPE_OPENGL || !m_gal )
586 return false;
587
588 DoRePaint( false );
589
590 return static_cast<KIGFX::OPENGL_GAL*>( m_gal )->GetScreenshot( aDstImage );
591}
592
593
595{
596 m_eventDispatcher = aEventDispatcher;
597}
598
599
601{
602 // Start querying GAL if it is ready
603 m_refreshTimer.StartOnce( 100 );
604}
605
606
608{
609 m_refreshTimer.Stop();
610 m_drawingEnabled = false;
611
612 Disconnect( wxEVT_PAINT, wxPaintEventHandler( EDA_DRAW_PANEL_GAL::onPaint ), nullptr, this );
613 Disconnect( wxEVT_IDLE, wxIdleEventHandler( EDA_DRAW_PANEL_GAL::onIdle ), nullptr, this );
614}
615
616
618{
619 // Set display settings for high contrast mode
620 KIGFX::RENDER_SETTINGS* rSettings = m_view->GetPainter()->GetSettings();
621
622 SetTopLayer( aLayer );
623
624 rSettings->ClearHighContrastLayers();
625 rSettings->SetLayerIsHighContrast( aLayer );
626
627 m_view->UpdateAllLayersColor();
628}
629
630
632{
633 m_view->ClearTopLayers();
634 m_view->SetTopLayer( aLayer );
635 m_view->UpdateAllLayersOrder();
636}
637
638
640{
641 // Do not do anything if the currently used GAL is correct
642 if( aGalType == m_backend && m_gal != nullptr )
643 return true;
644
645 VECTOR2D grid_size = m_gal ? m_gal->GetGridSize() : VECTOR2D();
646 bool grid_visibility = m_gal ? m_gal->GetGridVisibility() : true;
647 bool result = true; // assume everything will be fine
648
649 // Prevent refreshing canvas during backend switch
650 StopDrawing();
651
652 KIGFX::GAL* new_gal = nullptr;
653
654 try
655 {
656 switch( aGalType )
657 {
658 case GAL_TYPE_OPENGL:
659 {
660 wxString errormsg = KIGFX::OPENGL_GAL::CheckFeatures( m_options );
661
662 if( errormsg.empty() )
663 {
664 new_gal = new KIGFX::OPENGL_GAL( GetVcSettings(), m_options, this, this, this );
665 }
666 else
667 {
668 if( GAL_FALLBACK != aGalType )
669 {
670 aGalType = GAL_FALLBACK;
671 DisplayInfoMessage( m_parent, _( "Could not use OpenGL, falling back to software rendering" ),
672 errormsg );
673 new_gal = new KIGFX::CAIRO_GAL( m_options, this, this, this );
674 }
675 else
676 {
677 // We're well and truly banjaxed if we get here without a fallback.
678 DisplayInfoMessage( m_parent, _( "Could not use OpenGL" ), errormsg );
679 }
680 }
681
682 break;
683 }
684
685 case GAL_TYPE_CAIRO:
686 new_gal = new KIGFX::CAIRO_GAL( m_options, this, this, this );
687 break;
688
689 default:
690 wxASSERT( false );
692 // warn about unhandled GAL canvas type, but continue with the fallback option
693
694 case GAL_TYPE_NONE:
695 // KIGFX::GAL is a stub - it actually does cannot display anything,
696 // but prevents code relying on GAL canvas existence from crashing
697 new_gal = new KIGFX::GAL( m_options );
698 break;
699 }
700 }
701 catch( std::runtime_error& err )
702 {
703 // Create a dummy GAL
704 new_gal = new KIGFX::GAL( m_options );
705 aGalType = GAL_TYPE_NONE;
706 DisplayErrorMessage( m_parent, _( "Error switching GAL backend" ), wxString( err.what() ) );
707 result = false;
708 }
709
710 // trigger update of the gal options in case they differ from the defaults
711 m_options.NotifyChanged();
712
713 // The native touchpad hook is attached to the backend's child window.
715
716 delete m_gal;
717 m_gal = new_gal;
718
719 wxSize clientSize = GetClientSize();
720 clientSize.x = std::max( 10, clientSize.x );
721 clientSize.y = std::max( 10, clientSize.y );
722 m_gal->ResizeScreen( clientSize.GetX(), clientSize.GetY() );
723
724 if( grid_size.x > 0 && grid_size.y > 0 )
725 m_gal->SetGridSize( grid_size );
726
727 m_gal->SetGridVisibility( grid_visibility );
728
729 // Make sure the cursor is set on the new canvas
731
732 if( m_painter )
733 m_painter->SetGAL( m_gal );
734
735 if( m_view )
736 {
737 m_view->SetGAL( m_gal );
738 // Note: OpenGL requires reverse draw order when draw priority is enabled
739 m_view->ReverseDrawOrder( aGalType == GAL_TYPE_OPENGL );
740 }
741
742 m_backend = aGalType;
743
744 // A shown backend window raises itself, which would bury an infobar overlaid on this canvas
745 for( wxWindow* child : GetChildren() )
746 {
747 if( dynamic_cast<WX_INFOBAR*>( child ) )
748 child->Raise();
749 }
750
752
754
755 return result;
756}
757
758
760{
762
763 if( Pgm().GetCommonSettings()->m_Input.touchpad_mode != TOUCHPAD_MODE::NATIVE_GESTURES )
764 return;
765
766 if( wxWindow* inputWindow = dynamic_cast<wxWindow*>( m_gal ) )
767 {
769 inputWindow,
770 [this]( const KIPLATFORM::UI::TOUCHPAD_GESTURE& aGesture )
771 {
772 if( !m_viewControls )
773 return;
774
775 m_viewControls->ApplyPanAndZoomGesture(
776 VECTOR2D( aGesture.panX, aGesture.panY ), aGesture.zoomFactor,
777 VECTOR2D( aGesture.zoomAnchor.x, aGesture.zoomAnchor.y ) );
778 } );
779 }
780}
781
782
783void EDA_DRAW_PANEL_GAL::OnEvent( wxEvent& aEvent )
784{
785 bool shouldSetFocus = m_lostFocus && m_stealsFocus
786 && !KIUI::IsInputControlFocused() // Don't steal from input controls
787 && !KIUI::IsModalDialogFocused() // Don't steal from dialogs
788 && KIPLATFORM::UI::IsWindowActive( m_edaFrame ); // Don't steal from other windows
789
790 if( shouldSetFocus )
791 SetFocus();
792
793 if( !m_eventDispatcher )
794 aEvent.Skip();
795 else
796 m_eventDispatcher->DispatchWxEvent( aEvent );
797
798 Refresh();
799}
800
801
802void EDA_DRAW_PANEL_GAL::onEnter( wxMouseEvent& aEvent )
803{
804 bool shouldSetFocus = m_stealsFocus
805 && !KIUI::IsInputControlFocused() // Don't steal from input controls
806 && !KIUI::IsModalDialogFocused() // Don't steal from dialogs
807 && KIPLATFORM::UI::IsWindowActive( m_edaFrame ); // Don't steal from other windows
808
809 // Getting focus is necessary in order to receive key events properly
810 if( shouldSetFocus )
811 SetFocus();
812
813 aEvent.Skip();
814}
815
816
817void EDA_DRAW_PANEL_GAL::onLostFocus( wxFocusEvent& aEvent )
818{
819 m_lostFocus = true;
820
821 m_viewControls->CancelDrag();
822
823 // Reset the tool dispatcher's button state when focus is lost. This prevents
824 // the dispatcher from thinking the button is still pressed when focus returns,
825 // which can cause selection and drag operations to stop working.
827 m_eventDispatcher->ResetState();
828
829 aEvent.Skip();
830}
831
832
833void EDA_DRAW_PANEL_GAL::onIdle( wxIdleEvent& aEvent )
834{
836 {
837 m_needIdleRefresh = false;
838 Refresh();
839 }
840
841 aEvent.Skip();
842}
843
844
845void EDA_DRAW_PANEL_GAL::onRefreshTimer( wxTimerEvent& aEvent )
846{
847 ForceRefresh();
848}
849
850
851void EDA_DRAW_PANEL_GAL::onShowEvent( wxShowEvent& aEvent )
852{
853 if( m_gal && m_gal->IsInitialized() && m_gal->IsVisible() )
854 {
855 OnShow();
856 }
857}
858
859
861{
862 if( !m_gal )
863 return;
864
865 DPI_SCALING_COMMON dpi( nullptr, m_parent );
866
867 bool hidpi = false;
868
869 // Cursor scaling factor cannot be set for a wxCursor on GTK and OSX (at least before wx 3.3),
870 // resulting in 4x rendered size on 2x window scale.
871 // MSW renders the bitmap as-is, without scaling, so this works here.
872#ifdef __WXMSW__
873 hidpi = dpi.GetContentScaleFactor() >= 2.0;
874#endif
875
876 m_gal->SetNativeCursorStyle( aCursor, hidpi );
877}
878
879
880std::shared_ptr<KIGFX::VIEW_OVERLAY> EDA_DRAW_PANEL_GAL::DebugOverlay()
881{
882 if( !m_debugOverlay )
883 {
884 m_debugOverlay.reset( new KIGFX::VIEW_OVERLAY() );
885 m_view->Add( m_debugOverlay.get() );
886 }
887
888 return m_debugOverlay;
889}
890
891
893{
894 if( m_debugOverlay )
895 {
896 m_view->Remove( m_debugOverlay.get() );
897 m_debugOverlay = nullptr;
898 }
899}
900
901
903{
905
906 KIGFX::VC_SETTINGS vcSettings;
907 vcSettings.m_warpCursor = cfg->m_Input.center_on_zoom;
909 vcSettings.m_autoPanSettingEnabled = cfg->m_Input.auto_pan;
911 vcSettings.m_horizontalPan = cfg->m_Input.horizontal_pan;
913 vcSettings.m_zoomSpeed = cfg->m_Input.zoom_speed;
914 vcSettings.m_zoomSpeedAuto = cfg->m_Input.zoom_speed_auto;
919 vcSettings.m_dragLeft = cfg->m_Input.drag_left;
920 vcSettings.m_dragMiddle = cfg->m_Input.drag_middle;
921 vcSettings.m_dragRight = cfg->m_Input.drag_right;
924
925 return vcSettings;
926}
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.
std::unique_ptr< PROF_COUNTER > m_PaintEventCounter
bool m_glRecoveryAttempted
Set after an OpenGL recovery attempt to prevent infinite retry loops.
EDA_DRAW_FRAME * m_edaFrame
Parent EDA_DRAW_FRAME (if available)
void onLostFocus(wxFocusEvent &aEvent)
static constexpr GAL_TYPE GAL_FALLBACK
std::unique_ptr< KIGFX::PAINTER > m_painter
Contains information about how to draw items using GAL.
void onSize(wxSizeEvent &aEvent)
bool m_needIdleRefresh
True when canvas needs to be refreshed from idle handler.
virtual void SetHighContrastLayer(int aLayer)
Take care of display settings for the given layer to be displayed in high contrast mode.
bool m_stealsFocus
Flag to indicate whether the panel should take focus at certain times (when moused over,...
KIGFX::GAL_DISPLAY_OPTIONS & m_options
void StopDrawing()
Prevent the GAL canvas from further drawing until it is recreated or StartDrawing() is called.
static KIGFX::VC_SETTINGS GetVcSettings()
Gets a populated View Controls settings object dervived from our program settings.
virtual void SetTopLayer(int aLayer)
Move the selected layer to the top, so it is displayed above all others.
void ClearDebugOverlay()
Clear the contents of the debug overlay and removes it from the VIEW.
virtual KIGFX::VIEW * GetView() const
Return a pointer to the #VIEW instance used in the panel.
void ForceRefresh()
Force a redraw.
bool recoverFromGalError(const std::exception &aErr)
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)
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.
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.
bool DoRePaint(bool aAllowSkip=true)
Repaint the canvas, and fix scrollbar cursors.
void OnEvent(wxEvent &aEvent)
Used to forward events to the canvas from popups, etc.
bool m_drawingEnabled
Flag that determines if VIEW may use GAL for redrawing the screen.
std::shared_ptr< KIGFX::VIEW_OVERLAY > DebugOverlay()
Create an overlay for rendering debug graphics.
void onShowEvent(wxShowEvent &aEvent)
static constexpr bool GAL_FALLBACK_AVAILABLE
GAL_TYPE m_backend
Currently used GAL.
VECTOR2D m_lastCursorPosition
Last cursor position sent to GAL for drawing.
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:70
static wxString CheckFeatures(GAL_DISPLAY_OPTIONS &aOptions)
Checks OpenGL features.
Container for all the knowledge about how graphical objects are drawn on any output surface/device.
void ClearHighContrastLayers()
Clear the list of active layers.
virtual const COLOR4D & GetGridColor()=0
Return current grid color settings.
virtual const COLOR4D & GetBackgroundColor() const =0
Return current background color settings.
void SetLayerIsHighContrast(int aLayerId, bool aEnabled=true)
Set the specified layer as high-contrast.
virtual const COLOR4D & GetCursorColor()=0
Return current cursor color settings.
const VECTOR2D & GetCenter() const
Return the center point of this VIEW (in world space coordinates).
Definition view.h:351
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:153
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
#define _(s)
static const wxChar traceDrawPanel[]
Flag to enable drawing panel debugging output.
const wxChar *const traceGalProfile
Flag to enable debug output of GAL performance profiling.
This file contains miscellaneous commonly used macros and functions.
#define KI_FALLTHROUGH
The KI_FALLTHROUGH macro is to be used when switch statement cases should purposely fallthrough from ...
Definition macros.h:79
@ 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:491
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:496
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:682
VECTOR2I ToVECTOR2I(const wxSize &aSize)
Definition vector2wx.h:26
WX_VIEW_CONTROLS class definition.