WxMac-specific topics

From WxWiki
Jump to navigation Jump to search

See also the wxMac FAQ


My app can't be brought to the front!

This is a common problem met by people new to wxMac. Simply building a wxWidgets app from terminal and producing a raw executable is not enough on wxMac. You need to build an application bundle (there is a section about this below). The most easy way to get a bundle is to use an "Application" target in xCode (a "shell tool" target will not produce a bundle). Another possible way to solve this quickly is to add the following lines of code to your app :

#include <ApplicationServices/ApplicationServices.h>

ProcessSerialNumber PSN;
GetCurrentProcess(&PSN);
TransformProcessType(&PSN,kProcessTransformToForegroundApplication);

Tis is also covered in the official wxMac FAQ

The Mac OS menu bar

All versions of Mac OS have a single menu bar at the top of the screen. While pop-up menus and context-sensitive menus are supported and are appropriate under some circumstances, Mac windows never have their own menu bar.

wxMac handles this automatically by displaying the menu bar associated with each wxFrame at the top of the screen whenever that frame is in front. If your program has multiple frames and the user brings a different frame to the front, that frame's menu bar will be switched in.

Warning: be careful of modeless windows which do not have menu bars. (Modal dialogs are okay.) If a modeless window gets brought to the front and it doesn't have a menu bar, the last menu bar will stay at the top of the screen. When the user selects something from one of these menus, the selection might never get handled, since the active frame doesn't recognize the command. You have two choices: either handle your commands in your wxApp subclass (since the commands will eventually get sent there), or create a degenerate wxMenuBar for all of your frames (maybe with only a Quit item).

On the Mac, the name of the item which exits the program is traditionally called "Quit" instead of "Exit". wxMac handles this for you - just name the item "Exit" and wxMac will change it for you.

Keyboard shortcuts use the command-key (the cloverleaf or open-apple key on the keyboard) instead of the control key. wxMac lets you specify keyboard shortcuts MS Windows style, and they are automatically translated. So Open should be specified as "&Open\tCtrl+O", and on the Mac the accelerator will be removed and the Ctrl will be replaced with a cloverleaf in the menu.

The layout of Mac menus is slightly different, and here is where you will have to add a line of code to your program to accomodate it. On the Mac, the "About" menu item should go in a particular place (in the Apple menu on Mac OS 8/9, or in the program menu on Mac OS X). wxMac will automatically move it for you if you tell it the ID of your About item:

#ifdef __WXMAC__
wxApp::s_macAboutMenuItemId = AboutID;
#endif

On Mac OS X, the Preferences item goes in a special place, too. To tell it the ID of your Preferences item:

#ifdef __WXMAC__
wxApp::s_macPreferencesMenuItemId = PreferencesID;
#endif

Look at defs.h for other such items.

Remark: You might have to tell wxMac the name of your help menu as well, since it assumes that it's "&Help". For example add the following lines

#ifdef __WXMAC__
wxApp::s_macHelpMenuTitleName = "Help";
#endif

if your help menu has the name "Help".

The easier and cleaner way of doing all this: You can achieve similar effects by using standard widget IDs. Here is a list of the Mac IDs that might have to be tweaked if you are not yet using their standard names (from defs.h): wxID_ABOUT, wxID_EXIT, wxID_PREFERENCES, wxID_HELP. These constants are not Mac-specific, they can be used on all platforms.

See also the wxMac FAQ.

  • Example of how to catch about and preferences events:
#include "wx/wx.h"

class MyApp: public wxApp
{
    bool OnInit();
    
    wxFrame *frame;
public:
    DECLARE_EVENT_TABLE()
    
    void OnAbout(wxCommandEvent& evt);
    void OnPrefs(wxCommandEvent& evt);
};

IMPLEMENT_APP(MyApp)

BEGIN_EVENT_TABLE(MyApp, wxApp)
EVT_MENU(wxID_ABOUT, MyApp::OnAbout)
EVT_MENU(wxID_PREFERENCES, MyApp::OnPrefs)
END_EVENT_TABLE()

