aboutsummaryrefslogtreecommitdiffstats
path: root/src/lib/ecore/ecore_main.c
blob: d1f4e787f75e3c66de0fb283f91a19d6b40a7654 (plain) (blame)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
2095
2096
2097
2098
2099
2100
2101
2102
2103
2104
2105
2106
2107
2108
2109
2110
2111
2112
2113
2114
2115
2116
2117
2118
2119
2120
2121
2122
2123
2124
2125
2126
2127
2128
2129
2130
2131
2132
2133
2134
2135
2136
2137
2138
2139
2140
2141
2142
2143
2144
2145
2146
2147
2148
2149
2150
2151
2152
2153
2154
2155
2156
2157
2158
2159
2160
2161
2162
2163
2164
2165
2166
2167
2168
2169
2170
2171
2172
2173
2174
2175
2176
2177
2178
2179
2180
2181
2182
2183
2184
2185
2186
2187
2188
2189
2190
2191
2192
2193
2194
2195
2196
2197
2198
2199
2200
2201
2202
2203
2204
2205
2206
2207
2208
2209
2210
2211
2212
2213
2214
2215
2216
2217
2218
2219
2220
2221
2222
2223
2224
2225
2226
2227
2228
2229
2230
2231
2232
2233
2234
2235
2236
2237
2238
2239
2240
2241
2242
2243
2244
2245
2246
2247
2248
2249
2250
2251
2252
2253
2254
2255
2256
2257
2258
2259
2260
2261
2262
2263
2264
2265
2266
2267
2268
2269
2270
2271
2272
2273
2274
2275
2276
2277
2278
2279
2280
2281
2282
2283
2284
2285
2286
2287
2288
2289
2290
2291
2292
2293
2294
2295
2296
2297
2298
2299
2300
2301
2302
2303
2304
2305
2306
2307
2308
2309
2310
2311
2312
2313
2314
2315
2316
2317
2318
2319
2320
2321
2322
2323
2324
2325
2326
2327
2328
2329
2330
2331
2332
2333
2334
2335
2336
2337
2338
2339
2340
2341
2342
2343
2344
2345
2346
2347
2348
2349
2350
2351
2352
2353
2354
2355
2356
2357
2358
2359
2360
2361
2362
2363
2364
2365
2366
2367
2368
2369
2370
2371
2372
2373
#ifdef HAVE_CONFIG_H
# include <config.h>
#endif

#ifdef _WIN32
# define WIN32_LEAN_AND_MEAN
# include <winsock2.h>
# undef WIN32_LEAN_AND_MEAN
# ifndef USER_TIMER_MINIMUM
#  define USER_TIMER_MINIMUM 0x0a
# endif
#endif

#ifdef __SUNPRO_C
# include <ieeefp.h>
# include <string.h>
#endif

#include <stdlib.h>
#include <stdio.h>
#include <unistd.h>
#include <math.h>
#include <sys/types.h>
#include <errno.h>
#include <fcntl.h>
#include <sys/time.h>

#ifdef HAVE_SYSTEMD
# include <systemd/sd-daemon.h>
#endif

#ifdef _MSC_VER
# include <float.h>
#endif

#ifdef HAVE_ISFINITE
# define ECORE_FINITE(t)  isfinite(t)
#else
# ifdef _MSC_VER
#  define ECORE_FINITE(t) _finite(t)
# else
#  define ECORE_FINITE(t) finite(t)
# endif
#endif

//#define FIX_HZ 1

#ifdef FIX_HZ
# ifndef _MSC_VER
#  include <sys/param.h>
# endif
# ifndef HZ
#  define HZ 100
# endif
#endif

#ifdef HAVE_EVIL
# include <Evil.h>
#endif

#include "Ecore.h"
#include "ecore_private.h"

#ifdef HAVE_SYS_EPOLL_H
# define HAVE_EPOLL   1
# include <sys/epoll.h>
#else

# define HAVE_EPOLL   0
# define EPOLLIN      1
# define EPOLLPRI     2
# define EPOLLOUT     4
# define EPOLLERR     8

#define EPOLL_CTL_ADD 1
#define EPOLL_CTL_DEL 2
#define EPOLL_CTL_MOD 3

typedef union epoll_data {
   void    *ptr;
   int      fd;
   uint32_t u32;
   uint64_t u64;
} epoll_data_t;

struct epoll_event
{
   uint32_t     events;
   epoll_data_t data;
};

static inline int
epoll_create(int size EINA_UNUSED)
{
   return -1;
}

static inline int
epoll_wait(int                 epfd EINA_UNUSED,
           struct epoll_event *events EINA_UNUSED,
           int                 maxevents EINA_UNUSED,
           int                 timeout EINA_UNUSED)
{
   return -1;
}

static inline int
epoll_ctl(int                 epfd EINA_UNUSED,
          int                 op EINA_UNUSED,
          int                 fd EINA_UNUSED,
          struct epoll_event *event EINA_UNUSED)
{
   return -1;
}

#endif

#ifdef HAVE_SYS_TIMERFD_H
# include <sys/timerfd.h>
#else
/* fallback code if we don't have real timerfd - reduces number of ifdefs  */
# ifndef CLOCK_MONOTONIC
#  define CLOCK_MONOTONIC 0 /* bogus value */
# endif
# ifndef TFD_NONBLOCK
#  define TFD_NONBLOCK    0 /* bogus value */
# endif
#endif /* HAVE_SYS_TIMERFD_H */

#ifndef TFD_TIMER_ABSTIME
# define TFD_TIMER_ABSTIME (1 << 0)
#endif
#ifndef TFD_TIMER_CANCELON_SET
# define TFD_TIMER_CANCELON_SET (1 << 1)
#endif

#ifndef HAVE_TIMERFD_CREATE
static inline int
timerfd_create(int clockid EINA_UNUSED,
               int flags EINA_UNUSED)
{
   return -1;
}

static inline int
timerfd_settime(int                      fd EINA_UNUSED,
                int                      flags EINA_UNUSED,
                const struct itimerspec *new_value EINA_UNUSED,
                struct itimerspec       *old_value EINA_UNUSED)
{
   return -1;
}

#endif /* HAVE_TIMERFD_CREATE */

#ifdef USE_G_MAIN_LOOP
# include <glib.h>
#endif

#define NS_PER_SEC (1000.0 * 1000.0 * 1000.0)

struct _Ecore_Fd_Handler
{
   EINA_INLIST;
                          ECORE_MAGIC;
   Ecore_Fd_Handler      *next_ready;
   int                    fd;
   Ecore_Fd_Handler_Flags flags;
   Ecore_Fd_Cb            func;
   void                  *data;
   Ecore_Fd_Cb            buf_func;
   void                  *buf_data;
   Ecore_Fd_Prep_Cb       prep_func;
   void                  *prep_data;
   int                    references;
   Eina_Bool              read_active : 1;
   Eina_Bool              write_active : 1;
   Eina_Bool              error_active : 1;
   Eina_Bool              delete_me : 1;
   Eina_Bool              file : 1;
#if defined(USE_G_MAIN_LOOP)
   GPollFD                gfd;
#endif
};
GENERIC_ALLOC_SIZE_DECLARE(Ecore_Fd_Handler);

#ifdef _WIN32
struct _Ecore_Win32_Handler
{
   EINA_INLIST;
                         ECORE_MAGIC;
   HANDLE                h;
   Ecore_Win32_Handle_Cb func;
   void                 *data;
   int                   references;
   Eina_Bool             delete_me : 1;
};
GENERIC_ALLOC_SIZE_DECLARE(Ecore_Win32_Handler);
#endif

#ifndef USE_G_MAIN_LOOP
static int  _ecore_main_select(double timeout);
#endif
static void _ecore_main_prepare_handlers(void);
static void _ecore_main_fd_handlers_cleanup(void);
#ifndef _WIN32
# ifndef USE_G_MAIN_LOOP
static void _ecore_main_fd_handlers_bads_rem(void);
# endif
#endif
static void _ecore_main_fd_handlers_call(void);
static int  _ecore_main_fd_handlers_buf_call(void);
#ifndef USE_G_MAIN_LOOP
static void _ecore_main_loop_iterate_internal(int once_only);
#endif

#ifdef _WIN32
static int _ecore_main_win32_select(int             nfds,
                                    fd_set         *readfds,
                                    fd_set         *writefds,
                                    fd_set         *exceptfds,
                                    struct timeval *timeout);
static void _ecore_main_win32_handlers_cleanup(void);
#endif

static int in_main_loop = 0;
static int do_quit = 0;
static Ecore_Fd_Handler *fd_handlers = NULL;
static Ecore_Fd_Handler *fd_handler_current = NULL;
static Eina_List *fd_handlers_with_prep = NULL;
static Eina_List *file_fd_handlers = NULL;
static Eina_List *fd_handlers_with_buffer = NULL;
static Eina_List *fd_handlers_to_delete = NULL;

/* single linked list of ready fdhs, terminated by loop to self */
static Ecore_Fd_Handler *fd_handlers_to_call;
static Ecore_Fd_Handler *fd_handlers_to_call_current;

#ifdef _WIN32
static Ecore_Win32_Handler *win32_handlers = NULL;
static Ecore_Win32_Handler *win32_handler_current = NULL;
static Eina_List *win32_handlers_to_delete = NULL;
#endif

