Skip to content

fix incorrect window destroy#4323

Merged
leaanthony merged 11 commits into
wailsapp:v3-alphafrom
atterpac:v3/mac-window-hide-fix
Jun 17, 2025
Merged

fix incorrect window destroy#4323
leaanthony merged 11 commits into
wailsapp:v3-alphafrom
atterpac:v3/mac-window-hide-fix

Conversation

@atterpac

@atterpac atterpac commented May 29, 2025

Copy link
Copy Markdown
Member

removes a mapping for WindowShouldClose on Mac, this incorrecty triggers a window.destroy call on every hide()

Summary by CodeRabbit

  • New Features
    • Improved control over window closing behavior on macOS, allowing certain windows to close immediately without additional prompts.
  • Bug Fixes
    • Removed duplicate event mappings for macOS window events to ensure more accurate event handling.
  • Refactor
    • Enhanced debug logging for window show, hide, and close actions, as well as key window lifecycle events, to improve traceability and troubleshooting.
    • Updated internal window close flag handling to use thread-safe atomic operations across platforms.

@coderabbitai

coderabbitai Bot commented May 29, 2025

Copy link
Copy Markdown
Contributor

Walkthrough

The changes remove duplicate macOS event mappings, add debug logging for window lifecycle events on macOS, and introduce a thread-safe atomic flag to control unconditional window closing. A new platform-specific Go function is exposed to Objective-C to determine if a window should close unconditionally, integrating conditional close logic between Go and native layers.

Changes

File(s) Change Summary
v3/pkg/events/defaults.go Removed three duplicate macOS event mapping entries for window focus and resize events.
v3/pkg/application/webview_window.go, webview_window_windows.go Changed unconditionallyClose from bool to uint32; replaced boolean checks with atomic operations for thread safety.
v3/pkg/application/webview_window_darwin.go Added debug logging to hide() and close(); atomically set unconditionallyClose flag before closing; removed commented code.
v3/pkg/application/webview_window_darwin.m Added debug logs to window lifecycle handlers; declared and used new external C function for conditional window close logic.
v3/pkg/application/webview_window_close_darwin.go Added new Go file implementing windowShouldUnconditionallyClose for C linkage to check atomic close flag.

Sequence Diagram(s)

sequenceDiagram
    participant User
    participant Native (Obj-C)
    participant App (Go)
    
    User->>Native: Initiate window close
    Native->>App (Go): windowShouldUnconditionallyClose(windowId)
    App (Go)->>App (Go): Retrieve window, atomically read close flag
    App (Go)-->>Native: Return true/false
    alt Close unconditionally
        Native-->>User: Close window immediately
    else User-initiated close
        Native->>App (Go): Emit WindowShouldClose event
        App (Go)-->>User: Application handles close event
    end
Loading

Poem

🐇 Hopping through code with a keen little eye,
Windows now close with a whisper, not a sigh.
Atomic flags guard the paths they must tread,
Debug logs tell stories of what lies ahead.
No duplicates here, just clear, tidy tracks—
The rabbit’s delight in these well-crafted hacks! 🪟✨


📜 Recent review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between f1a3dc6 and 468b74b.

📒 Files selected for processing (2)
  • v3/pkg/application/webview_window_darwin.go (4 hunks)
  • v3/pkg/application/webview_window_windows.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • v3/pkg/application/webview_window_darwin.go
  • v3/pkg/application/webview_window_windows.go
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run Go Tests v3 (windows-latest, 1.24)
  • GitHub Check: Run Go Tests v3 (ubuntu-latest, 1.24)
  • GitHub Check: Run Go Tests v3 (macos-latest, 1.24)
✨ Finishing Touches
  • 📝 Generate Docstrings

Thanks for using CodeRabbit! It's free for OSS, and your support helps us grow. If you like it, consider giving us a shout-out.

❤️ Share
🪧 Tips

Chat

