Debian Codegraph @

generic/tclTimer.c

raw
1 /*
2 * tclTimer.c --
3 *
4 * This file provides timer event management facilities for Tcl,
5 * including the "after" command.
6 *
7 * Copyright (c) 1997 by Sun Microsystems, Inc.
8 *
9 * See the file "license.terms" for information on usage and redistribution of
10 * this file, and for a DISCLAIMER OF ALL WARRANTIES.
11 */
12
13 #include "tclInt.h"
14
15 /*
16 * For each timer callback that's pending there is one record of the following
17 * type. The normal handlers (created by Tcl_CreateTimerHandler) are chained
18 * together in a list sorted by time (earliest event first).
19 */
20
21 typedef struct TimerHandler {
22 Tcl_Time time; /* When timer is to fire. */
23 Tcl_TimerProc *proc; /* Function to call. */
24 ClientData clientData; /* Argument to pass to proc. */
25 Tcl_TimerToken token; /* Identifies handler so it can be deleted. */
26 struct TimerHandler *nextPtr;
27 /* Next event in queue, or NULL for end of
28 * queue. */
29 } TimerHandler;
30
31 /*
32 * The data structure below is used by the "after" command to remember the
33 * command to be executed later. All of the pending "after" commands for an
34 * interpreter are linked together in a list.
35 */
36
37 typedef struct AfterInfo {
38 struct AfterAssocData *assocPtr;
39 /* Pointer to the "tclAfter" assocData for the
40 * interp in which command will be
41 * executed. */
42 Tcl_Obj *commandPtr; /* Command to execute. */
43 int id; /* Integer identifier for command; used to
44 * cancel it. */
45 Tcl_TimerToken token; /* Used to cancel the "after" command. NULL
46 * means that the command is run as an idle
47 * handler rather than as a timer handler.
48 * NULL means this is an "after idle" handler
49 * rather than a timer handler. */
50 struct AfterInfo *nextPtr; /* Next in list of all "after" commands for
51 * this interpreter. */
52 } AfterInfo;
53
54 /*
55 * One of the following structures is associated with each interpreter for
56 * which an "after" command has ever been invoked. A pointer to this structure
57 * is stored in the AssocData for the "tclAfter" key.
58 */
59
60 typedef struct AfterAssocData {
61 Tcl_Interp *interp; /* The interpreter for which this data is
62 * registered. */
63 AfterInfo *firstAfterPtr; /* First in list of all "after" commands still
64 * pending for this interpreter, or NULL if
65 * none. */
66 } AfterAssocData;
67
68 /*
69 * There is one of the following structures for each of the handlers declared
70 * in a call to Tcl_DoWhenIdle. All of the currently-active handlers are
71 * linked together into a list.
72 */
73
74 typedef struct IdleHandler {
75 Tcl_IdleProc *proc; /* Function to call. */
76 ClientData clientData; /* Value to pass to proc. */
77 int generation; /* Used to distinguish older handlers from
78 * recently-created ones. */
79 struct IdleHandler *nextPtr;/* Next in list of active handlers. */
80 } IdleHandler;
81
82 /*
83 * The timer and idle queues are per-thread because they are associated with
84 * the notifier, which is also per-thread.
85 *
86 * All static variables used in this file are collected into a single instance
87 * of the following structure. For multi-threaded implementations, there is
88 * one instance of this structure for each thread.
89 *
90 * Notice that different structures with the same name appear in other files.
91 * The structure defined below is used in this file only.
92 */
93
94 typedef struct ThreadSpecificData {
95 TimerHandler *firstTimerHandlerPtr; /* First event in queue. */
96 int lastTimerId; /* Timer identifier of most recently created
97 * timer. */
98 int timerPending; /* 1 if a timer event is in the queue. */
99 IdleHandler *idleList; /* First in list of all idle handlers. */
100 IdleHandler *lastIdlePtr; /* Last in list (or NULL for empty list). */
101 int idleGeneration; /* Used to fill in the "generation" fields of
102 * IdleHandler structures. Increments each
103 * time Tcl_DoOneEvent starts calling idle
104 * handlers, so that all old handlers can be
105 * called without calling any of the new ones
106 * created by old ones. */
107 int afterId; /* For unique identifiers of after events. */
108 } ThreadSpecificData;
109
110 static Tcl_ThreadDataKey dataKey;
111
112 /*
113 * Helper macros for working with times. TCL_TIME_BEFORE encodes how to write
114 * the ordering relation on (normalized) times, and TCL_TIME_DIFF_MS computes
115 * the number of milliseconds difference between two times. Both macros use
116 * both of their arguments multiple times, so make sure they are cheap and
117 * side-effect free. The "prototypes" for these macros are:
118 *
119 * static int TCL_TIME_BEFORE(Tcl_Time t1, Tcl_Time t2);
120 * static long TCL_TIME_DIFF_MS(Tcl_Time t1, Tcl_Time t2);
121 */
122
123 #define TCL_TIME_BEFORE(t1, t2) \
124 (((t1).sec<(t2).sec) || ((t1).sec==(t2).sec && (t1).usec<(t2).usec))
125
126 #define TCL_TIME_DIFF_MS(t1, t2) \
127 (1000*((Tcl_WideInt)(t1).sec - (Tcl_WideInt)(t2).sec) + \
128 ((long)(t1).usec - (long)(t2).usec)/1000)
129
130 #define TCL_TIME_DIFF_MS_CEILING(t1, t2) \
131 (1000*((Tcl_WideInt)(t1).sec - (Tcl_WideInt)(t2).sec) + \
132 ((long)(t1).usec - (long)(t2).usec + 999)/1000)
133
134 /*
135 * Sleeps under that number of milliseconds don't get double-checked
136 * and are done in exactly one Tcl_Sleep(). This to limit gettimeofday()s.
137 */
138
139 #define SLEEP_OFFLOAD_GETTIMEOFDAY 20
140
141 /*
142 * The maximum number of milliseconds for each Tcl_Sleep call in AfterDelay.
143 * This is used to limit the maximum lag between interp limit and script
144 * cancellation checks.
145 */
146
147 #define TCL_TIME_MAXIMUM_SLICE 500
148
149 /*
150 * Prototypes for functions referenced only in this file:
151 */
152
153 static void AfterCleanupProc(ClientData clientData,
154 Tcl_Interp *interp);
155 static int AfterDelay(Tcl_Interp *interp, Tcl_WideInt ms);
156 static void AfterProc(ClientData clientData);
157 static void FreeAfterPtr(AfterInfo *afterPtr);
158 static AfterInfo * GetAfterEvent(AfterAssocData *assocPtr,
159 Tcl_Obj *commandPtr);
160 static ThreadSpecificData *InitTimer(void);
161 static void TimerExitProc(ClientData clientData);
162 static int TimerHandlerEventProc(Tcl_Event *evPtr, int flags);
163 static void TimerCheckProc(ClientData clientData, int flags);
164 static void TimerSetupProc(ClientData clientData, int flags);
165
166 /*
167 *----------------------------------------------------------------------
168 *
169 * InitTimer --
170 *
171 * This function initializes the timer module.
172 *
173 * Results:
174 * A pointer to the thread specific data.
175 *
176 * Side effects:
177 * Registers the idle and timer event sources.
178 *
179 *----------------------------------------------------------------------
180 */
181
182 static ThreadSpecificData *
183 InitTimer(void)
184 {
185 ThreadSpecificData *tsdPtr = TclThreadDataKeyGet(&dataKey);
186
187 if (tsdPtr == NULL) {
188 tsdPtr = TCL_TSD_INIT(&dataKey);
189 Tcl_CreateEventSource(TimerSetupProc, TimerCheckProc, NULL);
190 Tcl_CreateThreadExitHandler(TimerExitProc, NULL);
191 }
192 return tsdPtr;
193 }
194
195 /*
196 *----------------------------------------------------------------------
197 *
198 * TimerExitProc --
199 *
200 * This function is call at exit or unload time to remove the timer and
201 * idle event sources.
202 *
203 * Results:
204 * None.
205 *
206 * Side effects:
207 * Removes the timer and idle event sources and remaining events.
208 *
209 *----------------------------------------------------------------------
210 */
211
212 static void
213 TimerExitProc(
214 ClientData clientData) /* Not used. */
215 {
216 ThreadSpecificData *tsdPtr = TclThreadDataKeyGet(&dataKey);
217
218 Tcl_DeleteEventSource(TimerSetupProc, TimerCheckProc, NULL);
219 if (tsdPtr != NULL) {
220 TimerHandler *timerHandlerPtr;
221
222 timerHandlerPtr = tsdPtr->firstTimerHandlerPtr;
223 while (timerHandlerPtr != NULL) {
224 tsdPtr->firstTimerHandlerPtr = timerHandlerPtr->nextPtr;
225 ckfree(timerHandlerPtr);
226 timerHandlerPtr = tsdPtr->firstTimerHandlerPtr;
227 }
228 }
229 }
230
231 /*
232 *--------------------------------------------------------------
233 *
234 * Tcl_CreateTimerHandler --
235 *
236 * Arrange for a given function to be invoked at a particular time in the
237 * future.
238 *
239 * Results:
240 * The return value is a token for the timer event, which may be used to
241 * delete the event before it fires.
242 *
243 * Side effects:
244 * When milliseconds have elapsed, proc will be invoked exactly once.
245 *
246 *--------------------------------------------------------------
247 */
248
249 Tcl_TimerToken
250 Tcl_CreateTimerHandler(
251 int milliseconds, /* How many milliseconds to wait before
252 * invoking proc. */
253 Tcl_TimerProc *proc, /* Function to invoke. */
254 ClientData clientData) /* Arbitrary data to pass to proc. */
255 {
256 Tcl_Time time;
257
258 /*
259 * Compute when the event should fire.
260 */
261
262 Tcl_GetTime(&time);
263 time.sec += milliseconds/1000;
264 time.usec += (milliseconds%1000)*1000;
265 if (time.usec >= 1000000) {
266 time.usec -= 1000000;
267 time.sec += 1;
268 }
269 return TclCreateAbsoluteTimerHandler(&time, proc, clientData);
270 }
271
272 /*
273 *--------------------------------------------------------------
274 *
275 * TclCreateAbsoluteTimerHandler --
276 *
277 * Arrange for a given function to be invoked at a particular time in the
278 * future.
279 *
280 * Results:
281 * The return value is a token for the timer event, which may be used to
282 * delete the event before it fires.
283 *
284 * Side effects:
285 * When the time in timePtr has been reached, proc will be invoked
286 * exactly once.
287 *
288 *--------------------------------------------------------------
289 */
290
291 Tcl_TimerToken
292 TclCreateAbsoluteTimerHandler(
293 Tcl_Time *timePtr,
294 Tcl_TimerProc *proc,
295 ClientData clientData)
296 {
297 TimerHandler *timerHandlerPtr, *tPtr2, *prevPtr;
298 ThreadSpecificData *tsdPtr = InitTimer();
299
300 timerHandlerPtr = ckalloc(sizeof(TimerHandler));
301
302 /*
303 * Fill in fields for the event.
304 */
305
306 memcpy(&timerHandlerPtr->time, timePtr, sizeof(Tcl_Time));
307 timerHandlerPtr->proc = proc;
308 timerHandlerPtr->clientData = clientData;
309 tsdPtr->lastTimerId++;
310 timerHandlerPtr->token = (Tcl_TimerToken) INT2PTR(tsdPtr->lastTimerId);
311
312 /*
313 * Add the event to the queue in the correct position (ordered by event
314 * firing time).
315 */
316
317 for (tPtr2 = tsdPtr->firstTimerHandlerPtr, prevPtr = NULL; tPtr2 != NULL;
318 prevPtr = tPtr2, tPtr2 = tPtr2->nextPtr) {
319 if (TCL_TIME_BEFORE(timerHandlerPtr->time, tPtr2->time)) {
320 break;
321 }
322 }
323 timerHandlerPtr->nextPtr = tPtr2;
324 if (prevPtr == NULL) {
325 tsdPtr->firstTimerHandlerPtr = timerHandlerPtr;
326 } else {
327 prevPtr->nextPtr = timerHandlerPtr;
328 }
329
330 TimerSetupProc(NULL, TCL_ALL_EVENTS);
331
332 return timerHandlerPtr->token;
333 }
334
335 /*
336 *--------------------------------------------------------------
337 *
338 * Tcl_DeleteTimerHandler --
339 *
340 * Delete a previously-registered timer handler.
341 *
342 * Results:
343 * None.
344 *
345 * Side effects:
346 * Destroy the timer callback identified by TimerToken, so that its
347 * associated function will not be called. If the callback has already
348 * fired, or if the given token doesn't exist, then nothing happens.
349 *
350 *--------------------------------------------------------------
351 */
352
353 void
354 Tcl_DeleteTimerHandler(
355 Tcl_TimerToken token) /* Result previously returned by
356 * Tcl_DeleteTimerHandler. */
357 {
358 TimerHandler *timerHandlerPtr, *prevPtr;
359 ThreadSpecificData *tsdPtr = InitTimer();
360
361 if (token == NULL) {
362 return;
363 }
364
365 for (timerHandlerPtr = tsdPtr->firstTimerHandlerPtr, prevPtr = NULL;
366 timerHandlerPtr != NULL; prevPtr = timerHandlerPtr,
367 timerHandlerPtr = timerHandlerPtr->nextPtr) {
368 if (timerHandlerPtr->token != token) {
369 continue;
370 }
371 if (prevPtr == NULL) {
372 tsdPtr->firstTimerHandlerPtr = timerHandlerPtr->nextPtr;
373 } else {
374 prevPtr->nextPtr = timerHandlerPtr->nextPtr;
375 }
376 ckfree(timerHandlerPtr);
377 return;
378 }
379 }
380
381 /*
382 *----------------------------------------------------------------------
383 *
384 * TimerSetupProc --
385 *
386 * This function is called by Tcl_DoOneEvent to setup the timer event
387 * source for before blocking. This routine checks both the idle and
388 * after timer lists.
389 *
390 * Results:
391 * None.
392 *
393 * Side effects:
394 * May update the maximum notifier block time.
395 *
396 *----------------------------------------------------------------------
397 */
398
399 static void
400 TimerSetupProc(
401 ClientData data, /* Not used. */
402 int flags) /* Event flags as passed to Tcl_DoOneEvent. */
403 {
404 Tcl_Time blockTime;
405 ThreadSpecificData *tsdPtr = InitTimer();
406
407 if (((flags & TCL_IDLE_EVENTS) && tsdPtr->idleList)
408 || ((flags & TCL_TIMER_EVENTS) && tsdPtr->timerPending)) {
409 /*
410 * There is an idle handler or a pending timer event, so just poll.
411 */
412
413 blockTime.sec = 0;
414 blockTime.usec = 0;
415 } else if ((flags & TCL_TIMER_EVENTS) && tsdPtr->firstTimerHandlerPtr) {
416 /*
417 * Compute the timeout for the next timer on the list.
418 */
419
420 Tcl_GetTime(&blockTime);
421 blockTime.sec = tsdPtr->firstTimerHandlerPtr->time.sec - blockTime.sec;
422 blockTime.usec = tsdPtr->firstTimerHandlerPtr->time.usec -
423 blockTime.usec;
424 if (blockTime.usec < 0) {
425 blockTime.sec -= 1;
426 blockTime.usec += 1000000;
427 }
428 if (blockTime.sec < 0) {
429 blockTime.sec = 0;
430 blockTime.usec = 0;
431 }
432 } else {
433 return;
434 }
435
436 Tcl_SetMaxBlockTime(&blockTime);
437 }
438
439 /*
440 *----------------------------------------------------------------------
441 *
442 * TimerCheckProc --
443 *
444 * This function is called by Tcl_DoOneEvent to check the timer event
445 * source for events. This routine checks both the idle and after timer
446 * lists.
447 *
448 * Results:
449 * None.
450 *
451 * Side effects:
452 * May queue an event and update the maximum notifier block time.
453 *
454 *----------------------------------------------------------------------
455 */
456
457 static void
458 TimerCheckProc(
459 ClientData data, /* Not used. */
460 int flags) /* Event flags as passed to Tcl_DoOneEvent. */
461 {
462 Tcl_Event *timerEvPtr;
463 Tcl_Time blockTime;
464 ThreadSpecificData *tsdPtr = InitTimer();
465
466 if ((flags & TCL_TIMER_EVENTS) && tsdPtr->firstTimerHandlerPtr) {
467 /*
468 * Compute the timeout for the next timer on the list.
469 */
470
471 Tcl_GetTime(&blockTime);
472 blockTime.sec = tsdPtr->firstTimerHandlerPtr->time.sec - blockTime.sec;
473 blockTime.usec = tsdPtr->firstTimerHandlerPtr->time.usec -
474 blockTime.usec;
475 if (blockTime.usec < 0) {
476 blockTime.sec -= 1;
477 blockTime.usec += 1000000;
478 }
479 if (blockTime.sec < 0) {
480 blockTime.sec = 0;
481 blockTime.usec = 0;
482 }
483
484 /*
485 * If the first timer has expired, stick an event on the queue.
486 */
487
488 if (blockTime.sec == 0 && blockTime.usec == 0 &&
489 !tsdPtr->timerPending) {
490 tsdPtr->timerPending = 1;
491 timerEvPtr = ckalloc(sizeof(Tcl_Event));
492 timerEvPtr->proc = TimerHandlerEventProc;
493 Tcl_QueueEvent(timerEvPtr, TCL_QUEUE_TAIL);
494 }
495 }
496 }
497
498 /*
499 *----------------------------------------------------------------------
500 *
501 * TimerHandlerEventProc --
502 *
503 * This function is called by Tcl_ServiceEvent when a timer event reaches
504 * the front of the event queue. This function handles the event by
505 * invoking the callbacks for all timers that are ready.
506 *
507 * Results:
508 * Returns 1 if the event was handled, meaning it should be removed from
509 * the queue. Returns 0 if the event was not handled, meaning it should
510 * stay on the queue. The only time the event isn't handled is if the
511 * TCL_TIMER_EVENTS flag bit isn't set.
512 *
513 * Side effects:
514 * Whatever the timer handler callback functions do.
515 *
516 *----------------------------------------------------------------------
517 */
518
519 static int
520 TimerHandlerEventProc(
521 Tcl_Event *evPtr, /* Event to service. */
522 int flags) /* Flags that indicate what events to handle,
523 * such as TCL_FILE_EVENTS. */
524 {
525 TimerHandler *timerHandlerPtr, **nextPtrPtr;
526 Tcl_Time time;
527 int currentTimerId;
528 ThreadSpecificData *tsdPtr = InitTimer();
529
530 /*
531 * Do nothing if timers aren't enabled. This leaves the event on the
532 * queue, so we will get to it as soon as ServiceEvents() is called with
533 * timers enabled.
534 */
535
536 if (!(flags & TCL_TIMER_EVENTS)) {
537 return 0;
538 }
539
540 /*
541 * The code below is trickier than it may look, for the following reasons:
542 *
543 * 1. New handlers can get added to the list while the current one is
544 * being processed. If new ones get added, we don't want to process
545 * them during this pass through the list to avoid starving other event
546 * sources. This is implemented using the token number in the handler:
547 * new handlers will have a newer token than any of the ones currently
548 * on the list.
549 * 2. The handler can call Tcl_DoOneEvent, so we have to remove the
550 * handler from the list before calling it. Otherwise an infinite loop
551 * could result.
552 * 3. Tcl_DeleteTimerHandler can be called to remove an element from the
553 * list while a handler is executing, so the list could change
554 * structure during the call.
555 * 4. Because we only fetch the current time before entering the loop, the
556 * only way a new timer will even be considered runnable is if its
557 * expiration time is within the same millisecond as the current time.
558 * This is fairly likely on Windows, since it has a course granularity
559 * clock. Since timers are placed on the queue in time order with the
560 * most recently created handler appearing after earlier ones with the
561 * same expiration time, we don't have to worry about newer generation
562 * timers appearing before later ones.
563 */
564
565 tsdPtr->timerPending = 0;
566 currentTimerId = tsdPtr->lastTimerId;
567 Tcl_GetTime(&time);
568 while (1) {
569 nextPtrPtr = &tsdPtr->firstTimerHandlerPtr;
570 timerHandlerPtr = tsdPtr->firstTimerHandlerPtr;
571 if (timerHandlerPtr == NULL) {
572 break;
573 }
574
575 if (TCL_TIME_BEFORE(time, timerHandlerPtr->time)) {
576 break;
577 }
578
579 /*
580 * Bail out if the next timer is of a newer generation.
581 */
582
583 if ((currentTimerId - PTR2INT(timerHandlerPtr->token)) < 0) {
584 break;
585 }
586
587 /*
588 * Remove the handler from the queue before invoking it, to avoid
589 * potential reentrancy problems.
590 */
591
592 *nextPtrPtr = timerHandlerPtr->nextPtr;
593 timerHandlerPtr->proc(timerHandlerPtr->clientData);
594 ckfree(timerHandlerPtr);
595 }
596 TimerSetupProc(NULL, TCL_TIMER_EVENTS);
597 return 1;
598 }
599
600 /*
601 *--------------------------------------------------------------
602 *
603 * Tcl_DoWhenIdle --
604 *
605 * Arrange for proc to be invoked the next time the system is idle (i.e.,
606 * just before the next time that Tcl_DoOneEvent would have to wait for
607 * something to happen).
608 *
609 * Results:
610 * None.
611 *
612 * Side effects:
613 * Proc will eventually be called, with clientData as argument. See the
614 * manual entry for details.
615 *
616 *--------------------------------------------------------------
617 */
618
619 void
620 Tcl_DoWhenIdle(
621 Tcl_IdleProc *proc, /* Function to invoke. */
622 ClientData clientData) /* Arbitrary value to pass to proc. */
623 {
624 IdleHandler *idlePtr;
625 Tcl_Time blockTime;
626 ThreadSpecificData *tsdPtr = InitTimer();
627
628 idlePtr = ckalloc(sizeof(IdleHandler));
629 idlePtr->proc = proc;
630 idlePtr->clientData = clientData;
631 idlePtr->generation = tsdPtr->idleGeneration;
632 idlePtr->nextPtr = NULL;
633 if (tsdPtr->lastIdlePtr == NULL) {
634 tsdPtr->idleList = idlePtr;
635 } else {
636 tsdPtr->lastIdlePtr->nextPtr = idlePtr;
637 }
638 tsdPtr->lastIdlePtr = idlePtr;
639
640 blockTime.sec = 0;
641 blockTime.usec = 0;
642 Tcl_SetMaxBlockTime(&blockTime);
643 }
644
645 /*
646 *----------------------------------------------------------------------
647 *
648 * Tcl_CancelIdleCall --
649 *
650 * If there are any when-idle calls requested to a given function with
651 * given clientData, cancel all of them.
652 *
653 * Results:
654 * None.
655 *
656 * Side effects:
657 * If the proc/clientData combination were on the when-idle list, they
658 * are removed so that they will never be called.
659 *
660 *----------------------------------------------------------------------
661 */
662
663 void
664 Tcl_CancelIdleCall(
665 Tcl_IdleProc *proc, /* Function that was previously registered. */
666 ClientData clientData) /* Arbitrary value to pass to proc. */
667 {
668 IdleHandler *idlePtr, *prevPtr;
669 IdleHandler *nextPtr;
670 ThreadSpecificData *tsdPtr = InitTimer();
671
672 for (prevPtr = NULL, idlePtr = tsdPtr->idleList; idlePtr != NULL;
673 prevPtr = idlePtr, idlePtr = idlePtr->nextPtr) {
674 while ((idlePtr->proc == proc)
675 && (idlePtr->clientData == clientData)) {
676 nextPtr = idlePtr->nextPtr;
677 ckfree(idlePtr);
678 idlePtr = nextPtr;
679 if (prevPtr == NULL) {
680 tsdPtr->idleList = idlePtr;
681 } else {
682 prevPtr->nextPtr = idlePtr;
683 }
684 if (idlePtr == NULL) {
685 tsdPtr->lastIdlePtr = prevPtr;
686 return;
687 }
688 }
689 }
690 }
691
692 /*
693 *----------------------------------------------------------------------
694 *
695 * TclServiceIdle --
696 *
697 * This function is invoked by the notifier when it becomes idle. It will
698 * invoke all idle handlers that are present at the time the call is
699 * invoked, but not those added during idle processing.
700 *
701 * Results:
702 * The return value is 1 if TclServiceIdle found something to do,
703 * otherwise return value is 0.
704 *
705 * Side effects:
706 * Invokes all pending idle handlers.
707 *
708 *----------------------------------------------------------------------
709 */
710
711 int
712 TclServiceIdle(void)
713 {
714 IdleHandler *idlePtr;
715 int oldGeneration;
716 Tcl_Time blockTime;
717 ThreadSpecificData *tsdPtr = InitTimer();
718
719 if (tsdPtr->idleList == NULL) {
720 return 0;
721 }
722
723 oldGeneration = tsdPtr->idleGeneration;
724 tsdPtr->idleGeneration++;
725
726 /*
727 * The code below is trickier than it may look, for the following reasons:
728 *
729 * 1. New handlers can get added to the list while the current one is
730 * being processed. If new ones get added, we don't want to process
731 * them during this pass through the list (want to check for other work
732 * to do first). This is implemented using the generation number in the
733 * handler: new handlers will have a different generation than any of
734 * the ones currently on the list.
735 * 2. The handler can call Tcl_DoOneEvent, so we have to remove the
736 * handler from the list before calling it. Otherwise an infinite loop
737 * could result.
738 * 3. Tcl_CancelIdleCall can be called to remove an element from the list
739 * while a handler is executing, so the list could change structure
740 * during the call.
741 */
742
743 for (idlePtr = tsdPtr->idleList;
744 ((idlePtr != NULL)
745 && ((oldGeneration - idlePtr->generation) >= 0));
746 idlePtr = tsdPtr->idleList) {
747 tsdPtr->idleList = idlePtr->nextPtr;
748 if (tsdPtr->idleList == NULL) {
749 tsdPtr->lastIdlePtr = NULL;
750 }
751 idlePtr->proc(idlePtr->clientData);
752 ckfree(idlePtr);
753 }
754 if (tsdPtr->idleList) {
755 blockTime.sec = 0;
756 blockTime.usec = 0;
757 Tcl_SetMaxBlockTime(&blockTime);
758 }
759 return 1;
760 }
761
762 /*
763 *----------------------------------------------------------------------
764 *
765 * Tcl_AfterObjCmd --
766 *
767 * This function is invoked to process the "after" Tcl command. See the
768 * user documentation for details on what it does.
769 *
770 * Results:
771 * A standard Tcl result.
772 *
773 * Side effects:
774 * See the user documentation.
775 *
776 *----------------------------------------------------------------------
777 */
778
779 /* ARGSUSED */
780 int
781 Tcl_AfterObjCmd(
782 ClientData clientData, /* Unused */
783 Tcl_Interp *interp, /* Current interpreter. */
784 int objc, /* Number of arguments. */
785 Tcl_Obj *const objv[]) /* Argument objects. */
786 {
787 Tcl_WideInt ms = 0; /* Number of milliseconds to wait */
788 Tcl_Time wakeup;
789 AfterInfo *afterPtr;
790 AfterAssocData *assocPtr;
791 int length;
792 int index;
793 static const char *const afterSubCmds[] = {
794 "cancel", "idle", "info", NULL
795 };
796 enum afterSubCmds {AFTER_CANCEL, AFTER_IDLE, AFTER_INFO};
797 ThreadSpecificData *tsdPtr = InitTimer();
798
799 if (objc < 2) {
800 Tcl_WrongNumArgs(interp, 1, objv, "option ?arg ...?");
801 return TCL_ERROR;
802 }
803
804 /*
805 * Create the "after" information associated for this interpreter, if it
806 * doesn't already exist.
807 */
808
809 assocPtr = Tcl_GetAssocData(interp, "tclAfter", NULL);
810 if (assocPtr == NULL) {
811 assocPtr = ckalloc(sizeof(AfterAssocData));
812 assocPtr->interp = interp;
813 assocPtr->firstAfterPtr = NULL;
814 Tcl_SetAssocData(interp, "tclAfter", AfterCleanupProc, assocPtr);
815 }
816
817 /*
818 * First lets see if the command was passed a number as the first argument.
819 */
820
821 if (objv[1]->typePtr == &tclIntType
822 #ifndef TCL_WIDE_INT_IS_LONG
823 || objv[1]->typePtr == &tclWideIntType
824 #endif
825 || objv[1]->typePtr == &tclBignumType
826 || (Tcl_GetIndexFromObj(NULL, objv[1], afterSubCmds, "", 0,
827 &index) != TCL_OK)) {
828 index = -1;
829 if (Tcl_GetWideIntFromObj(NULL, objv[1], &ms) != TCL_OK) {
830 const char *arg = TclGetString(objv[1]);
831
832 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
833 "bad argument \"%s\": must be"
834 " cancel, idle, info, or an integer", arg));
835 Tcl_SetErrorCode(interp, "TCL", "LOOKUP", "INDEX", "argument",
836 arg, (char *)NULL);
837 return TCL_ERROR;
838 }
839 }
840
841 /*
842 * At this point, either index = -1 and ms contains the number of ms
843 * to wait, or else index is the index of a subcommand.
844 */
845
846 switch (index) {
847 case -1: {
848 if (ms < 0) {
849 ms = 0;
850 }
851 if (objc == 2) {
852 return AfterDelay(interp, ms);
853 }
854 afterPtr = ckalloc(sizeof(AfterInfo));
855 afterPtr->assocPtr = assocPtr;
856 if (objc == 3) {
857 afterPtr->commandPtr = objv[2];
858 } else {
859 afterPtr->commandPtr = Tcl_ConcatObj(objc-2, objv+2);
860 }
861 Tcl_IncrRefCount(afterPtr->commandPtr);
862
863 /*
864 * The variable below is used to generate unique identifiers for after
865 * commands. This id can wrap around, which can potentially cause
866 * problems. However, there are not likely to be problems in practice,
867 * because after commands can only be requested to about a month in
868 * the future, and wrap-around is unlikely to occur in less than about
869 * 1-10 years. Thus it's unlikely that any old ids will still be
870 * around when wrap-around occurs.
871 */
872
873 afterPtr->id = tsdPtr->afterId;
874 tsdPtr->afterId += 1;
875 Tcl_GetTime(&wakeup);
876 wakeup.sec += (long)(ms / 1000);
877 wakeup.usec += ((long)(ms % 1000)) * 1000;
878 if (wakeup.usec > 1000000) {
879 wakeup.sec++;
880 wakeup.usec -= 1000000;
881 }
882 afterPtr->token = TclCreateAbsoluteTimerHandler(&wakeup,
883 AfterProc, afterPtr);
884 afterPtr->nextPtr = assocPtr->firstAfterPtr;
885 assocPtr->firstAfterPtr = afterPtr;
886 Tcl_SetObjResult(interp, Tcl_ObjPrintf("after#%d", afterPtr->id));
887 return TCL_OK;
888 }
889 case AFTER_CANCEL: {
890 Tcl_Obj *commandPtr;
891 const char *command, *tempCommand;
892 int tempLength;
893
894 if (objc < 3) {
895 Tcl_WrongNumArgs(interp, 2, objv, "id|command");
896 return TCL_ERROR;
897 }
898 if (objc == 3) {
899 commandPtr = objv[2];
900 } else {
901 commandPtr = Tcl_ConcatObj(objc-2, objv+2);
902 }
903 command = TclGetStringFromObj(commandPtr, &length);
904 for (afterPtr = assocPtr->firstAfterPtr; afterPtr != NULL;
905 afterPtr = afterPtr->nextPtr) {
906 tempCommand = TclGetStringFromObj(afterPtr->commandPtr,
907 &tempLength);
908 if ((length == tempLength)
909 && !memcmp(command, tempCommand, length)) {
910 break;
911 }
912 }
913 if (afterPtr == NULL) {
914 afterPtr = GetAfterEvent(assocPtr, commandPtr);
915 }
916 if (objc != 3) {
917 Tcl_DecrRefCount(commandPtr);
918 }
919 if (afterPtr != NULL) {
920 if (afterPtr->token != NULL) {
921 Tcl_DeleteTimerHandler(afterPtr->token);
922 } else {
923 Tcl_CancelIdleCall(AfterProc, afterPtr);
924 }
925 FreeAfterPtr(afterPtr);
926 }
927 break;
928 }
929 case AFTER_IDLE:
930 if (objc < 3) {
931 Tcl_WrongNumArgs(interp, 2, objv, "script ?script ...?");
932 return TCL_ERROR;
933 }
934 afterPtr = ckalloc(sizeof(AfterInfo));
935 afterPtr->assocPtr = assocPtr;
936 if (objc == 3) {
937 afterPtr->commandPtr = objv[2];
938 } else {
939 afterPtr->commandPtr = Tcl_ConcatObj(objc-2, objv+2);
940 }
941 Tcl_IncrRefCount(afterPtr->commandPtr);
942 afterPtr->id = tsdPtr->afterId;
943 tsdPtr->afterId += 1;
944 afterPtr->token = NULL;
945 afterPtr->nextPtr = assocPtr->firstAfterPtr;
946 assocPtr->firstAfterPtr = afterPtr;
947 Tcl_DoWhenIdle(AfterProc, afterPtr);
948 Tcl_SetObjResult(interp, Tcl_ObjPrintf("after#%d", afterPtr->id));
949 break;
950 case AFTER_INFO:
951 if (objc == 2) {
952 Tcl_Obj *resultObj;
953
954 TclNewObj(resultObj);
955 for (afterPtr = assocPtr->firstAfterPtr; afterPtr != NULL;
956 afterPtr = afterPtr->nextPtr) {
957 if (assocPtr->interp == interp) {
958 Tcl_ListObjAppendElement(NULL, resultObj, Tcl_ObjPrintf(
959 "after#%d", afterPtr->id));
960 }
961 }
962 Tcl_SetObjResult(interp, resultObj);
963 return TCL_OK;
964 }
965 if (objc != 3) {
966 Tcl_WrongNumArgs(interp, 2, objv, "?id?");
967 return TCL_ERROR;
968 }
969 afterPtr = GetAfterEvent(assocPtr, objv[2]);
970 if (afterPtr == NULL) {
971 const char *eventStr = TclGetString(objv[2]);
972
973 Tcl_SetObjResult(interp, Tcl_ObjPrintf(
974 "event \"%s\" doesn't exist", eventStr));
975 Tcl_SetErrorCode(interp, "TCL","LOOKUP","EVENT", eventStr, (char *)NULL);
976 return TCL_ERROR;
977 } else {
978 Tcl_Obj *resultListPtr;
979
980 TclNewObj(resultListPtr);
981 Tcl_ListObjAppendElement(interp, resultListPtr,
982 afterPtr->commandPtr);
983 Tcl_ListObjAppendElement(interp, resultListPtr, Tcl_NewStringObj(
984 (afterPtr->token == NULL) ? "idle" : "timer", -1));
985 Tcl_SetObjResult(interp, resultListPtr);
986 }
987 break;
988 default:
989 Tcl_Panic("Tcl_AfterObjCmd: bad subcommand index to afterSubCmds");
990 }
991 return TCL_OK;
992 }
993
994 /*
995 *----------------------------------------------------------------------
996 *
997 * AfterDelay --
998 *
999 * Implements the blocking delay behaviour of [after $time]. Tricky
1000 * because it has to take into account any time limit that has been set.
1001 *
1002 * Results:
1003 * Standard Tcl result code (with error set if an error occurred due to a
1004 * time limit being exceeded or being canceled).
1005 *
1006 * Side effects:
1007 * May adjust the time limit granularity marker.
1008 *
1009 *----------------------------------------------------------------------
1010 */
1011
1012 static int
1013 AfterDelay(
1014 Tcl_Interp *interp,
1015 Tcl_WideInt ms)
1016 {
1017 Interp *iPtr = (Interp *) interp;
1018
1019 Tcl_Time endTime, now;
1020 Tcl_WideInt diff;
1021
1022 Tcl_GetTime(&now);
1023 endTime = now;
1024 endTime.sec += (long)(ms / 1000);
1025 endTime.usec += ((int)(ms % 1000)) * 1000;
1026 if (endTime.usec >= 1000000) {
1027 endTime.sec++;
1028 endTime.usec -= 1000000;
1029 }
1030
1031 do {
1032 if (Tcl_AsyncReady()) {
1033 if (Tcl_AsyncInvoke(interp, TCL_OK) != TCL_OK) {
1034 return TCL_ERROR;
1035 }
1036 }
1037 if (Tcl_Canceled(interp, TCL_LEAVE_ERR_MSG) == TCL_ERROR) {
1038 return TCL_ERROR;
1039 }
1040 if (iPtr->limit.timeEvent != NULL
1041 && TCL_TIME_BEFORE(iPtr->limit.time, now)) {
1042 iPtr->limit.granularityTicker = 0;
1043 if (Tcl_LimitCheck(interp) != TCL_OK) {
1044 return TCL_ERROR;
1045 }
1046 }
1047 if (iPtr->limit.timeEvent == NULL
1048 || TCL_TIME_BEFORE(endTime, iPtr->limit.time)) {
1049 diff = TCL_TIME_DIFF_MS_CEILING(endTime, now);
1050 #ifndef TCL_WIDE_INT_IS_LONG
1051 if (diff > LONG_MAX) {
1052 diff = LONG_MAX;
1053 }
1054 #endif
1055 if (diff > TCL_TIME_MAXIMUM_SLICE) {
1056 diff = TCL_TIME_MAXIMUM_SLICE;
1057 }
1058 if (diff == 0 && TCL_TIME_BEFORE(now, endTime)) {
1059 diff = 1;
1060 }
1061 if (diff > 0) {
1062 Tcl_Sleep((long) diff);
1063 if (diff < SLEEP_OFFLOAD_GETTIMEOFDAY) {
1064 break;
1065 }
1066 } else {
1067 break;
1068 }
1069 } else {
1070 diff = TCL_TIME_DIFF_MS(iPtr->limit.time, now);
1071 #ifndef TCL_WIDE_INT_IS_LONG
1072 if (diff > LONG_MAX) {
1073 diff = LONG_MAX;
1074 }
1075 #endif
1076 if (diff > TCL_TIME_MAXIMUM_SLICE) {
1077 diff = TCL_TIME_MAXIMUM_SLICE;
1078 }
1079 if (diff > 0) {
1080 Tcl_Sleep((long) diff);
1081 }
1082 if (Tcl_AsyncReady()) {
1083 if (Tcl_AsyncInvoke(interp, TCL_OK) != TCL_OK) {
1084 return TCL_ERROR;
1085 }
1086 }
1087 if (Tcl_Canceled(interp, TCL_LEAVE_ERR_MSG) == TCL_ERROR) {
1088 return TCL_ERROR;
1089 }
1090 if (Tcl_LimitCheck(interp) != TCL_OK) {
1091 return TCL_ERROR;
1092 }
1093 }
1094 Tcl_GetTime(&now);
1095 } while (TCL_TIME_BEFORE(now, endTime));
1096 return TCL_OK;
1097 }
1098
1099 /*
1100 *----------------------------------------------------------------------
1101 *
1102 * GetAfterEvent --
1103 *
1104 * This function parses an "after" id such as "after#4" and returns a
1105 * pointer to the AfterInfo structure.
1106 *
1107 * Results:
1108 * The return value is either a pointer to an AfterInfo structure, if one
1109 * is found that corresponds to "cmdString" and is for interp, or NULL if
1110 * no corresponding after event can be found.
1111 *
1112 * Side effects:
1113 * None.
1114 *
1115 *----------------------------------------------------------------------
1116 */
1117
1118 static AfterInfo *
1119 GetAfterEvent(
1120 AfterAssocData *assocPtr, /* Points to "after"-related information for
1121 * this interpreter. */
1122 Tcl_Obj *commandPtr)
1123 {
1124 const char *cmdString; /* Textual identifier for after event, such as
1125 * "after#6". */
1126 AfterInfo *afterPtr;
1127 int id;
1128 char *end;
1129
1130 cmdString = TclGetString(commandPtr);
1131 if (strncmp(cmdString, "after#", 6) != 0) {
1132 return NULL;
1133 }
1134 cmdString += 6;
1135 id = strtoul(cmdString, &end, 10);
1136 if ((end == cmdString) || (*end != 0)) {
1137 return NULL;
1138 }
1139 for (afterPtr = assocPtr->firstAfterPtr; afterPtr != NULL;
1140 afterPtr = afterPtr->nextPtr) {
1141 if (afterPtr->id == id) {
1142 return afterPtr;
1143 }
1144 }
1145 return NULL;
1146 }
1147
1148 /*
1149 *----------------------------------------------------------------------
1150 *
1151 * AfterProc --
1152 *
1153 * Timer callback to execute commands registered with the "after"
1154 * command.
1155 *
1156 * Results:
1157 * None.
1158 *
1159 * Side effects:
1160 * Executes whatever command was specified. If the command returns an
1161 * error, then the command "bgerror" is invoked to process the error; if
1162 * bgerror fails then information about the error is output on stderr.
1163 *
1164 *----------------------------------------------------------------------
1165 */
1166
1167 static void
1168 AfterProc(
1169 ClientData clientData) /* Describes command to execute. */
1170 {
1171 AfterInfo *afterPtr = clientData;
1172 AfterAssocData *assocPtr = afterPtr->assocPtr;
1173 AfterInfo *prevPtr;
1174 int result;
1175 Tcl_Interp *interp;
1176
1177 /*
1178 * First remove the callback from our list of callbacks; otherwise someone
1179 * could delete the callback while it's being executed, which could cause
1180 * a core dump.
1181 */
1182
1183 if (assocPtr->firstAfterPtr == afterPtr) {
1184 assocPtr->firstAfterPtr = afterPtr->nextPtr;
1185 } else {
1186 for (prevPtr = assocPtr->firstAfterPtr; prevPtr->nextPtr != afterPtr;
1187 prevPtr = prevPtr->nextPtr) {
1188 /* Empty loop body. */
1189 }
1190 prevPtr->nextPtr = afterPtr->nextPtr;
1191 }
1192
1193 /*
1194 * Execute the callback.
1195 */
1196
1197 interp = assocPtr->interp;
1198 Tcl_Preserve(interp);
1199 result = Tcl_EvalObjEx(interp, afterPtr->commandPtr, TCL_EVAL_GLOBAL);
1200 if (result != TCL_OK) {
1201 Tcl_AddErrorInfo(interp, "\n (\"after\" script)");
1202 Tcl_BackgroundException(interp, result);
1203 }
1204 Tcl_Release(interp);
1205
1206 /*
1207 * Free the memory for the callback.
1208 */
1209
1210 Tcl_DecrRefCount(afterPtr->commandPtr);
1211 ckfree(afterPtr);
1212 }
1213
1214 /*
1215 *----------------------------------------------------------------------
1216 *
1217 * FreeAfterPtr --
1218 *
1219 * This function removes an "after" command from the list of those that
1220 * are pending and frees its resources. This function does *not* cancel
1221 * the timer handler; if that's needed, the caller must do it.
1222 *
1223 * Results:
1224 * None.
1225 *
1226 * Side effects:
1227 * The memory associated with afterPtr is released.
1228 *
1229 *----------------------------------------------------------------------
1230 */
1231
1232 static void
1233 FreeAfterPtr(
1234 AfterInfo *afterPtr) /* Command to be deleted. */
1235 {
1236 AfterInfo *prevPtr;
1237 AfterAssocData *assocPtr = afterPtr->assocPtr;
1238
1239 if (assocPtr->firstAfterPtr == afterPtr) {
1240 assocPtr->firstAfterPtr = afterPtr->nextPtr;
1241 } else {
1242 for (prevPtr = assocPtr->firstAfterPtr; prevPtr->nextPtr != afterPtr;
1243 prevPtr = prevPtr->nextPtr) {
1244 /* Empty loop body. */
1245 }
1246 prevPtr->nextPtr = afterPtr->nextPtr;
1247 }
1248 Tcl_DecrRefCount(afterPtr->commandPtr);
1249 ckfree(afterPtr);
1250 }
1251
1252 /*
1253 *----------------------------------------------------------------------
1254 *
1255 * AfterCleanupProc --
1256 *
1257 * This function is invoked whenever an interpreter is deleted
1258 * to cleanup the AssocData for "tclAfter".
1259 *
1260 * Results:
1261 * None.
1262 *
1263 * Side effects:
1264 * After commands are removed.
1265 *
1266 *----------------------------------------------------------------------
1267 */
1268
1269 /* ARGSUSED */
1270 static void
1271 AfterCleanupProc(
1272 ClientData clientData, /* Points to AfterAssocData for the
1273 * interpreter. */
1274 Tcl_Interp *interp) /* Interpreter that is being deleted. */
1275 {
1276 AfterAssocData *assocPtr = clientData;
1277 AfterInfo *afterPtr;
1278
1279 while (assocPtr->firstAfterPtr != NULL) {
1280 afterPtr = assocPtr->firstAfterPtr;
1281 assocPtr->firstAfterPtr = afterPtr->nextPtr;
1282 if (afterPtr->token != NULL) {
1283 Tcl_DeleteTimerHandler(afterPtr->token);
1284 } else {
1285 Tcl_CancelIdleCall(AfterProc, afterPtr);
1286 }
1287 Tcl_DecrRefCount(afterPtr->commandPtr);
1288 ckfree(afterPtr);
1289 }
1290 ckfree(assocPtr);
1291 }
1292
1293 /*
1294 * Local Variables:
1295 * mode: c
1296 * c-basic-offset: 4
1297 * fill-column: 78
1298 * tab-width: 8
1299 * indent-tabs-mode: nil
1300 * End:
1301 */