#ifdef _WIN32
Ecore_Select_Function main_loop_select = _ecore_main_win32_select;
#else
# if !defined EXOTIC_NO_SELECT
#   include <sys/select.h>
Ecore_Select_Function main_loop_select = select;
# else
Ecore_Select_Function main_loop_select = NULL;
# endif
#endif

#ifndef USE_G_MAIN_LOOP
static double t1 = 0.0;
static double t2 = 0.0;
#endif

static int timer_fd = -1;
static int epoll_fd = -1;
static pid_t epoll_pid;

#ifdef USE_G_MAIN_LOOP
static GPollFD ecore_epoll_fd;
static GPollFD ecore_timer_fd;
static GSource *ecore_glib_source;
static guint ecore_glib_source_id;
static GMainLoop *ecore_main_loop;
static gboolean ecore_idling;
static gboolean _ecore_glib_idle_enterer_called;
static gboolean ecore_fds_ready;
#endif

void
_ecore_fd_close_on_exec(int fd)
{
#ifdef HAVE_FCNTL
   int flags;

   flags = fcntl(fd, F_GETFD);
   if (flags == -1) return;
   flags |= FD_CLOEXEC;
   if (fcntl(fd, F_SETFD, flags) == -1)  return;
#else
   (void) fd;
#endif
}

static inline void
_ecore_fd_valid(void)
{
   if (HAVE_EPOLL && epoll_fd >= 0)
     {
        if (fcntl(epoll_fd, F_GETFD) < 0)
          {
             ERR("arghhh you caught me! report a backtrace to edevel!");
#ifdef HAVE_PAUSE
             pause();
#else
             sleep(60);
#endif
          }
     }
}

static inline void
_ecore_try_add_to_call_list(Ecore_Fd_Handler *fdh)
{
   /* check if this fdh is already in the list */
   if (fdh->next_ready)
     return;
   if (fdh->read_active || fdh->write_active || fdh->error_active)
     {
        /*
         * make sure next_ready is non-null by pointing to ourselves
         * use that to indicate this fdh is in the ready list
         * insert at the head of the list to avoid trouble
         */
        fdh->next_ready = fd_handlers_to_call ? fd_handlers_to_call : fdh;
        fd_handlers_to_call = fdh;
     }
}

static inline int
_ecore_get_epoll_fd(void)
{
   if (epoll_pid && epoll_pid != getpid())
     {
        /* forked! */
        _ecore_main_loop_shutdown();
     }
   if (epoll_pid == 0 && epoll_fd < 0)
     {
        _ecore_main_loop_init();
     }
   return epoll_fd;
}

static inline int
_ecore_epoll_add(int   efd,
                 int   fd,
                 int   events,
                 void *ptr)
{
   struct epoll_event ev;

   memset(&ev, 0, sizeof (ev));
   ev.events = events;
   ev.data.ptr = ptr;
   DBG("adding poll on %d %08x", fd, events);
   return epoll_ctl(efd, EPOLL_CTL_ADD, fd, &ev);
}

static inline int
_ecore_poll_events_from_fdh(Ecore_Fd_Handler *fdh)
{
   int events = 0;
   if (fdh->flags & ECORE_FD_READ) events |= EPOLLIN;
   if (fdh->flags & ECORE_FD_WRITE) events |= EPOLLOUT;
   if (fdh->flags & ECORE_FD_ERROR) events |= EPOLLERR | EPOLLPRI;
   return events;
}

#ifdef USE_G_MAIN_LOOP
static inline int
_gfd_events_from_fdh(Ecore_Fd_Handler *fdh)
{
   int events = 0;
   if (fdh->flags & ECORE_FD_READ) events |= G_IO_IN;
   if (fdh->flags & ECORE_FD_WRITE) events |= G_IO_OUT;
   if (fdh->flags & ECORE_FD_ERROR) events |= G_IO_ERR;
   return events;
}
#endif

static inline int
_ecore_main_fdh_poll_add(Ecore_Fd_Handler *fdh)
{
   int r = 0;

   if ((!fdh->file) && HAVE_EPOLL && epoll_fd >= 0)
     {
        r = _ecore_epoll_add(_ecore_get_epoll_fd(), fdh->fd,
                             _ecore_poll_events_from_fdh(fdh), fdh);
     }
#ifdef USE_G_MAIN_LOOP
   else
     {
        fdh->gfd.fd = fdh->fd;
        fdh->gfd.events = _gfd_events_from_fdh(fdh);
        fdh->gfd.revents = 0;
        DBG("adding gpoll on %d %08x", fdh->fd, fdh->gfd.events);
        g_source_add_poll(ecore_glib_source, &fdh->gfd);
     }
#endif
   return r;
}

static inline void
_ecore_main_fdh_poll_del(Ecore_Fd_Handler *fdh)
{
   if ((!fdh->file) && HAVE_EPOLL && epoll_fd >= 0)
     {
        struct epoll_event ev;
        int efd = _ecore_get_epoll_fd();

        memset(&ev, 0, sizeof (ev));
        DBG("removing poll on %d", fdh->fd);
        /* could get an EBADF if somebody closed the FD before removing it */
        if ((epoll_ctl(efd, EPOLL_CTL_DEL, fdh->fd, &ev) < 0))
          {
             if (errno == EBADF)
               {
                  WRN("fd %d was closed, can't remove from epoll - reinit!",
                      fdh->fd);
                  _ecore_main_loop_shutdown();
                  _ecore_main_loop_init();
               }
             else
               {
                  ERR("Failed to delete epoll fd %d! (errno=%d)", fdh->fd, errno);
               }
          }
     }
#ifdef USE_G_MAIN_LOOP
   else
     {
        fdh->gfd.fd = fdh->fd;
        fdh->gfd.events = _gfd_events_from_fdh(fdh);
        fdh->gfd.revents = 0;
        DBG("removing gpoll on %d %08x", fdh->fd, fdh->gfd.events);
        g_source_remove_poll(ecore_glib_source, &fdh->gfd);
     }
#endif
}

static inline int
_ecore_main_fdh_poll_modify(Ecore_Fd_Handler *fdh)
{
   int r = 0;
   if ((!fdh->file) && HAVE_EPOLL && epoll_fd >= 0)
     {
        struct epoll_event ev;
        int efd = _ecore_get_epoll_fd();

        memset(&ev, 0, sizeof (ev));
        ev.events = _ecore_poll_events_from_fdh(fdh);
        ev.data.ptr = fdh;
        DBG("modifing epoll on %d to %08x", fdh->fd, ev.events);
        r = epoll_ctl(efd, EPOLL_CTL_MOD, fdh->fd, &ev);
     }
#ifdef USE_G_MAIN_LOOP
   else
     {
        fdh->gfd.fd = fdh->fd;
        fdh->gfd.events = _gfd_events_from_fdh(fdh);
        fdh->gfd.revents = 0;
        DBG("modifing gpoll on %d to %08x", fdh->fd, fdh->gfd.events);
     }
#endif
   return r;
}

static inline int
_ecore_main_fdh_epoll_mark_active(void)
{
   struct epoll_event ev[32];
   int i, ret;
   int efd = _ecore_get_epoll_fd();

   memset(&ev, 0, sizeof (ev));
   ret = epoll_wait(efd, ev, sizeof(ev) / sizeof(struct epoll_event), 0);
   if (ret < 0)
     {
        if (errno == EINTR) return -1;
        ERR("epoll_wait failed on fd: %d %s", efd, strerror(errno));
        return -1;
     }

   for (i = 0; i < ret; i++)
     {
        Ecore_Fd_Handler *fdh;

        fdh = ev[i].data.ptr;
        if (!ECORE_MAGIC_CHECK(fdh, ECORE_MAGIC_FD_HANDLER))
          {
             ECORE_MAGIC_FAIL(fdh, ECORE_MAGIC_FD_HANDLER,
                              "_ecore_main_fdh_epoll_mark_active");
             continue;
          }
        if (fdh->delete_me)
          {
             ERR("deleted fd in epoll");
             continue;
          }

        if (ev[i].events & EPOLLIN)
          fdh->read_active = EINA_TRUE;
        if (ev[i].events & EPOLLOUT)
          fdh->write_active = EINA_TRUE;
        if (ev[i].events & EPOLLERR)
          fdh->error_active = EINA_TRUE;

        _ecore_try_add_to_call_list(fdh);
     }

   return ret;
}

#ifdef USE_G_MAIN_LOOP

static inline int
_ecore_main_fdh_glib_mark_active(void)
{
   Ecore_Fd_Handler *fdh;
   int ret = 0;

   /* call the prepare callback for all handlers */
   EINA_INLIST_FOREACH(fd_handlers, fdh)
     {
        if (fdh->delete_me)
          continue;

        if (fdh->gfd.revents & G_IO_IN)
          fdh->read_active = EINA_TRUE;
        if (fdh->gfd.revents & G_IO_OUT)
          fdh->write_active = EINA_TRUE;
        if (fdh->gfd.revents & G_IO_ERR)
          fdh->error_active = EINA_TRUE;

        _ecore_try_add_to_call_list(fdh);

        if (fdh->gfd.revents & (G_IO_IN | G_IO_OUT | G_IO_ERR)) ret++;
     }

   return ret;
}

