In this follow-up to my post on turning a GTK# app into a Mac app bundle, I describe how to integrate your application with Mac-specific features such as the main menu, the dock, and file/URL events. This is based on the work I did to integrate MonoDevelop and MonoDoc with the Mac, and largely involves cherry-picking code snippets from these projects. Although it would be nice to isolate this code into a library, I don't have the time at the moment to maintain such a library myself.
GTK# is a nice toolkit, and in my opinion the best cross-platform toolkit for Mono/.NET, but there are some things that just don't have direct cross-platform analogues, such as the Mac main menu. To integrate with such features, you need to implement platform-specific code paths. MonoDevelop does this in some cases using runtime checks:
if (PropertyService.IsMac) { //some mac-specific behaviour } else if (PropertyService.IsWindows) //some windows-specific behaviour } else { //some default behaviour }
System.PlatformID.MacOSX so we have to use some other techniques for platform detection. In MonoDevelop's PropertyService we can find code based on Mono's Managed.Windows.Forms/XplatUI that detects whether the program is running on Mac or Windows. Here are the pertinent parts, copied into a new class:public static class PlatformDetection { public readonly static bool IsWindows; public readonly static bool IsMac; static PlatformDetection () { IsWindows = Path.DirectorySeparatorChar == '\\'; IsMac = !IsWindows && IsRunningOnMac(); } //From Managed.Windows.Forms/XplatUI static bool IsRunningOnMac () { IntPtr buf = IntPtr.Zero; try { buf = System.Runtime.InteropServices.Marshal.AllocHGlobal (8192); // This is a hacktastic way of getting sysname from uname () if (uname (buf) == 0) { string os = System.Runtime.InteropServices.Marshal.PtrToStringAnsi (buf); if (os == "Darwin") return true; } } catch { } finally { if (buf != IntPtr.Zero) System.Runtime.InteropServices.Marshal.FreeHGlobal (buf); } return false; } [System.Runtime.InteropServices.DllImport ("libc")] static extern int uname (IntPtr buf); }
For certain other cases in MonoDevelop, particularly ones that introduce dependencies that only exist on some platforms, we have a "platform service" extension point using Mono.Addins, where a platform-specific addins can provide a platform-specific implementation of our PlatformService abstract class, and if none is found we fall back to a default implementation. This means that just one of our binaries is platform-specific. It's also nice because a lot of the platform-specific code is in one place. But there are still many places where certain platforms just need a small behavioural tweak and the overhead of pulling something out into this abstraction layer isn't worthwhile. In such cases we use a quick runtime check instead.
A third option is do build a different version of your binary for Mac, using ifdefs. This is what I did for MonoDoc, because it was easier for a quick hack, but I'll probably go back later and change it to use runtime checks.
#if MACOS //some mac-specific behaviour that only gets included when you pass /define:MACOS to the C# compiler #endif
The first platform-specific codepath we'll add is the main menu, because that's the one your users are going to notice. There is a GTK library called ige-mac-integration that provides some platform integration features for the main menu and dock, and is included in the Mono framework for Mac. If you exported the DYLD_FALLBACK_LIBRARY_PATH like I described in my post about building the app bundle, you should be able to P/Invoke it. Unfortunately it's quite limited in what it can do, so we don't use it at all in MonoDevelop, but its menu integration is effective for simpler apps like MonoDoc. In the MonoDoc source you can find a small IGE wrapper in a single file that you can copy into your app. Since P/Invokes are only resolved at runtime if they're used, you can include the code on all platforms provided you only call it on Mac .
if (PlatformDetection.IsMac) { //enable the global key handler for keyboard shortcuts IgeMainMenu.GlobalKeyHandlerEnabled = true; //Tell the IGE library to use your GTK menu as the Mac main menu IgeMainMenu.MenuBar = yourGtkMenuBar; //tell IGE which menu item should be used for the app menu's quit item IgeMainMenu.QuitMenuItem = yourQuitMenuItem; //add a new group to the app menu, and add some items to it var appGroup = IgeMainMenu.AddAppMenuGroup (); appGroup.AddMenuItem (yourAboutItem, "About FooApp..."); appGroup.AddMenuItem (yourPrefsItem, "Preferences..."); //hide the menu bar so it no longer displays within the window yourGtkMenuBar.Hide (); }
The IGE library automatically converts your menu's shortcuts to use Command instead of Control, but if you explicitly check modifiers elsewhere in your code, for example in custom widgets, you may wish to make Mac-specific tweaks to behaviour. If you do need to access modifiers from key events directly, beware that the Mac GTK modifier mappings are very strange; see the MapRawKeys method on MonoDevelop's KeyBindingManager for details.
Next we'll handle the Apple Events that Mac applications in App Bundle form are expected to handle.
The Quit event is sent when the Quit command on your app's the Dock icon is used (among other things), and obviously should cause your app to quit. The Reopen event is sent when the dock is clicked, and should cause your app to show its windows if they're hidden, or if you follow the Mac document-per-window model and no document is open, optionally create a new empty document.
The strange events for developers from other OSes are the file open and URL open events that your app gets set if it's registered to handle file types or URL types. Because the Mac only expects to have a single instance of a bundle app running at once, each app handling multiple documents, Launch Services sends the files or URLs as events to the running instance of the app, or if the app is not running, starts it then sends the events. They are not ever passed to your app as command-line arguments.
MonoDevelop's MacPlatform addin has a wrapper for these events that exposes them as simple static .NET events on a static class called OSXIntegration.Framework.ApplicationEvents. Simply copy the entire contents of the MacPlatform/Framework directory and include it in your app, then connect handlers to the ApplicationEvents class's static events sometime before starting the GTK mainloop:
if (PlatformDetection.IsMac) { ApplicationEvents.Quit += delegate (object sender, ApplicationEventArgs e) { Application.Quit (); e.Handled = true; }; ApplicationEvents.Reopen += delegate (object sender, ApplicationEventArgs e) { mainWindow.Deiconify (); mainWindow.Visible = true; e.Handled = true; }; //optional, only need this if your Info.plist registers to handle urls ApplicationEvents.OpenUrls += delegate (object sender, ApplicationUrlEventArgs e) { if (e.Urls != null || e.Urls.Count > 0) { OpenUrls (e.Urls); } e.Handled = true; }; //optional, only need this if your Info.plist registers to handle files ApplicationEvents.OpenFiles += delegate (object sender, ApplicationFileEventArgs e) { if (e.Files != null || e.Files.Count > 0) { OpenUrls (e.Files); } e.Handled = true; }; }
You might wonder how to register to handle files and URLs in your Info.plist. The Apple docs have the full details, but we can look at the MonoDoc Info.plist and the MonoDevelop Info.plist for some basics.
To register URLs, add the CFBundleURLTypes key to the Info.plist's main dictionary. Its value should be an array of URL types, where each one is a dictionary defining the name and the schemes (prefixes):
<key>CFBundleURLTypes</key> <array> <dict> <key>CFBundleURLName</key> <string>MonoDoc</string> <key>CFBundleURLSchemes</key> <array> <string>monodoc</string> </array> </dict> </array>
icns file to be loaded from your app's Resources directory, just like the bundle's icon, and this will show up in Finder.
Registering file types is similar, but there are more keys. You can also register whether your bundle is the default editor, and whether it's an editor or viewer.
<key>CFBundleDocumentTypes</key> <array> <dict> <key>CFBundleTypeIconFile</key> <string>monodevelop.sln.icns</string> <key>CFBundleTypeExtensions</key> <array> <string>sln</string> </array> <key>CFBundleTypeName</key> <string>MonoDevelop Solution</string> <key>CFBundleTypeRole</key> <string>Editor</string> <key>LSIsAppleDefaultForType</key> <true/> </dict> </array>
With these examples, you should now be able to make your application fit in much better on Mac.
I'm still investigating other Mac integration points for MonoDevelop, such as native file dialogs, but that's likely to take some time, as binding the native toolkits and getting them to play nicely with the GTK mainloop is likely to be difficult, and there are other important things keeping me busy. When they're done I'll be sure to share that code too.
This is part of the Catchup 2010 series of posts.
While making the MonoDevelop and MonoDoc packages for Mac I learned a few things about adapting GTK# apps for Mac, and I'd like to share them so that anyone else who's built a GTK# app on Windows or Linux can provide a nice self-contained Mac app bundle for their Mac users. This first part will cover building an app bundle, and a later post will cover building platform-specific code paths so that your app integrates with the main menu and dock.
If you're not a Mac developer, you might be wondering exactly what an app bundle is. Well, it's simply a directory with a ".app" extension that contains an application and everything it needs. The Mac GUI shell treats this folder as a self-contained application that can be run directly. It never has to be "installed" as such, but can simply kept wherever the user wants, typically in the system's Applications folder, and to "uninstall", it's simply deleted. To look inside an app bundle, use the context menu on the bundle in Finder.
The most important part of the app bundle is the Info.plist manifest, which lives in the Contents subdirectory of your app bundle, and describes the application. A plist ("property list") is an Apple structured data format that can be represented in binary or xml formats. We'll be using the xml format, which is fairly simple, if a little odd. Let's look at a simplified version of the MonoDoc app bundle's manifest:
<?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE plist PUBLIC "-//Apple Computer//DTD PLIST 1.0//EN" "http://www.apple.com/DTDs/PropertyList-1.0.dtd"> <plist version="1.0"> <dict> <key>CFBundleDevelopmentRegion</key> <string>English</string> <key>CFBundleExecutable</key> <string>monodoc</string> <key>CFBundleIconFile</key> <string>monodoc.icns</string> <key>CFBundleIdentifier</key> <string>com.novell.monodoc</string> <key>CFBundleInfoDictionaryVersion</key> <string>6.0</string> <key>CFBundleName</key> <string>MonoDoc</string> <key>CFBundlePackageType</key> <string>APPL</string> <key>CFBundleShortVersionString</key> <string>2.2</string> <key>CFBundleSignature</key> <string>xmmd</string> <key>CFBundleVersion</key> <string>2.2</string> <key>NSAppleScriptEnabled</key> <string>NO</string> </dict> </plist>
As you can see, it simply contains key/value pairs to set properties of the app bundle. This is just a subset of the keys you can set, but they're the important ones for our purposes. If you need more, see the Apple docs.
The one you need to change are:
Contents/MacOS subdirectory of your bundle that Launch Services will run when opening your app. We'll be using a shell script to run your real executable using Mono.Contents/Resources subdirectory of your bundle.Treat the other keys as boilerplate that must be included. Much of the app bundle layout and properties are designed for apps using the native toolkits; we are using just enough of them to fit in and work correctly.
If you read the descriptions of the keys, you'll see that your app bundle directory should have the following structure:
.app
Contents
Info.plist
Resources
.icnsMacOS
After you've written your Info.plist, made an icon file using Icon Composer (from the Apple Developer Tools), and copied all your app's real file into the bundle's MacOS folder, all we're missing is the launch script. The Apple Launch services can run shell scripts, but doesn't know how to open Mono programs directly, so we use a shell script to start Mono. Let's look at the MonoDoc launch script:
#!/bin/sh # Author: Michael Hutchinson (mhutchinson@novell.com) DIR=$(cd "$(dirname "$0")"; pwd) MONO_FRAMEWORK_PATH=/Library/Frameworks/Mono.framework/Versions/Current export DYLD_FALLBACK_LIBRARY_PATH="$DIR:$MONO_FRAMEWORK_PATH/lib:/lib:/usr/lib" export PATH="$MONO_FRAMEWORK_PATH/bin:$PATH" exec mono "$DIR/browser.exe"
This is very straightforward. It simply gets a full path to the bundle's MacOS directory and puts it in the DIR variable so that can be used later in the script, and sets DYLD_FALLBACK_LIBRARY_PATH to include this directory and the Mono framework directory, so that you can P/Invoke native libraries in your MacOS directory and the Mono framework lib directory. It also sets the PATH environment variable to include the official Mono framework's bin directory, ensuring that the official Mono is used. Using the official Mono is important, because it means you avoid issues specific to users who have MacPorts or some other custom Mono in their PATH, which are likely to be difficult to reproduce or fix. It then executes the app using Mono.
This is a simple script, but it has some deficiencies. We can improve it by taking some code and tricks from the MonoDevelop Mac launch script.
First, we'll detect whether the Mono Framework is installed, and if it's not, show a message using AppleScript telling the user to download it. This prevents your app from dying silently if Mono isn't installed. Put this in your script before the exec call.
#mono version check REQUIRED_MAJOR=2 REQUIRED_MINOR=4 APPNAME="MonoDevelop" VERSION_TITLE="Cannot launch $APPNAME" VERSION_MSG="$APPNAME requires the Mono Framework version $REQUIRED_MAJOR.$REQUIRED_MINOR or later." DOWNLOAD_URL="http://www.go-mono.com/mono-downloads/download.html" MONO_VERSION="$(mono --version | grep 'Mono JIT compiler version ' | cut -f5 -d\ )" MONO_VERSION_MAJOR="$(echo $MONO_VERSION | cut -f1 -d.)" MONO_VERSION_MINOR="$(echo $MONO_VERSION | cut -f2 -d.)" if [ -z "$MONO_VERSION" ] \ || [ $MONO_VERSION_MAJOR -lt $REQUIRED_MAJOR ] \ || [ $MONO_VERSION_MAJOR -eq $REQUIRED_MAJOR -a $MONO_VERSION_MINOR -lt $REQUIRED_MINOR ] then osascript \ -e "set question to display dialog \"$VERSION_MSG\" with title \"$VERSION_TITLE\" buttons {\"Cancel\", \"Download...\"} default button 2" \ -e "if button returned of question is equal to \"Download...\" then open location \"$DOWNLOAD_URL\"" echo "$VERSION_TITLE" echo "$VERSION_MSG" exit 1 fi
We can also take some code to use the "-a" argument to exec to set the process name that will be see by the "ps" commandline tool. Note that this doesn't work on OS 10.4, so we check the OS version and define an exec command in a variable that we can use later.
# Work around a limitation in 'exec' in older versions of macosx OSX_VERSION=$(uname -r | cut -f1 -d.) if [ $OSX_VERSION -lt 9 ]; then # If OSX version is 10.4 MONO_EXEC="exec mono" else MONO_EXEC="exec -a appname mono" fi
Finally, change the exec call from the original version to use our new MONO_EXEC variable, write all console output to a log file in a subdirectory of ~/Library/Logs, and pass the value of the MONO_OPTIONS environment variable to Mono. The MONO_OPTIONS environment variable is useful to enable you to to pass diagnostic options to the Mono runtime, such as "--debug", without altering your script.
EXE_PATH="$DIR\appname.exe" LOG_FILE="$HOME/Library/Logs/$APPNAME/$APPNAME.log" mkdir -p "`dirname \"$LOG_FILE\"`" $MONO_EXEC $MONO_OPTIONS "$EXE_PATH" $* 2>&1 1> "$LOG_FILE"
Let's tidy this all up into a single script, with all the values you need to change for your specific app in one place at the top.
#!/bin/sh #get the bundle's MacOS directory full path DIR=$(cd "$(dirname "$0")"; pwd) #change these values to match your app EXE_PATH="$DIR\appname.exe" PROCESS_NAME=appname APPNAME="AppName" #set up environment MONO_FRAMEWORK_PATH=/Library/Frameworks/Mono.framework/Versions/Current export DYLD_FALLBACK_LIBRARY_PATH="$DIR:$MONO_FRAMEWORK_PATH/lib:/lib:/usr/lib" export PATH="$MONO_FRAMEWORK_PATH/bin:$PATH" #mono version check REQUIRED_MAJOR=2 REQUIRED_MINOR=4 VERSION_TITLE="Cannot launch $APPNAME" VERSION_MSG="$APPNAME requires the Mono Framework version $REQUIRED_MAJOR.$REQUIRED_MINOR or later." DOWNLOAD_URL="http://www.go-mono.com/mono-downloads/download.html" MONO_VERSION="$(mono --version | grep 'Mono JIT compiler version ' | cut -f5 -d\ )" MONO_VERSION_MAJOR="$(echo $MONO_VERSION | cut -f1 -d.)" MONO_VERSION_MINOR="$(echo $MONO_VERSION | cut -f2 -d.)" if [ -z "$MONO_VERSION" ] \ || [ $MONO_VERSION_MAJOR -lt $REQUIRED_MAJOR ] \ || [ $MONO_VERSION_MAJOR -eq $REQUIRED_MAJOR -a $MONO_VERSION_MINOR -lt $REQUIRED_MINOR ] then osascript \ -e "set question to display dialog \"$VERSION_MSG\" with title \"$VERSION_TITLE\" buttons {\"Cancel\", \"Download...\"} default button 2" \ -e "if button returned of question is equal to \"Download...\" then open location \"$DOWNLOAD_URL\"" echo "$VERSION_TITLE" echo "$VERSION_MSG" exit 1 fi #get an exec command that will work on the current OS version OSX_VERSION=$(uname -r | cut -f1 -d.) if [ $OSX_VERSION -lt 9 ]; then # If OSX version is 10.4 MONO_EXEC="exec mono" else MONO_EXEC="exec -a \"$PROCESS_NAME\" mono" fi #create log file directory if it doesn't exist LOG_FILE="$HOME/Library/Logs/$APPNAME/$APPNAME.log" mkdir -p "`dirname \"$LOG_FILE\"`" #run app using mono $MONO_EXEC $MONO_OPTIONS "$EXE_PATH" $* 2>&1 1> "$LOG_FILE"
Now open a terminal, make the script executable, and execute it.
chmod +x AppName.app/Contents/MacOS/scriptname ./AppName.app/Contents/MacOS/scriptname
It's useful to run the script directly like this because you will immediately see the result of any errors in it. Assuming the script worked, your app bundle is complete, and you can double-click on it to run it.
In my follow-up post I cover writing platform-specific code paths to integrate your new bundle better with the platform, including using the Mac main menu, and handling Apple events, which will enable your app to handle files and URLs.
This is part of the Catchup 2010 series of posts.
It's strange to think that's it's 2010 already and I haven't blogged since June. It certainly hasn't been for lack of things to blog about — if anything, I've been too busy working on things to blog about them, so whenever I've had something to share I've usually used Twitter because much easier to fire off a quick tweet than to write a blog post. However, I'm determined to start blogging again so that I can share detailed information to which I can refer people more easily.
So, over the next few weeks, I'm going to try to catch up a bit. I intend to blog about the following topics:
I don't have any particular order planned, so if there's something you'd particularly like to see, leave a comment and I'll try to take it into consideration. I'll link the items in the list through to the posts as I make them.