10a4fd3439501e9b37941eea96fcf5556d482651
[profile/ivi/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 #define FIX_HZ 1
34
35 #ifdef FIX_HZ
36 # ifndef _MSC_VER
37 #  include <sys/param.h>
38 # endif
39 # ifndef HZ
40 #  define HZ 100
41 # endif
42 #endif
43
44 #ifdef HAVE_EVIL
45 # include <Evil.h>
46 #endif
47
48 #include "Ecore.h"
49 #include "ecore_private.h"
50
51 #ifdef HAVE_SYS_EPOLL_H
52 # define HAVE_EPOLL
53 # include <sys/epoll.h>
54 #endif
55
56 #ifdef USE_G_MAIN_LOOP
57 #include <glib.h>
58 #endif
59
60 struct _Ecore_Fd_Handler
61 {
62    EINA_INLIST;
63    ECORE_MAGIC;
64    int                      fd;
65    Ecore_Fd_Handler_Flags   flags;
66    Ecore_Fd_Cb              func;
67    void                    *data;
68    Ecore_Fd_Cb              buf_func;
69    void                    *buf_data;
70    Ecore_Fd_Prep_Cb         prep_func;
71    void                    *prep_data;
72    int                      references;
73    Eina_Bool                read_active : 1;
74    Eina_Bool                write_active : 1;
75    Eina_Bool                error_active : 1;
76    Eina_Bool                delete_me : 1;
77 };
78
79 #ifdef _WIN32
80 struct _Ecore_Win32_Handler
81 {
82    EINA_INLIST;
83    ECORE_MAGIC;
84    HANDLE         h;
85    Ecore_Fd_Win32_Cb func;
86    void          *data;
87    int            references;
88    Eina_Bool      delete_me : 1;
89 };
90 #endif
91
92
93 static int  _ecore_main_select(double timeout);
94 static void _ecore_main_prepare_handlers(void);
95 static void _ecore_main_fd_handlers_cleanup(void);
96 #ifndef _WIN32
97 static void _ecore_main_fd_handlers_bads_rem(void);
98 #endif
99 static void _ecore_main_fd_handlers_call(void);
100 static int  _ecore_main_fd_handlers_buf_call(void);
101 #ifndef USE_G_MAIN_LOOP
102 static void _ecore_main_loop_iterate_internal(int once_only);
103 #endif
104
105 #ifdef _WIN32
106 static int _ecore_main_win32_select(int nfds, fd_set *readfds, fd_set *writefds,
107                                     fd_set *exceptfds, struct timeval *timeout);
108 static void _ecore_main_win32_handlers_cleanup(void);
109 #endif
110
111 static int               in_main_loop = 0;
112 static int               do_quit = 0;
113 static Ecore_Fd_Handler *fd_handlers = NULL;
114 static Ecore_Fd_Handler *fd_handler_current = NULL;
115 static int               fd_handlers_delete_me = 0;
116 #ifdef _WIN32
117 static Ecore_Win32_Handler *win32_handlers = NULL;
118 static Ecore_Win32_Handler *win32_handler_current = NULL;
119 static int                  win32_handlers_delete_me = 0;
120 #endif
121
122 #ifdef _WIN32
123 static Ecore_Select_Function main_loop_select = _ecore_main_win32_select;
124 #else
125 static Ecore_Select_Function main_loop_select = select;
126 #endif
127
128 static double            t1 = 0.0;
129 static double            t2 = 0.0;
130
131 #ifdef HAVE_EPOLL
132 static int epoll_fd = -1;
133 #endif
134
135 #ifdef USE_G_MAIN_LOOP
136 static GSource *ecore_epoll_source;
137 static GPollFD ecore_epoll_fd;
138 static guint ecore_epoll_id;
139 static GMainLoop* ecore_main_loop;
140 static gboolean ecore_idling;
141 static gboolean ecore_fds_ready;
142 #endif
143
144 static inline int _ecore_poll_events_from_fdh(Ecore_Fd_Handler *fdh)
145 {
146    int events = 0;
147 #ifdef HAVE_EPOLL
148    if (fdh->flags & ECORE_FD_READ)  events |= EPOLLIN;
149    if (fdh->flags & ECORE_FD_WRITE) events |= EPOLLOUT;
150    if (fdh->flags & ECORE_FD_ERROR) events |= EPOLLERR;
151 #endif
152    return events;
153 }
154
155 static inline int _ecore_main_fdh_epoll_add(Ecore_Fd_Handler *fdh)
156 {
157    int r = 0;
158 #ifdef HAVE_EPOLL
159    struct epoll_event ev = {0};
160
161    ev.events = _ecore_poll_events_from_fdh(fdh);
162    ev.data.ptr = fdh;
163    INF("adding poll on %d %08x", fdh->fd, ev.events);
164    r = epoll_ctl(epoll_fd, EPOLL_CTL_ADD, fdh->fd, &ev);
165 #endif
166    return r;
167 }
168
169 static inline void _ecore_main_fdh_epoll_del(Ecore_Fd_Handler *fdh)
170 {
171 #ifdef HAVE_EPOLL
172    struct epoll_event ev = {0};
173    
174    INF("removing poll on %d", fdh->fd);
175    /* could get an EBADF if somebody closed the FD before removing it */
176    if ((epoll_ctl(epoll_fd, EPOLL_CTL_DEL, fdh->fd, &ev) < 0) &&
177        (errno != EBADF))
178      {
179         ERR("Failed to delete epoll fd %d! (errno=%d)", fdh->fd, errno);
180      }
181 #endif
182 }
183
184 static inline int _ecore_main_fdh_epoll_modify(Ecore_Fd_Handler *fdh)
185 {
186    int r = 0;
187 #ifdef HAVE_EPOLL
188    struct epoll_event ev = {0};
189
190    ev.events = _ecore_poll_events_from_fdh(fdh);
191    ev.data.ptr = fdh;
192    INF("modifing epoll on %d to %08x", fdh->fd, ev.events);
193    r = epoll_ctl(epoll_fd, EPOLL_CTL_MOD, fdh->fd, &ev);
194 #endif
195    return r;
196 }
197
198 #ifdef HAVE_EPOLL
199 static inline int _ecore_main_fdh_epoll_mark_active(void)
200 {
201    struct epoll_event ev[32] = {0};
202    int i, ret;
203
204    ret = epoll_wait(epoll_fd, ev, sizeof(ev) / sizeof(struct epoll_event), 0);
205    if (ret < 0)
206      {
207         if (errno == EINTR) return -1;
208         ERR("epoll_wait failed %d", errno);
209         return -1;
210      }
211
212    for (i = 0; i < ret; i++)
213      {
214         Ecore_Fd_Handler *fdh;
215         
216         fdh = ev[i].data.ptr;
217         if (!ECORE_MAGIC_CHECK(fdh, ECORE_MAGIC_FD_HANDLER))
218           {
219              ECORE_MAGIC_FAIL(fdh, ECORE_MAGIC_FD_HANDLER,
220                               "_ecore_main_fdh_epoll_mark_active");
221              continue;
222           }
223         if (fdh->delete_me)
224           {
225              ERR("deleted fd in epoll");
226              continue;
227           }
228         if (ev->events & EPOLLIN)
229           fdh->read_active = 1;
230         if (ev->events & EPOLLOUT)
231           fdh->write_active = 1;
232         if (ev->events & EPOLLERR)
233           fdh->error_active = 1;
234      }
235
236    return ret;
237 }
238 #endif
239
240 #ifdef USE_G_MAIN_LOOP
241
242 /* like we are about to enter main_loop_select in  _ecore_main_select */
243 static gboolean
244 _ecore_main_gsource_prepare(GSource *source, gint *next_time)
245 {
246    double t = _ecore_timer_next_get();
247    gboolean running;
248
249    INF("enter, next timeout in %.1f", t);
250    in_main_loop++;
251
252    if (!ecore_idling)
253      {
254          while (_ecore_timer_call(_ecore_loop_time));
255           _ecore_timer_cleanup();
256
257          /* when idling, busy loop checking the fds only */
258          if (!ecore_idling) _ecore_idle_enterer_call();
259      }
260
261    /* don't check fds if somebody quit */
262    running = g_main_loop_is_running(ecore_main_loop);
263    if (running)
264      {
265         /* only set idling state in dispatch */
266         if (ecore_idling && !_ecore_idler_exist())
267           {
268              if (_ecore_timers_exists())
269                {
270                   double t = _ecore_timer_next_get();
271                   *next_time = (t / 1000.0);
272                }
273              else
274                *next_time = -1;
275           }
276         else
277           *next_time = 0;
278
279         _ecore_main_prepare_handlers();
280      }
281
282    in_main_loop--;
283    INF("leave, timeout = %d", *next_time);
284
285    /* ready if we're not running (about to quit) */
286    return !running;
287 }
288
289 static gboolean
290 _ecore_main_gsource_check(GSource *source)
291 {
292    INF("enter");
293    in_main_loop++;
294
295    ecore_fds_ready = (_ecore_main_fdh_epoll_mark_active() > 0);
296    _ecore_main_fd_handlers_cleanup();
297
298    _ecore_loop_time = ecore_time_get();
299    _ecore_timer_enable_new();
300
301    in_main_loop--;
302    INF("leave");
303
304    return TRUE; /* always dispatch */
305 }
306
307 /* like we just came out of main_loop_select in  _ecore_main_select */
308 static gboolean
309 _ecore_main_gsource_dispatch(GSource *source, GSourceFunc callback, gpointer user_data)
310 {
311    gboolean events_ready, timers_ready, idlers_ready, signals_ready;
312    double next_time = _ecore_timer_next_get();
313
314    events_ready = _ecore_event_exist();
315    timers_ready = _ecore_timers_exists() && (0.0 <= next_time);
316    idlers_ready = _ecore_idler_exist();
317    signals_ready = (_ecore_signal_count_get() > 0);
318
319    in_main_loop++;
320    INF("enter idling=%d fds=%d events=%d signals=%d timers=%d (next=%.2f) idlers=%d",
321        ecore_idling, ecore_fds_ready, events_ready, signals_ready,
322        _ecore_timers_exists(), next_time, idlers_ready);
323
324    if (ecore_idling && events_ready)
325      {
326         INF("calling idle exiters");
327         _ecore_idle_exiter_call();
328         ecore_idling = 0;
329      }
330    else if (!ecore_idling && !events_ready)
331      {
332         INF("start idling");
333         ecore_idling = 1;
334      }
335
336    if (ecore_idling)
337      {
338         INF("calling idler");
339         _ecore_idler_call();
340
341         events_ready = _ecore_event_exist();
342         timers_ready = _ecore_timers_exists() && (0.0 <= next_time);
343         idlers_ready = _ecore_idler_exist();
344
345         if ((ecore_fds_ready || events_ready || timers_ready || idlers_ready || signals_ready))
346           {
347              INF("calling idle exiters");
348              _ecore_idle_exiter_call();
349              ecore_idling = 0;
350           }
351      }
352
353    /* process events */
354    if (!ecore_idling)
355      {
356         INF("work");
357         _ecore_main_fd_handlers_call();
358         _ecore_main_fd_handlers_buf_call();
359         while (_ecore_signal_count_get()) _ecore_signal_call();
360         _ecore_event_call();
361         _ecore_main_fd_handlers_cleanup();
362      }
363
364    in_main_loop--;
365
366    INF("leave");
367
368    return TRUE; /* what should be returned here? */
369 }
370
371 static void
372 _ecore_main_gsource_finalize(GSource *source)
373 {
374    INF("finalize");
375 }
376
377 static GSourceFuncs ecore_gsource_funcs = {
378    .prepare  = _ecore_main_gsource_prepare,
379    .check    = _ecore_main_gsource_check,
380    .dispatch = _ecore_main_gsource_dispatch,
381    .finalize = _ecore_main_gsource_finalize,
382 };
383
384 #endif
385
386 void
387 _ecore_main_loop_init(void)
388 {
389    INF("enter");
390 #ifdef HAVE_EPOLL
391    epoll_fd = epoll_create(1);
392    if (epoll_fd < 0)
393      CRIT("Failed to create epoll fd!");
394 #endif
395
396 #ifdef USE_G_MAIN_LOOP
397    ecore_epoll_source = g_source_new(&ecore_gsource_funcs, sizeof (GSource));
398    if (!ecore_epoll_source)
399      CRIT("Failed to create glib source for epoll!");
400    ecore_epoll_fd.fd = epoll_fd;
401    ecore_epoll_fd.events = G_IO_IN;
402    ecore_epoll_fd.revents = 0;
403    g_source_add_poll(ecore_epoll_source, &ecore_epoll_fd);
404    ecore_epoll_id = g_source_attach(ecore_epoll_source, NULL);
405    if (ecore_epoll_id <= 0)
406      CRIT("Failed to attach glib source to default context");
407 #endif
408    INF("leave");
409 }
410
411 void
412 _ecore_main_loop_shutdown(void)
413 {
414 #ifdef USE_G_MAIN_LOOP
415    g_source_destroy(ecore_epoll_source);
416 #endif
417
418 #ifdef HAVE_EPOLL
419    close(epoll_fd);
420 #endif
421 }
422
423
424 /**
425  * @defgroup Ecore_Main_Loop_Group Main Loop Functions
426  *
427  * These functions control the Ecore event handling loop.  This loop is
428  * designed to work on embedded systems all the way to large and
429  * powerful mutli-cpu workstations.
430  *
431  * It serialises all system signals and events into a single event
432  * queue, that can be easily processed without needing to worry about
433  * concurrency.  A properly written, event-driven program using this
434  * kind of programming does not need threads.  It makes the program very
435  * robust and easy to follow.
436  *
437  * Here is an example of simple program and its basic event loop flow:
438  * @image html prog_flow.png
439  *
440  * For examples of setting up and using a main loop, see
441  * @ref event_handler_example.c and @ref timer_example.c.
442  */
443
444 /**
445  * Runs a single iteration of the main loop to process everything on the
446  * queue.
447  * @ingroup Ecore_Main_Loop_Group
448  */
449 EAPI void
450 ecore_main_loop_iterate(void)
451 {
452 #ifndef USE_G_MAIN_LOOP
453    _ecore_main_loop_iterate_internal(1);
454 #else
455     g_main_context_iteration(NULL, 1);
456 #endif
457 }
458
459 /**
460  * Runs the application main loop.
461  *
462  * This function will not return until @ref ecore_main_loop_quit is called.
463  *
464  * @ingroup Ecore_Main_Loop_Group
465  */
466 EAPI void
467 ecore_main_loop_begin(void)
468 {
469 #ifndef USE_G_MAIN_LOOP
470    in_main_loop++;
471    while (do_quit == 0) _ecore_main_loop_iterate_internal(0);
472    do_quit = 0;
473    in_main_loop--;
474 #else
475    ecore_main_loop = g_main_loop_new(NULL, FALSE);
476    g_main_loop_run(ecore_main_loop);
477 #endif
478 }
479
480 /**
481  * Quits the main loop once all the events currently on the queue have
482  * been processed.
483  * @ingroup Ecore_Main_Loop_Group
484  */
485 EAPI void
486 ecore_main_loop_quit(void)
487 {
488 #ifndef USE_G_MAIN_LOOP
489    do_quit = 1;
490 #else
491    INF("enter");
492    g_main_loop_quit(ecore_main_loop);
493    INF("leave");
494 #endif
495 }
496
497 /**
498  * Sets the function to use when monitoring multiple file descriptors,
499  * and waiting until one of more of the file descriptors before ready
500  * for some class of I/O operation.
501  *
502  * This function will be used instead of the system call select and
503  * could possible be used to integrate the Ecore event loop with an
504  * external event loop.
505  *
506  * @warning you don't know how to use, don't even try to use it.
507  *
508  * @ingroup Ecore_Main_Loop_Group
509  */
510 EAPI void
511 ecore_main_loop_select_func_set(Ecore_Select_Function func)
512 {
513    main_loop_select = func;
514 }
515
516 /**
517  * Gets the select function set by ecore_select_func_set(),
518  * or the native select function if none was set.
519  *
520  * @ingroup Ecore_Main_Loop_Group
521  */
522 EAPI void *
523 ecore_main_loop_select_func_get(void)
524 {
525    return main_loop_select;
526 }
527
528 /**
529  * @defgroup Ecore_FD_Handler_Group File Event Handling Functions
530  *
531  * Functions that deal with file descriptor handlers.
532  */
533
534 /**
535  * Adds a callback for activity on the given file descriptor.
536  *
537  * @p func will be called during the execution of @ref ecore_main_loop_begin
538  * when the file descriptor is available for reading, or writing, or both.
539  *
540  * Normally the return value from the @p func is "zero means this handler is
541  * finished and can be deleted" as is usual for handler callbacks.  However,
542  * if the @p buf_func is supplied, then the return value from the @p func is
543  * "non zero means the handler should be called again in a tight loop".
544  *
545  * @p buf_func is called during event loop handling to check if data that has
546  * been read from the file descriptor is in a buffer and is available to
547  * read.  Some systems (notably xlib) handle their own buffering, and would
548  * otherwise not work with select().  These systems should use a @p buf_func.
549  * This is a most annoying hack, only ecore_x uses it, so refer to that for
550  * an example.  NOTE - @p func should probably return "one" always if
551  * @p buf_func is used, to avoid confusion with the other return value
552  * semantics.
553  *
554  * @param   fd       The file descriptor to watch.
555  * @param   flags    To watch it for read (@c ECORE_FD_READ) and/or
556  *                   (@c ECORE_FD_WRITE) write ability.  @c ECORE_FD_ERROR
557  *
558  * @param   func     The callback function.
559  * @param   data     The data to pass to the callback.
560  * @param   buf_func The function to call to check if any data has been
561  *                   buffered and already read from the fd.  Can be @c NULL.
562  * @param   buf_data The data to pass to the @p buf_func function.
563  * @return  A fd handler handle if successful.  @c NULL otherwise.
564  * @ingroup Ecore_FD_Handler_Group
565  */
566 EAPI Ecore_Fd_Handler *
567 ecore_main_fd_handler_add(int fd, Ecore_Fd_Handler_Flags flags, Ecore_Fd_Cb func, const void *data,
568                           Ecore_Fd_Cb buf_func, const void *buf_data)
569 {
570    Ecore_Fd_Handler *fdh;
571
572    if ((fd < 0) || (flags == 0) || (!func)) return NULL;
573
574    fdh = calloc(1, sizeof(Ecore_Fd_Handler));
575    if (!fdh) return NULL;
576    ECORE_MAGIC_SET(fdh, ECORE_MAGIC_FD_HANDLER);
577    fdh->fd = fd;
578    fdh->flags = flags;
579    if (0 > _ecore_main_fdh_epoll_add(fdh))
580      {
581         ERR("Failed to add epoll fd %d (errno = %d)!", fd, errno);
582         free(fdh);
583         return NULL;
584      }
585    fdh->read_active = 0;
586    fdh->write_active = 0;
587    fdh->error_active = 0;
588    fdh->delete_me = 0;
589    fdh->func = func;
590    fdh->data = (void *)data;
591    fdh->buf_func = buf_func;
592    fdh->buf_data = (void *)buf_data;
593    fd_handlers = (Ecore_Fd_Handler *)
594      eina_inlist_append(EINA_INLIST_GET(fd_handlers),
595                         EINA_INLIST_GET(fdh));
596    return fdh;
597 }
598
599 #ifdef _WIN32
600 EAPI Ecore_Win32_Handler *
601 ecore_main_win32_handler_add(void *h, Ecore_Fd_Win32_Cb func, const void *data)
602 {
603    Ecore_Win32_Handler *wh;
604
605    if (!h || !func) return NULL;
606
607    wh = calloc(1, sizeof(Ecore_Win32_Handler));
608    if (!wh) return NULL;
609    ECORE_MAGIC_SET(wh, ECORE_MAGIC_WIN32_HANDLER);
610    wh->h = (HANDLE)h;
611    wh->delete_me = 0;
612    wh->func = func;
613    wh->data = (void *)data;
614    win32_handlers = (Ecore_Win32_Handler *)
615      eina_inlist_append(EINA_INLIST_GET(win32_handlers),
616                         EINA_INLIST_GET(wh));
617    return wh;
618 }
619 #else
620 EAPI Ecore_Win32_Handler *
621 ecore_main_win32_handler_add(void *h __UNUSED__, Ecore_Fd_Win32_Cb func __UNUSED__,
622                              const void *data __UNUSED__)
623 {
624    return NULL;
625 }
626 #endif
627
628 /**
629  * Deletes the given FD handler.
630  * @param   fd_handler The given FD handler.
631  * @return  The data pointer set using @ref ecore_main_fd_handler_add,
632  *          for @p fd_handler on success.  @c NULL otherwise.
633  * @ingroup Ecore_FD_Handler_Group
634  *
635  * Beware that if the fd is already closed, ecore may complain if it uses
636  * epoll internally, and that in some rare cases this may be able to cause
637  * crashes and instability. Remember to delete your fd handlers before the
638  * fd's they listen to are closed.
639  */
640 EAPI void *
641 ecore_main_fd_handler_del(Ecore_Fd_Handler *fd_handler)
642 {
643    if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
644      {
645         ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
646                          "ecore_main_fd_handler_del");
647         return NULL;
648      }
649    fd_handler->delete_me = 1;
650    fd_handlers_delete_me = 1;
651    _ecore_main_fdh_epoll_del(fd_handler);
652    return fd_handler->data;
653 }
654
655 #ifdef _WIN32
656 EAPI void *
657 ecore_main_win32_handler_del(Ecore_Win32_Handler *win32_handler)
658 {
659    if (!ECORE_MAGIC_CHECK(win32_handler, ECORE_MAGIC_WIN32_HANDLER))
660      {
661         ECORE_MAGIC_FAIL(win32_handler, ECORE_MAGIC_WIN32_HANDLER,
662                          "ecore_main_win32_handler_del");
663         return NULL;
664      }
665    win32_handler->delete_me = 1;
666    win32_handlers_delete_me = 1;
667    return win32_handler->data;
668 }
669 #else
670 EAPI void *
671 ecore_main_win32_handler_del(Ecore_Win32_Handler *win32_handler __UNUSED__)
672 {
673    return NULL;
674 }
675 #endif
676
677 EAPI void
678 ecore_main_fd_handler_prepare_callback_set(Ecore_Fd_Handler *fd_handler, Ecore_Fd_Prep_Cb func, const void *data)
679 {
680    if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
681      {
682         ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
683                          "ecore_main_fd_handler_prepare_callback_set");
684         return;
685      }
686    fd_handler->prep_func = func;
687    fd_handler->prep_data = (void *) data;
688 }
689
690 /**
691  * Retrieves the file descriptor that the given handler is handling.
692  * @param   fd_handler The given FD handler.
693  * @return  The file descriptor the handler is watching.
694  * @ingroup Ecore_FD_Handler_Group
695  */
696 EAPI int
697 ecore_main_fd_handler_fd_get(Ecore_Fd_Handler *fd_handler)
698 {
699    if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
700      {
701         ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
702                          "ecore_main_fd_handler_fd_get");
703         return -1;
704      }
705    return fd_handler->fd;
706 }
707
708 /**
709  * Return if read, write or error, or a combination thereof, is active on the
710  * file descriptor of the given FD handler.
711  * @param   fd_handler The given FD handler.
712  * @param   flags      The flags, @c ECORE_FD_READ, @c ECORE_FD_WRITE or
713  *                     @c ECORE_FD_ERROR to query.
714  * @return  @c 1 if any of the given flags are active. @c 0 otherwise.
715  * @ingroup Ecore_FD_Handler_Group
716  */
717 EAPI int
718 ecore_main_fd_handler_active_get(Ecore_Fd_Handler *fd_handler, Ecore_Fd_Handler_Flags flags)
719 {
720    int ret;
721
722    if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
723      {
724         ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
725                          "ecore_main_fd_handler_active_get");
726         return 0;
727      }
728    ret = 0;
729    if ((flags & ECORE_FD_READ) && (fd_handler->read_active)) ret = 1;
730    if ((flags & ECORE_FD_WRITE) && (fd_handler->write_active)) ret = 1;
731    if ((flags & ECORE_FD_ERROR) && (fd_handler->error_active)) ret = 1;
732    return ret;
733 }
734
735 /**
736  * Set what active streams the given FD handler should be monitoring.
737  * @param   fd_handler The given FD handler.
738  * @param   flags      The flags to be watching.
739  * @ingroup Ecore_FD_Handler_Group
740  */
741 EAPI void
742 ecore_main_fd_handler_active_set(Ecore_Fd_Handler *fd_handler, Ecore_Fd_Handler_Flags flags)
743 {
744    if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
745      {
746         ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
747                          "ecore_main_fd_handler_active_set");
748         return;
749      }
750    fd_handler->flags = flags;
751    if (0 > _ecore_main_fdh_epoll_modify(fd_handler))
752      {
753        ERR("Failed to mod epoll fd %d!", fd_handler->fd);
754      }
755 }
756
757 void
758 _ecore_main_shutdown(void)
759 {
760    if (in_main_loop)
761      {
762        ERR("\n"
763            "*** ECORE WARINING: Calling ecore_shutdown() while still in the main loop.\n"
764            "***                 Program may crash or behave strangely now.");
765         return;
766      }
767    while (fd_handlers)
768      {
769         Ecore_Fd_Handler *fdh;
770
771         fdh = fd_handlers;
772         fd_handlers = (Ecore_Fd_Handler *) eina_inlist_remove(EINA_INLIST_GET(fd_handlers),
773                                                               EINA_INLIST_GET(fdh));
774         ECORE_MAGIC_SET(fdh, ECORE_MAGIC_NONE);
775         free(fdh);
776      }
777    fd_handlers_delete_me = 0;
778    fd_handler_current = NULL;
779
780 #ifdef _WIN32
781    while (win32_handlers)
782      {
783         Ecore_Win32_Handler *wh;
784
785         wh = win32_handlers;
786         win32_handlers = (Ecore_Win32_Handler *) eina_inlist_remove(EINA_INLIST_GET(win32_handlers),
787                                                                     EINA_INLIST_GET(wh));
788         ECORE_MAGIC_SET(wh, ECORE_MAGIC_NONE);
789         free(wh);
790      }
791    win32_handlers_delete_me = 0;
792    win32_handler_current = NULL;
793 #endif
794 }
795
796 static void
797 _ecore_main_prepare_handlers(void)
798 {
799    Ecore_Fd_Handler *fdh;
800
801    /* call the prepare callback for all handlers */
802    EINA_INLIST_FOREACH(fd_handlers, fdh)
803      {
804         if (!fdh->delete_me && fdh->prep_func)
805           {
806              fdh->references++;
807              fdh->prep_func (fdh->prep_data, fdh);
808              fdh->references--;
809           }
810      }
811 }
812
813 static int
814 _ecore_main_select(double timeout)
815 {
816    struct timeval tv, *t;
817    fd_set         rfds, wfds, exfds;
818    int            max_fd;
819    int            ret;
820
821    t = NULL;
822    if ((!finite(timeout)) || (timeout == 0.0))  /* finite() tests for NaN, too big, too small, and infinity.  */
823      {
824         tv.tv_sec = 0;
825         tv.tv_usec = 0;
826         t = &tv;
827      }
828    else if (timeout > 0.0)
829      {
830         int sec, usec;
831
832 #ifdef FIX_HZ
833         timeout += (0.5 / HZ);
834         sec = (int)timeout;
835         usec = (int)((timeout - (double)sec) * 1000000);
836 #else
837         sec = (int)timeout;
838         usec = (int)((timeout - (double)sec) * 1000000);
839 #endif
840         tv.tv_sec = sec;
841         tv.tv_usec = usec;
842         t = &tv;
843      }
844    max_fd = 0;
845    FD_ZERO(&rfds);
846    FD_ZERO(&wfds);
847    FD_ZERO(&exfds);
848
849    /* call the prepare callback for all handlers */
850    _ecore_main_prepare_handlers();
851 #ifndef HAVE_EPOLL
852    Ecore_Fd_Handler *fdh;
853
854    EINA_INLIST_FOREACH(fd_handlers, fdh)
855      {
856         if (!fdh->delete_me)
857           {
858              if (fdh->flags & ECORE_FD_READ)
859                {
860                   FD_SET(fdh->fd, &rfds);
861                   if (fdh->fd > max_fd) max_fd = fdh->fd;
862                }
863              if (fdh->flags & ECORE_FD_WRITE)
864                {
865                   FD_SET(fdh->fd, &wfds);
866                   if (fdh->fd > max_fd) max_fd = fdh->fd;
867                }
868              if (fdh->flags & ECORE_FD_ERROR)
869                {
870                   FD_SET(fdh->fd, &exfds);
871                   if (fdh->fd > max_fd) max_fd = fdh->fd;
872                }
873           }
874      }
875 #else /* HAVE_EPOLL */
876    /* polling on the epoll fd will wake when an fd in the epoll set is active */
877    FD_SET(epoll_fd, &rfds);
878    max_fd = epoll_fd;
879 #endif /* HAVE_EPOLL */
880
881    if (_ecore_signal_count_get()) return -1;
882
883    ret = main_loop_select(max_fd + 1, &rfds, &wfds, &exfds, t);
884
885    _ecore_loop_time = ecore_time_get();
886    if (ret < 0)
887      {
888 #ifndef _WIN32
889         if (errno == EINTR) return -1;
890         else if (errno == EBADF) _ecore_main_fd_handlers_bads_rem();
891 #endif
892      }
893    if (ret > 0)
894      {
895 #ifdef HAVE_EPOLL
896         _ecore_main_fdh_epoll_mark_active();
897 #else /* HAVE_EPOLL */
898         Ecore_Fd_Handler *fdh;
899
900         EINA_INLIST_FOREACH(fd_handlers, fdh)
901           {
902              if (!fdh->delete_me)
903                {
904                   if (FD_ISSET(fdh->fd, &rfds))
905                      fdh->read_active = 1;
906                   if (FD_ISSET(fdh->fd, &wfds))
907                      fdh->write_active = 1;
908                   if (FD_ISSET(fdh->fd, &exfds))
909                      fdh->error_active = 1;
910                }
911           }
912 #endif /* HAVE_EPOLL */
913         _ecore_main_fd_handlers_cleanup();
914 #ifdef _WIN32
915         _ecore_main_win32_handlers_cleanup();
916 #endif
917         return 1;
918      }
919    return 0;
920 }
921
922 #ifndef _WIN32
923 static void
924 _ecore_main_fd_handlers_bads_rem(void)
925 {
926    Ecore_Fd_Handler *fdh;
927    Eina_Inlist *l;
928    int found = 0;
929
930    ERR("Removing bad fds");
931    for (l = EINA_INLIST_GET(fd_handlers); l; )
932      {
933         fdh = (Ecore_Fd_Handler *) l;
934         l = l->next;
935         errno = 0;
936
937         if ((fcntl(fdh->fd, F_GETFD) < 0) && (errno == EBADF))
938           {
939              ERR("Found bad fd at index %d", fdh->fd);
940              if (fdh->flags & ECORE_FD_ERROR)
941                {
942                   ERR("Fd set for error! calling user");
943                   fdh->references++;
944                   if (!fdh->func(fdh->data, fdh))
945                     {
946                        ERR("Fd function err returned 0, remove it");
947                        fdh->delete_me = 1;
948                        fd_handlers_delete_me = 1;
949                        found++;
950                     }
951                   fdh->references--;
952                }
953              else
954                {
955                   ERR("Problematic fd found at %d! setting it for delete", fdh->fd);
956                   fdh->delete_me = 1;
957                   fd_handlers_delete_me = 1;
958                   found++;
959                }
960           }
961     }
962    if (found == 0)
963      {
964 #ifdef HAVE_GLIB
965         ERR("No bad fd found. Maybe a foreign fd from glib?");
966 #else        
967         ERR("No bad fd found. EEEK!");
968 #endif        
969      }
970    _ecore_main_fd_handlers_cleanup();
971 }
972 #endif
973
974 static void
975 _ecore_main_fd_handlers_cleanup(void)
976 {
977    Ecore_Fd_Handler *fdh;
978    Eina_Inlist *l;
979    int deleted_in_use = 0;
980
981    if (!fd_handlers_delete_me) return;
982    for (l = EINA_INLIST_GET(fd_handlers); l; )
983      {
984         fdh = (Ecore_Fd_Handler *) l;
985
986         l = l->next;
987         if (fdh->delete_me)
988           {
989              if (fdh->references)
990                {
991                   deleted_in_use++;
992                   continue;
993                }
994              
995              fd_handlers = (Ecore_Fd_Handler *)
996                 eina_inlist_remove(EINA_INLIST_GET(fd_handlers),
997                                    EINA_INLIST_GET(fdh));
998              ECORE_MAGIC_SET(fdh, ECORE_MAGIC_NONE);
999              free(fdh);
1000           }
1001      }
1002    if (!deleted_in_use) fd_handlers_delete_me = 0;
1003 }
1004
1005 #ifdef _WIN32
1006 static void
1007 _ecore_main_win32_handlers_cleanup(void)
1008 {
1009    Ecore_Win32_Handler *wh;
1010    Eina_Inlist *l;
1011    int deleted_in_use = 0;
1012
1013    if (!win32_handlers_delete_me) return;
1014    for (l = EINA_INLIST_GET(win32_handlers); l; )
1015      {
1016         wh = (Ecore_Win32_Handler *)l;
1017
1018         l = l->next;
1019         if (wh->delete_me)
1020           {
1021              if (wh->references)
1022                {
1023                   deleted_in_use++;
1024                   continue;
1025                }
1026              
1027              win32_handlers = (Ecore_Win32_Handler *)
1028                 eina_inlist_remove(EINA_INLIST_GET(win32_handlers),
1029                                    EINA_INLIST_GET(wh));
1030              ECORE_MAGIC_SET(wh, ECORE_MAGIC_NONE);
1031              free(wh);
1032           }
1033      }
1034    if (!deleted_in_use) win32_handlers_delete_me = 0;
1035 }
1036 #endif
1037
1038 static void
1039 _ecore_main_fd_handlers_call(void)
1040 {
1041    if (!fd_handler_current)
1042      {
1043         /* regular main loop, start from head */
1044         fd_handler_current = fd_handlers;
1045      }
1046    else
1047      {
1048         /* recursive main loop, continue from where we were */
1049         fd_handler_current = (Ecore_Fd_Handler *)EINA_INLIST_GET(fd_handler_current)->next;
1050      }
1051
1052    while (fd_handler_current)
1053      {
1054         Ecore_Fd_Handler *fdh = fd_handler_current;
1055
1056         if (!fdh->delete_me)
1057           {
1058              if ((fdh->read_active) ||
1059                  (fdh->write_active) ||
1060                  (fdh->error_active))
1061                {
1062                   fdh->references++;
1063                   if (!fdh->func(fdh->data, fdh))
1064                     {
1065                        fdh->delete_me = 1;
1066                        fd_handlers_delete_me = 1;
1067                     }
1068                   fdh->references--;
1069
1070                   fdh->read_active = 0;
1071                   fdh->write_active = 0;
1072                   fdh->error_active = 0;
1073                }
1074           }
1075
1076         if (fd_handler_current) /* may have changed in recursive main loops */
1077           fd_handler_current = (Ecore_Fd_Handler *)EINA_INLIST_GET(fd_handler_current)->next;
1078      }
1079 }
1080
1081 static int
1082 _ecore_main_fd_handlers_buf_call(void)
1083 {
1084    Ecore_Fd_Handler *fdh;
1085    int ret;
1086
1087    ret = 0;
1088    EINA_INLIST_FOREACH(fd_handlers, fdh)
1089      {
1090         if (!fdh->delete_me)
1091           {
1092              if (fdh->buf_func)
1093                {
1094                   fdh->references++;
1095                   if (fdh->buf_func(fdh->buf_data, fdh))
1096                     {
1097                        ret |= fdh->func(fdh->data, fdh);
1098                        fdh->read_active = 1;
1099                     }
1100                   fdh->references--;
1101                }
1102           }
1103      }
1104    return ret;
1105 }
1106
1107 #ifndef USE_G_MAIN_LOOP
1108 static void
1109 _ecore_main_loop_iterate_internal(int once_only)
1110 {
1111    double next_time = -1.0;
1112    int    have_event = 0;
1113    int    have_signal;
1114
1115    in_main_loop++;
1116    /* expire any timers */
1117    while (_ecore_timer_call(_ecore_loop_time));
1118    _ecore_timer_cleanup();
1119
1120    /* process signals into events .... */
1121    while (_ecore_signal_count_get()) _ecore_signal_call();
1122    if (_ecore_event_exist())
1123      {
1124         _ecore_idle_enterer_call();
1125         have_event = 1;
1126         _ecore_main_select(0.0);
1127         _ecore_loop_time = ecore_time_get();
1128         _ecore_timer_enable_new();
1129         goto process_events;
1130      }
1131    /* call idle enterers ... */
1132    if (!once_only) _ecore_idle_enterer_call();
1133    else
1134      {
1135         have_event = have_signal = 0;
1136
1137         if (_ecore_main_select(0.0) > 0) have_event = 1;
1138         if (_ecore_signal_count_get() > 0) have_signal = 1;
1139         if (have_signal || have_event)
1140           {
1141              _ecore_loop_time = ecore_time_get();
1142              _ecore_timer_enable_new();
1143              goto process_events;
1144           }
1145      }
1146
1147    /* if these calls caused any buffered events to appear - deal with them */
1148    _ecore_main_fd_handlers_buf_call();
1149
1150    /* if ther are any - jump to processing them */
1151    if (_ecore_event_exist())
1152      {
1153         have_event = 1;
1154         _ecore_main_select(0.0);
1155         _ecore_loop_time = ecore_time_get();
1156         _ecore_timer_enable_new();
1157         goto process_events;
1158      }
1159    if (once_only)
1160      {
1161         _ecore_idle_enterer_call();
1162         in_main_loop--;
1163         _ecore_loop_time = ecore_time_get();
1164         _ecore_timer_enable_new();
1165         return;
1166      }
1167
1168    if (_ecore_fps_debug)
1169      {
1170         t2 = ecore_time_get();
1171         if ((t1 > 0.0) && (t2 > 0.0))
1172           _ecore_fps_debug_runtime_add(t2 - t1);
1173      }
1174    start_loop:
1175    /* any timers re-added as a result of these are allowed to go */
1176    _ecore_timer_enable_new();
1177    if (do_quit)
1178      {
1179         _ecore_loop_time = ecore_time_get();
1180         in_main_loop--;
1181         _ecore_timer_enable_new();
1182         return;
1183      }
1184    if (!_ecore_event_exist())
1185      {
1186         /* init flags */
1187         have_event = have_signal = 0;
1188         next_time = _ecore_timer_next_get();
1189         /* no timers */
1190         if (next_time < 0)
1191           {
1192              /* no idlers */
1193              if (!_ecore_idler_exist())
1194                {
1195                   if (_ecore_main_select(-1.0) > 0) have_event = 1;
1196                }
1197              /* idlers */
1198              else
1199                {
1200                   for (;;)
1201                     {
1202                        if (!_ecore_idler_call()) goto start_loop;
1203                        if (_ecore_event_exist()) break;
1204                        if (_ecore_main_select(0.0) > 0) have_event = 1;
1205                        if (_ecore_signal_count_get() > 0) have_signal = 1;
1206                        if (have_event || have_signal) break;
1207                        if (_ecore_timers_exists()) goto start_loop;
1208                        if (do_quit) break;
1209                     }
1210                }
1211           }
1212         /* timers */
1213         else
1214           {
1215              /* no idlers */
1216              if (!_ecore_idler_exist())
1217                {
1218                   if (_ecore_main_select(next_time) > 0) have_event = 1;
1219                }
1220              /* idlers */
1221              else
1222                {
1223                   for (;;)
1224                     {
1225                        if (!_ecore_idler_call()) goto start_loop;
1226                        if (_ecore_event_exist()) break;
1227                        if (_ecore_main_select(0.0) > 0) have_event = 1;
1228                        if (_ecore_signal_count_get() > 0) have_signal = 1;
1229                        if (have_event || have_signal) break;
1230                        next_time = _ecore_timer_next_get();
1231                        if (next_time <= 0) break;
1232                        if (do_quit) break;
1233                     }
1234                }
1235           }
1236         _ecore_loop_time = ecore_time_get();
1237      }
1238    if (_ecore_fps_debug) t1 = ecore_time_get();
1239    /* we came out of our "wait state" so idle has exited */
1240    if (!once_only) _ecore_idle_exiter_call();
1241    /* call the fd handler per fd that became alive... */
1242    /* this should read or write any data to the monitored fd and then */
1243    /* post events onto the ecore event pipe if necessary */
1244    process_events:
1245    _ecore_main_fd_handlers_call();
1246    _ecore_main_fd_handlers_buf_call();
1247    /* process signals into events .... */
1248    while (_ecore_signal_count_get()) _ecore_signal_call();
1249    /* handle events ... */
1250    _ecore_event_call();
1251    _ecore_main_fd_handlers_cleanup();
1252
1253    if (once_only) _ecore_idle_enterer_call();
1254    in_main_loop--;
1255 }
1256 #endif
1257
1258 #ifdef _WIN32
1259 static int
1260 _ecore_main_win32_select(int nfds __UNUSED__, fd_set *readfds, fd_set *writefds,
1261                          fd_set *exceptfds, struct timeval *tv)
1262 {
1263    HANDLE       objects[MAXIMUM_WAIT_OBJECTS];
1264    int          sockets[MAXIMUM_WAIT_OBJECTS];
1265    Ecore_Fd_Handler *fdh;
1266    Ecore_Win32_Handler *wh;
1267    unsigned int objects_nbr = 0;
1268    unsigned int handles_nbr = 0;
1269    unsigned int events_nbr = 0;
1270    DWORD        result;
1271    DWORD        timeout;
1272    MSG          msg;
1273    unsigned int i;
1274    int          res;
1275
1276    /* Create an event object per socket */
1277    EINA_INLIST_FOREACH(fd_handlers, fdh)
1278      {
1279         WSAEVENT event;
1280         long network_event;
1281
1282         network_event = 0;
1283         if (FD_ISSET(fdh->fd, readfds))
1284           network_event |= FD_READ;
1285         if (FD_ISSET(fdh->fd, writefds))
1286           network_event |= FD_WRITE;
1287         if (FD_ISSET(fdh->fd, exceptfds))
1288           network_event |= FD_OOB;
1289
1290         if (network_event)
1291           {
1292              event = WSACreateEvent();
1293              WSAEventSelect(fdh->fd, event, network_event);
1294              objects[objects_nbr] = event;
1295              sockets[events_nbr] = fdh->fd;
1296              events_nbr++;
1297              objects_nbr++;
1298           }
1299      }
1300
1301    /* store the HANDLEs in the objects to wait for */
1302    EINA_INLIST_FOREACH(win32_handlers, wh)
1303      {
1304         objects[objects_nbr] = wh->h;
1305         handles_nbr++;
1306         objects_nbr++;
1307      }
1308
1309    /* Empty the queue before waiting */
1310    while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
1311      {
1312         TranslateMessage(&msg);
1313         DispatchMessage(&msg);
1314      }
1315
1316    /* Wait for any message sent or posted to this queue */
1317    /* or for one of the passed handles be set to signaled. */
1318    if (!tv)
1319      timeout = INFINITE;
1320    else
1321      timeout = (DWORD)((tv->tv_sec * 1000.0) + (tv->tv_usec / 1000.0));
1322
1323    if (timeout == 0) return 0;
1324
1325    result = MsgWaitForMultipleObjects(objects_nbr, (const HANDLE *)objects, EINA_FALSE,
1326                                       timeout, QS_ALLINPUT);
1327
1328    FD_ZERO(readfds);
1329    FD_ZERO(writefds);
1330    FD_ZERO(exceptfds);
1331
1332    /* The result tells us the type of event we have. */
1333    if (result == WAIT_FAILED)
1334      {
1335         char *msg;
1336
1337         msg = evil_last_error_get();
1338         ERR(" * %s\n", msg);
1339         free(msg);
1340         res = -1;
1341      }
1342    else if (result == WAIT_TIMEOUT)
1343      {
1344         ERR("time out\n");
1345         res = 0;
1346      }
1347    else if (result == (WAIT_OBJECT_0 + objects_nbr))
1348      {
1349         while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
1350           {
1351              TranslateMessage(&msg);
1352              DispatchMessage(&msg);
1353           }
1354
1355         res = 0;
1356      }
1357    else if ((result >= 0) && (result < WAIT_OBJECT_0 + events_nbr))
1358      {
1359         WSANETWORKEVENTS network_event;
1360
1361         WSAEnumNetworkEvents(sockets[result], objects[result], &network_event);
1362
1363         if (network_event.lNetworkEvents & FD_READ)
1364           FD_SET(sockets[result], readfds);
1365         if (network_event.lNetworkEvents & FD_WRITE)
1366           FD_SET(sockets[result], writefds);
1367         if (network_event.lNetworkEvents & FD_OOB)
1368           FD_SET(sockets[result], exceptfds);
1369
1370         res = 1;
1371      }
1372    else if ((result >= (WAIT_OBJECT_0 + events_nbr)) && 
1373             (result < (WAIT_OBJECT_0 + objects_nbr)))
1374      {
1375         if (!win32_handler_current)
1376           {
1377              /* regular main loop, start from head */
1378              win32_handler_current = win32_handlers;
1379           }
1380         else
1381           {
1382              /* recursive main loop, continue from where we were */
1383              win32_handler_current = (Ecore_Win32_Handler *)EINA_INLIST_GET(win32_handler_current)->next;
1384           }
1385
1386         while (win32_handler_current)
1387           {
1388              wh = win32_handler_current;
1389
1390              if (objects[result - WAIT_OBJECT_0] == wh->h)
1391                {
1392                   if (!wh->delete_me)
1393                     {
1394                        wh->references++;
1395                        if (!wh->func(wh->data, wh))
1396                          {
1397                             wh->delete_me = 1;
1398                             win32_handlers_delete_me = 1;
1399                          }
1400                        wh->references--;
1401                     }
1402                }
1403              if (win32_handler_current) /* may have changed in recursive main loops */
1404                win32_handler_current = (Ecore_Win32_Handler *)EINA_INLIST_GET(win32_handler_current)->next;
1405           }
1406         res = 1;
1407      }
1408    else
1409      {
1410         ERR("unknown result...\n");
1411         res = -1;
1412      }
1413
1414    /* Remove event objects again */
1415    for (i = 0; i < events_nbr; i++) WSACloseEvent(objects[i]);
1416
1417    return res;
1418 }
1419 #endif