/* like we are about to enter main_loop_select in  _ecore_main_select */
static gboolean
_ecore_main_gsource_prepare(GSource *source EINA_UNUSED,
                            gint    *next_time)
{
   gboolean ready = FALSE;

   _ecore_lock();
   in_main_loop++;

   if (!ecore_idling && !_ecore_glib_idle_enterer_called)
     {
        _ecore_time_loop_time = ecore_time_get();
        _ecore_timer_expired_timers_call(_ecore_time_loop_time);
        _ecore_timer_cleanup();

        _ecore_idle_enterer_call();
        _ecore_throttle();
        _ecore_glib_idle_enterer_called = FALSE;

        if (fd_handlers_with_buffer)
          _ecore_main_fd_handlers_buf_call();
     }

   _ecore_signal_received_process();

   /* don't check fds if somebody quit */
   if (g_main_loop_is_running(ecore_main_loop))
     {
        /* only set idling state in dispatch */
         if (ecore_idling && !_ecore_idler_exist() && !_ecore_event_exist())
           {
              if (_ecore_timers_exists())
                {
                   int r = -1;
                   double t = _ecore_timer_next_get();
                   if (timer_fd >= 0 && t > 0.0)
                     {
                        struct itimerspec ts;

                        ts.it_interval.tv_sec = 0;
                        ts.it_interval.tv_nsec = 0;
                        ts.it_value.tv_sec = t;
                        ts.it_value.tv_nsec = fmod(t * NS_PER_SEC, NS_PER_SEC);

     /* timerfd cannot sleep for 0 time */
                        if (ts.it_value.tv_sec || ts.it_value.tv_nsec)
                          {
                             r = timerfd_settime(timer_fd, 0, &ts, NULL);
                             if (r < 0)
                               {
                                  ERR("timer set returned %d (errno=%d)", r, errno);
                                  close(timer_fd);
                                  timer_fd = -1;
                               }
                             else
                               INF("sleeping for %ld s %06ldus",
                                   ts.it_value.tv_sec,
                                   ts.it_value.tv_nsec / 1000);
                          }
                     }
                   if (r == -1)
                     {
                        *next_time = ceil(t * 1000.0);
                        if (t == 0.0)
                          ready = TRUE;
                     }
                }
              else
                *next_time = -1;
           }
         else
           {
              *next_time = 0;
              if (_ecore_event_exist())
                ready = TRUE;
           }

         if (fd_handlers_with_prep)
           _ecore_main_prepare_handlers();
     }
   else
     ready = TRUE;

   in_main_loop--;
   DBG("leave, timeout = %d", *next_time);
   _ecore_unlock();

   /* ready if we're not running (about to quit) */
   return ready;
}

static gboolean
_ecore_main_gsource_check(GSource *source EINA_UNUSED)
{
   gboolean ret = FALSE;

   _ecore_lock();
   in_main_loop++;

   /* check if old timers expired */
   if (ecore_idling && !_ecore_idler_exist() && !_ecore_event_exist())
     {
        if (timer_fd >= 0)
          {
             uint64_t count = 0;
             int r = read(timer_fd, &count, sizeof count);
             if (r == -1 && errno == EAGAIN)
               ;
             else if (r == sizeof count)
               ret = TRUE;
             else
               {
     /* unexpected things happened... fail back to old way */
                   ERR("timer read returned %d (errno=%d)", r, errno);
                   close(timer_fd);
                   timer_fd = -1;
               }
          }
     }
   else
     ret = TRUE;

   /* check if fds are ready */
   if (HAVE_EPOLL && epoll_fd >= 0)
     ecore_fds_ready = (_ecore_main_fdh_epoll_mark_active() > 0);
   else
     ecore_fds_ready = (_ecore_main_fdh_glib_mark_active() > 0);
   _ecore_main_fd_handlers_cleanup();
   if (ecore_fds_ready)
     ret = TRUE;

   /* check timers after updating loop time */
   if (!ret && _ecore_timers_exists())
     ret = (0.0 == _ecore_timer_next_get());

   in_main_loop--;
   _ecore_unlock();

   return ret;
}

/* like we just came out of main_loop_select in  _ecore_main_select */
static gboolean
_ecore_main_gsource_dispatch(GSource    *source EINA_UNUSED,
                             GSourceFunc callback EINA_UNUSED,
                             gpointer    user_data EINA_UNUSED)
{
   gboolean events_ready, timers_ready, idlers_ready;
   double next_time;

   _ecore_lock();
   _ecore_time_loop_time = ecore_time_get();
   _ecore_timer_enable_new();
   next_time = _ecore_timer_next_get();

   events_ready = _ecore_event_exist();
   timers_ready = _ecore_timers_exists() && (0.0 == next_time);
   idlers_ready = _ecore_idler_exist();

   in_main_loop++;
   DBG("enter idling=%d fds=%d events=%d timers=%d (next=%.2f) idlers=%d",
       ecore_idling, ecore_fds_ready, events_ready,
       timers_ready, next_time, idlers_ready);

   if (ecore_idling && events_ready)
     {
        _ecore_animator_run_reset();
        _ecore_idle_exiter_call();
        ecore_idling = 0;
     }
   else if (!ecore_idling && !events_ready)
     {
        ecore_idling = 1;
     }

   if (ecore_idling)
     {
        _ecore_idler_all_call();

        events_ready = _ecore_event_exist();

        if (ecore_fds_ready || events_ready || timers_ready)
          {
             _ecore_animator_run_reset();
             _ecore_idle_exiter_call();
             ecore_idling = 0;
          }
     }

   /* process events */
   if (!ecore_idling)
     {
        _ecore_main_fd_handlers_call();
        if (fd_handlers_with_buffer)
          _ecore_main_fd_handlers_buf_call();
        _ecore_signal_received_process();
        _ecore_event_call();
        _ecore_main_fd_handlers_cleanup();

        _ecore_timer_expired_timers_call(_ecore_time_loop_time);
        _ecore_timer_cleanup();

        _ecore_idle_enterer_call();
        _ecore_throttle();
        _ecore_glib_idle_enterer_called = TRUE;

        if (fd_handlers_with_buffer)
          _ecore_main_fd_handlers_buf_call();
     }

   in_main_loop--;
   _ecore_unlock();

   return TRUE; /* what should be returned here? */
}

static void
_ecore_main_gsource_finalize(GSource *source EINA_UNUSED)
{
}

static GSourceFuncs ecore_gsource_funcs =
{
   .prepare = _ecore_main_gsource_prepare,
   .check = _ecore_main_gsource_check,
   .dispatch = _ecore_main_gsource_dispatch,
   .finalize = _ecore_main_gsource_finalize,
};

#endif

#ifdef HAVE_SYS_TIMERFD_H
static int realtime_fd = -1;

static void detect_time_changes_start(void);
static Eina_Bool
_realtime_update(void *data EINA_UNUSED, Ecore_Fd_Handler *fdh EINA_UNUSED)
{
   char buf[64];

   if (read(realtime_fd, buf, sizeof(buf)) >= 0) return EINA_TRUE;

   DBG("system clock changed");
   ecore_event_add(ECORE_EVENT_SYSTEM_TIMEDATE_CHANGED, NULL, NULL, NULL);

   close(realtime_fd);
   realtime_fd = -1;
   detect_time_changes_start();
   return EINA_FALSE;
}
#endif

static void
detect_time_changes_start(void)
{
#ifdef HAVE_SYS_TIMERFD_H
   struct itimerspec its;

   if (realtime_fd >= 0) return;

   realtime_fd = timerfd_create(CLOCK_REALTIME, TFD_NONBLOCK | TFD_CLOEXEC);
   if (realtime_fd < 0) return;

   memset(&its, 0, sizeof(its));
   its.it_value.tv_sec += 0xfffffff0; // end of time - 0xf
   if (timerfd_settime(realtime_fd,
                       TFD_TIMER_ABSTIME | TFD_TIMER_CANCELON_SET,
                       &its, NULL) < 0)
     {
        WRN("Couldn't arm timerfd to detect clock changes: %s",
            strerror(errno));
        close(realtime_fd);
        realtime_fd = -1;
        return;
     }

   ecore_main_fd_handler_add(realtime_fd, ECORE_FD_READ,
                             _realtime_update, NULL, NULL, NULL);
#endif
}

static void
detect_time_changes_stop(void)
{
#ifdef HAVE_SYS_TIMERFD_H
   if (realtime_fd > 0)
     {
        close(realtime_fd);
        realtime_fd = -1;
     }
#endif
}

void
_ecore_main_loop_init(void)
{
   epoll_fd = epoll_create(1);
   if ((epoll_fd < 0) && HAVE_EPOLL)
     WRN("Failed to create epoll fd!");
   epoll_pid = getpid();
   _ecore_fd_close_on_exec(epoll_fd);

   /* add polls on all our file descriptors */
   Ecore_Fd_Handler *fdh;
   EINA_INLIST_FOREACH(fd_handlers, fdh)
     {
        if (fdh->delete_me)
          continue;
        _ecore_epoll_add(epoll_fd, fdh->fd,
                         _ecore_poll_events_from_fdh(fdh), fdh);
        _ecore_main_fdh_poll_add(fdh);
     }

   /* setup for the g_main_loop only integration */
#ifdef USE_G_MAIN_LOOP
   ecore_glib_source = g_source_new(&ecore_gsource_funcs, sizeof (GSource));
   if (!ecore_glib_source)
     CRI("Failed to create glib source for epoll!");
   else
     {
        g_source_set_priority(ecore_glib_source, G_PRIORITY_HIGH_IDLE + 20);
        if (HAVE_EPOLL && epoll_fd >= 0)
          {
             /* epoll multiplexes fds into the g_main_loop */
              ecore_epoll_fd.fd = epoll_fd;
              ecore_epoll_fd.events = G_IO_IN;
              ecore_epoll_fd.revents = 0;
              g_source_add_poll(ecore_glib_source, &ecore_epoll_fd);
          }

        /* timerfd gives us better than millisecond accuracy in g_main_loop */
        timer_fd = timerfd_create(CLOCK_MONOTONIC, TFD_NONBLOCK);
        if (timer_fd < 0)
          WRN("failed to create timer fd!");
        else
          {
             _ecore_fd_close_on_exec(timer_fd);
             ecore_timer_fd.fd = timer_fd;
             ecore_timer_fd.events = G_IO_IN;
             ecore_timer_fd.revents = 0;
             g_source_add_poll(ecore_glib_source, &ecore_timer_fd);
          }

        ecore_glib_source_id = g_source_attach(ecore_glib_source, NULL);
        if (ecore_glib_source_id <= 0)
          CRI("Failed to attach glib source to default context");
     }
#endif

   detect_time_changes_start();
}