bool MyApp::OnInit()
{
    wxBoxSizer* sizer = new wxBoxSizer(wxHORIZONTAL);
    frame = new wxFrame((wxFrame *)NULL, -1,  wxT("Hello wxWidgets"), wxPoint(50,50), wxSize(800,600));
	
    wxMenuBar* menubar = new wxMenuBar();
    wxMenu* testmenu = new  wxMenu(wxT("File"));
	
    testmenu->Append(wxID_ANY, wxT("New"));
    testmenu->Append(wxID_ANY, wxT("Open"));
    
    testmenu->Append(wxID_ABOUT, wxT("About this app!!"));
    testmenu->Append(wxID_PREFERENCES, wxT("Preferences"));
    
    menubar->Append(testmenu, wxT("File"));
    
    frame->SetMenuBar(menubar);
    
    frame->Show();
    return true;
} 

void MyApp::OnAbout(wxCommandEvent& evt)
{
    wxMessageBox(wxT("hello world"));
}
void MyApp::OnPrefs(wxCommandEvent& evt)
{
    wxMessageBox(wxT("no options in preferences for this simple demo..."));
}

When to close the program

On all versions of the Mac OS, it is okay for a program to be open but to have no windows open at all. This is similar to how a MS Windows MDI program can have its MDI Parent Frame open with no documents open within it, but on the Mac it has no open frames at all. The only clue that the program is active is that the menu bar changes.

If your program is dialog-based or otherwise just has one main frame, don't worry about this. When the user closes the main program or dialog, your program can just exit.

On the other hand, if your program is document-based, a Mac user will be confused if he/she closes a frame and the whole program exits. The user may have been intending to close one document and then open another.

If you want to support this behavior, there is a standard wxApp call, SetExitOnFrameDelete(), which tells the program not to exit when its last top-level frame is closed. To setup the menubar to be displayed when no frames are open, there is a wxMac-only static function in wxMenuBar, MacSetCommonMenuBar().

bool myApp::OnInit() {
  wxApp::SetExitOnFrameDelete(false);
  wxMenuBar *menubar = new wxMenuBar;
  // add open, new, etc options to your menubar.
  wxMenuBar::MacSetCommonMenuBar(menubar);
}

