Mail preferences modules in Mac OS X 10.7

This is could be interesting for other Mail plug-in (mailbundle) developers who are porting their software to Mac OS X 10.7 Lion:

Did you notice that your plug-ins preference pane is sometimes missing in Mail preferences (i.e. it’s not visible in the toolbar)? This happens only when the preferences window was open the last time you quit Mail. Mail remembers whether the preferences window was open and reopens it before your plug-in loads. If this happens, any preference modules that you add to +[NSPreferences sharedPreferences] will not be added in the toolbar.

Here’s a snippet of code that you can add to the +[NSPreferences sharedPreferences] method to fix it. The code assumes that you swap the Foo_sharedPreferences and sharedPreferences class methods when loading your plug-in, and contains some (probably unnecessary) super cautious error handling. It is safe for multiple plug-ins to use such code at the same time and given that the method isn’t called very often, it will not have any noticeable performance impact. I already use it in the current version of Attachment Tamer.

Update 2 December 2011: Since 10.7.3 (developer preview), Mail does not seem to call +[NSPreferences sharedPreferences] after loading Mail plug-ins. You have to call the code implemented in +[NSPreferences Foo_sharedPreferences] below yourself (see the other update below): either you still override the -[NSPreferences sharedPreferences] method and call it, or you may as well do without overriding and just put it in some function (also see the “Update” comment in the code).

Update 15 December 2011: It turns out that +[NSPreferences sharedPreferences] does not return a valid (non-nil) instance until some undetermined moment after application launch. It is therefore necessary to call the code below repeatedly (e.g. via [NSObject performSelector:withObject:afterDelay:] until the shared preferences instance is availble.

That’s it. Feel free to use it in your plug-in, you can consider it public domain. Just say thank you:).