There are 3 ways to chat with CodeRabbit:

  • Review comments: Directly reply to a review comment made by CodeRabbit. Example:
    • I pushed a fix in commit <commit_id>, please review it.
    • Explain this complex logic.
    • Open a follow-up GitHub issue for this discussion.
  • Files and specific lines of code (under the "Files changed" tab): Tag @coderabbitai in a new review comment at the desired location with your query. Examples:
    • @coderabbitai explain this code block.
    • @coderabbitai modularize this function.
  • PR comments: Tag @coderabbitai in a new PR comment to ask questions about the PR branch. For the best results, please provide a very specific query, as very limited context is provided in this mode. Examples:
    • @coderabbitai gather interesting stats about this repository and render them as a table. Additionally, render a pie chart showing the language distribution in the codebase.
    • @coderabbitai read src/utils.ts and explain its main purpose.
    • @coderabbitai read the files in the src/scheduler package and generate a class diagram using mermaid and a README in the markdown format.
    • @coderabbitai help me debug CodeRabbit configuration file.

Support

Need help? Create a ticket on our support page for assistance with any issues or questions.

Note: Be mindful of the bot's finite context window. It's strongly recommended to break down tasks such as reading entire modules into smaller chunks. For a focused discussion, use review comments to chat about specific files and their changes, instead of using the PR comments.

CodeRabbit Commands (Invoked using PR comments)

  • @coderabbitai pause to pause the reviews on a PR.
  • @coderabbitai resume to resume the paused reviews.
  • @coderabbitai review to trigger an incremental review. This is useful when automatic reviews are disabled for the repository.
  • @coderabbitai full review to do a full review from scratch and review all the files again.
  • @coderabbitai summary to regenerate the summary of the PR.
  • @coderabbitai generate docstrings to generate docstrings for this PR.
  • @coderabbitai generate sequence diagram to generate a sequence diagram of the changes in this PR.
  • @coderabbitai resolve resolve all the CodeRabbit review comments.
  • @coderabbitai configuration to show the current CodeRabbit configuration for the repository.
  • @coderabbitai help to get help.

Other keywords and placeholders

  • Add @coderabbitai ignore anywhere in the PR description to prevent this PR from being reviewed.
  • Add @coderabbitai summary to generate the high-level summary at a specific location in the PR description.
  • Add @coderabbitai anywhere in the PR title to generate the title automatically.

Documentation and Community

  • Visit our Documentation for detailed information on how to use CodeRabbit.
  • Join our Discord Community to get help, request features, and share feedback.
  • Follow us on X/Twitter for updates and announcements.

@atterpac atterpac force-pushed the v3/mac-window-hide-fix branch from 42c9016 to 0434e94 Compare May 29, 2025 23:38
leaanthony
leaanthony previously approved these changes May 30, 2025
@joshhardy

joshhardy commented Jun 9, 2025

Copy link
Copy Markdown
Contributor

@atterpac @leaanthony I'm trying to apply this fix to resolve a crash during macOS window destroy, but it seems to be stopping the window close button from working at all.

I believe it is due to the fact that the window delegate always returns false from windowShouldClose and as such, windowWillClose will never fire.
https://github.com/wailsapp/wails/blob/v3-alpha/v3/pkg/application/webview_window_darwin.m#L235

Am I missing some other event handling I need to do to get the window to close when the close button is clicked with this change, or does the window delegate need a corresponding change?

UPDATE:
This appears to have been specific to my app's window event handling and not an inherent issue with this change.
Please disregard!

@leaanthony leaanthony left a comment

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

@atterpac - If I run the "events" example, none of the windows close.

@atterpac

Copy link
Copy Markdown
Member Author

@atterpac - If I run the "events" example, none of the windows close.

Interesting, I'll have to take the look I was only testing with the window example

@dosubot dosubot Bot added the size:S This PR changes 10-29 lines, ignoring generated files. label Jun 10, 2025
@github-actions github-actions Bot added the MacOS label Jun 10, 2025
@dosubot dosubot Bot added size:M This PR changes 30-99 lines, ignoring generated files. and removed size:S This PR changes 10-29 lines, ignoring generated files. labels Jun 11, 2025
@github-actions github-actions Bot removed the size:M This PR changes 30-99 lines, ignoring generated files. label Jun 11, 2025
@leaanthony

Copy link
Copy Markdown
Member

Fix Summary for Issue #4251

