browseui: Add Hungarian translation.
[wine] / dlls / winmm / time.c
1 /* -*- tab-width: 8; c-basic-offset: 4 -*- */
2
3 /*
4  * MMSYSTEM time functions
5  *
6  * Copyright 1993 Martin Ayotte
7  *
8  * This library is free software; you can redistribute it and/or
9  * modify it under the terms of the GNU Lesser General Public
10  * License as published by the Free Software Foundation; either
11  * version 2.1 of the License, or (at your option) any later version.
12  *
13  * This library is distributed in the hope that it will be useful,
14  * but WITHOUT ANY WARRANTY; without even the implied warranty of
15  * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
16  * Lesser General Public License for more details.
17  *
18  * You should have received a copy of the GNU Lesser General Public
19  * License along with this library; if not, write to the Free Software
20  * Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301, USA
21  */
22
23 #include "config.h"
24 #include "wine/port.h"
25
26 #include <stdarg.h>
27 #include <errno.h>
28 #include <time.h>
29 #ifdef HAVE_SYS_TIME_H
30 # include <sys/time.h>
31 #endif
32 #ifdef HAVE_UNISTD_H
33 # include <unistd.h>
34 #endif
35 #ifdef HAVE_POLL_H
36 #include <poll.h>
37 #endif
38 #ifdef HAVE_SYS_POLL_H
39 #include <sys/poll.h>
40 #endif
41
42 #include "windef.h"
43 #include "winbase.h"
44 #include "mmsystem.h"
45
46 #include "winemm.h"
47
48 #include "wine/list.h"
49 #include "wine/debug.h"
50
51 WINE_DEFAULT_DEBUG_CHANNEL(mmtime);
52
53 typedef struct tagWINE_TIMERENTRY {
54     struct list                 entry;
55     UINT                        wDelay;
56     UINT                        wResol;
57     LPTIMECALLBACK              lpFunc; /* can be lots of things */
58     DWORD_PTR                   dwUser;
59     UINT16                      wFlags;
60     UINT16                      wTimerID;
61     DWORD                       dwTriggerTime;
62 } WINE_TIMERENTRY, *LPWINE_TIMERENTRY;
63
64 static struct list timer_list = LIST_INIT(timer_list);
65
66 static CRITICAL_SECTION TIME_cbcrst;
67 static CRITICAL_SECTION_DEBUG critsect_debug =
68 {
69     0, 0, &TIME_cbcrst,
70     { &critsect_debug.ProcessLocksList, &critsect_debug.ProcessLocksList },
71       0, 0, { (DWORD_PTR)(__FILE__ ": TIME_cbcrst") }
72 };
73 static CRITICAL_SECTION TIME_cbcrst = { &critsect_debug, -1, 0, 0, 0, 0 };
74
75 static    HANDLE                TIME_hMMTimer;
76 static    BOOL                  TIME_TimeToDie = TRUE;
77 static    int                   TIME_fdWake[2] = { -1, -1 };
78
79 /* link timer at the appropriate spot in the list */
80 static inline void link_timer( WINE_TIMERENTRY *timer )
81 {
82     WINE_TIMERENTRY *next;
83
84     LIST_FOR_EACH_ENTRY( next, &timer_list, WINE_TIMERENTRY, entry )
85         if ((int)(next->dwTriggerTime - timer->dwTriggerTime) >= 0) break;
86
87     list_add_before( &next->entry, &timer->entry );
88 }
89
90 /*
91  * Some observations on the behavior of winmm on Windows.
92  * First, the call to timeBeginPeriod(xx) can never be used
93  * to raise the timer resolution, only lower it.
94  *
95  * Second, a brief survey of a variety of Win 2k and Win X
96  * machines showed that a 'standard' (aka default) timer
97  * resolution was 1 ms (Win9x is documented as being 1).  However, one 
98  * machine had a standard timer resolution of 10 ms.
99  *
100  * Further, if we set our default resolution to 1,
101  * the implementation of timeGetTime becomes GetTickCount(),
102  * and we can optimize the code to reduce overhead.
103  *
104  * Additionally, a survey of Event behaviors shows that
105  * if we request a Periodic event every 50 ms, then Windows
106  * makes sure to trigger that event 20 times in the next
107  * second.  If delays prevent that from happening on exact
108  * schedule, Windows will trigger the events as close
109  * to the original schedule as is possible, and will eventually
110  * bring the event triggers back onto a schedule that is
111  * consistent with what would have happened if there were
112  * no delays.
113  *
114  *   Jeremy White, October 2004
115  */
116 #define MMSYSTIME_MININTERVAL (1)
117 #define MMSYSTIME_MAXINTERVAL (65535)
118
119 #ifdef HAVE_POLL
120
121 /**************************************************************************
122  *           TIME_MMSysTimeCallback
123  */
124 static int TIME_MMSysTimeCallback(void)
125 {
126     WINE_TIMERENTRY *timer, *to_free;
127     int delta_time;
128
129     /* since timeSetEvent() and timeKillEvent() can be called
130      * from 16 bit code, there are cases where win16 lock is
131      * locked upon entering timeSetEvent(), and then the mm timer
132      * critical section is locked. This function cannot call the
133      * timer callback with the crit sect locked (because callback
134      * may need to acquire Win16 lock, thus providing a deadlock
135      * situation).
136      * To cope with that, we just copy the WINE_TIMERENTRY struct
137      * that need to trigger the callback, and call it without the
138      * mm timer crit sect locked.
139      */
140
141     for (;;)
142     {
143         struct list *ptr = list_head( &timer_list );
144         if (!ptr)
145         {
146             delta_time = -1;
147             break;
148         }
149
150         timer = LIST_ENTRY( ptr, WINE_TIMERENTRY, entry );
151         delta_time = timer->dwTriggerTime - GetTickCount();
152         if (delta_time > 0) break;
153
154         list_remove( &timer->entry );
155         if (timer->wFlags & TIME_PERIODIC)
156         {
157             timer->dwTriggerTime += timer->wDelay;
158             link_timer( timer );  /* restart it */
159             to_free = NULL;
160         }
161         else to_free = timer;
162
163         switch(timer->wFlags & (TIME_CALLBACK_EVENT_SET|TIME_CALLBACK_EVENT_PULSE))
164         {
165         case TIME_CALLBACK_EVENT_SET:
166             SetEvent(timer->lpFunc);
167             break;
168         case TIME_CALLBACK_EVENT_PULSE:
169             PulseEvent(timer->lpFunc);
170             break;
171         case TIME_CALLBACK_FUNCTION:
172             {
173                 DWORD_PTR user = timer->dwUser;
174                 UINT16 id = timer->wTimerID;
175                 UINT16 flags = timer->wFlags;
176                 LPTIMECALLBACK func = timer->lpFunc;
177
178                 if (flags & TIME_KILL_SYNCHRONOUS) EnterCriticalSection(&TIME_cbcrst);
179                 LeaveCriticalSection(&WINMM_cs);
180
181                 func(id, 0, user, 0, 0);
182
183                 EnterCriticalSection(&WINMM_cs);
184                 if (flags & TIME_KILL_SYNCHRONOUS) LeaveCriticalSection(&TIME_cbcrst);
185             }
186             break;
187         }
188         HeapFree( GetProcessHeap(), 0, to_free );
189     }
190     return delta_time;
191 }
192
193 /**************************************************************************
194  *           TIME_MMSysTimeThread
195  */
196 static DWORD CALLBACK TIME_MMSysTimeThread(LPVOID arg)
197 {
198     int sleep_time, ret;
199     char readme[16];
200     struct pollfd pfd;
201
202     pfd.fd = TIME_fdWake[0];
203     pfd.events = POLLIN;
204
205     TRACE("Starting main winmm thread\n");
206
207     EnterCriticalSection(&WINMM_cs);
208     while (! TIME_TimeToDie) 
209     {
210         sleep_time = TIME_MMSysTimeCallback();
211
212         if (sleep_time < 0)
213             break;
214         if (sleep_time == 0)
215             continue;
216
217         LeaveCriticalSection(&WINMM_cs);
218         ret = poll(&pfd, 1, sleep_time);
219         EnterCriticalSection(&WINMM_cs);
220
221         if (ret < 0)
222         {
223             if (errno != EINTR && errno != EAGAIN)
224             {
225                 ERR("Unexpected error in poll: %s(%d)\n", strerror(errno), errno);
226                 break;
227             }
228          }
229
230         while (ret > 0) ret = read(TIME_fdWake[0], readme, sizeof(readme));
231     }
232     CloseHandle(TIME_hMMTimer);
233     TIME_hMMTimer = NULL;
234     LeaveCriticalSection(&WINMM_cs);
235     TRACE("Exiting main winmm thread\n");
236     FreeLibraryAndExitThread(arg, 0);
237     return 0;
238 }
239
240 /**************************************************************************
241  *                              TIME_MMTimeStart
242  */
243 static void TIME_MMTimeStart(void)
244 {
245     TIME_TimeToDie = 0;
246     if (!TIME_hMMTimer) {
247         HMODULE mod;
248         if (pipe(TIME_fdWake) < 0)
249         {
250             TIME_fdWake[0] = TIME_fdWake[1] = -1;
251             ERR("Cannot create pipe: %s\n", strerror(errno));
252         } else {
253             fcntl(TIME_fdWake[0], F_SETFL, O_NONBLOCK);
254             fcntl(TIME_fdWake[1], F_SETFL, O_NONBLOCK);
255         }
256         GetModuleHandleExW(GET_MODULE_HANDLE_EX_FLAG_FROM_ADDRESS, (LPCWSTR)TIME_MMSysTimeThread, &mod);
257         TIME_hMMTimer = CreateThread(NULL, 0, TIME_MMSysTimeThread, mod, 0, NULL);
258         SetThreadPriority(TIME_hMMTimer, THREAD_PRIORITY_TIME_CRITICAL);
259     }
260 }
261
262 #else  /* HAVE_POLL */
263
264 static void TIME_MMTimeStart(void)
265 {
266     FIXME( "not starting system thread\n" );
267 }
268
269 #endif  /* HAVE_POLL */
270
271 /**************************************************************************
272  *                              TIME_MMTimeStop
273  */
274 void    TIME_MMTimeStop(void)
275 {
276     if (TIME_hMMTimer) {
277         EnterCriticalSection(&WINMM_cs);
278         if (TIME_hMMTimer) {
279             ERR("Timer still active?!\n");
280             CloseHandle(TIME_hMMTimer);
281         }
282         close(TIME_fdWake[0]);
283         close(TIME_fdWake[1]);
284         DeleteCriticalSection(&TIME_cbcrst);
285     }
286 }
287
288 /**************************************************************************
289  *                              timeGetSystemTime       [WINMM.@]
290  */
291 MMRESULT WINAPI timeGetSystemTime(LPMMTIME lpTime, UINT wSize)
292 {
293
294     if (wSize >= sizeof(*lpTime)) {
295         lpTime->wType = TIME_MS;
296         lpTime->u.ms = GetTickCount();
297
298     }
299
300     return 0;
301 }
302
303 /**************************************************************************
304  *                              timeSetEvent            [WINMM.@]
305  */
306 MMRESULT WINAPI timeSetEvent(UINT wDelay, UINT wResol, LPTIMECALLBACK lpFunc,
307                             DWORD_PTR dwUser, UINT wFlags)
308 {
309     WORD                wNewID = 0;
310     LPWINE_TIMERENTRY   lpNewTimer;
311     LPWINE_TIMERENTRY   lpTimer;
312     const char c = 'c';
313
314     TRACE("(%u, %u, %p, %08lX, %04X);\n", wDelay, wResol, lpFunc, dwUser, wFlags);
315
316     if (wDelay < MMSYSTIME_MININTERVAL || wDelay > MMSYSTIME_MAXINTERVAL)
317         return 0;
318
319     lpNewTimer = HeapAlloc(GetProcessHeap(), 0, sizeof(WINE_TIMERENTRY));
320     if (lpNewTimer == NULL)
321         return 0;
322
323     lpNewTimer->wDelay = wDelay;
324     lpNewTimer->dwTriggerTime = GetTickCount() + wDelay;
325
326     /* FIXME - wResol is not respected, although it is not clear
327                that we could change our precision meaningfully  */
328     lpNewTimer->wResol = wResol;
329     lpNewTimer->lpFunc = lpFunc;
330     lpNewTimer->dwUser = dwUser;
331     lpNewTimer->wFlags = wFlags;
332
333     EnterCriticalSection(&WINMM_cs);
334
335     LIST_FOR_EACH_ENTRY( lpTimer, &timer_list, WINE_TIMERENTRY, entry )
336         wNewID = max(wNewID, lpTimer->wTimerID);
337
338     link_timer( lpNewTimer );
339     lpNewTimer->wTimerID = wNewID + 1;
340
341     TIME_MMTimeStart();
342
343     LeaveCriticalSection(&WINMM_cs);
344
345     /* Wake the service thread in case there is work to be done */
346     write(TIME_fdWake[1], &c, sizeof(c));
347
348     TRACE("=> %u\n", wNewID + 1);
349
350     return wNewID + 1;
351 }
352
353 /**************************************************************************
354  *                              timeKillEvent           [WINMM.@]
355  */
356 MMRESULT WINAPI timeKillEvent(UINT wID)
357 {
358     WINE_TIMERENTRY *lpSelf = NULL, *lpTimer;
359     DWORD wFlags;
360
361     TRACE("(%u)\n", wID);
362     EnterCriticalSection(&WINMM_cs);
363     /* remove WINE_TIMERENTRY from list */
364     LIST_FOR_EACH_ENTRY( lpTimer, &timer_list, WINE_TIMERENTRY, entry )
365     {
366         if (wID == lpTimer->wTimerID) {
367             lpSelf = lpTimer;
368             list_remove( &lpTimer->entry );
369             break;
370         }
371     }
372     if (list_empty(&timer_list)) {
373         char c = 'q';
374         TIME_TimeToDie = 1;
375         write(TIME_fdWake[1], &c, sizeof(c));
376     }
377     LeaveCriticalSection(&WINMM_cs);
378
379     if (!lpSelf)
380     {
381         WARN("wID=%u is not a valid timer ID\n", wID);
382         return MMSYSERR_INVALPARAM;
383     }
384     wFlags = lpSelf->wFlags;
385     if (wFlags & TIME_KILL_SYNCHRONOUS)
386         EnterCriticalSection(&TIME_cbcrst);
387     HeapFree(GetProcessHeap(), 0, lpSelf);
388     if (wFlags & TIME_KILL_SYNCHRONOUS)
389         LeaveCriticalSection(&TIME_cbcrst);
390     return TIMERR_NOERROR;
391 }
392
393 /**************************************************************************
394  *                              timeGetDevCaps          [WINMM.@]
395  */
396 MMRESULT WINAPI timeGetDevCaps(LPTIMECAPS lpCaps, UINT wSize)
397 {
398     TRACE("(%p, %u)\n", lpCaps, wSize);
399
400     if (lpCaps == 0) {
401         WARN("invalid lpCaps\n");
402         return TIMERR_NOCANDO;
403     }
404
405     if (wSize < sizeof(TIMECAPS)) {
406         WARN("invalid wSize\n");
407         return TIMERR_NOCANDO;
408     }
409
410     lpCaps->wPeriodMin = MMSYSTIME_MININTERVAL;
411     lpCaps->wPeriodMax = MMSYSTIME_MAXINTERVAL;
412     return TIMERR_NOERROR;
413 }
414
415 /**************************************************************************
416  *                              timeBeginPeriod         [WINMM.@]
417  */
418 MMRESULT WINAPI timeBeginPeriod(UINT wPeriod)
419 {
420     if (wPeriod < MMSYSTIME_MININTERVAL || wPeriod > MMSYSTIME_MAXINTERVAL)
421         return TIMERR_NOCANDO;
422
423     if (wPeriod > MMSYSTIME_MININTERVAL)
424     {
425         WARN("Stub; we set our timer resolution at minimum\n");
426     }
427
428     return 0;
429 }
430
431 /**************************************************************************
432  *                              timeEndPeriod           [WINMM.@]
433  */
434 MMRESULT WINAPI timeEndPeriod(UINT wPeriod)
435 {
436     if (wPeriod < MMSYSTIME_MININTERVAL || wPeriod > MMSYSTIME_MAXINTERVAL)
437         return TIMERR_NOCANDO;
438
439     if (wPeriod > MMSYSTIME_MININTERVAL)
440     {
441         WARN("Stub; we set our timer resolution at minimum\n");
442     }
443     return 0;
444 }