Tk Source Code

Artifact [8894f82c]
Login

Artifact 8894f82c202b644af65dd8ac0c066184e011aa47bb1aa347123bcc8e47c98890:

Attachment "tk-bug-591829e948-A-followup.patch" to ticket [591829e9] added by nab 2026-05-19 21:15:29.
diff -urN macosx/tkMacOSXPrivate.h macosx/tkMacOSXPrivate.h
--- macosx/tkMacOSXPrivate.h	2026-05-19 13:45:44
+++ macosx/tkMacOSXPrivate.h	2026-05-19 22:54:07
@@ -254,6 +254,7 @@
 			    CGContextRef context, BOOL useDarkAppearance);
 MODULE_SCOPE void       TkMacOSXRedrawViewIdleTask(void *clientData);
 MODULE_SCOPE void       TkMacOSXUpdateViewIdleTask(void *clientData);
+MODULE_SCOPE void       DeferredOrderFrontRootWindow(void *clientData);
 #define TkMacOSXGetTkWindow(window) ((TkWindow *)Tk_MacOSXGetTkWindow(window))
 #define TkMacOSXGetNSWindowForDrawable(drawable) ((NSWindow *)Tk_MacOSXGetNSWindowForDrawable(drawable))
 #define TkMacOSXGetNSViewForDrawable(macWin) ((NSView *)Tk_MacOSXGetNSViewForDrawable((Drawable)(macWin)))
@@ -421,6 +422,19 @@
     NSTrackingArea *trackingArea;
 }
 @property CGContextRef tkLayerBitmapContext;
+
+/*
+ * One-shot "drain pending widget display procs at the next updateLayer"
+ * flag, restoring the semantic that the (now-removed on this branch)
+ * [self onScreen] flag used to carry.  YES at view creation, re-armed
+ * each time the toplevel is unmapped or withdrawn, cleared by updateLayer
+ * once it has drained pending TCL_IDLE_EVENTS.  [self.window isVisible]
+ * alone cannot serve here because it flips to YES synchronously inside
+ * TkpWmSetState/orderFront, often before all of the toplevel's children
+ * have been (re)mapped — so without this flag, the post-deiconify
+ * updateLayer would publish an incomplete bitmap.
+ */
+@property BOOL tkNeedsInitialDrain;
 @end
 
 @interface TKContentView(TKKeyEvent)
