From d59ed4dce0c4babdfad3dd09789c4d97c6fbec4d Mon Sep 17 00:00:00 2001
From: Scott Lahteine <thinkyhead@users.noreply.github.com>
Date: Sun, 15 Apr 2018 18:26:25 -0500
Subject: [PATCH] Abort SD printing more safely (#10405)

Allow the current command to complete when aborting an SD print, otherwise some commands (G28, G29, etc.) will cause trouble.
---
 Marlin/Marlin_main.cpp | 27 +++++++++++++++++++++++++--
 Marlin/ultralcd.cpp    | 16 +++-------------
 Marlin/ultralcd.h      |  6 ++++++
 3 files changed, 34 insertions(+), 15 deletions(-)

diff --git a/Marlin/Marlin_main.cpp b/Marlin/Marlin_main.cpp
index 30044d73b70..7981b262092 100644
--- a/Marlin/Marlin_main.cpp
+++ b/Marlin/Marlin_main.cpp
@@ -14220,6 +14220,7 @@ void setup() {
 /**
  * The main Marlin program loop
  *
+ *  - Abort SD printing if flagged
  *  - Save or log commands to SD
  *  - Process available commands (if not saving)
  *  - Call heater manager
@@ -14228,11 +14229,33 @@ void setup() {
  *  - Call LCD update
  */
 void loop() {
-  if (commands_in_queue < BUFSIZE) get_available_commands();
 
   #if ENABLED(SDSUPPORT)
+
     card.checkautostart(false);
-  #endif
+
+    #if ENABLED(ULTIPANEL)
+      if (abort_sd_printing) {
+        abort_sd_printing = false;
+        card.stopSDPrint(
+          #if SD_RESORT
+            true
+          #endif
+        );
+        clear_command_queue();
+        quickstop_stepper();
+        print_job_timer.stop();
+        thermalManager.disable_all_heaters();
+        #if FAN_COUNT > 0
+          for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
+        #endif
+        wait_for_heatup = false;
+      }
+    #endif
+
+  #endif // SDSUPPORT
+
+  if (commands_in_queue < BUFSIZE) get_available_commands();
 
   if (commands_in_queue) {
 
diff --git a/Marlin/ultralcd.cpp b/Marlin/ultralcd.cpp
index 743ace30ce1..b0b833d0c7c 100644
--- a/Marlin/ultralcd.cpp
+++ b/Marlin/ultralcd.cpp
@@ -829,20 +829,10 @@ void kill_screen(const char* lcd_msg) {
       lcd_reset_status();
     }
 
+    bool abort_sd_printing; // =false
+
     void lcd_sdcard_stop() {
-      card.stopSDPrint(
-        #if SD_RESORT
-          true
-        #endif
-      );
-      clear_command_queue();
-      quickstop_stepper();
-      print_job_timer.stop();
-      thermalManager.disable_all_heaters();
-      #if FAN_COUNT > 0
-        for (uint8_t i = 0; i < FAN_COUNT; i++) fanSpeeds[i] = 0;
-      #endif
-      wait_for_heatup = false;
+      abort_sd_printing = true;
       lcd_setstatusPGM(PSTR(MSG_PRINT_ABORTED), -1);
       lcd_return_to_status();
     }
diff --git a/Marlin/ultralcd.h b/Marlin/ultralcd.h
index b93b7198d39..f9dadc3056e 100644
--- a/Marlin/ultralcd.h
+++ b/Marlin/ultralcd.h
@@ -254,4 +254,10 @@ void lcd_reset_status();
   void lcd_reselect_last_file();
 #endif
 
+#if ENABLED(ULTIPANEL) && ENABLED(SDSUPPORT)
+  extern bool abort_sd_printing;
+#else
+  constexpr bool abort_sd_printing = false;
+#endif
+
 #endif // ULTRALCD_H