void
_ecore_main_loop_shutdown(void)
{
#ifdef USE_G_MAIN_LOOP
   if (ecore_glib_source)
     {
        g_source_destroy(ecore_glib_source);
        ecore_glib_source = NULL;
     }
#endif

   detect_time_changes_stop();

   if (epoll_fd >= 0)
     {
        close(epoll_fd);
        epoll_fd = -1;
     }
   epoll_pid = 0;

   if (timer_fd >= 0)
     {
        close(timer_fd);
        timer_fd = -1;
     }
}

void *
_ecore_main_fd_handler_del(Ecore_Fd_Handler *fd_handler)
{
   if (fd_handler->delete_me)
     {
        ERR("fdh %p deleted twice", fd_handler);
        return NULL;
     }

   _ecore_main_fdh_poll_del(fd_handler);
   fd_handler->delete_me = EINA_TRUE;
   fd_handlers_to_delete = eina_list_append(fd_handlers_to_delete, fd_handler);
   if (fd_handler->prep_func && fd_handlers_with_prep)
     fd_handlers_with_prep = eina_list_remove(fd_handlers_with_prep, fd_handler);
   if (fd_handler->buf_func && fd_handlers_with_buffer)
     fd_handlers_with_buffer = eina_list_remove(fd_handlers_with_buffer, fd_handler);
   return fd_handler->data;
}

EAPI void
ecore_main_loop_iterate(void)
{
   EINA_MAIN_LOOP_CHECK_RETURN;
#ifndef USE_G_MAIN_LOOP
   _ecore_lock();
   _ecore_time_loop_time = ecore_time_get();
   _ecore_main_loop_iterate_internal(1);
   _ecore_unlock();
#else
   g_main_context_iteration(NULL, 0);
#endif
}

EAPI int
ecore_main_loop_iterate_may_block(int may_block)
{
   EINA_MAIN_LOOP_CHECK_RETURN_VAL(0);
#ifndef USE_G_MAIN_LOOP
   _ecore_lock();
   _ecore_time_loop_time = ecore_time_get();
in_main_loop++;
   _ecore_main_loop_iterate_internal(!may_block);
in_main_loop--;
   _ecore_unlock();
   return _ecore_event_exist();
#else
   return g_main_context_iteration(NULL, may_block);
#endif
}

EAPI void
ecore_main_loop_begin(void)
{
   EINA_MAIN_LOOP_CHECK_RETURN;
   if (in_main_loop > 0)
     {
        ERR("Running ecore_main_loop_begin() inside an existing main loop");
        return;
     }
   eina_evlog("+mainloop", NULL, 0.0, NULL);
#ifdef HAVE_SYSTEMD
   sd_notify(0, "READY=1");
#endif
#ifndef USE_G_MAIN_LOOP
   _ecore_lock();
   in_main_loop++;
   _ecore_time_loop_time = ecore_time_get();
   while (do_quit == 0) _ecore_main_loop_iterate_internal(0);
   do_quit = 0;
   in_main_loop--;
   _ecore_unlock();
#else
   if (!do_quit)
     {
        if (!ecore_main_loop)
          ecore_main_loop = g_main_loop_new(NULL, FALSE);
        g_main_loop_run(ecore_main_loop);
     }
   do_quit = 0;
#endif
   eina_evlog("-mainloop", NULL, 0.0, NULL);
}

EAPI void
ecore_main_loop_quit(void)
{
   EINA_MAIN_LOOP_CHECK_RETURN;
   do_quit = 1;
#ifdef USE_G_MAIN_LOOP
   if (ecore_main_loop)
     g_main_loop_quit(ecore_main_loop);
#endif
}

EAPI int 
ecore_main_loop_nested_get(void)
{
   return in_main_loop;
}

EAPI Eina_Bool
ecore_main_loop_animator_ticked_get(void)
{
   return _ecore_animator_run_get();
}

EAPI void
ecore_main_loop_select_func_set(Ecore_Select_Function func)
{
   EINA_MAIN_LOOP_CHECK_RETURN;
   main_loop_select = func;
}

EAPI Ecore_Select_Function
ecore_main_loop_select_func_get(void)
{
   EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
   return main_loop_select;
}

Ecore_Fd_Handler *
_ecore_main_fd_handler_add(int                    fd,
                           Ecore_Fd_Handler_Flags flags,
                           Ecore_Fd_Cb            func,
                           const void            *data,
                           Ecore_Fd_Cb            buf_func,
                           const void            *buf_data,
                           Eina_Bool              is_file)
{
   Ecore_Fd_Handler *fdh = NULL;

   if ((fd < 0) || (flags == 0) || (!func)) return NULL;

   fdh = ecore_fd_handler_calloc(1);
   if (!fdh) return NULL;
   ECORE_MAGIC_SET(fdh, ECORE_MAGIC_FD_HANDLER);
   fdh->next_ready = NULL;
   fdh->fd = fd;
   fdh->flags = flags;
   fdh->file = is_file;
   if (_ecore_main_fdh_poll_add(fdh) < 0)
     {
        int err = errno;
        ERR("Failed to add poll on fd %d (errno = %d: %s)!", fd, err, strerror(err));
        ecore_fd_handler_mp_free(fdh);
        return NULL;
     }
   fdh->read_active = EINA_FALSE;
   fdh->write_active = EINA_FALSE;
   fdh->error_active = EINA_FALSE;
   fdh->delete_me = EINA_FALSE;
   fdh->func = func;
   fdh->data = (void *)data;
   fdh->buf_func = buf_func;
   if (buf_func)
     fd_handlers_with_buffer = eina_list_append(fd_handlers_with_buffer, fdh);
   fdh->buf_data = (void *)buf_data;
   fd_handlers = (Ecore_Fd_Handler *)
     eina_inlist_append(EINA_INLIST_GET(fd_handlers),
                        EINA_INLIST_GET(fdh));

   return fdh;
}

EAPI Ecore_Fd_Handler *
ecore_main_fd_handler_add(int                    fd,
                          Ecore_Fd_Handler_Flags flags,
                          Ecore_Fd_Cb            func,
                          const void            *data,
                          Ecore_Fd_Cb            buf_func,
                          const void            *buf_data)
{
   Ecore_Fd_Handler *fdh = NULL;
   EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
   _ecore_lock();
   fdh = _ecore_main_fd_handler_add(fd, flags, func, data, buf_func, buf_data, EINA_FALSE);
   _ecore_unlock();
   return fdh;
}

EAPI Ecore_Fd_Handler *
ecore_main_fd_handler_file_add(int                    fd,
                               Ecore_Fd_Handler_Flags flags,
                               Ecore_Fd_Cb            func,
                               const void            *data,
                               Ecore_Fd_Cb            buf_func,
                               const void            *buf_data)
{
   Ecore_Fd_Handler *fdh = NULL;
   EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
   _ecore_lock();
   fdh = _ecore_main_fd_handler_add(fd, flags, func, data, buf_func, buf_data, EINA_TRUE);
   _ecore_unlock();

   return fdh;
}

#ifdef _WIN32
EAPI Ecore_Win32_Handler *
ecore_main_win32_handler_add(void                 *h,
                             Ecore_Win32_Handle_Cb func,
                             const void           *data)
{
   Ecore_Win32_Handler *wh;

   EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
   if (!h || !func) return NULL;

   wh = ecore_win32_handler_calloc(1);
   if (!wh) return NULL;
   ECORE_MAGIC_SET(wh, ECORE_MAGIC_WIN32_HANDLER);
   wh->h = (HANDLE)h;
   wh->delete_me = EINA_FALSE;
   wh->func = func;
   wh->data = (void *)data;
   win32_handlers = (Ecore_Win32_Handler *)
     eina_inlist_append(EINA_INLIST_GET(win32_handlers),
                        EINA_INLIST_GET(wh));
   return wh;
}

#else
EAPI Ecore_Win32_Handler *
ecore_main_win32_handler_add(void                 *h EINA_UNUSED,
                             Ecore_Win32_Handle_Cb func EINA_UNUSED,
                             const void           *data EINA_UNUSED)
{
   return NULL;
}

#endif

EAPI void *
ecore_main_fd_handler_del(Ecore_Fd_Handler *fd_handler)
{
   void *ret = NULL;

   if (!fd_handler) return NULL;
   EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
   _ecore_lock();

   if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
     {
        ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
                         "ecore_main_fd_handler_del");
        goto unlock;
     }
   ret = _ecore_main_fd_handler_del(fd_handler);
unlock:
   _ecore_unlock();
   return ret;
}

