Lay off the ground of our very efficient event loop.
[apps/madmutt.git] / lib-sys / evtloop.c
diff --git a/lib-sys/evtloop.c b/lib-sys/evtloop.c
new file mode 100644 (file)
index 0000000..1b5d723
--- /dev/null
@@ -0,0 +1,91 @@
+/*
+ *  This program is free software; you can redistribute it and/or modify
+ *  it under the terms of the GNU General Public License as published by
+ *  the Free Software Foundation; either version 2 of the License, or (at
+ *  your option) any later version.
+ *
+ *  This program is distributed in the hope that it will be useful, but
+ *  WITHOUT ANY WARRANTY; without even the implied warranty of
+ *  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
+ *  General Public License for more details.
+ *
+ *  You should have received a copy of the GNU General Public License
+ *  along with this program; if not, write to the Free Software
+ *  Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston,
+ *  MA 02110-1301, USA.
+ *
+ *  Copyright © 2006 Pierre Habouzit
+ */
+
+#include <sys/epoll.h>
+#include <sys/socket.h>
+#ifndef EPOLLRDHUP
+#  include <linux/poll.h>
+#  ifdef POLLRDHUP
+#    define EPOLLRDHUP POLLRDHUP
+#  else
+#    define EPOLLRDHUP 0
+#  endif
+#endif
+#include "evtloop.h"
+#include "mutt.h"
+
+static int epollfd = -1;
+
+int el_job_release(job_t *w, el_status reason)
+{
+    w->state = EL_LLP_FINI;
+    if (w->m && w->m->finalize) {
+        w->m->finalize(w, reason);
+    }
+    if (w->fd >= 0) {
+        close(w->fd);
+    }
+    p_delete(&w);
+    return -1;
+}
+
+int el_dispatch(int timeout)
+{
+    struct epoll_event events[FD_SETSIZE];
+    int count = epoll_wait(epollfd, events, countof(events), timeout);
+
+    if (count < 0) {
+        if (errno == EAGAIN || errno == EINTR)
+            return 0;
+        mutt_error("epoll_wait");
+        mutt_exit(EXIT_FAILURE);
+    }
+
+    while (--count >= 0) {
+        job_t *w  = events[count].data.ptr;
+        int event = events[count].events;
+        int evt   = 0;
+
+        switch (w->state) {
+          case EL_LLP_INIT:
+            w->llp(w);
+            break;
+
+          case EL_LLP_READY:
+            if (event & EPOLLRDHUP) {
+                IGNORE(el_job_release(w, EL_RDHUP));
+            } else if (w->mode != w->emode) {
+                    w->m->on_event(w, EL_EVT_INOUT ^ w->emode);
+            } else {
+                if (event & EPOLLIN)
+                    evt |= EL_EVT_IN;
+                if (event & EPOLLOUT)
+                    evt |= EL_EVT_OUT;
+                w->m->on_event(w, evt);
+            }
+            break;
+
+          default:
+            IGNORE(el_job_release(w, EL_ERROR));
+            break;
+        }
+    }
+
+    return 0;
+}