From 6dea82a668540a16096fffb513eebc7ad98e7500 Mon Sep 17 00:00:00 2001
From: yellows8 <yellows8@users.noreply.github.com>
Date: Wed, 27 Feb 2019 19:03:35 -0500
Subject: [PATCH] Moved applet notification-msg handling code into new funcs
 appletGetMessage and appletProcessMessage (with some improvements), which
 appletMainLoop now calls.

---
 nx/include/switch/services/applet.h | 13 +++++++++++
 nx/source/services/applet.c         | 36 ++++++++++++++++++++---------
 2 files changed, 38 insertions(+), 11 deletions(-)

diff --git a/nx/include/switch/services/applet.h b/nx/include/switch/services/applet.h
index 4746691f..dac8bce0 100644
--- a/nx/include/switch/services/applet.h
+++ b/nx/include/switch/services/applet.h
@@ -459,8 +459,21 @@ Result appletStorageGetHandle(AppletStorage *s, s64 *out, Handle *handle);
  */
 Result appletStorageMap(AppletStorage *s, void** addr, size_t *size);
 
+/**
+ * @brief Gets a notification message.
+ */
+Result appletGetMessage(u32 *msg);
+
+/**
+ * @brief Processes the current applet status using the specified msg.
+ * @param msg Notification message, normally from \ref appletGetMessage.
+ * @return Whether the application should continue running.
+ */
+bool appletProcessMessage(u32 msg);
+
 /**
  * @brief Processes the current applet status. Generally used within a main loop.
+ * @note Uses \ref appletGetMessage and \ref appletProcessMessage internally.
  * @return Whether the application should continue running.
  */
 bool appletMainLoop(void);
diff --git a/nx/source/services/applet.c b/nx/source/services/applet.c
index 90d7718c..2166ec7b 100644
--- a/nx/source/services/applet.c
+++ b/nx/source/services/applet.c
@@ -2292,23 +2292,29 @@ AppletFocusState appletGetFocusState(void) {
     return (AppletFocusState)g_appletFocusState;
 }
 
-bool appletMainLoop(void) {
-    Result rc;
-    u32    msg = 0;
-
-    if (R_FAILED(eventWait(&g_appletMessageEvent, 0)))
-        return true;
-
-    rc = _appletReceiveMessage(&msg);
+Result appletGetMessage(u32 *msg) {
+    Result rc=0;
+    if (msg==NULL) return MAKERESULT(Module_Libnx, LibnxError_BadInput);
 
+    rc = eventWait(&g_appletMessageEvent, 0);
     if (R_FAILED(rc))
-    {
-        if ((rc & 0x3fffff) == 0x680)
-            return true;
+        return rc;
+
+    rc = _appletReceiveMessage(msg);
+
+    if (R_FAILED(rc)) {
+        if (R_VALUE(rc) == MAKERESULT(128, 3))
+            return rc;
 
         fatalSimple(MAKERESULT(Module_Libnx, LibnxError_BadAppletReceiveMessage));
     }
 
+    return 0;
+}
+
+bool appletProcessMessage(u32 msg) {
+    Result rc;
+
     switch(msg) {
         case 0x4:
             appletCallHook(AppletHookType_OnExitRequest);
@@ -2342,3 +2348,11 @@ bool appletMainLoop(void) {
 
     return true;
 }
+
+bool appletMainLoop(void) {
+    u32 msg = 0;
+
+    if (R_FAILED(appletGetMessage(&msg))) return true;
+
+    return appletProcessMessage(msg);
+}