os/persistentdata/persistentstorage/sqlite3api/TEST/TCL/tcldistribution/win/tclWinNotify.c
First public contribution.
4 * This file contains Windows-specific procedures for the notifier,
5 * which is the lowest-level part of the Tcl event loop. This file
6 * works together with ../generic/tclNotify.c.
8 * Copyright (c) 1995-1997 Sun Microsystems, Inc.
10 * See the file "license.terms" for information on usage and redistribution
11 * of this file, and for a DISCLAIMER OF ALL WARRANTIES.
13 * RCS: @(#) $Id: tclWinNotify.c,v 1.11.2.1 2003/03/21 03:24:09 dgp Exp $
16 #include "tclWinInt.h"
19 * The follwing static indicates whether this module has been initialized.
22 #define INTERVAL_TIMER 1 /* Handle of interval timer. */
24 #define WM_WAKEUP WM_USER /* Message that is send by
25 * Tcl_AlertNotifier. */
27 * The following static structure contains the state information for the
28 * Windows implementation of the Tcl notifier. One of these structures
29 * is created for each thread that is using the notifier.
32 typedef struct ThreadSpecificData {
33 CRITICAL_SECTION crit; /* Monitor for this notifier. */
34 DWORD thread; /* Identifier for thread associated with this
36 HANDLE event; /* Event object used to wake up the notifier
38 int pending; /* Alert message pending, this field is
39 * locked by the notifierMutex. */
40 HWND hwnd; /* Messaging window. */
41 int timeout; /* Current timeout value. */
42 int timerActive; /* 1 if interval timer is running. */
45 static Tcl_ThreadDataKey dataKey;
47 extern TclStubs tclStubs;
48 extern Tcl_NotifierProcs tclOriginalNotifier;
51 * The following static indicates the number of threads that have
52 * initialized notifiers. It controls the lifetime of the TclNotifier
55 * You must hold the notifierMutex lock before accessing this variable.
58 static int notifierCount = 0;
59 TCL_DECLARE_MUTEX(notifierMutex)
62 * Static routines defined in this file.
65 static LRESULT CALLBACK NotifierProc(HWND hwnd, UINT message,
66 WPARAM wParam, LPARAM lParam);
70 *----------------------------------------------------------------------
74 * Initializes the platform specific notifier state.
77 * Returns a handle to the notifier state for this thread..
82 *----------------------------------------------------------------------
88 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
92 * Register Notifier window class if this is the first thread to
96 Tcl_MutexLock(¬ifierMutex);
97 if (notifierCount == 0) {
100 class.cbWndExtra = 0;
101 class.hInstance = TclWinGetTclInstance();
102 class.hbrBackground = NULL;
103 class.lpszMenuName = NULL;
104 class.lpszClassName = "TclNotifier";
105 class.lpfnWndProc = NotifierProc;
107 class.hCursor = NULL;
109 if (!RegisterClassA(&class)) {
110 panic("Unable to register TclNotifier window class");
114 Tcl_MutexUnlock(¬ifierMutex);
117 tsdPtr->timerActive = 0;
119 InitializeCriticalSection(&tsdPtr->crit);
122 tsdPtr->thread = GetCurrentThreadId();
123 tsdPtr->event = CreateEvent(NULL, TRUE /* manual */,
124 FALSE /* !signaled */, NULL);
126 return (ClientData) tsdPtr;
130 *----------------------------------------------------------------------
132 * Tcl_FinalizeNotifier --
134 * This function is called to cleanup the notifier state before
135 * a thread is terminated.
141 * May dispose of the notifier window and class.
143 *----------------------------------------------------------------------
147 Tcl_FinalizeNotifier(clientData)
148 ClientData clientData; /* Pointer to notifier data. */
150 ThreadSpecificData *tsdPtr = (ThreadSpecificData *) clientData;
153 * Only finalize the notifier if a notifier was installed in the
154 * current thread; there is a route in which this is not
155 * guaranteed to be true (when tclWin32Dll.c:DllMain() is called
156 * with the flag DLL_PROCESS_DETACH by the OS, which could be
157 * doing so from a thread that's never previously been involved
158 * with Tcl, e.g. the task manager) so this check is important.
160 * Fixes Bug #217982 reported by Hugh Vu and Gene Leache.
162 if (tsdPtr == NULL) {
166 DeleteCriticalSection(&tsdPtr->crit);
167 CloseHandle(tsdPtr->event);
170 * Clean up the timer and messaging window for this thread.
174 KillTimer(tsdPtr->hwnd, INTERVAL_TIMER);
175 DestroyWindow(tsdPtr->hwnd);
179 * If this is the last thread to use the notifier, unregister
180 * the notifier window class.
183 Tcl_MutexLock(¬ifierMutex);
185 if (notifierCount == 0) {
186 UnregisterClassA("TclNotifier", TclWinGetTclInstance());
188 Tcl_MutexUnlock(¬ifierMutex);
192 *----------------------------------------------------------------------
194 * Tcl_AlertNotifier --
196 * Wake up the specified notifier from any thread. This routine
197 * is called by the platform independent notifier code whenever
198 * the Tcl_ThreadAlert routine is called. This routine is
199 * guaranteed not to be called on a given notifier after
200 * Tcl_FinalizeNotifier is called for that notifier. This routine
201 * is typically called from a thread other than the notifier's
208 * Sends a message to the messaging window for the notifier
209 * if there isn't already one pending.
211 *----------------------------------------------------------------------
215 Tcl_AlertNotifier(clientData)
216 ClientData clientData; /* Pointer to thread data. */
218 ThreadSpecificData *tsdPtr = (ThreadSpecificData *) clientData;
221 * Note that we do not need to lock around access to the hwnd
222 * because the race condition has no effect since any race condition
223 * implies that the notifier thread is already awake.
228 * We do need to lock around access to the pending flag.
231 EnterCriticalSection(&tsdPtr->crit);
232 if (!tsdPtr->pending) {
233 PostMessage(tsdPtr->hwnd, WM_WAKEUP, 0, 0);
236 LeaveCriticalSection(&tsdPtr->crit);
238 SetEvent(tsdPtr->event);
243 *----------------------------------------------------------------------
247 * This procedure sets the current notifier timer value. The
248 * notifier will ensure that Tcl_ServiceAll() is called after
249 * the specified interval, even if no events have occurred.
255 * Replaces any previous timer.
257 *----------------------------------------------------------------------
262 Tcl_Time *timePtr) /* Maximum block time, or NULL. */
264 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
268 * Allow the notifier to be hooked. This may not make sense
269 * on Windows, but mirrors the UNIX hook.
272 if (tclStubs.tcl_SetTimer != tclOriginalNotifier.setTimerProc) {
273 tclStubs.tcl_SetTimer(timePtr);
278 * We only need to set up an interval timer if we're being called
279 * from an external event loop. If we don't have a window handle
280 * then we just return immediately and let Tcl_WaitForEvent handle
292 * Make sure we pass a non-zero value into the timeout argument.
293 * Windows seems to get confused by zero length timers.
296 timeout = timePtr->sec * 1000 + timePtr->usec / 1000;
301 tsdPtr->timeout = timeout;
303 tsdPtr->timerActive = 1;
304 SetTimer(tsdPtr->hwnd, INTERVAL_TIMER,
305 (unsigned long) tsdPtr->timeout, NULL);
307 tsdPtr->timerActive = 0;
308 KillTimer(tsdPtr->hwnd, INTERVAL_TIMER);
313 *----------------------------------------------------------------------
315 * Tcl_ServiceModeHook --
317 * This function is invoked whenever the service mode changes.
323 * If this is the first time the notifier is set into
324 * TCL_SERVICE_ALL, then the communication window is created.
326 *----------------------------------------------------------------------
330 Tcl_ServiceModeHook(mode)
331 int mode; /* Either TCL_SERVICE_ALL, or
332 * TCL_SERVICE_NONE. */
334 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
337 * If this is the first time that the notifier has been used from a
338 * modal loop, then create a communication window. Note that after
339 * this point, the application needs to service events in a timely
340 * fashion or Windows will hang waiting for the window to respond
341 * to synchronous system messages. At some point, we may want to
342 * consider destroying the window if we leave the modal loop, but
343 * for now we'll leave it around.
346 if (mode == TCL_SERVICE_ALL && !tsdPtr->hwnd) {
347 tsdPtr->hwnd = CreateWindowA("TclNotifier", "TclNotifier", WS_TILED,
348 0, 0, 0, 0, NULL, NULL, TclWinGetTclInstance(), NULL);
350 * Send an initial message to the window to ensure that we wake up the
351 * notifier once we get into the modal loop. This will force the
352 * notifier to recompute the timeout value and schedule a timer
356 Tcl_AlertNotifier((ClientData)tsdPtr);
361 *----------------------------------------------------------------------
365 * This procedure is invoked by Windows to process events on
366 * the notifier window. Messages will be sent to this window
367 * in response to external timer events or calls to
371 * A standard windows result.
374 * Services any pending events.
376 *----------------------------------------------------------------------
379 static LRESULT CALLBACK
386 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
388 if (message == WM_WAKEUP) {
389 EnterCriticalSection(&tsdPtr->crit);
391 LeaveCriticalSection(&tsdPtr->crit);
392 } else if (message != WM_TIMER) {
393 return DefWindowProc(hwnd, message, wParam, lParam);
397 * Process all of the runnable events.
405 *----------------------------------------------------------------------
407 * Tcl_WaitForEvent --
409 * This function is called by Tcl_DoOneEvent to wait for new
410 * events on the message queue. If the block time is 0, then
411 * Tcl_WaitForEvent just polls the event queue without blocking.
414 * Returns -1 if a WM_QUIT message is detected, returns 1 if
415 * a message was dispatched, otherwise returns 0.
418 * Dispatches a message to a window procedure, which could do
421 *----------------------------------------------------------------------
426 Tcl_Time *timePtr) /* Maximum block time, or NULL. */
428 ThreadSpecificData *tsdPtr = TCL_TSD_INIT(&dataKey);
430 DWORD timeout, result;
434 * Allow the notifier to be hooked. This may not make
435 * sense on windows, but mirrors the UNIX hook.
438 if (tclStubs.tcl_WaitForEvent != tclOriginalNotifier.waitForEventProc) {
439 return tclStubs.tcl_WaitForEvent(timePtr);
443 * Compute the timeout in milliseconds.
447 timeout = timePtr->sec * 1000 + timePtr->usec / 1000;
453 * Check to see if there are any messages in the queue before waiting
454 * because MsgWaitForMultipleObjects will not wake up if there are events
455 * currently sitting in the queue.
458 if (!PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
460 * Wait for something to happen (a signal from another thread, a
461 * message, or timeout).
464 result = MsgWaitForMultipleObjects(1, &tsdPtr->event, FALSE, timeout,
469 * Check to see if there are any messages to process.
472 if (PeekMessage(&msg, NULL, 0, 0, PM_NOREMOVE)) {
474 * Retrieve and dispatch the first message.
477 result = GetMessage(&msg, NULL, 0, 0);
480 * We received a request to exit this thread (WM_QUIT), so
481 * propagate the quit message and start unwinding.
484 PostQuitMessage((int) msg.wParam);
486 } else if (result == -1) {
488 * We got an error from the system. I have no idea why this would
489 * happen, so we'll just unwind.
494 TranslateMessage(&msg);
495 DispatchMessage(&msg);
502 ResetEvent(tsdPtr->event);
507 *----------------------------------------------------------------------
511 * Delay execution for the specified number of milliseconds.
519 *----------------------------------------------------------------------
524 int ms; /* Number of milliseconds to sleep. */
527 * Simply calling 'Sleep' for the requisite number of milliseconds
528 * can make the process appear to wake up early because it isn't
529 * synchronized with the CPU performance counter that is used in
530 * tclWinTime.c. This behavior is probably benign, but messes
531 * up some of the corner cases in the test suite. We get around
532 * this problem by repeating the 'Sleep' call as many times
533 * as necessary to make the clock advance by the requisite amount.
536 Tcl_Time now; /* Current wall clock time */
537 Tcl_Time desired; /* Desired wakeup time */
538 DWORD sleepTime = ms; /* Time to sleep */
541 desired.sec = now.sec + ( ms / 1000 );
542 desired.usec = now.usec + 1000 * ( ms % 1000 );
543 if ( desired.usec > 1000000 ) {
545 desired.usec -= 1000000;
551 if ( now.sec > desired.sec ) {
553 } else if ( ( now.sec == desired.sec )
554 && ( now.usec >= desired.usec ) ) {
557 sleepTime = ( ( 1000 * ( desired.sec - now.sec ) )
558 + ( ( desired.usec - now.usec ) / 1000 ) );