#ifdef _WIN32
static void *
_ecore_main_win32_handler_del(Ecore_Win32_Handler *win32_handler)
{
   if (win32_handler->delete_me)
     {
        ERR("win32 handler %p deleted twice", win32_handler);
        return NULL;
     }

   win32_handler->delete_me = EINA_TRUE;
   win32_handlers_to_delete = eina_list_append(win32_handlers_to_delete, win32_handler);
   return win32_handler->data;
}

EAPI void *
ecore_main_win32_handler_del(Ecore_Win32_Handler *win32_handler)
{
   void *ret = NULL;

   if (!win32_handler) return NULL;
   EINA_MAIN_LOOP_CHECK_RETURN_VAL(NULL);
   if (!ECORE_MAGIC_CHECK(win32_handler, ECORE_MAGIC_WIN32_HANDLER))
     {
        ECORE_MAGIC_FAIL(win32_handler, ECORE_MAGIC_WIN32_HANDLER,
                         "ecore_main_win32_handler_del");
        return NULL;
     }
   ret = _ecore_main_win32_handler_del(win32_handler);
   return ret;
}

#else
EAPI void *
ecore_main_win32_handler_del(Ecore_Win32_Handler *win32_handler EINA_UNUSED)
{
   return NULL;
}

#endif

EAPI void
ecore_main_fd_handler_prepare_callback_set(Ecore_Fd_Handler *fd_handler,
                                           Ecore_Fd_Prep_Cb  func,
                                           const void       *data)
{
   EINA_MAIN_LOOP_CHECK_RETURN;
   _ecore_lock();

   if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
     {
        ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
                         "ecore_main_fd_handler_prepare_callback_set");
        goto unlock;
     }
   fd_handler->prep_func = func;
   fd_handler->prep_data = (void *)data;
   if ((!fd_handlers_with_prep) ||
       (fd_handlers_with_prep && (!eina_list_data_find(fd_handlers_with_prep, fd_handler))))
     /* FIXME: THIS WILL NOT SCALE WITH LOTS OF PREP FUNCTIONS!!! */
     fd_handlers_with_prep = eina_list_append(fd_handlers_with_prep, fd_handler);
unlock:
   _ecore_unlock();
}

EAPI int
ecore_main_fd_handler_fd_get(Ecore_Fd_Handler *fd_handler)
{
   int fd = -1;

   EINA_MAIN_LOOP_CHECK_RETURN_VAL(-1);
   _ecore_lock();

   if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
     {
        ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
                         "ecore_main_fd_handler_fd_get");
        goto unlock;
     }
   fd = fd_handler->fd;
unlock:
   _ecore_unlock();
   return fd;
}

EAPI Eina_Bool
ecore_main_fd_handler_active_get(Ecore_Fd_Handler      *fd_handler,
                                 Ecore_Fd_Handler_Flags flags)
{
   int ret = EINA_FALSE;

   EINA_MAIN_LOOP_CHECK_RETURN_VAL(EINA_FALSE);
   _ecore_lock();

   if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
     {
        ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
                         "ecore_main_fd_handler_active_get");
        goto unlock;
     }
   if ((flags & ECORE_FD_READ) && (fd_handler->read_active)) ret = EINA_TRUE;
   if ((flags & ECORE_FD_WRITE) && (fd_handler->write_active)) ret = EINA_TRUE;
   if ((flags & ECORE_FD_ERROR) && (fd_handler->error_active)) ret = EINA_TRUE;
unlock:
   _ecore_unlock();
   return ret;
}

EAPI void
ecore_main_fd_handler_active_set(Ecore_Fd_Handler      *fd_handler,
                                 Ecore_Fd_Handler_Flags flags)
{
   int ret;

   EINA_MAIN_LOOP_CHECK_RETURN;
   _ecore_lock();

   if (!ECORE_MAGIC_CHECK(fd_handler, ECORE_MAGIC_FD_HANDLER))
     {
        ECORE_MAGIC_FAIL(fd_handler, ECORE_MAGIC_FD_HANDLER,
                         "ecore_main_fd_handler_active_set");
        goto unlock;
     }
   fd_handler->flags = flags;
   ret = _ecore_main_fdh_poll_modify(fd_handler);
   if (ret < 0)
     {
        ERR("Failed to mod epoll fd %d: %s!", fd_handler->fd, strerror(ret));
     }
unlock:
   _ecore_unlock();
}

void
_ecore_main_shutdown(void)
{
   if (in_main_loop)
     {
        ERR("\n"
            "*** ECORE WARNING: Calling ecore_shutdown() while still in the main loop.\n"
            "***                 Program may crash or behave strangely now.");
        return;
     }
   while (fd_handlers)
     {
        Ecore_Fd_Handler *fdh;

        fdh = fd_handlers;
        fd_handlers = (Ecore_Fd_Handler *)eina_inlist_remove(EINA_INLIST_GET(fd_handlers),
                                                             EINA_INLIST_GET(fdh));
        ECORE_MAGIC_SET(fdh, ECORE_MAGIC_NONE);
        ecore_fd_handler_mp_free(fdh);
     }
   if (fd_handlers_with_buffer)
     fd_handlers_with_buffer = eina_list_free(fd_handlers_with_buffer);
   if (fd_handlers_with_prep)
     fd_handlers_with_prep = eina_list_free(fd_handlers_with_prep);
   if (fd_handlers_to_delete)
     fd_handlers_to_delete = eina_list_free(fd_handlers_to_delete);
   if (file_fd_handlers)
     file_fd_handlers = eina_list_free(file_fd_handlers);

   fd_handlers_to_call = NULL;
   fd_handlers_to_call_current = NULL;
   fd_handlers_to_delete = NULL;
   fd_handler_current = NULL;

#ifdef _WIN32
   while (win32_handlers)
     {
        Ecore_Win32_Handler *wh;

        wh = win32_handlers;
        win32_handlers = (Ecore_Win32_Handler *)eina_inlist_remove(EINA_INLIST_GET(win32_handlers),
                                                                   EINA_INLIST_GET(wh));
        ECORE_MAGIC_SET(wh, ECORE_MAGIC_NONE);
        ecore_win32_handler_mp_free(wh);
     }
   if (win32_handlers_to_delete)
     win32_handlers_to_delete = eina_list_free(win32_handlers_to_delete);
   win32_handlers_to_delete = NULL;
   win32_handler_current = NULL;
#endif
}

static void
_ecore_main_prepare_handlers(void)
{
   Ecore_Fd_Handler *fdh;
   Eina_List *l, *l2;

   /* call the prepare callback for all handlers with prep functions */
   EINA_LIST_FOREACH_SAFE(fd_handlers_with_prep, l, l2, fdh)
     {
        if (!fdh)
          {
             fd_handlers_with_prep = eina_list_remove_list(l, fd_handlers_with_prep);
             continue;
          }
        if (!fdh->delete_me && fdh->prep_func)
          {
             fdh->references++;
             _ecore_call_prep_cb(fdh->prep_func, fdh->prep_data, fdh);
             fdh->references--;
          }
        else
          fd_handlers_with_prep = eina_list_remove_list(fd_handlers_with_prep, l);
     }
}