I've successfully fixed the duplicate symbol compilation issue that was preventing this PR from building. Here's a comprehensive summary of the solution:

Problem Addressed

This PR fixes issue #4251 where macOS windows would crash the system when using hide/show functionality. The core issue was that window.Close() and user-initiated window closes weren't properly
distinguishable, causing windows to actually close instead of just hiding when applications wanted hide-on-close behavior.

Root Cause

The original issue was in the event mapping in v3/pkg/events/defaults.go where Mac.WindowWillClose was incorrectly mapped to Common.WindowClosing. This caused every window hide operation to
incorrectly trigger a window destroy event.

Solution Components

  1. Event Mapping Fix (v3/pkg/events/defaults.go)
  • Changed mapping from Mac.WindowWillClose → Common.WindowClosing
  • To: Mac.WindowShouldClose → Common.WindowClosing
  • This ensures the WindowClosing event is emitted at the right time (when close is requested) rather than when the window is actually closing
  1. Window Close Logic (v3/pkg/application/webview_window_darwin.m)
  • Enhanced windowShouldClose: delegate method to check if window should close unconditionally
  • When Close() method is called programmatically, sets unconditionallyClose flag and allows actual close
  • When user clicks close button, emits WindowClosing event and returns false to prevent close (unless application handles the event)
  1. Unconditional Close Support (v3/pkg/application/webview_window_close_darwin.go)
  • Added new exported function windowShouldUnconditionallyClose()
  • Created separate file to avoid CGo symbol conflicts during compilation
  • Allows C code to check if a window should close without application intervention
  1. Go Integration (v3/pkg/application/webview_window_darwin.go)
  • Modified close() method to set unconditionallyClose = true before calling native close
  • This distinguishes programmatic Close() calls from user-initiated close attempts

How It Works

For Hide-on-Close Applications:

  1. User clicks close button → windowShouldClose called
  2. unconditionallyClose is false → emits WindowClosing event
  3. Application handles WindowClosing with window.Hide() + e.Cancel()
  4. Window hides instead of closing

For Normal Close Operations:

  1. Application calls window.Close() → sets unconditionallyClose = true
  2. windowShouldClose called → checks flag and returns true
  3. Window actually closes as expected

Compilation Fix

The original code had 60 duplicate C symbols during linking. Fixed by:

  • Moving the //export windowShouldUnconditionallyClose function to a separate file
  • This isolates the CGo export directive from the main webview file which has extensive C code
  • Prevents symbol conflicts while maintaining functionality

Debug Messages Added

I've added comprehensive debug logging for testing purposes:

Go Debug Messages:

  • Window showing/hiding operations
  • Close method calls and flag setting
  • Unconditional close checks

Objective-C NSLog Messages:

  • windowShouldClose calls and decisions
  • Window order on/off screen events
  • Window will close events

Testing

✅ Compilation: All examples build successfully
✅ Functionality: Hide-on-close behavior works correctly in v3/examples/hide-window
✅ Event Flow: Debug logs confirm proper event sequence

Example logs for hide-on-close:
[DEBUG] windowShouldClose called for window X
[DEBUG] Window X close requested by user - emitting WindowClosing event
[DEBUG] Window hiding
[DEBUG] Window X WILL order off screen
[DEBUG] Window X ordered OFF screen