diff -urN macosx/tkMacOSXSubwindows.c macosx/tkMacOSXSubwindows.c
--- macosx/tkMacOSXSubwindows.c	2026-05-19 13:45:44
+++ macosx/tkMacOSXSubwindows.c	2026-05-19 23:08:57
@@ -176,17 +176,34 @@
 	if (!Tk_IsEmbedded(winPtr)) {
 	    TkMacOSXApplyWindowAttributes(winPtr, win);
 	    [win setExcludedFromWindowsMenu:NO];
-	    [NSApp activateIgnoringOtherApps:YES];
 	    if (winPtr == (TkWindow *)Tk_MainWindow(winPtr->mainPtr->interp)) {
-		if (winPtr->wmInfoPtr->hints.initial_state == NormalState) {
 
-		    /*
-		     * Order the Tk root window front unless it was immediately withdrawn.
-		     */
+		/*
+		 * Defer ordering the Tk root window front until idle time, so
+		 * the startup script has a chance to create and map the
+		 * children of "." before the root NSWindow becomes visible.
+		 * Otherwise the root window flashes empty on screen for a
+		 * noticeable amount of time while the rest of the
+		 * initialization finishes (regression of ticket d1989fb7cf).
+		 * The idle handler rechecks initial_state so we still skip
+		 * ordering it front if it was withdrawn immediately after
+		 * creation.
+		 *
+		 * Also skip [NSApp activateIgnoringOtherApps:YES] here.  That
+		 * call posts NSApplicationDidBecomeActiveNotification whose
+		 * handler applicationActivate: does
+		 * [[self keyWindow] orderFront:self] — which would defeat the
+		 * deferral above and flip the root NSWindow to isVisible=YES
+		 * before its children are laid out.  The
+		 * makeKeyAndOrderFront: emitted by
+		 * DeferredOrderFrontRootWindow activates the app naturally
+		 * when it eventually fires.
+		 */
 
-		    [win makeKeyAndOrderFront:NSApp];
-		}
+		Tcl_CancelIdleCall(DeferredOrderFrontRootWindow, win);
+		Tcl_DoWhenIdle(DeferredOrderFrontRootWindow, win);
 	    } else {
+		[NSApp activateIgnoringOtherApps:YES];
 		if ([win canBecomeKeyWindow]) {
 		    [win makeKeyAndOrderFront:NSApp];
 		    [NSApp setTkEventTarget:TkMacOSXGetTkWindow(win)];
@@ -250,6 +267,100 @@
 /*
  *----------------------------------------------------------------------
  *
+ * DeferredOrderFrontRootWindow --
+ *
+ *	Idle task scheduled from XMapWindow() when it is invoked for the
+ *	Tk root window.  Ordering the root NSWindow front from inside
+ *	XMapWindow itself happens too early in the startup sequence: the
+ *	wish script has not yet finished creating and mapping the children
+ *	of ".", so the root window briefly appears empty on screen.
+ *	Deferring the orderFront to idle time lets the rest of the script
+ *	run first, then the root window appears with all its widgets
+ *	already in place.
+ *
+ *	The handler rechecks initial_state because the script may have
+ *	withdrawn the window immediately after creation, in which case it
+ *	should not be shown.
+ *
+ * Results:
+ *	None.
+ *
+ * Side effects:
+ *	The given NSWindow becomes the key window and is ordered front,
+ *	unless its Tk wm state has changed to non-NormalState in the
+ *	meantime, or the application is exiting.
+ *
+ *----------------------------------------------------------------------
+ */
+
+void
+DeferredOrderFrontRootWindow(
+    void *clientData)
+{
+    NSWindow *win = (NSWindow *) clientData;
+
+    if ([NSApp tkWillExit]) {
+	return;
+    }
+    TkWindow *winPtr = TkMacOSXGetTkWindow(win);
+    if (!winPtr || !winPtr->wmInfoPtr ||
+	    winPtr->wmInfoPtr->hints.initial_state != NormalState) {
+	return;
+    }
+
+    /*
+     * Drain all pending idle handlers AND window events before showing
+     * the root window.  Mapping the children of "." queues a chain of
+     * idle handlers (geometry managers, MapFrame,
+     * TkMacOSXRedrawViewIdleTask, ...) that re-post each other.  Some
+     * of these idle tasks ultimately post Expose events via
+     * [view generateExposeEvents:] (TkMacOSXRedrawViewIdleTask
+     * defined at the bottom of this file), and the corresponding
+     * widget DisplayXxx procs are scheduled when those Expose events
+     * are dispatched — which only happens for TCL_WINDOW_EVENTS, not
+     * for TCL_IDLE_EVENTS.  Including both event masks in the drain
+     * lets the Expose / Display cascade reach a fixed point so the
+     * bitmap context is fully repainted before updateLayer publishes
+     * it as layer.contents.  Without TCL_WINDOW_EVENTS, the Expose
+     * events stay queued, the widgets never paint, and the root
+     * window appears with an empty bitmap.
+     */
+
+    while (Tcl_DoOneEvent(TCL_WINDOW_EVENTS | TCL_IDLE_EVENTS
+	    | TCL_DONT_WAIT)) {
+    }
+
+    /*
+     * The drain above may have changed the wm state (e.g. a startup
+     * script that calls "wm withdraw ." from an idle task), so recheck.
+     */
+
+    if (winPtr->wmInfoPtr->hints.initial_state != NormalState) {
+	return;
+    }
+
+    /*
+     * Force the TKContentView's CALayer.contents to reflect the
+     * freshly-drawn bitmap context BEFORE the window becomes visible.
+     * Otherwise AppKit would present the previous CGImage (cached from
+     * before the wm withdraw) for one frame, and the user would
+     * briefly see the old layout until the next updateLayer call
+     * replaces layer.contents.  Invoking updateLayer here is
+     * synchronous and uses the same CGBitmapContextCreateImage path
+     * AppKit would use.
+     */
+
+    TKContentView *view = (TKContentView *)[win contentView];
+    if ([view isKindOfClass:[TKContentView class]]) {
+	[view updateLayer];
+    }
+
+    [win makeKeyAndOrderFront:NSApp];
+}
+
+/*
+ *----------------------------------------------------------------------
+ *
  * NotifyVisibility --
  *
  *	Helper for XMapWindow().  Generates VisibilityNotify events
@@ -331,6 +442,26 @@
 		winPtr->wmInfoPtr->hints.initial_state!=IconicState) {
 	    [win setExcludedFromWindowsMenu:YES];
 	    [win orderOut:NSApp]; /* Note: side effects described above. */
+	    /*
+	     * Wipe both the cached CGImage that the layer is currently
+	     * presenting and the bitmap context that backs it, and re-arm
+	     * the one-shot drain flag.  Without this, a subsequent
+	     * "wm deiconify $tl" cycle (with $tl's content potentially
+	     * modified, recreated, or destroyed-and-rebuilt while $tl was
+	     * withdrawn) would briefly show the previous bitmap through
+	     * CALayer's content cache: the new widget display procs paint
+	     * only their own rectangles into the bitmap, and pixels
+	     * outside those rectangles still carry the old toplevel's
+	     * contents until updateLayer runs.  Children that are still
+	     * pack/grid-managed will repaint during the next updateLayer
+	     * drain (triggered by the tkNeedsInitialDrain flag set below).
+	     */
+	    TKContentView *cv = (TKContentView *)[win contentView];
+	    if ([cv isKindOfClass:[TKContentView class]]) {
+		cv.layer.contents = nil;
+		[cv resetTkLayerBitmapContext];
+		cv.tkNeedsInitialDrain = YES;
+	    }
 	}
 	TkMacOSXInvalClipRgns((Tk_Window)winPtr);
     } else {
diff -urN macosx/tkMacOSXWindowEvent.c macosx/tkMacOSXWindowEvent.c
--- macosx/tkMacOSXWindowEvent.c	2026-05-19 13:45:44
+++ macosx/tkMacOSXWindowEvent.c	2026-05-19 22:54:57
@@ -439,6 +439,16 @@
 	}
 	if (winPtr->wmInfoPtr->hints.initial_state == WithdrawnState) {
 	    [win orderOut:NSApp];
+	    /*
+	     * Wipe stale bitmap + re-arm one-shot drain so the next
+	     * mapping presents a fresh layer (see TKContentView.h).
+	     */
+	    TKContentView *cv = (TKContentView *)[win contentView];
+	    if ([cv isKindOfClass:[TKContentView class]]) {
+		cv.layer.contents = nil;
+		[cv resetTkLayerBitmapContext];
+		cv.tkNeedsInitialDrain = YES;
+	    }
 	}
 	if (winPtr->dispPtr->grabWinPtr == winPtr) {
 	    Tcl_Preserve(winPtr);
@@ -996,6 +1006,7 @@
 	self.layerContentsRedrawPolicy = NSViewLayerContentsRedrawOnSetNeedsDisplay;
 	self.layer.contentsGravity = self.layer.contentsAreFlipped ?
 	    kCAGravityTopLeft : kCAGravityBottomLeft;
+	self.tkNeedsInitialDrain = YES;
 	trackingArea = [[NSTrackingArea alloc]
 			   initWithRect:[self bounds]
 				options:(NSTrackingMouseEnteredAndExited |
@@ -1018,13 +1029,23 @@
     CGContextRef context = self.tkLayerBitmapContext;
     if (context && ![NSApp tkWillExit]) {
 	/*
-	 * If this ContentView is off screen, Run any pending widget
-	 * display procs before updating the layer.
+	 * Drain pending widget display procs before updating the layer
+	 * when either the NSWindow is not yet visible (initial mapping
+	 * cycle), or the view has been (re)attached to a window that
+	 * became visible but has not yet rendered all its children once.
+	 * The latter case is tracked by the tkNeedsInitialDrain one-shot
+	 * flag, which is re-armed each time the toplevel is unmapped or
+	 * withdrawn.  Without the flag-based path, isVisible alone is
+	 * insufficient on the deiconify path: TkpWmSetState/orderFront
+	 * flips isVisible to YES synchronously, before the script has
+	 * finished (re)mapping the toplevel's children — so the first
+	 * updateLayer after the orderFront would render an incomplete
+	 * bitmap and the widgets would appear progressively on screen.
 	 */
 
-	if (! self.window.isVisible) {
-	    //printf("Running event loop.\n");
+	if (!self.window.isVisible || self.tkNeedsInitialDrain) {
 	    while(Tcl_DoOneEvent(TCL_IDLE_EVENTS)){}
+	    self.tkNeedsInitialDrain = NO;
 	}
 
 	/*
diff -urN macosx/tkMacOSXWm.c macosx/tkMacOSXWm.c
--- macosx/tkMacOSXWm.c	2026-05-19 13:45:44
+++ macosx/tkMacOSXWm.c	2026-05-19 23:08:37
@@ -1357,6 +1357,16 @@
 	TKContentView *deadView = [deadNSWindow contentView];
 	Tcl_CancelIdleCall(TkMacOSXRedrawViewIdleTask, (void *) deadView);
 	Tcl_CancelIdleCall(TkMacOSXUpdateViewIdleTask, (void *) deadView);
+
+	/*
+	 * If XMapWindow scheduled a deferred orderFront for this window
+	 * (only happens for the Tk root window) and it has not fired yet,
+	 * cancel it now so the idle handler cannot dereference a released
+	 * NSWindow.
+	 */
+
+	Tcl_CancelIdleCall(DeferredOrderFrontRootWindow, (void *) deadNSWindow);
+
 	CGContextRelease(deadView.tkLayerBitmapContext);
 	[deadNSWindow close];
 #if MAC_OS_X_VERSION_MAX_ALLOWED >= 101400
@@ -2481,7 +2491,14 @@
     if (win) {
 	[win setExcludedFromWindowsMenu:NO];
 	TkMacOSXApplyWindowAttributes(winPtr, win);
-	[win orderFront:NSApp];
+	/*
+	 * Skip the synchronous orderFront for the Tk root window.  Same
+	 * reasoning as in TkpWmSetState — DeferredOrderFrontRootWindow
+	 * makes it visible after draining children.
+	 */
+	if (winPtr != (TkWindow *)Tk_MainWindow(winPtr->mainPtr->interp)) {
+	    [win orderFront:NSApp];
+	}
     }
     if (wmPtr->icon) {
 	Tk_UnmapWindow((Tk_Window)wmPtr->icon);
@@ -3472,6 +3489,15 @@
 		}
 	    }
 	    [win orderOut:NSApp];
+	    /* Wipe stale bitmap + re-arm one-shot drain (see TKContentView.h). */
+	    {
+		TKContentView *cv = (TKContentView *)[win contentView];
+		if ([cv isKindOfClass:[TKContentView class]]) {
+		    cv.layer.contents = nil;
+		    [cv resetTkLayerBitmapContext];
+		    cv.tkNeedsInitialDrain = YES;
+		}
+	    }
 	    [win setExcludedFromWindowsMenu:YES];
 	}
 	Tk_MakeWindowExist(tkwin2);
@@ -7010,7 +7036,18 @@
     } else if (state == NormalState || state == ZoomState) {
 	TkWmMapWindow(winPtr);
 	[macWin deminiaturize:NSApp];
-	[macWin orderFront:NSApp];
+	/*
+	 * For the Tk root window, defer [orderFront:] to the
+	 * DeferredOrderFrontRootWindow idle handler scheduled by
+	 * XMapWindow.  That handler drains pending widget display procs
+	 * first, so the root window appears with all its children already
+	 * laid out — instead of becoming visible synchronously here and
+	 * then showing an incomplete bitmap while the rest of the
+	 * startup or a content rebuild finishes mapping children.
+	 */
+	if (winPtr != (TkWindow *)Tk_MainWindow(winPtr->mainPtr->interp)) {
+	    [macWin orderFront:NSApp];
+	}
 	TkMacOSXZoomToplevel(macWin, state == NormalState ? inZoomIn : inZoomOut);
     }