#ifndef USE_G_MAIN_LOOP
static int
_ecore_main_select(double timeout)
{
   struct timeval tv, *t;
   fd_set rfds, wfds, exfds;
   Ecore_Fd_Handler *fdh;
   Eina_List *l;
   int max_fd;
   int ret;

   t = NULL;
   if ((!ECORE_FINITE(timeout)) || (timeout == 0.0)) /* finite() tests for NaN, too big, too small, and infinity.  */
     {
        tv.tv_sec = 0;
        tv.tv_usec = 0;
        t = &tv;
     }
   else if (timeout > 0.0)
     {
        int sec, usec;

#ifdef FIX_HZ
        timeout += (0.5 / HZ);
        sec = (int)timeout;
        usec = (int)((timeout - (double)sec) * 1000000);
#else
        sec = (int)timeout;
        usec = (int)((timeout - (double)sec) * 1000000);
#endif
        tv.tv_sec = sec;
        tv.tv_usec = usec;
        t = &tv;
     }
   max_fd = 0;
   FD_ZERO(&rfds);
   FD_ZERO(&wfds);
   FD_ZERO(&exfds);

   /* call the prepare callback for all handlers */
   if (fd_handlers_with_prep)
     _ecore_main_prepare_handlers();

   if (!HAVE_EPOLL || epoll_fd < 0)
     {
        EINA_INLIST_FOREACH(fd_handlers, fdh)
          {
             if (!fdh->delete_me)
               {
                  if (fdh->flags & ECORE_FD_READ)
                    {
                       FD_SET(fdh->fd, &rfds);
                       if (fdh->fd > max_fd) max_fd = fdh->fd;
                    }
                  if (fdh->flags & ECORE_FD_WRITE)
                    {
                       FD_SET(fdh->fd, &wfds);
                       if (fdh->fd > max_fd) max_fd = fdh->fd;
                    }
                  if (fdh->flags & ECORE_FD_ERROR)
                    {
                       FD_SET(fdh->fd, &exfds);
                       if (fdh->fd > max_fd) max_fd = fdh->fd;
                    }
               }
          }
     }
   else
     {
        /* polling on the epoll fd will wake when an fd in the epoll set is active */
         max_fd = _ecore_get_epoll_fd();
         FD_SET(max_fd, &rfds);
     }
   EINA_LIST_FOREACH(file_fd_handlers, l, fdh)
     if (!fdh->delete_me)
       {
          if (fdh->flags & ECORE_FD_READ)
            {
               FD_SET(fdh->fd, &rfds);
               if (fdh->fd > max_fd) max_fd = fdh->fd;
            }
          if (fdh->flags & ECORE_FD_WRITE)
            {
               FD_SET(fdh->fd, &wfds);
               if (fdh->fd > max_fd) max_fd = fdh->fd;
            }
          if (fdh->flags & ECORE_FD_ERROR)
            {
               FD_SET(fdh->fd, &exfds);
               if (fdh->fd > max_fd) max_fd = fdh->fd;
            }
          if (fdh->fd > max_fd) max_fd = fdh->fd;
       }
   if (_ecore_signal_count_get()) return -1;

   _ecore_unlock();
   eina_evlog("!SLEEP", NULL, 0.0, t ? "timeout" : "forever");
   ret = main_loop_select(max_fd + 1, &rfds, &wfds, &exfds, t);
   eina_evlog("!WAKE", NULL, 0.0, NULL);
   _ecore_lock();

   _ecore_time_loop_time = ecore_time_get();
   if (ret < 0)
     {
#ifndef _WIN32
        if (errno == EINTR) return -1;
        else if (errno == EBADF)
          _ecore_main_fd_handlers_bads_rem();
#endif
     }
   if (ret > 0)
     {
        if (HAVE_EPOLL && epoll_fd >= 0)
          _ecore_main_fdh_epoll_mark_active();
        else
          {
             EINA_INLIST_FOREACH(fd_handlers, fdh)
               {
                  if (!fdh->delete_me)
                    {
                       if (FD_ISSET(fdh->fd, &rfds))
                         fdh->read_active = EINA_TRUE;
                       if (FD_ISSET(fdh->fd, &wfds))
                         fdh->write_active = EINA_TRUE;
                       if (FD_ISSET(fdh->fd, &exfds))
                         fdh->error_active = EINA_TRUE;
                       _ecore_try_add_to_call_list(fdh);
                    }
               }
          }
        EINA_LIST_FOREACH(file_fd_handlers, l, fdh)
          {
             if (!fdh->delete_me)
               {
                  if (FD_ISSET(fdh->fd, &rfds))
                    fdh->read_active = EINA_TRUE;
                  if (FD_ISSET(fdh->fd, &wfds))
                    fdh->write_active = EINA_TRUE;
                  if (FD_ISSET(fdh->fd, &exfds))
                    fdh->error_active = EINA_TRUE;
                  _ecore_try_add_to_call_list(fdh);
               }
          }
        _ecore_main_fd_handlers_cleanup();
#ifdef _WIN32
        _ecore_main_win32_handlers_cleanup();
#endif
        return 1;
     }
   return 0;
}

#endif

#ifndef _WIN32
# ifndef USE_G_MAIN_LOOP
static void
_ecore_main_fd_handlers_bads_rem(void)
{
   Ecore_Fd_Handler *fdh;
   Eina_Inlist *l;
   int found = 0;

   ERR("Removing bad fds");
   for (l = EINA_INLIST_GET(fd_handlers); l; )
     {
        fdh = (Ecore_Fd_Handler *)l;
        l = l->next;
        errno = 0;

        if ((fcntl(fdh->fd, F_GETFD) < 0) && (errno == EBADF))
          {
             ERR("Found bad fd at index %d", fdh->fd);
             if (fdh->flags & ECORE_FD_ERROR)
               {
                  ERR("Fd set for error! calling user");
                  fdh->references++;
                  if (!_ecore_call_fd_cb(fdh->func, fdh->data, fdh))
                    {
                       ERR("Fd function err returned 0, remove it");
                       if (!fdh->delete_me)
                         {
                            _ecore_main_fdh_poll_del(fdh);
                            fdh->delete_me = EINA_TRUE;
                            fd_handlers_to_delete = eina_list_append(fd_handlers_to_delete, fdh);
                         }
                       found++;
                    }
                  fdh->references--;
               }
             else
               {
                  ERR("Problematic fd found at %d! setting it for delete", fdh->fd);
                  if (!fdh->delete_me)
                    {
                       _ecore_main_fdh_poll_del(fdh);
                       fdh->delete_me = EINA_TRUE;
                       fd_handlers_to_delete = eina_list_append(fd_handlers_to_delete, fdh);
                    }

                  found++;
               }
          }
     }
   if (found == 0)
     {
#  ifdef HAVE_GLIB
        ERR("No bad fd found. Maybe a foreign fd from glib?");
#  else
        ERR("No bad fd found. EEEK!");
#  endif
     }
   _ecore_main_fd_handlers_cleanup();
}

# endif
#endif

static void
_ecore_main_fd_handlers_cleanup(void)
{
   Ecore_Fd_Handler *fdh;
   Eina_List *l, *l2;

   if (!fd_handlers_to_delete) return;
   EINA_LIST_FOREACH_SAFE(fd_handlers_to_delete, l, l2, fdh)
     {
        if (!fdh)
          {
             fd_handlers_to_delete = eina_list_remove_list(l, fd_handlers_to_delete);
             continue;
          }
        /* fdh->delete_me should be set for all fdhs at the start of the list */
        if (fdh->references)
          continue;
        if (fdh->buf_func && fd_handlers_with_buffer)
          fd_handlers_with_buffer = eina_list_remove(fd_handlers_with_buffer, fdh);
        if (fdh->prep_func && fd_handlers_with_prep)
          fd_handlers_with_prep = eina_list_remove(fd_handlers_with_prep, fdh);
        fd_handlers = (Ecore_Fd_Handler *)
          eina_inlist_remove(EINA_INLIST_GET(fd_handlers), EINA_INLIST_GET(fdh));
        if (fdh->file)
          file_fd_handlers = eina_list_remove(file_fd_handlers, fdh);
        ECORE_MAGIC_SET(fdh, ECORE_MAGIC_NONE);
        ecore_fd_handler_mp_free(fdh);
        fd_handlers_to_delete = eina_list_remove_list(fd_handlers_to_delete, l);
     }
}

#ifdef _WIN32
static void
_ecore_main_win32_handlers_cleanup(void)
{
   Ecore_Win32_Handler *wh;
   Eina_List *l;
   Eina_List *l2;

   if (!win32_handlers_to_delete) return;
   EINA_LIST_FOREACH_SAFE(win32_handlers_to_delete, l, l2, wh)
     {
       printf(" -- %s 1 : wh %p\n", __FUNCTION__, wh);
        if (!wh)
          {
             win32_handlers_to_delete = eina_list_remove_list(l, win32_handlers_to_delete);
             continue;
          }
        /* wh->delete_me should be set for all whs at the start of the list */
        if (wh->references)
          continue;
        win32_handlers = (Ecore_Win32_Handler *)
          eina_inlist_remove(EINA_INLIST_GET(win32_handlers), EINA_INLIST_GET(wh));
        ECORE_MAGIC_SET(wh, ECORE_MAGIC_NONE);
       printf(" -- %s 2 : wh %p\n", __FUNCTION__, wh);
        ecore_win32_handler_mp_free(wh);
        win32_handlers_to_delete = eina_list_remove_list(win32_handlers_to_delete, l);
     }
}

#endif

static void
_ecore_main_fd_handlers_call(void)
{
   /* grab a new list */
    if (!fd_handlers_to_call_current)
      {
         fd_handlers_to_call_current = fd_handlers_to_call;
         fd_handlers_to_call = NULL;
      }

   if (!fd_handlers_to_call_current) return;
   eina_evlog("+fd_handlers", NULL, 0.0, NULL);

    while (fd_handlers_to_call_current)
      {
         Ecore_Fd_Handler *fdh = fd_handlers_to_call_current;

         if (!fdh->delete_me)
           {
              if ((fdh->read_active) ||
                  (fdh->write_active) ||
                  (fdh->error_active))
                {
                   fdh->references++;
                   if (!_ecore_call_fd_cb(fdh->func, fdh->data, fdh))
                     {
                        if (!fdh->delete_me)
                          {
                             _ecore_main_fdh_poll_del(fdh);
                             fdh->delete_me = EINA_TRUE;
                             fd_handlers_to_delete = eina_list_append(fd_handlers_to_delete, fdh);
                          }
                     }
                   fdh->references--;
                   _ecore_fd_valid();

                   fdh->read_active = EINA_FALSE;
                   fdh->write_active = EINA_FALSE;
                   fdh->error_active = EINA_FALSE;
                }
           }

         /* stop when we point to ourselves */
         if (fdh->next_ready == fdh)
           {
              fdh->next_ready = NULL;
              fd_handlers_to_call_current = NULL;
              break;
           }

         fd_handlers_to_call_current = fdh->next_ready;
         fdh->next_ready = NULL;
      }
   eina_evlog("-fd_handlers", NULL, 0.0, NULL);
}