Next Steps for @atterpac

  1. Test the fix with your specific use case using the debug messages
  2. If testing is successful, please remove the debug messages from:
    - v3/pkg/application/webview_window_darwin.go (lines with globalApplication.debug)
    - v3/pkg/application/webview_window_close_darwin.go (debug messages in the exported function)
    - v3/pkg/application/webview_window_darwin.m (all NSLog(@"[DEBUG]..." lines)
  3. Push the cleaned-up changes for final review

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 2

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between e64acd7 and 963024e.

📒 Files selected for processing (3)
  • v3/pkg/application/webview_window_close_darwin.go (1 hunks)
  • v3/pkg/application/webview_window_darwin.go (3 hunks)
  • v3/pkg/application/webview_window_darwin.m (5 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • v3/pkg/application/webview_window_darwin.go
  • v3/pkg/application/webview_window_darwin.m
🧰 Additional context used
🧬 Code Graph Analysis (1)
v3/pkg/application/webview_window_close_darwin.go (1)
v3/pkg/application/webview_window.go (1)
  • WebviewWindow (136-170)
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run Go Tests v3 (macos-latest, 1.24)
  • GitHub Check: Run Go Tests v3 (ubuntu-latest, 1.24)
  • GitHub Check: Run Go Tests v3 (windows-latest, 1.24)

Comment thread v3/pkg/application/webview_window_close_darwin.go Outdated
Comment thread v3/pkg/application/webview_window_close_darwin.go Outdated
@dosubot dosubot Bot added the size:M This PR changes 30-99 lines, ignoring generated files. label Jun 11, 2025
@leaanthony

Copy link
Copy Markdown
Member

ABI Safety Fix - Addressed CodeRabbit Feedback

Fixed the ABI safety issues identified by @coderabbitai[bot] in the exported function:

Changes Made:

Function Signature - Now uses proper C types:

// Before
func windowShouldUnconditionallyClose(windowId uint) bool

// After  
func windowShouldUnconditionallyClose(windowId C.uint) C.bool

Implementation Updates:

  • Cast C.uint to uint for internal Go function calls: uint(windowId)
  • All return statements now use C.bool() casting
  • Maintains all error handling and functionality

Why This Matters:

  • ABI Stability - C types guarantee consistent size/alignment across platforms
  • Portability - Works reliably across different architectures and compilers
  • Future-Proofing - Prevents issues if Go's native types change representation
  • Best Practice - Standard pattern for CGo exported functions

Testing:

  • ✅ Builds successfully on macOS
  • ✅ All functionality preserved
  • ✅ No performance impact

This follows CGo best practices and ensures the exported function has a stable, compiler-verified ABI between the Go and Objective-C layers. Thanks @coderabbitai[bot] for the excellent feedback!

@coderabbitai

coderabbitai Bot commented Jun 11, 2025

Copy link
Copy Markdown
Contributor

Tip

For best results, initiate chat on the files or code changes.

@leaanthony Awesome – thanks for jumping on that so quickly!
Using C.uint / C.bool on the exported boundary is exactly what I was after, and casting back to Go-level uint keeps the internal logic tidy. That covers the ABI-stability concern I raised, so we’re ✅ on that front.

I skimmed the latest diff and everything looks consistent:

//export windowShouldUnconditionallyClose still precedes the correct function.
• No additional cgo header is needed because C.bool and C.uint come from <stdbool.h> / <stdint.h> that cgo pulls in automatically.
• All return paths now wrap the Go bool with C.bool(...), eliminating implicit conversions.

No further changes required from my side – feel free to proceed with the cleanup of the temporary debug logs whenever you’re ready.

Nice work! 🐇✨

Address CodeRabbit feedback on ABI safety and data races:
- Change exported function signature to use C types (C.uint, C.bool) for ABI safety
- Convert unconditionallyClose field from bool to atomic uint32 for thread safety
- Update all read/write operations to use atomic operations across platforms

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

@coderabbitai coderabbitai Bot left a comment

Copy link
Copy Markdown
Contributor

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Actionable comments posted: 0

🧹 Nitpick comments (1)
v3/pkg/application/webview_window.go (1)

169-171: Flag type switched to uint32 – consider atomic.Uint32 wrapper

Moving from bool to uint32 is mandatory for the low-level atomic functions you’re using.
As a minor readability enhancement you could adopt the Go 1.19+ struct-friendly wrapper:

- // unconditionallyClose marks the window to be unconditionally closed (atomic)
- unconditionallyClose uint32
+ // unconditionallyClose marks the window to be unconditionally closed.
+ unconditionallyClose atomic.Uint32

This eliminates manual addr-of calls (&w.unconditionallyClose) and makes intent explicit.

📜 Review details

Configuration used: .coderabbit.yaml
Review profile: CHILL
Plan: Pro

📥 Commits

Reviewing files that changed from the base of the PR and between 963024e and f1a3dc6.

📒 Files selected for processing (4)
  • v3/pkg/application/webview_window.go (3 hunks)
  • v3/pkg/application/webview_window_close_darwin.go (1 hunks)
  • v3/pkg/application/webview_window_darwin.go (4 hunks)
  • v3/pkg/application/webview_window_windows.go (1 hunks)
🚧 Files skipped from review as they are similar to previous changes (2)
  • v3/pkg/application/webview_window_close_darwin.go
  • v3/pkg/application/webview_window_darwin.go
⏰ Context from checks skipped due to timeout of 90000ms (3)
  • GitHub Check: Run Go Tests v3 (ubuntu-latest, 1.24)
  • GitHub Check: Run Go Tests v3 (macos-latest, 1.24)
  • GitHub Check: Run Go Tests v3 (windows-latest, 1.24)
🔇 Additional comments (3)
v3/pkg/application/webview_window_windows.go (1)

1132-1136: Thread-safe flag read is correct – 👍

Switching to atomic.LoadUint32 removes the data-race that existed when the flag could be mutated from Go while being read inside the window procedure that runs on a different OS thread.
Logic (== 0) still matches the previous boolean semantics, so behaviour is preserved.

No further action required.

v3/pkg/application/webview_window.go (2)

10-10: Necessary import added

sync/atomic is now required after the migration to uint32 + atomic ops. Import looks good and keeps the set alphabetically sorted.


277-278: Atomic store before re-entering native close path – looks good

Using atomic.StoreUint32(&result.unconditionallyClose, 1) guarantees the second WM_CLOSE pass is recognised as “unconditional”. The store happens synchronously inside InvokeSync, so window-procedure reads have the correct happens-before relation.

@leaanthony leaanthony enabled auto-merge (squash) June 17, 2025 10:08
@sonarqubecloud

Copy link
Copy Markdown

Quality Gate Failed Quality Gate failed

Failed conditions
C Maintainability Rating on New Code (required ≥ A)

See analysis details on SonarQube Cloud

Catch issues before they fail your Quality Gate with our IDE extension SonarQube for IDE

@leaanthony leaanthony disabled auto-merge June 17, 2025 12:45
@dosubot dosubot Bot added the lgtm This PR has been approved by a maintainer label Jun 17, 2025
@leaanthony leaanthony enabled auto-merge (squash) June 17, 2025 12:46
@leaanthony

Copy link
Copy Markdown
Member

Merging with debug statements for now.

@leaanthony leaanthony disabled auto-merge June 17, 2025 21:31
@leaanthony leaanthony merged commit 0b7d1f4 into wailsapp:v3-alpha Jun 17, 2025
93 of 94 checks passed
Etesam913 pushed a commit to Etesam913/wails that referenced this pull request Jul 6, 2025
* fix incorrect window destroy

* remove duplicate common signals

* Better handling of "shouldclose"

* Better handling of "shouldclose"

* Fix ABI safety issues in exported function for macOS window closing

Address CodeRabbit feedback on ABI safety and data races:
- Change exported function signature to use C types (C.uint, C.bool) for ABI safety
- Convert unconditionallyClose field from bool to atomic uint32 for thread safety
- Update all read/write operations to use atomic operations across platforms

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Lea Anthony <lea.anthony@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Grantmartin2002 pushed a commit to Grantmartin2002/wails that referenced this pull request Apr 29, 2026
* fix incorrect window destroy

* remove duplicate common signals

* Better handling of "shouldclose"

* Better handling of "shouldclose"

* Fix ABI safety issues in exported function for macOS window closing

Address CodeRabbit feedback on ABI safety and data races:
- Change exported function signature to use C types (C.uint, C.bool) for ABI safety
- Convert unconditionallyClose field from bool to atomic uint32 for thread safety
- Update all read/write operations to use atomic operations across platforms

🤖 Generated with [Claude Code](https://claude.ai/code)

Co-Authored-By: Claude <noreply@anthropic.com>

---------

Co-authored-by: Lea Anthony <lea.anthony@gmail.com>
Co-authored-by: Claude <noreply@anthropic.com>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

lgtm This PR has been approved by a maintainer MacOS size:M This PR changes 30-99 lines, ignoring generated files. v3-alpha Windows

Projects

None yet

Development

Successfully merging this pull request may close these issues.

3 participants