Subject: Re: bug#52761: 29.0.50; (--with-pgtk) poor point movement performance when global-flycheck-mode is called during start-up

From: Yuuki Harano <[email-masked]>
Date: Thu, 06 Jan 2022 23:56:17 +0900 (JST)

On Thu, 23 Dec 2021 19:51:09 +0000,
	Simon Pugnet <[email-masked]> wrote:
> I've noticed a strange performance issue with Emacs when built
> --with-pgtk, but only when global-flycheck-mode is called during Emacs
> start-up.

Please try the attached patch.

-- 
Yuuki Harano
diff --git a/src/xgselect.c b/src/xgselect.c
index 674c259db7..14a8c73541 100644
--- a/src/xgselect.c
+++ b/src/xgselect.c
@@ -96,10 +96,21 @@ xg_select (int fds_lim, fd_set *rfds, fd_set *wfds, fd_set *efds,
   int n_gfds, retval = 0, our_fds = 0, max_fds = fds_lim - 1;
   int i, nfds, tmo_in_millisec, must_free = 0;
   bool need_to_dispatch;
+#ifdef HAVE_PGTK
+  bool already_has_events = false;
+#endif
 
   context = g_main_context_default ();
   acquire_select_lock (context);
 
+#ifdef HAVE_PGTK
+  {
+    int errno_back = errno;
+    already_has_events = g_main_context_pending (context);
+    errno = errno_back;
+  }
+#endif
+
   if (rfds) all_rfds = *rfds;
   else FD_ZERO (&all_rfds);
   if (wfds) all_wfds = *wfds;
@@ -146,10 +157,41 @@ xg_select (int fds_lim, fd_set *rfds, fd_set *wfds, fd_set *efds,
 	tmop = &tmo;
     }
 
+#ifndef HAVE_PGTK
   fds_lim = max_fds + 1;
   nfds = thread_select (pselect, fds_lim,
 			&all_rfds, have_wfds ? &all_wfds : NULL, efds,
 			tmop, sigmask);
+#else
+  /*
+    On PGTK, when you type a key, the key press event are received,
+    and one more key press event seems to be received internally.
+    The second event is not via a socket, so there are weird status:
+      - socket read buffer is empty
+      - a key press event is pending
+    In that case, we should not sleep, and dispatch the event immediately.
+    Bug#52761
+   */
+  if (!already_has_events)
+    {
+      fds_lim = max_fds + 1;
+      nfds = thread_select (pselect, fds_lim,
+			    &all_rfds, have_wfds ? &all_wfds : NULL, efds,
+			    tmop, sigmask);
+    }
+  else
+    {
+      /* Emulate return values */
+      nfds = 1;
+      FD_ZERO(&all_rfds);
+      if (have_wfds)
+	FD_ZERO(&all_wfds);
+      if (efds)
+	FD_ZERO(efds);
+      our_fds++;
+    }
+#endif
+
   if (nfds < 0)
     retval = nfds;
   else if (nfds > 0)