static int
_ecore_main_fd_handlers_buf_call(void)
{
   Ecore_Fd_Handler *fdh;
   Eina_List *l, *l2;
   int ret;

   if (!fd_handlers_with_buffer) return 0;
   eina_evlog("+fd_handlers_buf", NULL, 0.0, NULL);
   ret = 0;
   EINA_LIST_FOREACH_SAFE(fd_handlers_with_buffer, l, l2, fdh)
     {
        if (!fdh)
          {
             fd_handlers_with_buffer = eina_list_remove_list(l, fd_handlers_with_buffer);
             continue;
          }
        if ((!fdh->delete_me) && fdh->buf_func)
          {
             fdh->references++;
             if (_ecore_call_fd_cb(fdh->buf_func, fdh->buf_data, fdh))
               {
                  ret |= _ecore_call_fd_cb(fdh->func, fdh->data, fdh);
                  fdh->read_active = EINA_TRUE;
                  _ecore_try_add_to_call_list(fdh);
               }
             fdh->references--;
          }
        else
          fd_handlers_with_buffer = eina_list_remove_list(fd_handlers_with_buffer, l);
     }
   eina_evlog("-fd_handlers_buf", NULL, 0.0, NULL);
   return ret;
}

#ifndef USE_G_MAIN_LOOP

enum {
   SPIN_MORE,
   SPIN_RESTART,
   LOOP_CONTINUE
};

static int
_ecore_main_loop_spin_core(void)
{
   /* as we are spinning we need to update loop time per spin */
    _ecore_time_loop_time = ecore_time_get();
    /* call all idlers, which returns false if no more idelrs exist */
    if (!_ecore_idler_all_call()) return SPIN_RESTART;
    /* sneaky - drop through or if checks - the first one to succeed
     * drops through and returns "continue" so further ones dont run */
    if ((_ecore_main_select(0.0) > 0) || (_ecore_event_exist()) ||
        (_ecore_signal_count_get() > 0) || (do_quit))
      return LOOP_CONTINUE;
    /* default - spin more */
    return SPIN_MORE;
}

static int
_ecore_main_loop_spin_no_timers(void)
{
   /* if we have idlers we HAVE to spin and handle everything
    * in a polling way - spin in a tight polling loop */
     for (;; )
       {
          int action = _ecore_main_loop_spin_core();
          if (action != SPIN_MORE) return action;
          /* if an idler has added a timer then we need to go through
           * the start of the spin cycle again to handle cases properly */
          if (_ecore_timers_exists()) return SPIN_RESTART;
       }
     /* just contiune handling events etc. */
     return LOOP_CONTINUE;
}

static int
_ecore_main_loop_spin_timers(void)
{
   /* if we have idlers we HAVE to spin and handle everything
    * in a polling way - spin in a tight polling loop */
     for (;; )
       {
          int action = _ecore_main_loop_spin_core();
          if (action != SPIN_MORE) return action;
          /* if next timer expires now or in the past - stop spinning and
           * continue the mainloop walk as our "select" timeout has
           * expired now */
          if (_ecore_timer_next_get() <= 0.0) return LOOP_CONTINUE;
       }
     /* just contiune handling events etc. */
     return LOOP_CONTINUE;
}

static void
_ecore_fps_marker_1(void)
{
   if (!_ecore_fps_debug) return;
   t2 = ecore_time_get();
   if ((t1 > 0.0) && (t2 > 0.0)) _ecore_fps_debug_runtime_add(t2 - t1);
}

static void
_ecore_fps_marker_2(void)
{
   if (!_ecore_fps_debug) return;
   t1 = ecore_time_get();
}

static void
_ecore_main_loop_iterate_internal(int once_only)
{
   double next_time = -1.0;

   in_main_loop++;
   /* expire any timers */
   _ecore_timer_expired_timers_call(_ecore_time_loop_time);
   _ecore_timer_cleanup();

   /* process signals into events .... */
   _ecore_signal_received_process();
   /* if as a result of timers/animators or signals we have accumulated
    * events, then instantly handle them */
   if (_ecore_event_exist())
     {
        /* but first conceptually enter an idle state */
        _ecore_idle_enterer_call();
        _ecore_throttle();
        /* now quickly poll to see which input fd's are active */
        _ecore_main_select(0.0);
        /* allow newly queued timers to expire from now on */
        _ecore_timer_enable_new();
        /* go straight to processing the events we had queued */
        goto process_all;
     }

   if (once_only)
     {
        /* in once_only mode we should quickly poll for inputs, signals
         * if we got any events or signals, allow new timers to process.
         * use bitwise or to force both conditions to be tested and
         * merged together */
        if (_ecore_main_select(0.0) | _ecore_signal_count_get())
          {
             _ecore_timer_enable_new();
             goto process_all;
          }
     }
   else
     {
        /* call idle enterers ... */
        _ecore_idle_enterer_call();
        _ecore_throttle();
     }

   /* if these calls caused any buffered events to appear - deal with them */
   if (fd_handlers_with_buffer)
     _ecore_main_fd_handlers_buf_call();

   /* if there are any (buffered fd handling may generate them)
    * then jump to processing them */
   if (_ecore_event_exist())
     {
        _ecore_main_select(0.0);
        _ecore_timer_enable_new();
        goto process_all;
     }

   if (once_only)
     {
        /* in once_only mode enter idle here instead and then return */
        _ecore_idle_enterer_call();
        _ecore_throttle();
        _ecore_timer_enable_new();
        goto done;
     }

   _ecore_fps_marker_1();

   /* start of the sleeping or looping section */
start_loop: /*-*************************************************************/
   /* any timers re-added as a result of these are allowed to go */
   _ecore_timer_enable_new();
   /* if we have been asked to quit the mainloop then exit at this point */
   if (do_quit)
     {
        _ecore_timer_enable_new();
        goto done;
     }
   if (!_ecore_event_exist())
     {
        /* init flags */
        next_time = _ecore_timer_next_get();
        /* no idlers */
        if (!_ecore_idler_exist())
          {
             /* sleep until timeout or forever (-1.0) waiting for on fds */
             _ecore_main_select(next_time);
          }
        else
          {
             int action = LOOP_CONTINUE;

             /* no timers - spin */
             if (next_time < 0) action = _ecore_main_loop_spin_no_timers();
             /* timers - spin */
             else action = _ecore_main_loop_spin_timers();
             if (action == SPIN_RESTART) goto start_loop;
          }
     }
   _ecore_fps_marker_2();

   /* actually wake up and deal with input, events etc. */
process_all: /*-*********************************************************/

   /* we came out of our "wait state" so idle has exited */
   if (!once_only)
     {
        _ecore_animator_run_reset();
        _ecore_idle_exiter_call();
     }
   /* call the fd handler per fd that became alive... */
   /* this should read or write any data to the monitored fd and then */
   /* post events onto the ecore event pipe if necessary */
   _ecore_main_fd_handlers_call();
   if (fd_handlers_with_buffer) _ecore_main_fd_handlers_buf_call();
   /* process signals into events .... */
   _ecore_signal_received_process();
   /* handle events ... */
   _ecore_event_call();
   _ecore_main_fd_handlers_cleanup();

   if (once_only)
     {
        /* if in once_only mode handle idle exiting */
        _ecore_idle_enterer_call();
        _ecore_throttle();
     }

done: /*-*****************************************************************/
   in_main_loop--;
}

#endif

#ifdef _WIN32
typedef struct
{
   DWORD objects_nbr;
   HANDLE *objects;
   DWORD timeout;
} Ecore_Main_Win32_Thread_Data;

static unsigned int __stdcall
_ecore_main_win32_objects_wait_thread(void *data)
{
   Ecore_Main_Win32_Thread_Data *td;
   DWORD result;

   td = (Ecore_Main_Win32_Thread_Data *)data;
   result = MsgWaitForMultipleObjects(td->objects_nbr,
                                      (const HANDLE *)td->objects,
                                      FALSE,
                                      td->timeout,
                                      QS_ALLINPUT);
   return result;
}