Alternatively, you may employ a little trick: create an offscreen frame with a menu bar (give it top-left coordinates of [5000, 5000] or something like that, but don't hide it using wxFrame::Hide). Give the frame a style of wxFRAME_NO_TASKBAR, so that the frame does not appear under the "Window" menu. When all of your other frames are closed, this frame will be the frontmost, and its menu bar will appear. This menu bar should include items like Open, Quit, and maybe Preferences.

On OSX, creating a window of wxSize(0,0) and window style 0 also works to create an invisible window - however this does not work under Classic.

Icons

OS X uses its own icon format : .icns. You can easily create icns files using an app like CocoThumbX.

File associations

In order to have your application handle files that are dropped on the application icon, and respond to double-clicking on some file types from the Finder, override the following method in your wxApp :

virtual void wxApp::MacOpenFile(const wxString &fileName)

This is handled automatically in wxMac-2.8.4 (osx)

As of OS X, there are two ways to bind a document to an application. The former is the file extension, for instance myfile.jpg. This mechanism is common on Linux and Windows. The second mechanism is the 4-character TYPE code. This code comes from OS pre-X, but was kept in OS X because it is arguably more powerful that plain file extensions. Any of the two or both can be used to perform file associations.

The file extension way

You will need to set the information correctly in the Info.plist file inside your app bundle. Example (full docs can be found at Apple and are out of the scope of this document) :

<?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>'your_executable_name'</string>
	<key>CFBundleInfoDictionaryVersion</key>   <string>6.0</string>
	<key>CFBundlePackageType</key>             <string>APPL</string>
	<key>CSResourcesFileMapped</key>           <true/>
	
	<key>CFBundleVersion</key>                 <string>'your app version, e.g. 1.5'</string>
	<key>CFBundleShortVersionString</key>      <string>'your app version, e.g. 1.5'</string>
	
	<key>CFBundleName</key>                    <string>'your apps user-visible name'</string>
	<key>CFBundleIconFile</key>                <string>'your_app_icon.icns'</string>
		
	<key>CFBundleDocumentTypes</key> <array>
		<dict>
			<key>CFBundleTypeExtensions</key>
			<array>
                                <!-- Here goes the file formats your app can read -->
				<string>'gif'</string>
				<string>'jpeg'</string>
				<string>'png'</string>
				<string>'tiff'</string>
			</array>
			<key>CFBundleTypeIconFile</key>      <string>'icon_for_your_documents.icns'</string>
			<key>CFBundleTypeName</key>          <string>'User-visible description for these documents, e.g. image files'</string>
			<key>CFBundleTypeRole</key>          <string>Editor</string>
			<key>LSIsAppleDefaultForType</key>   <true/>
			<key>LSTypeIsPackage</key>           <false/>
		</dict>
		
	</array>
	
</dict>
</plist>


The TYPE code way

Beyond the mechanism of file extensions, mac OS also uses four-character TYPE and CREATOR. The former specifiies the type of the file independent of its three-character extension (which is not required); the latter is the "signature" of the application that created it.

There are methods in wxFilename which allow you to get or set these codes:

bool wxFileName::MacSetTypeAndCreator( wxUint32 type , wxUint32 creator )
bool wxFileName::MacGetTypeAndCreator( wxUint32 *type , wxUint32 *creator )
bool wxFileName::MacSetDefaultTypeAndCreator()
bool wxFileName::MacFindDefaultTypeAndCreator( const wxString& ext , wxUint32 *type , wxUint32 *creator )
void wxFileName::MacRegisterDefaultTypeAndCreator( const wxString& ext , wxUint32 type , wxUint32 creator )

Note that types and creators are defined as wxUint32 instead of a string or character type because all Mac compilers allow you to specify types and creators as: 'TEXT', 'APPL', 'ttro', 'R*ch', etc. - where the four characters are packed into one 32-bit int.

If you want to set the type of a file (for example before distributing it), you can do something like this:

/Developer/Tools/Rez -t HTBD -o myfile.htb < /dev/null

This sets the wxWidgets HTML help file 'myfile.htb' to the appropriate type to invoke the HelpView application (see utils/helpview/src, CVS HEAD).




Building a MacOSX application bundle

MacOSX introduces a new way of putting together an application. Instead of adding a resource fork to the executable file, you can simply create a special directory (folder). This is the preferred method for OSX.

In it's most basic form, on OSX application bundle is a set of nested folders, with your executable in the "MacOS" folder:

  • YourApp.app
    • Contents
      • MacOS
        • YourApp (this is your executable file)
      • Resources
        • ...

Instead of being embeded in a resource fork, your application's resources can be placed as seperate files in "Contents/Resources". Additional metadata about your application can be contained in "Contents/Info.plist" and "Contents/version.plist". Locale/Language-specific data is contained in "Contents/Resources/<Language>.lproj". Dependent libraries and frameworks (e.g. wxWidgets) can also be contained in the bundle folders.

For more information on the file formats and layout of an application bundle folder, consult the Apple developer website. For example: http://developer.apple.com/documentation/CoreFoundation/Conceptual/CFBundles/CFBundles.html

If you are using XCode or ProjectBuilder, those tools will create an application bundle for you with metadata plist files based on values you enter in the project settings. See the wxWidgets example programs for a method to create an application bundle folder from makefiles. A basic bundle folder can be created from "make" with the following rule:

YourApp.app: Info.plist YourApp version.plist InfoPlist.strings YourAppMacIcons.icns AnotherResource.txt  
   -mkdir YourApp.app    
   -mkdir YourApp.app/Contents
   -mkdir YourApp.app/Contents/MacOS
   -mkdir YourApp.app/Contents/Resources
   -mkdir YourApp.app/Contents/Resources/English.lproj
   cp Info.plist YourApp.app/Contents/
   cp version.plist YourApp.app/Contents/
   cp InfoPlist.strings YourApp.app/Contents/Resources/English.lproj/
   echo -n 'APPL????' > YourApp.app/Contents/PkgInfo
   cp YourApp YourApp.app/Contents/MacOS/YourApp
   cp YourAppMacIcons.icns AnotherResource.txt YourApp.app/Contents/Resources/

Then you can run "make YourApp.app", or you can add "YourApp.app" as a dependency of "all". In my applications, I use autoconf, and generate Info.plist, version.plist, etc. from templates using configure.

How to deal with bundles and wxWidgets

  • Mac OS X comes with dynamic librairies of wxWidgets (2.5 on Tiger, 2.8 on Leopard). If you link against these librairies then you don't need to package wxWidgets in any way.
  • If you built wxWidgets the static way, by making sure to use built-in libs for e.g. png/regex/xml and not ones you installed yourself, you should have nothing special to do to make the bundle distributable.
  • wxWidgets dynamic librairies as built from the Xcode project will be automatically bundle-able (their path should be set to @executable_path/Contents/Frameworks/libname.dylib), which essentially means myProgram.app/Contents/Frameworks/libname.dylib To achieve this in your program's Xcode project, add a build phase to "Copy Files" and copy to the Executable path, with a subpath of "../Frameworks". Then when you build your app, Xcode will copy the dylib into the app's package where the linker can find it. And your app is linking to a relative path, which is easily transportable! (but check it manually with otool -L to make sure everything is right)
  • Otherwise, if you really need dynamic librairies, and can't use those installed by default on the system (because e.g. you can want OS X 10.4 compatibility AND wxWidgets 2.8) check otool (especially otool -L) and install_name_tool on the terminal
  • http://macdylibbundler.sf.net does the same but more automatized

Making apps look better on mac

Mac users expect apps on OS X to look pretty. If it doesn't look pretty you'll have cranky users. Cranky users can be avoided by implementing some of these tips. (This page is, of course, a work in progress)

This could also be seen as a page where wxMac specific functionality is documented...

Application Level

  • Handling files opened by double-clicking a file (or dragging file onto application): Implement the wxApp virtual method MacOpenFile. This is handled automatically for you if you use the Document/View Framework
  • Not Quitting when last window closes: (Mac users don't expect this behavior): call wxApp's SetExitOnFrameDelete(false) somewhere in you app (in your OnInit() maybe?)

Top Level Windows

  • The System Option mac.window-plain-transition can get rid of the "zooming" window transition that happens automatically when a window is opened or closed.
wxSystemOptions::SetOptionInt( wxMAC_WINDOW_PLAIN_TRANSITION, 0 )
  • Modal wxDialogs should not have enabled close buttons on them. Make sure your styles for wxDialog based instances of this type do not contain wxCLOSE_BOX. See the discussion of dialog boxes in the Apple Human Interface Guidelines

Fonts

Usually wxSMALL_FONT, etc do the right thing on OS X. But sometimes the HIGs recommend a font that doesn't exist as a preexisting wxWidgets font. There's an answer to this:

wxFont macFont;

macFont.MacCreateThemeFont(APPEARANCE MANAGER FONT ID );

The list of possible parameters for this function is found at Appearance Manager: Font IDs. The Human Interface Guidelines Font Section is useful for seeing the font required for a given situation. (Use the Carbon Constant!)

Automatic spellchecking

  • Spell Checking: OS X comes with a built-in spell checker for editable text controls that want to turn it on. OS X users expect their text to be spell checked, except in places where this checking just doesn't make any sense (like logs or source code).

By default this feature is off, but you can turn it on by default by turning on the system option wxMAC_TEXTCONTROL_USE_SPELL_CHECKER

wxSystemOptions::SetOptionInt( wxMAC_TEXTCONTROL_USE_SPELL_CHECKER, 1 );

If you want to turn spell checking on for an individual control, but not for every text control in your app, call the wxTextCtrl's MacCheckSpelling(spellCheckerOn).

wxTextCtrl* myTextControl = ....

#if __WXMAC__
myTextControl->MacCheckSpelling(true);   spell checking on!
#endif