From 9b849b1e0f583ff2f7671df06b8b896e043353f6 Mon Sep 17 00:00:00 2001
From: Lukas Holecek <hluk@email.cz>
Date: Sun, 28 Mar 2021 11:43:56 +0200
Subject: [PATCH] Avoid running menu filter commands in parallel

---
 src/scriptable/scriptable.cpp | 41 +++++++++++++++++++++++------------
 1 file changed, 27 insertions(+), 14 deletions(-)

diff --git a/src/scriptable/scriptable.cpp b/src/scriptable/scriptable.cpp
index 149c618cc..e07325e0a 100644
--- a/src/scriptable/scriptable.cpp
+++ b/src/scriptable/scriptable.cpp
@@ -2624,27 +2624,40 @@ void Scriptable::runMenuCommandFilters()
 
     const QString menuItemProperty = QLatin1String("menuItem");
     const QString enabledProperty = QLatin1String("enabled");
+    bool running = false;
+    bool restart = false;
     connect(&timer, &QTimer::timeout, &loop, [&]() {
         if ( bytes.isEmpty() )
             return;
 
-        const int currentRun = bytes.toInt();
+        if (running) {
+            restart = true;
+            return;
+        }
+        running = true;
 
-        getActionData(actionId);
-        const QStringList matchCommands =
-            m_data.value(COPYQ_MIME_PREFIX "match-commands").toStringList();
+        do {
+            restart = false;
+            const int currentRun = bytes.toInt();
 
-        PerformanceLogger logger( QLatin1String("Menu item filters") );
+            getActionData(actionId);
+            const QStringList matchCommands =
+                m_data.value(COPYQ_MIME_PREFIX "match-commands").toStringList();
 
-        for (int i = 0; i < matchCommands.length(); ++i) {
-            const auto obj = m_engine->newObject();
-            m_engine->globalObject().setProperty(menuItemProperty, obj);
-            const bool enabled = canExecuteCommandFilter(matchCommands[i]);
-            QVariantMap menuItem = toDataMap(obj);
-            menuItem[enabledProperty] = enabled && menuItem.value(enabledProperty, true).toBool();
-            if ( !m_proxy->enableMenuItem(actionId, currentRun, i, menuItem) )
-                break;
-        }
+            PerformanceLogger logger( QLatin1String("Menu item filters") );
+
+            for (int i = 0; i < matchCommands.length(); ++i) {
+                const auto obj = m_engine->newObject();
+                m_engine->globalObject().setProperty(menuItemProperty, obj);
+                const bool enabled = canExecuteCommandFilter(matchCommands[i]);
+                QVariantMap menuItem = toDataMap(obj);
+                menuItem[enabledProperty] = enabled && menuItem.value(enabledProperty, true).toBool();
+                if ( restart || !m_proxy->enableMenuItem(actionId, currentRun, i, menuItem) )
+                    break;
+            }
+        } while (restart);
+
+        running = false;
     });
 
     emit receiveData();
-- 
GitLab