Tizen 2.1 base
[framework/uifw/ecore.git] / src / lib / ecore / ecore_main.c
1 #ifdef HAVE_CONFIG_H
2 # include <config.h>
3 #endif
4
5 #ifdef _WIN32
6 # define WIN32_LEAN_AND_MEAN
7 # include <winsock2.h>
8 # undef WIN32_LEAN_AND_MEAN
9 # ifndef USER_TIMER_MINIMUM
10 #  define USER_TIMER_MINIMUM 0x0a
11 # endif
12 #endif
13
14 #ifdef __SUNPRO_C
15 # include <ieeefp.h>
16 # include <string.h>
17 #endif
18
19 #include <stdlib.h>
20 #include <stdio.h>
21 #include <math.h>
22 #include <sys/types.h>
23 #include <errno.h>
24 #include <fcntl.h>
25
26 #ifndef _MSC_VER
27 # include <sys/time.h>
28 # include <unistd.h>
29 #else
30 # include <float.h>
31 #endif
32
33 #ifdef HAVE_ISFINITE
34 # define ECORE_FINITE(t)  isfinite(t)
35 #else
36 # ifdef _MSC_VER
37 #  define ECORE_FINITE(t) _finite(t)
38 # else
39 #  define ECORE_FINITE(t) finite(t)
40 # endif
41 #endif
42
43 //#define FIX_HZ 1
44
45 #ifdef FIX_HZ
46 # ifndef _MSC_VER
47 #  include <sys/param.h>
48 # endif
49 # ifndef HZ
50 #  define HZ 100
51 # endif
52 #endif
53
54 #ifdef HAVE_EVIL
55 # include <Evil.h>
56 #endif
57
58 #include "Ecore.h"
59 #include "ecore_private.h"
60
61 #ifdef HAVE_SYS_EPOLL_H
62 # define HAVE_EPOLL   1
63 # include <sys/epoll.h>
64 #else
65
66 # define HAVE_EPOLL   0
67 # define EPOLLIN      1
68 # define EPOLLPRI     2
69 # define EPOLLOUT     4
70 # define EPOLLERR     8
71
72 #define EPOLL_CTL_ADD 1
73 #define EPOLL_CTL_DEL 2
74 #define EPOLL_CTL_MOD 3
75
76 typedef union epoll_data {
77    void    *ptr;
78    int      fd;
79    uint32_t u32;
80    uint64_t u64;
81 } epoll_data_t;
82
83 struct epoll_event
84 {
85    uint32_t     events;
86    epoll_data_t data;
87 };
88
89 static inline int
90 epoll_create(int size __UNUSED__)
91 {
92    return -1;
93 }
94
95 static inline int
96 epoll_wait(int                 epfd __UNUSED__,
97            struct epoll_event *events __UNUSED__,
98            int                 maxevents __UNUSED__,
99            int                 timeout __UNUSED__)
100 {
101    return -1;
102 }
103
104 static inline int
105 epoll_ctl(int                 epfd __UNUSED__,
106           int                 op __UNUSED__,
107           int                 fd __UNUSED__,
108           struct epoll_event *event __UNUSED__)
109 {
110    return -1;
111 }
112
113 #endif
114
115 #ifdef HAVE_SYS_TIMERFD_H
116 #include <sys/timerfd.h>
117 #else
118 /* fallback code if we don't have real timerfd - reduces number of ifdefs  */
119 #ifndef CLOCK_MONOTONIC
120 #define CLOCK_MONOTONIC 0 /* bogus value */
121 #endif
122 #ifndef TFD_NONBLOCK
123 #define TFD_NONBLOCK    0 /* bogus value */
124 #endif
125 static inline int
126 timerfd_create(int clockid __UNUSED__,
127                int flags __UNUSED__)
128 {
129    return -1;
130 }
131
132 static inline int
133 timerfd_settime(int                      fd __UNUSED__,
134                 int                      flags __UNUSED__,
135                 const struct itimerspec *new_value __UNUSED__,
136                 struct itimerspec       *old_value __UNUSED__)
137 {
138    return -1;
139 }
140
141 #endif /* HAVE_SYS_TIMERFD_H */
142
143 #ifdef USE_G_MAIN_LOOP
144 # include <glib.h>
145 #endif
146
147 #define NS_PER_SEC (1000.0 * 1000.0 * 1000.0)
148
149 struct _Ecore_Fd_Handler
150 {
151    EINA_INLIST;
152                           ECORE_MAGIC;
153    Ecore_Fd_Handler      *next_ready;
154    int                    fd;
155    Ecore_Fd_Handler_Flags flags;
156    Ecore_Fd_Cb            func;
157    void                  *data;
158    Ecore_Fd_Cb            buf_func;
159    void                  *buf_data;
160    Ecore_Fd_Prep_Cb       prep_func;
161    void                  *prep_data;
162    int                    references;
163    Eina_Bool              read_active : 1;
164    Eina_Bool              write_active : 1;
165    Eina_Bool              error_active : 1;
166    Eina_Bool              delete_me : 1;
167    Eina_Bool              file : 1;
168 #if defined(USE_G_MAIN_LOOP)
169    GPollFD                gfd;
170 #endif
171 };
172 GENERIC_ALLOC_SIZE_DECLARE(Ecore_Fd_Handler);
173
174 #ifdef _WIN32
175 struct _Ecore_Win32_Handler
176 {
177    EINA_INLIST;
178                          ECORE_MAGIC;
179    HANDLE                h;
180    Ecore_Win32_Handle_Cb func;
181    void                 *data;
182    int                   references;
183    Eina_Bool             delete_me : 1;
184 };
185 GENERIC_ALLOC_SIZE_DECLARE(Ecore_Win32_Handler);
186 #endif
187
188 #ifndef USE_G_MAIN_LOOP
189 static int  _ecore_main_select(double timeout);
190 #endif
191 static void _ecore_main_prepare_handlers(void);
192 static void _ecore_main_fd_handlers_cleanup(void);
193 #ifndef _WIN32
194 # ifndef USE_G_MAIN_LOOP
195 static void _ecore_main_fd_handlers_bads_rem(void);
196 # endif
197 #endif
198 static void _ecore_main_fd_handlers_call(void);
199 static int  _ecore_main_fd_handlers_buf_call(void);
200 #ifndef USE_G_MAIN_LOOP
201 static void _ecore_main_loop_iterate_internal(int once_only);
202 #endif
203
204 #ifdef _WIN32
205 static int _ecore_main_win32_select(int             nfds,
206                                     fd_set         *readfds,
207                                     fd_set         *writefds,
208                                     fd_set         *exceptfds,
209                                     struct timeval *timeout);
210 static void _ecore_main_win32_handlers_cleanup(void);
211 #endif
212
213 static int in_main_loop = 0;
214 static int do_quit = 0;
215 static Ecore_Fd_Handler *fd_handlers = NULL;
216 static Ecore_Fd_Handler *fd_handler_current = NULL;
217 static Eina_List *fd_handlers_with_prep = NULL;
218 static Eina_List *file_fd_handlers = NULL;
219 static Eina_List *fd_handlers_with_buffer = NULL;
220 static Eina_List *fd_handlers_to_delete = NULL;
221
222 /* single linked list of ready fdhs, terminated by loop to self */
223 static Ecore_Fd_Handler *fd_handlers_to_call;
224 static Ecore_Fd_Handler *fd_handlers_to_call_current;
225
226 #ifdef _WIN32
227 static Ecore_Win32_Handler *win32_handlers = NULL;
228 static Ecore_Win32_Handler *win32_handler_current = NULL;
229 static Eina_Bool win32_handlers_delete_me = EINA_FALSE;
230 #endif
231
232 #ifdef _WIN32
233 Ecore_Select_Function main_loop_select = _ecore_main_win32_select;
234 #else
235 # if !defined EXOTIC_NO_SELECT
236 #  ifdef HAVE_SYS_SELECT_H
237 #   include <sys/select.h>
238 #  endif
239 Ecore_Select_Function main_loop_select = select;
240 # else
241 Ecore_Select_Function main_loop_select = NULL;
242 # endif
243 #endif
244
245 #ifndef USE_G_MAIN_LOOP
246 static double t1 = 0.0;
247 static double t2 = 0.0;
248 #endif
249
250 static int timer_fd = -1;
251 static int epoll_fd = -1;
252 static pid_t epoll_pid;
253
254 #ifdef USE_G_MAIN_LOOP
255 static GPollFD ecore_epoll_fd;
256 static GPollFD ecore_timer_fd;
257 static GSource *ecore_glib_source;
258 static guint ecore_glib_source_id;
259 static GMainLoop *ecore_main_loop;
260 static gboolean ecore_idling;
261 static gboolean _ecore_glib_idle_enterer_called;
262 static gboolean ecore_fds_ready;
263 #endif
264
265 Eina_Bool
266 _ecore_fd_close_on_exec(int fd)
267 {
268 #ifdef HAVE_EXECVP
269    int flags;
270
271    flags = fcntl(fd, F_GETFD);
272    if (flags == -1)
273      return EINA_FALSE;
274
275    flags |= FD_CLOEXEC;
276    if (fcntl(fd, F_SETFD, flags) == -1)
277      return EINA_FALSE;
278    return EINA_TRUE;
279 #else
280    (void) fd;
281    return EINA_FALSE;
282 #endif
283 }
284
285 static inline void
286 _ecore_fd_valid(void)
287 {
288    if (HAVE_EPOLL && epoll_fd >= 0)
289      {
290         if (fcntl(epoll_fd, F_GETFD) < 0)
291           {
292              ERR("arghhh you caught me! report a backtrace to edevel!");
293              pause();
294           }
295      }
296 }
297
298 static inline void
299 _ecore_try_add_to_call_list(Ecore_Fd_Handler *fdh)
300 {
301    /* check if this fdh is already in the list */
302    if (fdh->next_ready)
303      return;
304    if (fdh->read_active || fdh->write_active || fdh->error_active)
305      {
306         /*
307          * make sure next_ready is non-null by pointing to ourselves
308          * use that to indicate this fdh is in the ready list
309          * insert at the head of the list to avoid trouble
310          */
311         fdh->next_ready = fd_handlers_to_call ? fd_handlers_to_call : fdh;
312         fd_handlers_to_call = fdh;
313      }
314 }
315
316 static inline int
317 _ecore_get_epoll_fd(void)
318 {
319    if (epoll_pid && epoll_pid != getpid())
320      {
321         /* forked! */
322         _ecore_main_loop_shutdown();
323      }
324    if (epoll_pid == 0 && epoll_fd < 0)
325      {
326         _ecore_main_loop_init();
327      }
328    return epoll_fd;
329 }
330
331 static inline int
332 _ecore_epoll_add(int   efd,
333                  int   fd,
334                  int   events,
335                  void *ptr)
336 {
337    struct epoll_event ev;
338
339    memset(&ev, 0, sizeof (ev));
340    ev.events = events;
341    ev.data.ptr = ptr;
342    INF("adding poll on %d %08x", fd, events);
343    return epoll_ctl(efd, EPOLL_CTL_ADD, fd, &ev);
344 }
345
346 static inline int
347 _ecore_poll_events_from_fdh(Ecore_Fd_Handler *fdh)
348 {
349    int events = 0;
350    if (fdh->flags & ECORE_FD_READ) events |= EPOLLIN;
351    if (fdh->flags & ECORE_FD_WRITE) events |= EPOLLOUT;
352    if (fdh->flags & ECORE_FD_ERROR) events |= EPOLLERR | EPOLLPRI;
353    return events;
354 }
355
356 #ifdef USE_G_MAIN_LOOP
357 static inline int
358 _gfd_events_from_fdh(Ecore_Fd_Handler *fdh)
359 {
360    int events = 0;
361    if (fdh->flags & ECORE_FD_READ) events |= G_IO_IN;
362    if (fdh->flags & ECORE_FD_WRITE) events |= G_IO_OUT;
363    if (fdh->flags & ECORE_FD_ERROR) events |= G_IO_ERR;
364    return events;
365 }
366
367 #endif
368
369 static inline int
370 _ecore_main_fdh_poll_add(Ecore_Fd_Handler *fdh)
371 {
372    int r = 0;
373
374    if ((!fdh->file) && HAVE_EPOLL && epoll_fd >= 0)
375      {
376         r = _ecore_epoll_add(_ecore_get_epoll_fd(), fdh->fd,
377                              _ecore_poll_events_from_fdh(fdh), fdh);
378      }
379    else
380      {
381 #ifdef USE_G_MAIN_LOOP
382         fdh->gfd.fd = fdh->fd;
383         fdh->gfd.events = _gfd_events_from_fdh(fdh);
384         fdh->gfd.revents = 0;
385         INF("adding gpoll on %d %08x", fdh->fd, fdh->gfd.events);
386         g_source_add_poll(ecore_glib_source, &fdh->gfd);
387 #endif
388      }
389    return r;
390 }
391
392 static inline void
393 _ecore_main_fdh_poll_del(Ecore_Fd_Handler *fdh)
394 {
395    if ((!fdh->file) && HAVE_EPOLL && epoll_fd >= 0)
396      {
397         struct epoll_event ev;
398         int efd = _ecore_get_epoll_fd();
399
400         memset(&ev, 0, sizeof (ev));
401         INF("removing poll on %d", fdh->fd);
402         /* could get an EBADF if somebody closed the FD before removing it */
403         if ((epoll_ctl(efd, EPOLL_CTL_DEL, fdh->fd, &ev) < 0))
404           {
405              if (errno == EBADF)
406                {
407                   WRN("fd %d was closed, can't remove from epoll - reinit!",
408                       fdh->fd);
409                   _ecore_main_loop_shutdown();
410                   _ecore_main_loop_init();
411                }
412              else
413                {
414                   ERR("Failed to delete epoll fd %d! (errno=%d)", fdh->fd, errno);
415                }
416           }
417      }
418    else
419      {
420 #ifdef USE_G_MAIN_LOOP
421         fdh->gfd.fd = fdh->fd;
422         fdh->gfd.events = _gfd_events_from_fdh(fdh);
423         fdh->gfd.revents = 0;
424         INF("adding gpoll on %d %08x", fdh->fd, fdh->gfd.events);
425         g_source_add_poll(ecore_glib_source, &fdh->gfd);
426 #endif
427      }
428 }
429
430 static inline int
431 _ecore_main_fdh_poll_modify(Ecore_Fd_Handler *fdh)
432 {
433    int r = 0;
434    if ((!fdh->file) && HAVE_EPOLL && epoll_fd >= 0)
435      {
436         struct epoll_event ev;
437         int efd = _ecore_get_epoll_fd();
438
439         memset(&ev, 0, sizeof (ev));
440         ev.events = _ecore_poll_events_from_fdh(fdh);
441         ev.data.ptr = fdh;
442         INF("modifing epoll on %d to %08x", fdh->fd, ev.events);
443         r = epoll_ctl(efd, EPOLL_CTL_MOD, fdh->fd, &ev);
444      }
445    else
446      {
447 #ifdef USE_G_MAIN_LOOP
448         fdh->gfd.fd = fdh->fd;
449         fdh->gfd.events = _gfd_events_from_fdh(fdh);
450         fdh->gfd.revents = 0;
451         INF("modifing gpoll on %d to %08x", fdh->fd, fdh->gfd.events);
452 #endif
453      }
454    return r;
455 }
456
457 static inline int
458 _ecore_main_fdh_epoll_mark_active(void)
459 {
460    struct epoll_event ev[32];
461    int i, ret;
462    int efd = _ecore_get_epoll_fd();
463
464    memset(&ev, 0, sizeof (ev));
465    ret = epoll_wait(efd, ev, sizeof(ev) / sizeof(struct epoll_event), 0);
466    if (ret < 0)
467      {
468         if (errno == EINTR) return -1;
469         ERR("epoll_wait failed %d", errno);
470         return -1;
471      }
472
473    for (i = 0; i < ret; i++)
474      {
475         Ecore_Fd_Handler *fdh;
476
477         fdh = ev[i].data.ptr;
478         if (!ECORE_MAGIC_CHECK(fdh, ECORE_MAGIC_FD_HANDLER))
479           {
480              ECORE_MAGIC_FAIL(fdh, ECORE_MAGIC_FD_HANDLER,
481                               "_ecore_main_fdh_epoll_mark_active");
482              continue;
483           }
484         if (fdh->delete_me)
485           {
486              ERR("deleted fd in epoll");
487              continue;
488           }
489
490         if (ev[i].events & EPOLLIN)
491           fdh->read_active = EINA_TRUE;
492         if (ev[i].events & EPOLLOUT)
493           fdh->write_active = EINA_TRUE;
494         if (ev[i].events & EPOLLERR)
495           fdh->error_active = EINA_TRUE;
496
497         _ecore_try_add_to_call_list(fdh);
498      }
499
500    return ret;
501 }
502
503 #ifdef USE_G_MAIN_LOOP
504
505 static inline int
506 _ecore_main_fdh_glib_mark_active(void)
507 {
508    Ecore_Fd_Handler *fdh;
509    int ret = 0;
510
511    /* call the prepare callback for all handlers */
512    EINA_INLIST_FOREACH(fd_handlers, fdh)
513      {
514         if (fdh->delete_me)
515           continue;
516
517         if (fdh->gfd.revents & G_IO_IN)
518           fdh->read_active = EINA_TRUE;
519         if (fdh->gfd.revents & G_IO_OUT)
520           fdh->write_active = EINA_TRUE;
521         if (fdh->gfd.revents & G_IO_ERR)
522           fdh->error_active = EINA_TRUE;
523
524         _ecore_try_add_to_call_list(fdh);
525
526         if (fdh->gfd.revents & (G_IO_IN | G_IO_OUT | G_IO_ERR)) ret++;
527      }
528
529    return ret;
530 }
531
532 /* like we are about to enter main_loop_select in  _ecore_main_select */
533 static gboolean
534 _ecore_main_gsource_prepare(GSource *source __UNUSED__,
535                             gint    *next_time)
536 {
537    gboolean ready = FALSE;
538
539    _ecore_lock();
540    in_main_loop++;
541
542    if (!ecore_idling && !_ecore_glib_idle_enterer_called)
543      {
544         _ecore_time_loop_time = ecore_time_get();
545         _ecore_timer_expired_timers_call(_ecore_time_loop_time);
546         _ecore_timer_cleanup();
547
548         _ecore_idle_enterer_call();
549         _ecore_throttle();
550         _ecore_glib_idle_enterer_called = FALSE;
551
552         if (fd_handlers_with_buffer)
553           _ecore_main_fd_handlers_buf_call();
554      }
555
556    _ecore_signal_received_process();
557
558    /* don't check fds if somebody quit */
559    if (g_main_loop_is_running(ecore_main_loop))
560      {
561         /* only set idling state in dispatch */
562          if (ecore_idling && !_ecore_idler_exist() && !_ecore_event_exist())
563            {
564               if (_ecore_timers_exists())
565                 {
566                    int r = -1;
567                    double t = _ecore_timer_next_get();
568                    if (timer_fd >= 0 && t > 0.0)
569                      {
570                         struct itimerspec ts;
571
572                         ts.it_interval.tv_sec = 0;
573                         ts.it_interval.tv_nsec = 0;
574                         ts.it_value.tv_sec = t;
575                         ts.it_value.tv_nsec = fmod(t * NS_PER_SEC, NS_PER_SEC);
576
577      /* timerfd cannot sleep for 0 time */
578                         if (ts.it_value.tv_sec || ts.it_value.tv_nsec)
579                           {
580                              r = timerfd_settime(timer_fd, 0, &ts, NULL);
581                              if (r < 0)
582                                {
583                                   ERR("timer set returned %d (errno=%d)", r, errno);
584                                   close(timer_fd);
585                                   timer_fd = -1;
586                                }
587                              else
588                                INF("sleeping for %ld s %06ldus",
589                                    ts.it_value.tv_sec,
590                                    ts.it_value.tv_nsec / 1000);
591                           }
592                      }
593                    if (r == -1)
594                      {
595                         *next_time = ceil(t * 1000.0);
596                         if (t == 0.0)
597                           ready = TRUE;
598                      }
599                 }
600               else
601                 *next_time = -1;
602            }
603          else
604            {
605               *next_time = 0;
606               if (_ecore_event_exist())
607                 ready = TRUE;
608            }
609
610          if (fd_handlers_with_prep)
611            _ecore_main_prepare_handlers();
612      }
613    else
614      ready = TRUE;
615
616    in_main_loop--;
617    INF("leave, timeout = %d", *next_time);
618    _ecore_unlock();
619
620    /* ready if we're not running (about to quit) */
621    return ready;
622 }
623
624 static gboolean
625 _ecore_main_gsource_check(GSource *source __UNUSED__)
626 {
627    gboolean ret = FALSE;
628
629    _ecore_lock();
630    in_main_loop++;
631
632    /* check if old timers expired */
633    if (ecore_idling && !_ecore_idler_exist() && !_ecore_event_exist())
634      {
635         if (timer_fd >= 0)
636           {
637              uint64_t count = 0;
638              int r = read(timer_fd, &count, sizeof count);
639              if (r == -1 && errno == EAGAIN)
640                ;
641              else if (r == sizeof count)
642                ret = TRUE;
643              else
644                {
645      /* unexpected things happened... fail back to old way */
646                    ERR("timer read returned %d (errno=%d)", r, errno);
647                    close(timer_fd);
648                    timer_fd = -1;
649                }
650           }
651      }
652    else
653      ret = TRUE;
654
655    /* check if fds are ready */
656    if (HAVE_EPOLL && epoll_fd >= 0)
657      ecore_fds_ready = (_ecore_main_fdh_epoll_mark_active() > 0);
658    else
659      ecore_fds_ready = (_ecore_main_fdh_glib_mark_active() > 0);
660    _ecore_main_fd_handlers_cleanup();
661    if (ecore_fds_ready)
662      ret = TRUE;
663
664    /* check timers after updating loop time */
665    if (!ret && _ecore_timers_exists())
666      ret = (0.0 == _ecore_timer_next_get());
667
668    in_main_loop--;
669    _ecore_unlock();
670
671    return ret;
672 }
673
674 /* like we just came out of main_loop_select in  _ecore_main_select */
675 static gboolean
676 _ecore_main_gsource_dispatch(GSource    *source __UNUSED__,
677                              GSourceFunc callback __UNUSED__,
678                              gpointer    user_data __UNUSED__)
679 {
680    gboolean events_ready, timers_ready, idlers_ready;
681    double next_time;
682
683    _ecore_lock();
684    _ecore_time_loop_time = ecore_time_get();
685    _ecore_timer_enable_new();
686    next_time = _ecore_timer_next_get();
687
688    events_ready = _ecore_event_exist();
689    timers_ready = _ecore_timers_exists() && (0.0 == next_time);
690    idlers_ready = _ecore_idler_exist();
691
692    in_main_loop++;
693    INF("enter idling=%d fds=%d events=%d timers=%d (next=%.2f) idlers=%d",
694        ecore_idling, ecore_fds_ready, events_ready,
695        timers_ready, next_time, idlers_ready);
696
697    if (ecore_idling && events_ready)
698      {
699         _ecore_idle_exiter_call();
700         ecore_idling = 0;
701      }
702    else if (!ecore_idling && !events_ready)
703      {
704         ecore_idling = 1;
705      }
706
707    if (ecore_idling)
708      {
709         _ecore_idler_all_call();
710
711         events_ready = _ecore_event_exist();
712
713         if (ecore_fds_ready || events_ready || timers_ready)
714           {
715              _ecore_idle_exiter_call();
716              ecore_idling = 0;
717           }
718      }
719
720    /* process events */
721    if (!ecore_idling)
722      {
723         _ecore_main_fd_handlers_call();
724         if (fd_handlers_with_buffer)
725           _ecore_main_fd_handlers_buf_call();
726         _ecore_signal_received_process();
727         _ecore_event_call();
728         _ecore_main_fd_handlers_cleanup();
729
730         _ecore_timer_expired_timers_call(_ecore_time_loop_time);
731         _ecore_timer_cleanup();
732
733         _ecore_idle_enterer_call();
734         _ecore_throttle();
735         _ecore_glib_idle_enterer_called = TRUE;
736
737         if (fd_handlers_with_buffer)
738           _ecore_main_fd_handlers_buf_call();
739      }
740
741    in_main_loop--;
742    _ecore_unlock();
743
744    return TRUE; /* what should be returned here? */
745 }
746
747 static void
748 _ecore_main_gsource_finalize(GSource *source __UNUSED__)
749 {
750 }
751
752 static GSourceFuncs ecore_gsource_funcs =
753 {
754    .prepare = _ecore_main_gsource_prepare,
755    .check = _ecore_main_gsource_check,
756    .dispatch = _ecore_main_gsource_dispatch,
757    .finalize = _ecore_main_gsource_finalize,
758 };
759
760 #endif
761
762 void
763 _ecore_main_loop_init(void)
764 {
765    epoll_fd = epoll_create(1);
766    if (epoll_fd < 0)
767      WRN("Failed to create epoll fd!");
768    epoll_pid = getpid();
769    _ecore_fd_close_on_exec(epoll_fd);
770
771    /* add polls on all our file descriptors */
772    Ecore_Fd_Handler *fdh;
773    EINA_INLIST_FOREACH(fd_handlers, fdh)
774      {
775         if (fdh->delete_me)
776           continue;
777         _ecore_epoll_add(epoll_fd, fdh->fd,
778                          _ecore_poll_events_from_fdh(fdh), fdh);
779         _ecore_main_fdh_poll_add(fdh);
780      }
781
782    /* setup for the g_main_loop only integration */
783 #ifdef USE_G_MAIN_LOOP
784    ecore_glib_source = g_source_new(&ecore_gsource_funcs, sizeof (GSource));
785    if (!ecore_glib_source)
786      CRIT("Failed to create glib source for epoll!");
787    else
788      {
789         g_source_set_priority(ecore_glib_source, G_PRIORITY_HIGH_IDLE + 20);
790         if (HAVE_EPOLL && epoll_fd >= 0)
791           {
792              /* epoll multiplexes fds into the g_main_loop */
793               ecore_epoll_fd.fd = epoll_fd;
794               ecore_epoll_fd.events = G_IO_IN;
795               ecore_epoll_fd.revents = 0;
796               g_source_add_poll(ecore_glib_source, &ecore_epoll_fd);
797           }
798
799         /* timerfd gives us better than millisecond accuracy in g_main_loop */
800         timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
801         if (timer_fd < 0)
802           WRN("failed to create timer fd!");
803         else
804           {
805              _ecore_fd_close_on_exec(timer_fd);
806              ecore_timer_fd.fd = timer_fd;
807              ecore_timer_fd.events = G_IO_IN;
808              ecore_timer_fd.revents = 0;
809              g_source_add_poll(ecore_glib_source, &ecore_timer_fd);
810           }
811
812         ecore_glib_source_id = g_source_attach(ecore_glib_source, NULL);
813         if (ecore_glib_source_id <= 0)
814           CRIT("Failed to attach glib source to default context");
815      }
816 #endif
817 }
818
819 void
820 _ecore_main_loop_shutdown(void)
821 {
822 #ifdef USE_G_MAIN_LOOP
823    if (ecore_glib_source)
824      {
825         g_source_destroy(ecore_glib_source);
826         ecore_glib_source = NULL;
827      }
828 #endif
829
830    if (epoll_fd >= 0)
831      {
832         close(epoll_fd);
833         epoll_fd = -1;
834      }
835    epoll_pid = 0;
836
837    if (timer_fd >= 0)
838      {
839         close(timer_fd);
840         timer_fd = -1;
841      }
842 }
843
844 void *
845 _ecore_main_fd_handler_del(Ecore_Fd_Handler *fd_handler)
846 {
847    if (fd_handler->delete_me)
848      {
849         ERR("fdh %p deleted twice", fd_handler);
850         return NULL;
851      }
852
853    _ecore_main_fdh_poll_del(fd_handler);
854    fd_handler->delete_me = EINA_TRUE;
855    fd_handlers_to_delete = eina_list_append(fd_handlers_to_delete, fd_handler);
856    if (fd_handler->prep_func && fd_handlers_with_prep)
857      fd_handlers_with_prep = eina_list_remove(fd_handlers_with_prep, fd_handler);
858    if (fd_handler->buf_func && fd_handlers_with_buffer)
859      fd_handlers_with_buffer = eina_list_remove(fd_handlers_with_buffer, fd_handler);
860    return fd_handler->data;
861 }
862
863 /**
864  * @addtogroup Ecore_Main_Loop_Group
865  *
866  * @{
867  */
868
869 /**
870  * Runs a single iteration of the main loop to process everything on the
871  * queue.
872  *
873  * It does everything that is already done inside an @c Ecore main loop, like
874  * checking for expired timers, idlers, etc. But it will do it only once and
875  * return, instead of keep watching for new events.
876  *
877  * DO NOT use this function unless you are the person God comes to ask for
878  * advice when He has trouble managing the Universe.
879  *
880  * @see ecore_main_loop_iterate_may_block()
881  */
882 EAPI void
883 ecore_main_loop_iterate(void)
884 {
885    EINA_MAIN_LOOP_CHECK_RETURN;
886 #ifndef USE_G_MAIN_LOOP
887    _ecore_lock();
888    _ecore_time_loop_time = ecore_time_get();
889    _ecore_main_loop_iterate_internal(1);
890    _ecore_unlock();
891 #else
892    g_main_context_iteration(NULL, 0);
893 #endif
894 }
895
896 /**
897  * Runs a single iteration of the main loop to process everything on the
898  * queue with block/non-blocking status.
899  *
900  * @param may_block A flag if the main loop has a possibility of blocking.
901  * (@c EINA_TRUE = may block/@c EINA_FALSE = non block)
902  *
903  * This is an extension API for ecore_main_loop_iterate() with additional
904  * parameter. It does everything that is already done inside an
905  * @c Ecore main loop, like checking for expired timers, idlers, etc. But it
906  * will do it only once and return, instead of keep watching for new events.
907  *
908  * DO NOT use this function unless you are the person God comes to ask for
909  * advice when He has trouble managing the Universe.
910  *
911  * @see ecore_main_loop_iterate()
912  */
913 EAPI int
914 ecore_main_loop_iterate_may_block(int may_block)
915 {
916    EINA_MAIN_LOOP_CHECK_RETURN_VAL(0);
917 #ifndef USE_G_MAIN_LOOP
918    _ecore_lock();
919    _ecore_time_loop_time = ecore_time_get();
920 in_main_loop++;
921    _ecore_main_loop_iterate_internal(!may_block);
922 in_main_loop--;
923    _ecore_unlock();
924    return _ecore_event_exist();
925 #else
926    return g_main_context_iteration(NULL, may_block);
927 #endif
928 }
929
930 /**
931  * Runs the application main loop.
932  *
933  * This function will not return until @ref ecore_main_loop_quit is called. It
934  * will check for expired timers, idlers, file descriptors being watched by fd
935  * handlers, etc. Once everything is done, before entering again on idle state,
936  * any callback set as @c Idle_Enterer will be called.
937  *
938  * Each main loop iteration is done by calling ecore_main_loop_iterate()
939  * internally.
940  *
941  * The polling (select) function used can be changed with
942  * ecore_main_loop_select_func_set().
943  *
944  * The function used to check for file descriptors, events, and that has a
945  * timeout for the timers can be changed using
946  * ecore_main_loop_select_func_set().
947  */
948 EAPI void
949 ecore_main_loop_begin(void)
950 {
951    EINA_MAIN_LOOP_CHECK_RETURN;
952 #ifndef USE_G_MAIN_LOOP
953    _ecore_lock();
954    in_main_loop++;
955    _ecore_time_loop_time = ecore_time_get();
956    while (do_quit == 0) _ecore_main_loop_iterate_internal(0);
957    do_quit = 0;
958    in_main_loop--;
959    _ecore_unlock();
960 #else
961    if (!do_quit)
962      {
963         if (!ecore_main_loop)
964           ecore_main_loop = g_main_loop_new(NULL, FALSE);
965         g_main_loop_run(ecore_main_loop);
966      }
967    do_quit = 0;
968 #endif
969 }
970
971 /**
972  * Quits the main loop once all the events currently on the queue have
973  * been processed.
974  *
975  * This function returns immediately, but will mark the ecore_main_loop_begin()
976  * function to return at the end of the current main loop iteration.
977  */
978 EAPI void
979 ecore_main_loop_quit(void)
980 {
981    EINA_MAIN_LOOP_CHECK_RETURN;
982    do_quit = 1;
983 #ifdef USE_G_MAIN_LOOP
984    if (ecore_main_loop)
985      g_main_loop_quit(ecore_main_loop);
986 #endif
987 }
988
989 /**
990  * Sets the function to use when monitoring multiple file descriptors,
991  * and waiting until one of more of the file descriptors before ready
992  * for some class of I/O operation.
993  *
994  * This function will be used instead of the system call select and
995  * could possible be used to integrate the Ecore event loop with an
996  * external event loop.
997  *
998  * @warning you don't know how to use, don't even try to use it.
999  *
1000  * @param func The function to be used.
1001  */
1002 EAPI void
1003 ecore_main_loop_select_func_set(Ecore_Select_Function func)
1004 {
1005    EINA_MAIN_LOOP_CHECK_RETURN;
1006    main_loop_select = func;
1007 }
1008
1009 /**
1010  * Gets the select function set by ecore_select_func_set(),
1011  * or the native select function if none was set.
1012  *
1013  */
1014 EAPI Ecore_Select_Function
1015 ecore_main_loop_select_func_get(void)
1016 {
1017    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
1018    return main_loop_select;
1019 }
1020
1021 EAPI Ecore_Fd_Handler *
1022 ecore_main_fd_handler_add(int                    fd,
1023                           Ecore_Fd_Handler_Flags flags,
1024                           Ecore_Fd_Cb            func,
1025                           const void            *data,
1026                           Ecore_Fd_Cb            buf_func,
1027                           const void            *buf_data)
1028 {
1029    Ecore_Fd_Handler *fdh = NULL;
1030
1031    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
1032    _ecore_lock();
1033
1034    if ((fd < 0) || (flags == 0) || (!func)) goto unlock;
1035
1036    fdh = ecore_fd_handler_calloc(1);
1037    if (!fdh) goto unlock;
1038    ECORE_MAGIC_SET(fdh, ECORE_MAGIC_FD_HANDLER);
1039    fdh->next_ready = NULL;
1040    fdh->fd = fd;
1041    fdh->flags = flags;
1042    if (_ecore_main_fdh_poll_add(fdh) < 0)
1043      {
1044         int err = errno;
1045         ERR("Failed to add poll on fd %d (errno = %d: %s)!", fd, err, strerror(err));
1046         ecore_fd_handler_mp_free(fdh);
1047         fdh = NULL;
1048         goto unlock;
1049      }
1050    fdh->read_active = EINA_FALSE;
1051    fdh->write_active = EINA_FALSE;
1052    fdh->error_active = EINA_FALSE;
1053    fdh->delete_me = EINA_FALSE;
1054    fdh->func = func;
1055    fdh->data = (void *)data;
1056    fdh->buf_func = buf_func;
1057    if (buf_func)
1058      fd_handlers_with_buffer = eina_list_append(fd_handlers_with_buffer, fdh);
1059    fdh->buf_data = (void *)buf_data;
1060    fd_handlers = (Ecore_Fd_Handler *)
1061      eina_inlist_append(EINA_INLIST_GET(fd_handlers),
1062                         EINA_INLIST_GET(fdh));
1063 unlock:
1064    _ecore_unlock();
1065
1066    return fdh;
1067 }
1068
1069 EAPI Ecore_Fd_Handler *
1070 ecore_main_fd_handler_file_add(int                    fd,
1071                                Ecore_Fd_Handler_Flags flags,
1072                                Ecore_Fd_Cb            func,
1073                                const void            *data,
1074                                Ecore_Fd_Cb            buf_func,
1075                                const void            *buf_data)
1076 {
1077    Ecore_Fd_Handler *fdh = NULL;
1078
1079    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
1080    _ecore_lock();
1081
1082    if ((fd < 0) || (flags == 0) || (!func)) goto unlock;
1083
1084    fdh = ecore_fd_handler_calloc(1);
1085    if (!fdh) goto unlock;
1086    ECORE_MAGIC_SET(fdh, ECORE_MAGIC_FD_HANDLER);
1087    fdh->next_ready = NULL;
1088    fdh->fd = fd;
1089    fdh->flags = flags;
1090    fdh->file = EINA_TRUE;
1091    if (_ecore_main_fdh_poll_add(fdh) < 0)
1092      {
1093         int err = errno;
1094         ERR("Failed to add poll on fd %d (errno = %d: %s)!", fd, err, strerror(err));
1095         ecore_fd_handler_mp_free(fdh);
1096         fdh = NULL;
1097         goto unlock;
1098      }
1099    fdh->read_active = EINA_FALSE;
1100    fdh->write_active = EINA_FALSE;
1101    fdh->error_active = EINA_FALSE;
1102    fdh->delete_me = EINA_FALSE;
1103    fdh->func = func;
1104    fdh->data = (void *)data;
1105    fdh->buf_func = buf_func;
1106    if (buf_func)
1107      fd_handlers_with_buffer = eina_list_append(fd_handlers_with_buffer, fdh);
1108    fdh->buf_data = (void *)buf_data;
1109    fd_handlers = (Ecore_Fd_Handler *)
1110      eina_inlist_append(EINA_INLIST_GET(fd_handlers),
1111                         EINA_INLIST_GET(fdh));
1112    file_fd_handlers = eina_list_append(file_fd_handlers, fdh);
1113 unlock:
1114    _ecore_unlock();
1115
1116    return fdh;
1117 }
1118
1119 #ifdef _WIN32
1120 EAPI Ecore_Win32_Handler *
1121 ecore_main_win32_handler_add(void                 *h,
1122                              Ecore_Win32_Handle_Cb func,
1123                              const void           *data)
1124 {
1125    Ecore_Win32_Handler *wh;
1126
1127    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
1128    if (!h || !func) return NULL;
1129
1130    wh = ecore_win32_handler_calloc(1);
1131    if (!wh) return NULL;
1132    ECORE_MAGIC_SET(wh, ECORE_MAGIC_WIN32_HANDLER);
1133    wh->h = (HANDLE)h;
1134    wh->delete_me = EINA_FALSE;
1135    wh->func = func;
1136    wh->data = (void *)data;
1137    win32_handlers = (Ecore_Win32_Handler *)
1138      eina_inlist_append(EINA_INLIST_GET(win32_handlers),
1139                         EINA_INLIST_GET(wh));
1140    return wh;
1141 }
1142
1143 #else
1144 EAPI Ecore_Win32_Handler *
1145 ecore_main_win32_handler_add(void                 *h __UNUSED__,
1146                              Ecore_Win32_Handle_Cb func __UNUSED__,
1147                              const void           *data __UNUSED__)
1148 {
1149    return NULL;
1150 }
1151
1152 #endif
1153
1154 EAPI void *
1155 ecore_main_fd_handler_del(Ecore_Fd_Handler *fd_handler)
1156 {
1157    void *ret = NULL;
1158
1159    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
1160    _ecore_lock();
1161
1162    if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
1163      {
1164         ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
1165                          "ecore_main_fd_handler_del");
1166         goto unlock;
1167      }
1168    ret = _ecore_main_fd_handler_del(fd_handler);
1169 unlock:
1170    _ecore_unlock();
1171    return ret;
1172 }
1173
1174 #ifdef _WIN32
1175 EAPI void *
1176 ecore_main_win32_handler_del(Ecore_Win32_Handler *win32_handler)
1177 {
1178    EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
1179    if (!ECORE_MAGIC_CHECK(win32_handler, ECORE_MAGIC_WIN32_HANDLER))
1180      {
1181         ECORE_MAGIC_FAIL(win32_handler, ECORE_MAGIC_WIN32_HANDLER,
1182                          "ecore_main_win32_handler_del");
1183         return NULL;
1184      }
1185    win32_handler->delete_me = EINA_TRUE;
1186    win32_handlers_delete_me = EINA_TRUE;
1187    return win32_handler->data;
1188 }
1189
1190 #else
1191 EAPI void *
1192 ecore_main_win32_handler_del(Ecore_Win32_Handler *win32_handler __UNUSED__)
1193 {
1194    return NULL;
1195 }
1196
1197 #endif
1198
1199 EAPI void
1200 ecore_main_fd_handler_prepare_callback_set(Ecore_Fd_Handler *fd_handler,
1201                                            Ecore_Fd_Prep_Cb  func,
1202                                            const void       *data)
1203 {
1204    EINA_MAIN_LOOP_CHECK_RETURN;
1205    _ecore_lock();
1206
1207    if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
1208      {
1209         ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
1210                          "ecore_main_fd_handler_prepare_callback_set");
1211         goto unlock;
1212      }
1213    fd_handler->prep_func = func;
1214    fd_handler->prep_data = (void *)data;
1215    if ((!fd_handlers_with_prep) ||
1216        (fd_handlers_with_prep && (!eina_list_data_find(fd_handlers_with_prep, fd_handler))))
1217      /* FIXME: THIS WILL NOT SCALE WITH LOTS OF PREP FUNCTIONS!!! */
1218      fd_handlers_with_prep = eina_list_append(fd_handlers_with_prep, fd_handler);
1219 unlock:
1220    _ecore_unlock();
1221 }
1222
1223 EAPI int
1224 ecore_main_fd_handler_fd_get(Ecore_Fd_Handler *fd_handler)
1225 {
1226    int fd = -1;
1227
1228    EINA_MAIN_LOOP_CHECK_RETURN_VAL(-1);
1229    _ecore_lock();
1230
1231    if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
1232      {
1233         ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
1234                          "ecore_main_fd_handler_fd_get");
1235         goto unlock;
1236      }
1237    fd = fd_handler->fd;
1238 unlock:
1239    _ecore_unlock();
1240    return fd;
1241 }
1242
1243 EAPI Eina_Bool
1244 ecore_main_fd_handler_active_get(Ecore_Fd_Handler      *fd_handler,
1245                                  Ecore_Fd_Handler_Flags flags)
1246 {
1247    int ret = EINA_FALSE;
1248
1249    EINA_MAIN_LOOP_CHECK_RETURN_VAL(EINA_FALSE);
1250    _ecore_lock();
1251
1252    if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
1253      {
1254         ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
1255                          "ecore_main_fd_handler_active_get");
1256         goto unlock;
1257      }
1258    if ((flags & ECORE_FD_READ) && (fd_handler->read_active)) ret = EINA_TRUE;
1259    if ((flags & ECORE_FD_WRITE) && (fd_handler->write_active)) ret = EINA_TRUE;
1260    if ((flags & ECORE_FD_ERROR) && (fd_handler->error_active)) ret = EINA_TRUE;
1261 unlock:
1262    _ecore_unlock();
1263    return ret;
1264 }
1265
1266 EAPI void
1267 ecore_main_fd_handler_active_set(Ecore_Fd_Handler      *fd_handler,
1268                                  Ecore_Fd_Handler_Flags flags)
1269 {
1270    int ret;
1271
1272    EINA_MAIN_LOOP_CHECK_RETURN;
1273    _ecore_lock();
1274
1275    if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
1276      {
1277         ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
1278                          "ecore_main_fd_handler_active_set");
1279         goto unlock;
1280      }
1281    fd_handler->flags = flags;
1282    ret = _ecore_main_fdh_poll_modify(fd_handler);
1283    if (ret < 0)
1284      {
1285         ERR("Failed to mod epoll fd %d: %s!", fd_handler->fd, strerror(ret));
1286      }
1287 unlock:
1288    _ecore_unlock();
1289 }
1290
1291 /**
1292  * @}
1293  */
1294
1295 void
1296 _ecore_main_shutdown(void)
1297 {
1298    if (in_main_loop)
1299      {
1300         ERR("\n"
1301             "*** ECORE WARNING: Calling ecore_shutdown() while still in the main loop.\n"
1302             "***                 Program may crash or behave strangely now.");
1303         return;
1304      }
1305    while (fd_handlers)
1306      {
1307         Ecore_Fd_Handler *fdh;
1308
1309         fdh = fd_handlers;
1310         fd_handlers = (Ecore_Fd_Handler *)eina_inlist_remove(EINA_INLIST_GET(fd_handlers),
1311                                                              EINA_INLIST_GET(fdh));
1312         ECORE_MAGIC_SET(fdh, ECORE_MAGIC_NONE);
1313         ecore_fd_handler_mp_free(fdh);
1314      }
1315    if (fd_handlers_with_buffer)
1316      fd_handlers_with_buffer = eina_list_free(fd_handlers_with_buffer);
1317    if (fd_handlers_with_prep)
1318      fd_handlers_with_prep = eina_list_free(fd_handlers_with_prep);
1319    if (fd_handlers_to_delete)
1320      fd_handlers_to_delete = eina_list_free(fd_handlers_to_delete);
1321    if (file_fd_handlers)
1322      file_fd_handlers = eina_list_free(file_fd_handlers);
1323
1324    fd_handlers_to_call = NULL;
1325    fd_handlers_to_call_current = NULL;
1326    fd_handlers_to_delete = NULL;
1327    fd_handler_current = NULL;
1328
1329 #ifdef _WIN32
1330    while (win32_handlers)
1331      {
1332         Ecore_Win32_Handler *wh;
1333
1334         wh = win32_handlers;
1335         win32_handlers = (Ecore_Win32_Handler *)eina_inlist_remove(EINA_INLIST_GET(win32_handlers),
1336                                                                    EINA_INLIST_GET(wh));
1337         ECORE_MAGIC_SET(wh, ECORE_MAGIC_NONE);
1338         ecore_win32_handler_mp_free(wh);
1339      }
1340    win32_handlers_delete_me = EINA_FALSE;
1341    win32_handler_current = NULL;
1342 #endif
1343 }
1344
1345 static void
1346 _ecore_main_prepare_handlers(void)
1347 {
1348    Ecore_Fd_Handler *fdh;
1349    Eina_List *l, *l2;
1350
1351    /* call the prepare callback for all handlers with prep functions */
1352    EINA_LIST_FOREACH_SAFE(fd_handlers_with_prep, l, l2, fdh)
1353      {
1354         if (!fdh)
1355           {
1356              fd_handlers_with_prep = eina_list_remove_list(l, fd_handlers_with_prep);
1357              continue;
1358           }
1359         if (!fdh->delete_me && fdh->prep_func)
1360           {
1361              fdh->references++;
1362              _ecore_call_prep_cb(fdh->prep_func, fdh->prep_data, fdh);
1363              fdh->references--;
1364           }
1365         else
1366           fd_handlers_with_prep = eina_list_remove_list(fd_handlers_with_prep, l);
1367      }
1368 }
1369
1370 #ifndef USE_G_MAIN_LOOP
1371 static int
1372 _ecore_main_select(double timeout)
1373 {
1374    struct timeval tv, *t;
1375    fd_set rfds, wfds, exfds;
1376    Ecore_Fd_Handler *fdh;
1377    Eina_List *l;
1378    int max_fd;
1379    int ret;
1380
1381    t = NULL;
1382    if ((!ECORE_FINITE(timeout)) || (timeout == 0.0)) /* finite() tests for NaN, too big, too small, and infinity.  */
1383      {
1384         tv.tv_sec = 0;
1385         tv.tv_usec = 0;
1386         t = &tv;
1387      }
1388    else if (timeout > 0.0)
1389      {
1390         int sec, usec;
1391
1392 #ifdef FIX_HZ
1393         timeout += (0.5 / HZ);
1394         sec = (int)timeout;
1395         usec = (int)((timeout - (double)sec) * 1000000);
1396 #else
1397         sec = (int)timeout;
1398         usec = (int)((timeout - (double)sec) * 1000000);
1399 #endif
1400         tv.tv_sec = sec;
1401         tv.tv_usec = usec;
1402         t = &tv;
1403      }
1404    max_fd = 0;
1405    FD_ZERO(&rfds);
1406    FD_ZERO(&wfds);
1407    FD_ZERO(&exfds);
1408
1409    /* call the prepare callback for all handlers */
1410    if (fd_handlers_with_prep)
1411      _ecore_main_prepare_handlers();
1412
1413    if (!HAVE_EPOLL || epoll_fd < 0)
1414      {
1415         EINA_INLIST_FOREACH(fd_handlers, fdh)
1416           {
1417              if (!fdh->delete_me)
1418                {
1419                   if (fdh->flags & ECORE_FD_READ)
1420                     {
1421                        FD_SET(fdh->fd, &rfds);
1422                        if (fdh->fd > max_fd) max_fd = fdh->fd;
1423                     }
1424                   if (fdh->flags & ECORE_FD_WRITE)
1425                     {
1426                        FD_SET(fdh->fd, &wfds);
1427                        if (fdh->fd > max_fd) max_fd = fdh->fd;
1428                     }
1429                   if (fdh->flags & ECORE_FD_ERROR)
1430                     {
1431                        FD_SET(fdh->fd, &exfds);
1432                        if (fdh->fd > max_fd) max_fd = fdh->fd;
1433                     }
1434                }
1435           }
1436      }
1437    else
1438      {
1439         /* polling on the epoll fd will wake when an fd in the epoll set is active */
1440          max_fd = _ecore_get_epoll_fd();
1441          FD_SET(max_fd, &rfds);
1442      }
1443    EINA_LIST_FOREACH(file_fd_handlers, l, fdh)
1444      if (!fdh->delete_me)
1445        {
1446           if (fdh->flags & ECORE_FD_READ)
1447             {
1448                FD_SET(fdh->fd, &rfds);
1449                if (fdh->fd > max_fd) max_fd = fdh->fd;
1450             }
1451           if (fdh->flags & ECORE_FD_WRITE)
1452             {
1453                FD_SET(fdh->fd, &wfds);
1454                if (fdh->fd > max_fd) max_fd = fdh->fd;
1455             }
1456           if (fdh->flags & ECORE_FD_ERROR)
1457             {
1458                FD_SET(fdh->fd, &exfds);
1459                if (fdh->fd > max_fd) max_fd = fdh->fd;
1460             }
1461           if (fdh->fd > max_fd) max_fd = fdh->fd;
1462        }
1463    if (_ecore_signal_count_get()) return -1;
1464
1465    _ecore_unlock();
1466    ret = main_loop_select(max_fd + 1, &rfds, &wfds, &exfds, t);
1467    _ecore_lock();
1468
1469    _ecore_time_loop_time = ecore_time_get();
1470    if (ret < 0)
1471      {
1472 #ifndef _WIN32
1473         if (errno == EINTR) return -1;
1474         else if (errno == EBADF)
1475           _ecore_main_fd_handlers_bads_rem();
1476 #endif
1477      }
1478    if (ret > 0)
1479      {
1480         if (HAVE_EPOLL && epoll_fd >= 0)
1481           _ecore_main_fdh_epoll_mark_active();
1482         else
1483           {
1484              EINA_INLIST_FOREACH(fd_handlers, fdh)
1485                {
1486                   if (!fdh->delete_me)
1487                     {
1488                        if (FD_ISSET(fdh->fd, &rfds))
1489                          fdh->read_active = EINA_TRUE;
1490                        if (FD_ISSET(fdh->fd, &wfds))
1491                          fdh->write_active = EINA_TRUE;
1492                        if (FD_ISSET(fdh->fd, &exfds))
1493                          fdh->error_active = EINA_TRUE;
1494                        _ecore_try_add_to_call_list(fdh);
1495                     }
1496                }
1497           }
1498         EINA_LIST_FOREACH(file_fd_handlers, l, fdh)
1499           {
1500              if (!fdh->delete_me)
1501                {
1502                   if (FD_ISSET(fdh->fd, &rfds))
1503                     fdh->read_active = EINA_TRUE;
1504                   if (FD_ISSET(fdh->fd, &wfds))
1505                     fdh->write_active = EINA_TRUE;
1506                   if (FD_ISSET(fdh->fd, &exfds))
1507                     fdh->error_active = EINA_TRUE;
1508                   _ecore_try_add_to_call_list(fdh);
1509                }
1510           }
1511         _ecore_main_fd_handlers_cleanup();
1512 #ifdef _WIN32
1513         _ecore_main_win32_handlers_cleanup();
1514 #endif
1515         return 1;
1516      }
1517    return 0;
1518 }
1519
1520 #endif
1521
1522 #ifndef _WIN32
1523 # ifndef USE_G_MAIN_LOOP
1524 static void
1525 _ecore_main_fd_handlers_bads_rem(void)
1526 {
1527    Ecore_Fd_Handler *fdh;
1528    Eina_Inlist *l;
1529    int found = 0;
1530
1531    ERR("Removing bad fds");
1532    for (l = EINA_INLIST_GET(fd_handlers); l; )
1533      {
1534         fdh = (Ecore_Fd_Handler *)l;
1535         l = l->next;
1536         errno = 0;
1537
1538         if ((fcntl(fdh->fd, F_GETFD) < 0) && (errno == EBADF))
1539           {
1540              ERR("Found bad fd at index %d", fdh->fd);
1541              if (fdh->flags & ECORE_FD_ERROR)
1542                {
1543                   ERR("Fd set for error! calling user");
1544                   fdh->references++;
1545                   if (!_ecore_call_fd_cb(fdh->func, fdh->data, fdh))
1546                     {
1547                        ERR("Fd function err returned 0, remove it");
1548                        if (!fdh->delete_me)
1549                          {
1550                             fdh->delete_me = EINA_TRUE;
1551                             fd_handlers_to_delete = eina_list_append(fd_handlers_to_delete, fdh);
1552                          }
1553                        found++;
1554                     }
1555                   fdh->references--;
1556                }
1557              else
1558                {
1559                   ERR("Problematic fd found at %d! setting it for delete", fdh->fd);
1560                   if (!fdh->delete_me)
1561                     {
1562                        fdh->delete_me = EINA_TRUE;
1563                        fd_handlers_to_delete = eina_list_append(fd_handlers_to_delete, fdh);
1564                     }
1565
1566                   found++;
1567                }
1568           }
1569      }
1570    if (found == 0)
1571      {
1572 #  ifdef HAVE_GLIB
1573         ERR("No bad fd found. Maybe a foreign fd from glib?");
1574 #  else
1575         ERR("No bad fd found. EEEK!");
1576 #  endif
1577      }
1578    _ecore_main_fd_handlers_cleanup();
1579 }
1580
1581 # endif
1582 #endif
1583
1584 static void
1585 _ecore_main_fd_handlers_cleanup(void)
1586 {
1587    Ecore_Fd_Handler *fdh;
1588    Eina_List *l, *l2;
1589
1590    if (!fd_handlers_to_delete) return;
1591    EINA_LIST_FOREACH_SAFE(fd_handlers_to_delete, l, l2, fdh)
1592      {
1593         if (!fdh)
1594           {
1595              fd_handlers_to_delete = eina_list_remove_list(l, fd_handlers_to_delete);
1596              continue;
1597           }
1598         /* fdh->delete_me should be set for all fdhs at the start of the list */
1599         if (fdh->references)
1600           continue;
1601         if (fdh->buf_func && fd_handlers_with_buffer)
1602           fd_handlers_with_buffer = eina_list_remove(fd_handlers_with_buffer, fdh);
1603         if (fdh->prep_func && fd_handlers_with_prep)
1604           fd_handlers_with_prep = eina_list_remove(fd_handlers_with_prep, fdh);
1605         fd_handlers = (Ecore_Fd_Handler *)
1606           eina_inlist_remove(EINA_INLIST_GET(fd_handlers), EINA_INLIST_GET(fdh));
1607         if (fdh->file)
1608           file_fd_handlers = eina_list_remove(file_fd_handlers, fdh);
1609         ECORE_MAGIC_SET(fdh, ECORE_MAGIC_NONE);
1610         ecore_fd_handler_mp_free(fdh);
1611         fd_handlers_to_delete = eina_list_remove_list(fd_handlers_to_delete, l);
1612      }
1613 }
1614
1615 #ifdef _WIN32
1616 static void
1617 _ecore_main_win32_handlers_cleanup(void)
1618 {
1619    Ecore_Win32_Handler *wh;
1620    Eina_Inlist *l;
1621    int deleted_in_use = 0;
1622
1623    if (!win32_handlers_delete_me) return;
1624    for (l = EINA_INLIST_GET(win32_handlers); l; )
1625      {
1626         wh = (Ecore_Win32_Handler *)l;
1627
1628         l = l->next;
1629         if (wh->delete_me)
1630           {
1631              if (wh->references)
1632                {
1633                   deleted_in_use++;
1634                   continue;
1635                }
1636
1637              win32_handlers = (Ecore_Win32_Handler *)
1638                eina_inlist_remove(EINA_INLIST_GET(win32_handlers),
1639                                   EINA_INLIST_GET(wh));
1640              ECORE_MAGIC_SET(wh, ECORE_MAGIC_NONE);
1641              ecore_win32_handler_mp_free(wh);
1642           }
1643      }
1644    if (!deleted_in_use) win32_handlers_delete_me = EINA_FALSE;
1645 }
1646
1647 #endif
1648
1649 static void
1650 _ecore_main_fd_handlers_call(void)
1651 {
1652    /* grab a new list */
1653     if (!fd_handlers_to_call_current)
1654       {
1655          fd_handlers_to_call_current = fd_handlers_to_call;
1656          fd_handlers_to_call = NULL;
1657       }
1658
1659     while (fd_handlers_to_call_current)
1660       {
1661          Ecore_Fd_Handler *fdh = fd_handlers_to_call_current;
1662
1663          if (!fdh->delete_me)
1664            {
1665               if ((fdh->read_active) ||
1666                   (fdh->write_active) ||
1667                   (fdh->error_active))
1668                 {
1669                    fdh->references++;
1670                    if (!_ecore_call_fd_cb(fdh->func, fdh->data, fdh))
1671                      {
1672                         if (!fdh->delete_me)
1673                           {
1674                              fdh->delete_me = EINA_TRUE;
1675                              fd_handlers_to_delete = eina_list_append(fd_handlers_to_delete, fdh);
1676                           }
1677                      }
1678                    fdh->references--;
1679                    _ecore_fd_valid();
1680
1681                    fdh->read_active = EINA_FALSE;
1682                    fdh->write_active = EINA_FALSE;
1683                    fdh->error_active = EINA_FALSE;
1684                 }
1685            }
1686
1687          /* stop when we point to ourselves */
1688          if (fdh->next_ready == fdh)
1689            {
1690               fdh->next_ready = NULL;
1691               fd_handlers_to_call_current = NULL;
1692               break;
1693            }
1694
1695          fd_handlers_to_call_current = fdh->next_ready;
1696          fdh->next_ready = NULL;
1697       }
1698 }
1699
1700 static int
1701 _ecore_main_fd_handlers_buf_call(void)
1702 {
1703    Ecore_Fd_Handler *fdh;
1704    Eina_List *l, *l2;
1705    int ret;
1706
1707    ret = 0;
1708    EINA_LIST_FOREACH_SAFE(fd_handlers_with_buffer, l, l2, fdh)
1709      {
1710         if (!fdh)
1711           {
1712              fd_handlers_with_buffer = eina_list_remove_list(l, fd_handlers_with_buffer);
1713              continue;
1714           }
1715         if ((!fdh->delete_me) && fdh->buf_func)
1716           {
1717              fdh->references++;
1718              if (_ecore_call_fd_cb(fdh->buf_func, fdh->buf_data, fdh))
1719                {
1720                   ret |= _ecore_call_fd_cb(fdh->func, fdh->data, fdh);
1721                   fdh->read_active = EINA_TRUE;
1722                   _ecore_try_add_to_call_list(fdh);
1723                }
1724              fdh->references--;
1725           }
1726         else
1727           fd_handlers_with_buffer = eina_list_remove_list(fd_handlers_with_buffer, l);
1728      }
1729    return ret;
1730 }
1731
1732 #ifndef USE_G_MAIN_LOOP
1733
1734 enum {
1735    SPIN_MORE,
1736    SPIN_RESTART,
1737    LOOP_CONTINUE
1738 };
1739
1740 static int
1741 _ecore_main_loop_spin_core(void)
1742 {
1743    /* as we are spinning we need to update loop time per spin */
1744     _ecore_time_loop_time = ecore_time_get();
1745     /* call all idlers, which returns false if no more idelrs exist */
1746     if (!_ecore_idler_all_call()) return SPIN_RESTART;
1747     /* sneaky - drop through or if checks - the first one to succeed
1748      * drops through and returns "continue" so further ones dont run */
1749     if ((_ecore_main_select(0.0) > 0) || (_ecore_event_exist()) ||
1750         (_ecore_signal_count_get() > 0) || (do_quit))
1751       return LOOP_CONTINUE;
1752     /* default - spin more */
1753     return SPIN_MORE;
1754 }
1755
1756 static int
1757 _ecore_main_loop_spin_no_timers(void)
1758 {
1759    /* if we have idlers we HAVE to spin and handle everything
1760     * in a polling way - spin in a tight polling loop */
1761      for (;; )
1762        {
1763           int action = _ecore_main_loop_spin_core();
1764           if (action != SPIN_MORE) return action;
1765           /* if an idler has added a timer then we need to go through
1766            * the start of the spin cycle again to handle cases properly */
1767           if (_ecore_timers_exists()) return SPIN_RESTART;
1768        }
1769      /* just contiune handling events etc. */
1770      return LOOP_CONTINUE;
1771 }
1772
1773 static int
1774 _ecore_main_loop_spin_timers(void)
1775 {
1776    /* if we have idlers we HAVE to spin and handle everything
1777     * in a polling way - spin in a tight polling loop */
1778      for (;; )
1779        {
1780           int action = _ecore_main_loop_spin_core();
1781           if (action != SPIN_MORE) return action;
1782           /* if next timer expires now or in the past - stop spinning and
1783            * continue the mainloop walk as our "select" timeout has
1784            * expired now */
1785           if (_ecore_timer_next_get() <= 0.0) return LOOP_CONTINUE;
1786        }
1787      /* just contiune handling events etc. */
1788      return LOOP_CONTINUE;
1789 }
1790
1791 static void
1792 _ecore_fps_marker_1(void)
1793 {
1794    if (!_ecore_fps_debug) return;
1795    t2 = ecore_time_get();
1796    if ((t1 > 0.0) && (t2 > 0.0)) _ecore_fps_debug_runtime_add(t2 - t1);
1797 }
1798
1799 static void
1800 _ecore_fps_marker_2(void)
1801 {
1802    if (!_ecore_fps_debug) return;
1803    t1 = ecore_time_get();
1804 }
1805
1806 static void
1807 _ecore_main_loop_iterate_internal(int once_only)
1808 {
1809    double next_time = -1.0;
1810
1811    in_main_loop++;
1812    /* expire any timers */
1813    _ecore_timer_expired_timers_call(_ecore_time_loop_time);
1814    _ecore_timer_cleanup();
1815
1816    /* process signals into events .... */
1817    _ecore_signal_received_process();
1818    /* if as a result of timers/animators or signals we have accumulated
1819     * events, then instantly handle them */
1820    if (_ecore_event_exist())
1821      {
1822         /* but first conceptually enter an idle state */
1823         _ecore_idle_enterer_call();
1824         _ecore_throttle();
1825         /* now quickly poll to see which input fd's are active */
1826         _ecore_main_select(0.0);
1827         /* allow newly queued timers to expire from now on */
1828         _ecore_timer_enable_new();
1829         /* go straight to processing the events we had queued */
1830         goto process_all;
1831      }
1832
1833    if (once_only)
1834      {
1835         /* in once_only mode we should quickly poll for inputs, signals
1836          * if we got any events or signals, allow new timers to process.
1837          * use bitwise or to force both conditions to be tested and
1838          * merged together */
1839         if (_ecore_main_select(0.0) | _ecore_signal_count_get())
1840           {
1841              _ecore_timer_enable_new();
1842              goto process_all;
1843           }
1844      }
1845    else
1846      {
1847         /* call idle enterers ... */
1848         _ecore_idle_enterer_call();
1849         _ecore_throttle();
1850      }
1851
1852    /* if these calls caused any buffered events to appear - deal with them */
1853    if (fd_handlers_with_buffer)
1854      _ecore_main_fd_handlers_buf_call();
1855
1856    /* if there are any (buffered fd handling may generate them)
1857     * then jump to processing them */
1858    if (_ecore_event_exist())
1859      {
1860         _ecore_main_select(0.0);
1861         _ecore_timer_enable_new();
1862         goto process_all;
1863      }
1864
1865    if (once_only)
1866      {
1867         /* in once_only mode enter idle here instead and then return */
1868         _ecore_idle_enterer_call();
1869         _ecore_throttle();
1870         _ecore_timer_enable_new();
1871         goto done;
1872      }
1873
1874    _ecore_fps_marker_1();
1875
1876    /* start of the sleeping or looping section */
1877 start_loop: /***************************************************************/
1878    /* any timers re-added as a result of these are allowed to go */
1879    _ecore_timer_enable_new();
1880    /* if we have been asked to quit the mainloop then exit at this point */
1881    if (do_quit)
1882      {
1883         _ecore_timer_enable_new();
1884         goto done;
1885      }
1886    if (!_ecore_event_exist())
1887      {
1888         /* init flags */
1889         next_time = _ecore_timer_next_get();
1890         /* no idlers */
1891         if (!_ecore_idler_exist())
1892           {
1893              /* sleep until timeout or forever (-1.0) waiting for on fds */
1894              _ecore_main_select(next_time);
1895           }
1896         else
1897           {
1898              int action = LOOP_CONTINUE;
1899
1900              /* no timers - spin */
1901              if (next_time < 0) action = _ecore_main_loop_spin_no_timers();
1902              /* timers - spin */
1903              else action = _ecore_main_loop_spin_timers();
1904              if (action == SPIN_RESTART) goto start_loop;
1905           }
1906      }
1907    _ecore_fps_marker_2();
1908
1909    /* actually wake up and deal with input, events etc. */
1910 process_all: /***********************************************************/
1911
1912    /* we came out of our "wait state" so idle has exited */
1913    if (!once_only) _ecore_idle_exiter_call();
1914    /* call the fd handler per fd that became alive... */
1915    /* this should read or write any data to the monitored fd and then */
1916    /* post events onto the ecore event pipe if necessary */
1917    _ecore_main_fd_handlers_call();
1918    if (fd_handlers_with_buffer) _ecore_main_fd_handlers_buf_call();
1919    /* process signals into events .... */
1920    _ecore_signal_received_process();
1921    /* handle events ... */
1922    _ecore_event_call();
1923    _ecore_main_fd_handlers_cleanup();
1924
1925    if (once_only)
1926      {
1927         /* if in once_only mode handle idle exiting */
1928         _ecore_idle_enterer_call();
1929         _ecore_throttle();
1930      }
1931
1932 done: /*******************************************************************/
1933    in_main_loop--;
1934 }
1935
1936 #endif
1937
1938 #ifdef _WIN32
1939 static int
1940 _ecore_main_win32_select(int             nfds __UNUSED__,
1941                          fd_set         *readfds,
1942                          fd_set         *writefds,
1943                          fd_set         *exceptfds,
1944                          struct timeval *tv)
1945 {
1946    HANDLE objects[MAXIMUM_WAIT_OBJECTS];
1947    int sockets[MAXIMUM_WAIT_OBJECTS];
1948    Ecore_Fd_Handler *fdh;
1949    Ecore_Win32_Handler *wh;
1950    unsigned int objects_nbr = 0;
1951    unsigned int handles_nbr = 0;
1952    unsigned int events_nbr = 0;
1953    DWORD result;
1954    DWORD timeout;
1955    MSG msg;
1956    unsigned int i;
1957    int res;
1958
1959    /* Create an event object per socket */
1960    EINA_INLIST_FOREACH(fd_handlers, fdh)
1961      {
1962         WSAEVENT event;
1963         long network_event;
1964
1965         network_event = 0;
1966         if (readfds)
1967           {
1968              if (FD_ISSET(fdh->fd, readfds))
1969                network_event |= FD_READ;
1970           }
1971         if (writefds)
1972           {
1973              if (FD_ISSET(fdh->fd, writefds))
1974                network_event |= FD_WRITE;
1975           }
1976         if (exceptfds)
1977           {
1978              if (FD_ISSET(fdh->fd, exceptfds))
1979                network_event |= FD_OOB;
1980           }
1981
1982         if (network_event)
1983           {
1984              event = WSACreateEvent();
1985              WSAEventSelect(fdh->fd, event, network_event);
1986              objects[objects_nbr] = event;
1987              sockets[events_nbr] = fdh->fd;
1988              events_nbr++;
1989              objects_nbr++;
1990           }
1991      }
1992
1993    /* store the HANDLEs in the objects to wait for */
1994    EINA_INLIST_FOREACH(win32_handlers, wh)
1995      {
1996         objects[objects_nbr] = wh->h;
1997         handles_nbr++;
1998         objects_nbr++;
1999      }
2000
2001    /* Empty the queue before waiting */
2002    while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
2003      {
2004         TranslateMessage(&msg);
2005         DispatchMessage(&msg);
2006      }
2007
2008    /* Wait for any message sent or posted to this queue */
2009    /* or for one of the passed handles be set to signaled. */
2010    if (!tv)
2011      timeout = INFINITE;
2012    else
2013      timeout = (DWORD)((tv->tv_sec * 1000.0) + (tv->tv_usec / 1000.0));
2014
2015    if (timeout == 0) return 0;
2016
2017    result = MsgWaitForMultipleObjects(objects_nbr, (const HANDLE *)objects, EINA_FALSE,
2018                                       timeout, QS_ALLINPUT);
2019
2020    if (readfds)
2021      FD_ZERO(readfds);
2022    if (writefds)
2023      FD_ZERO(writefds);
2024    if (exceptfds)
2025      FD_ZERO(exceptfds);
2026
2027    /* The result tells us the type of event we have. */
2028    if (result == WAIT_FAILED)
2029      {
2030         char *m;
2031
2032         m = evil_last_error_get();
2033         ERR("%s", m);
2034         free(m);
2035         res = -1;
2036      }
2037    else if (result == WAIT_TIMEOUT)
2038      {
2039         /* ERR("time out\n"); */
2040          res = 0;
2041      }
2042    else if (result == (WAIT_OBJECT_0 + objects_nbr))
2043      {
2044         while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
2045           {
2046              TranslateMessage(&msg);
2047              DispatchMessage(&msg);
2048           }
2049
2050         res = 0;
2051      }
2052    else if ((result >= 0) && (result < WAIT_OBJECT_0 + events_nbr))
2053      {
2054         WSANETWORKEVENTS network_event;
2055
2056         WSAEnumNetworkEvents(sockets[result], objects[result], &network_event);
2057
2058         if ((network_event.lNetworkEvents & FD_READ) && readfds)
2059           FD_SET(sockets[result], readfds);
2060         if ((network_event.lNetworkEvents & FD_WRITE) && writefds)
2061           FD_SET(sockets[result], writefds);
2062         if ((network_event.lNetworkEvents & FD_OOB) && exceptfds)
2063           FD_SET(sockets[result], exceptfds);
2064
2065         res = 1;
2066      }
2067    else if ((result >= (WAIT_OBJECT_0 + events_nbr)) &&
2068             (result < (WAIT_OBJECT_0 + objects_nbr)))
2069      {
2070         if (!win32_handler_current)
2071           {
2072              /* regular main loop, start from head */
2073               win32_handler_current = win32_handlers;
2074           }
2075         else
2076           {
2077              /* recursive main loop, continue from where we were */
2078               win32_handler_current = (Ecore_Win32_Handler *)EINA_INLIST_GET(win32_handler_current)->next;
2079           }
2080
2081         while (win32_handler_current)
2082           {
2083              wh = win32_handler_current;
2084
2085              if (objects[result - WAIT_OBJECT_0] == wh->h)
2086                {
2087                   if (!wh->delete_me)
2088                     {
2089                        wh->references++;
2090                        if (!wh->func(wh->data, wh))
2091                          {
2092                             wh->delete_me = EINA_TRUE;
2093                             win32_handlers_delete_me = EINA_TRUE;
2094                          }
2095                        wh->references--;
2096                     }
2097                }
2098              if (win32_handler_current) /* may have changed in recursive main loops */
2099                win32_handler_current = (Ecore_Win32_Handler *)EINA_INLIST_GET(win32_handler_current)->next;
2100           }
2101         res = 1;
2102      }
2103    else
2104      {
2105         ERR("unknown result...\n");
2106         res = -1;
2107      }
2108
2109    /* Remove event objects again */
2110    for (i = 0; i < events_nbr; i++) WSACloseEvent(objects[i]);
2111
2112    return res;
2113 }
2114
2115 #endif