static DWORD
_ecore_main_win32_objects_wait(DWORD objects_nbr,
                               const HANDLE *objects,
                               DWORD timeout)
{
   Ecore_Main_Win32_Thread_Data *threads_data;
   HANDLE *threads_handles;
   DWORD threads_nbr;
   DWORD threads_remain;
   DWORD objects_idx;
   DWORD result;
   DWORD i;

   if (objects_nbr < MAXIMUM_WAIT_OBJECTS)
     return MsgWaitForMultipleObjects(objects_nbr,
                                      objects,
                                      EINA_FALSE,
                                      timeout, QS_ALLINPUT);
   /*
    * too much objects, so we launch a bunch of threads to
    * wait for, each one calls MsgWaitForMultipleObjects
    */

   threads_nbr = objects_nbr / (MAXIMUM_WAIT_OBJECTS - 1);
   threads_remain = objects_nbr % (MAXIMUM_WAIT_OBJECTS - 1);
   if (threads_remain > 0)
     threads_nbr++;

   if (threads_nbr > MAXIMUM_WAIT_OBJECTS)
     {
        CRI("Too much objects to wait for (%lu).", objects_nbr);
        return WAIT_FAILED;
     }

   threads_handles = (HANDLE *)malloc(threads_nbr * sizeof(HANDLE));
   if (!threads_handles)
     {
        ERR("Can not allocate memory for the waiting thread.");
        return WAIT_FAILED;
     }

   threads_data = (Ecore_Main_Win32_Thread_Data *)malloc(threads_nbr * sizeof(Ecore_Main_Win32_Thread_Data));
   if (!threads_data)
     {
        ERR("Can not allocate memory for the waiting thread.");
        goto free_threads_handles;
     }

   objects_idx = 0;
   for (i = 0; i < threads_nbr; i++)
     {
        threads_data[i].timeout = timeout;
        threads_data[i].objects = (HANDLE *)objects + objects_idx;

        if ((i == (threads_nbr - 1)) && (threads_remain != 0))
          {
             threads_data[i].objects_nbr = threads_remain;
             objects_idx += threads_remain;
          }
        else
          {
             threads_data[i].objects_nbr = (MAXIMUM_WAIT_OBJECTS - 1);
             objects_idx += (MAXIMUM_WAIT_OBJECTS - 1);
          }

        threads_handles[i] = (HANDLE)_beginthreadex(NULL,
                                                    0,
                                                    _ecore_main_win32_objects_wait_thread,
                                                    &threads_data[i],
                                                    0,
                                                    NULL);
        if (!threads_handles[i])
          {
             DWORD j;

             ERR("Can not create the waiting threads.");
             WaitForMultipleObjects(i, threads_handles, TRUE, INFINITE);
             for (j = 0; j < i; j++)
               CloseHandle(threads_handles[i]);

             goto free_threads_data;
          }
     }

   result = WaitForMultipleObjects(threads_nbr,
                                   threads_handles,
                                   FALSE, /* we wait until one thread is signaled */
                                   INFINITE);

   if (result < (WAIT_OBJECT_0 + threads_nbr))
     {
        DWORD wait_res;

        /*
         * One of the thread callback has exited so we retrieve
         * its exit status, that is the returned value of
         * MsgWaitForMultipleObjects()
         */
        if (GetExitCodeThread(threads_handles[result - WAIT_OBJECT_0],
                              &wait_res))
          {
             WaitForMultipleObjects(threads_nbr, threads_handles, TRUE, INFINITE);
             for (i = 0; i < threads_nbr; i++)
               CloseHandle(threads_handles[i]);
             free(threads_data);
             free(threads_handles);
             return wait_res;
          }
     }
   else
     {
        ERR("Error when waiting threads.");
        if (result == WAIT_FAILED)
          {
             char *str;

             str = evil_last_error_get();
             ERR("%s", str);
             free(str);
          }
        goto close_thread;
     }

 close_thread:
   WaitForMultipleObjects(threads_nbr, threads_handles, TRUE, INFINITE);
   for (i = 0; i < threads_nbr; i++)
     CloseHandle(threads_handles[i]);
 free_threads_data:
   free(threads_data);
 free_threads_handles:
   free(threads_handles);

   return WAIT_FAILED;
}

static int
_ecore_main_win32_select(int             nfds EINA_UNUSED,
                         fd_set         *readfds,
                         fd_set         *writefds,
                         fd_set         *exceptfds,
                         struct timeval *tv)
{
   HANDLE *objects;
   int *sockets;
   Ecore_Fd_Handler *fdh;
   Ecore_Win32_Handler *wh;
   unsigned int fds_nbr = 0;
   unsigned int objects_nbr = 0;
   unsigned int events_nbr = 0;
   DWORD result;
   DWORD timeout;
   MSG msg;
   unsigned int i;
   int res;

   fds_nbr = eina_inlist_count(EINA_INLIST_GET(fd_handlers));
   sockets = (int *)malloc(fds_nbr * sizeof(int));
   if (!sockets)
     return -1;

   objects = (HANDLE)malloc((fds_nbr + eina_inlist_count(EINA_INLIST_GET(win32_handlers))) * sizeof(HANDLE));
   if (!objects)
     {
        free(sockets);
        return -1;
     }

   /* Create an event object per socket */
   EINA_INLIST_FOREACH(fd_handlers, fdh)
     {
        WSAEVENT event;
        long network_event;

        network_event = 0;
        if (readfds)
          {
             if (FD_ISSET(fdh->fd, readfds))
               network_event |= FD_READ | FD_CONNECT | FD_ACCEPT;
          }
        if (writefds)
          {
             if (FD_ISSET(fdh->fd, writefds))
               network_event |= FD_WRITE | FD_CLOSE;
          }
        if (exceptfds)
          {
             if (FD_ISSET(fdh->fd, exceptfds))
               network_event |= FD_OOB;
          }

        if (network_event)
          {
             event = WSACreateEvent();
             WSAEventSelect(fdh->fd, event, network_event);
             objects[objects_nbr] = event;
             sockets[events_nbr] = fdh->fd;
             events_nbr++;
             objects_nbr++;
          }
     }

   /* store the HANDLEs in the objects to wait for */
   EINA_INLIST_FOREACH(win32_handlers, wh)
     {
        objects[objects_nbr] = wh->h;
        objects_nbr++;
     }

   /* Empty the queue before waiting */
   while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
     {
        TranslateMessage(&msg);
        DispatchMessage(&msg);
     }

   /* Wait for any message sent or posted to this queue */
   /* or for one of the passed handles be set to signaled. */
   if (!tv)
     timeout = INFINITE;
   else
     timeout = (DWORD)((tv->tv_sec * 1000.0) + (tv->tv_usec / 1000.0));

   if (timeout == 0)
     {
        free(objects);
        free(sockets);
        return 0;
     }

   result = _ecore_main_win32_objects_wait(objects_nbr,
                                           (const HANDLE *)objects,
                                           timeout);

   if (readfds)
     FD_ZERO(readfds);
   if (writefds)
     FD_ZERO(writefds);
   if (exceptfds)
     FD_ZERO(exceptfds);

   /* The result tells us the type of event we have. */
   if (result == WAIT_FAILED)
     {
        char *m;

        m = evil_last_error_get();
        WRN("%s", m);
        free(m);
        res = -1;
     }
   else if (result == WAIT_TIMEOUT)
     {
        INF("time-out interval elapsed.");
        res = 0;
     }
   else if (result == (WAIT_OBJECT_0 + objects_nbr))
     {
        while (PeekMessage(&msg, NULL, 0, 0, PM_REMOVE))
          {
             TranslateMessage(&msg);
             DispatchMessage(&msg);
          }

        res = 0;
     }
   else if (result < WAIT_OBJECT_0 + events_nbr)
     {
        WSANETWORKEVENTS network_event;

        WSAEnumNetworkEvents(sockets[result], objects[result], &network_event);

        if ((network_event.lNetworkEvents & (FD_READ | FD_CONNECT | FD_ACCEPT)) && readfds)
          FD_SET(sockets[result], readfds);
        if ((network_event.lNetworkEvents & (FD_WRITE | FD_CLOSE)) && writefds)
          FD_SET(sockets[result], writefds);
        if ((network_event.lNetworkEvents & FD_OOB) && exceptfds)
          FD_SET(sockets[result], exceptfds);

        res = 1;
     }
   else if ((result >= (WAIT_OBJECT_0 + events_nbr)) &&
            (result < (WAIT_OBJECT_0 + objects_nbr)))
     {
        if (!win32_handler_current)
          {
             /* regular main loop, start from head */
              win32_handler_current = win32_handlers;
          }
        else
          {
             /* recursive main loop, continue from where we were */
              win32_handler_current = (Ecore_Win32_Handler *)EINA_INLIST_GET(win32_handler_current)->next;
          }

        while (win32_handler_current)
          {
             wh = win32_handler_current;

             if (objects[result - WAIT_OBJECT_0] == wh->h)
               {
                  if (!wh->delete_me)
                    {
                       wh->references++;
                       if (!wh->func(wh->data, wh))
                         {
                            wh->delete_me = EINA_TRUE;
                            win32_handlers_to_delete = eina_list_append(win32_handlers_to_delete, wh);
                         }
                       wh->references--;
                    }
               }
             if (win32_handler_current) /* may have changed in recursive main loops */
               win32_handler_current = (Ecore_Win32_Handler *)EINA_INLIST_GET(win32_handler_current)->next;
          }
        res = 1;
     }
   else
     {
        ERR("unknown result...\n");
        res = -1;
     }

   /* Remove event objects again */
   for (i = 0; i < events_nbr; i++) WSACloseEvent(objects[i]);

   free(objects);
   free(sockets);
   return res;
}

#endif

static Eo *_mainloop_singleton = NULL;

EAPI Eo *ecore_main_loop_get(void)
{
   if (!_mainloop_singleton)
     {
       eo_add(_mainloop_singleton, ECORE_MAINLOOP_CLASS, NULL);
     }

   return _mainloop_singleton;
}

EOLIAN static void
_ecore_mainloop_select_func_set(Eo *obj EINA_UNUSED, void *pd EINA_UNUSED, Ecore_Select_Function select_func)
{
   ecore_main_loop_select_func_set(select_func);
}

EOLIAN static Ecore_Select_Function
_ecore_mainloop_select_func_get(Eo *obj EINA_UNUSED, void *pd EINA_UNUSED)
{
   return ecore_main_loop_select_func_get();
}

EOLIAN static void
_ecore_mainloop_iterate(Eo *obj EINA_UNUSED, void *pd EINA_UNUSED)
{
   ecore_main_loop_iterate();
}

EOLIAN static int _ecore_mainloop_iterate_may_block(Eo *obj EINA_UNUSED, void *pd EINA_UNUSED, int may_block)
{
   return ecore_main_loop_iterate_may_block(may_block);
}

EOLIAN static void
_ecore_mainloop_begin(Eo *obj EINA_UNUSED, void *pd EINA_UNUSED)
{
   ecore_main_loop_begin();
}

EOLIAN static void
_ecore_mainloop_quit(Eo *obj EINA_UNUSED, void *pd EINA_UNUSED)
{
   ecore_main_loop_quit();
}

EOLIAN static Eina_Bool
_ecore_mainloop_animator_ticked(Eo *obj EINA_UNUSED, void *pd EINA_UNUSED)
{
   return ecore_main_loop_animator_ticked_get();
}

#include "ecore_mainloop.eo.c"