From 0a829c328e90f550994a7660b310630a5aa02361 Mon Sep 17 00:00:00 2001
From: jean-pierre charras <jp.charras@wanadoo.fr>
Date: Sat, 5 Oct 2019 10:39:12 +0200
Subject: [PATCH] Python scripting: fix a crash with some pythons scripts
 calling BOARD::ComputeBoundingBox()

This function calls Pgm(), but when running from a script (not from kicad) Pgm() uses a nullptr reference.
The nullptr reference is now tested in ComputeBoundingBox()
---
 cvpcb/cvpcb.cpp        | 8 ++++++++
 include/pgm_base.h     | 5 +++++
 pcbnew/class_board.cpp | 3 ++-
 pcbnew/pcbnew.cpp      | 8 ++++++++
 4 files changed, 23 insertions(+), 1 deletion(-)

diff --git a/cvpcb/cvpcb.cpp b/cvpcb/cvpcb.cpp
index 98d38236bd..b08ef3f120 100644
--- a/cvpcb/cvpcb.cpp
+++ b/cvpcb/cvpcb.cpp
@@ -105,6 +105,14 @@ PGM_BASE& Pgm()
 }
 
 
+// Similar to PGM_BASE& Pgm(), but return nullptr when a *.ki_face
+// is run from a python script, mot from a Kicad application
+PGM_BASE* PgmOrNull()
+{
+    return process;
+}
+
+
 //!!!!!!!!!!!!!!! This code is obsolete because of the merge into pcbnew, don't bother with it.
 
 FP_LIB_TABLE GFootprintTable;
diff --git a/include/pgm_base.h b/include/pgm_base.h
index 89109b40e2..5602df4c88 100644
--- a/include/pgm_base.h
+++ b/include/pgm_base.h
@@ -424,4 +424,9 @@ protected:
 /// Implemented in: 1) common/single_top.cpp,  2) kicad/kicad.cpp, and 3) scripting/kiway.i
 extern PGM_BASE& Pgm();
 
+/// similat to PGM_BASE& Pgm(), but return a reference that can be nullptr
+/// when running a shared lib from a script, not from a kicad appl
+extern PGM_BASE* PgmOrNull();
+
+
 #endif  // PGM_BASE_H_
diff --git a/pcbnew/class_board.cpp b/pcbnew/class_board.cpp
index f93617afad..26d4b3dc3b 100644
--- a/pcbnew/class_board.cpp
+++ b/pcbnew/class_board.cpp
@@ -761,7 +761,8 @@ EDA_RECT BOARD::ComputeBoundingBox( bool aBoardEdgesOnly ) const
 {
     EDA_RECT area;
     LSET     visible = GetVisibleLayers();
-    bool     showInvisibleText = IsElementVisible( LAYER_MOD_TEXT_INVISIBLE ) && !Pgm().m_Printing;
+    bool     showInvisibleText = IsElementVisible( LAYER_MOD_TEXT_INVISIBLE )
+                                 && PgmOrNull() && !PgmOrNull()->m_Printing;
 
     // Check segments, dimensions, texts, and fiducials
     for( auto item : m_drawings )
diff --git a/pcbnew/pcbnew.cpp b/pcbnew/pcbnew.cpp
index ae85589a0e..103157bfbb 100644
--- a/pcbnew/pcbnew.cpp
+++ b/pcbnew/pcbnew.cpp
@@ -192,6 +192,14 @@ PGM_BASE& Pgm()
     wxASSERT( process );    // KIFACE_GETTER has already been called.
     return *process;
 }
+
+// Similar to PGM_BASE& Pgm(), but return nullptr when a *.ki_face
+// is run from a python script, mot from a Kicad application
+PGM_BASE* PgmOrNull()
+{
+    return process;
+}
+
 #endif