TweetFollow Us on Twitter

Oct 97 - Getting Started

Volume Number: 13 (1997)
Issue Number: 10
Column Tag: Getting Started

OPENSTEP Localization

by Dave Mark, ©1997, All Rights Reserved

One of the strengths of the Mac OS is the way it handles localization. For example, pulling the strings out of your application and storing them as resources makes the app relatively simple to translate into another language. Of course there's more to localization than that, but the point is, the Mac OS supports an underlying mechanism that makes localization possible. Fortunately, OPENSTEP (and presumably Rhapsody) features a similar mechanism that greatly simplifies the localization process.

A Localization Example

Let's start off with a look at an existing application that takes advantage of the OPENSTEP localization mechanism.

  • In the Workspace, navigate into the directory:
/NextDeveloper/Examples/AppKit/TextEdit/English.lproj

These files are all part of the TextEdit ProjectBuilder project. Among the files in this directory, you'll find a series of nib files including one named FindPanel.nib. Each nib file implements a portion of the user interface. For example, the file Info.nib contains the specs for the TextEdit info panel (NeXTSpeak for about box).FindPanel.nib contains the specs for the Find panel.

In the same directory, you'll also notice a pair of files named Localizable.strings and FindPanel.strings. The collection of .strings files act as a repository for all the text strings embedded in the TextEdit source code. These files are created at build-time in response to a set of function calls you'll place in your code. Before we get to the functions, take a closer look at these files.

  • Double-click on the file Localizable.strings.

The file will open in Edit. As you scroll through the file, you'll notice that it consists of pairs of C comments and assignment statements. Here's an example:

/* Menu item to make the current document rich text */
"&Make Rich Text" = "&Make Rich Text";

Though this may look like some sick C code, this is really just a database of strings, where each entry consists of a comment, followed by a left side and right side pair of strings. The left side is the default string, which you'll specify in your code. The right side is the version of this string used by this particular language. This example specifies the text to use in the TextEdit menu item that specifies RTF (rich text format). The left side is the string that appeared in the source code, presumably done in the native language of the programmer. The right string is the localized string. Since we are in the directory English.lproj, the right string is in English.

One localization approach kicks in once you've done your final project build. Once your source is frozen, you duplicate the English.lproj directory, creating a copy for each foreign language you plan on supporting. For example, you might make a copy of English.lproj named German.lproj. You'd then hand this directory to your German translator. The German translator would step through each of the .strings files, translating all the right-hand strings in each of the assignment statements to German.

When you ship your application, you'll actually ship an accompanying directory that includes all your XXX.lproj subdirectories. When the user specifies their preferred language using the Preferences application, then runs your application, the system uses the .lproj directory that matches the current language. So on an English system, the strings in English.lproj will be used. On a German system, the German.lproj strings will be used. Of course, you don't have to support multiple languages, but since localization is so easy to do, you'll likely want to consider supporting more than just your native language.

An Existing Localized Example

Let's take a look at a shipping application that supports more than one language.

  • In the Workspace, point your browser to the /NextDeveloper/Demos directory.

A series of applications will appear in the directory (Figure 1). As you'd expect, if you double-click on any of these, they'll run. These .App files are known as "application wrappers". They hide the underlying directory structure that ships with your application and makes them appear as a single application file. The Workspace does give you a way to view this accompanying directory.

Figure 1. The /NextDeveloper/Demos directory.

  • In the File Viewer, click on TextEdit.App to select it.
  • Select Open as Folder from the Workspace's File menu.

A new File Viewer will appear, showing you the directory structure beneath the TextEdit.app application wrapper (Figure 2). At the top level of this directory is a directory named Resources. The XXX.lproj directories live inside this directory. Each of the XXX.lproj directories contains localized versions of the FindPanel.strings and Localizable.strings files.

Figure 2. TextEdit.App, opened as a folder instead of as an application.

Take some time to look at some other directories and applications. Check out some of the other applications in /NextDeveloper/Demos. Check out /NextDeveloper/Apps and /NextApps. Note that some of the applications are localized, others are not. Some are only partially localized. Some feature a Resources directory, othersplace their XXX.lproj directories one level higher, directly in the app's main directory. This last is a clue to the version of ProjectBuilder used to create the application. The Project Builder that shipped with OPENSTEP 4.0 was the first version to embed the XXX.lproj directories in a Resources directory.

A Simple Example

Let's use ProjectBuilder to build a simple application, then localize it.

  • Launch ProjectBuilder, then select New from the Project menu.
  • When the New Project panel appears, select Application from the Project Type popup men, type the name Foo into the Name field, then click OK.
  • In ProjectBuilder's browser, under Interfaces, double-click on NEXTSTEP_Foo.nib (assuming you are running under NextStep -- otherwise, double-click on your appropriate nib file).

You will now find yourself in InterfaceBuilder. As you've seen in past columns, InterfaceBuilder provides your application with a default window named My Window. We'll add a button and a static text item to this window, then localize the text associated with these two items, just to see localization in action. After that, we'll take a look at the functions that bring localization to life.

  • In InterfaceBuilder, select Palettes from the Tools menu, Palettes submenu.
  • When the Palettes window appears, click on the Views icon.
  • Drag a static text item (the text in the palette says "Title") into "My Window".
  • Double-click on the static text item and change the text to read:
This application allows you to control a vehicle on another planet
  • Go back to the Palettes window and drag a button into the window.
  • Double-click on the button and change the text to say OK.
  • Select Save from the Document menu.
  • Quit InterfaceBuilder.
  • Back in ProjectBuilder, click on the hammer icon to bring up the Project Build window.
  • Click on the hammer icon in the Project Build window to start the build process.

You should get a message that says build succeeded.

  • Quit ProjectBuilder.

Now we'll run the app, just to verify that our window appears with its static text and button. Once we know the app runs, we'll localize it in German, set the system prefs to German, then run the app again showing the German localization at work.

  • * In the workspace, find the file Foo.app (it'll be inside the Foo folder you created when you first built the ProjectBuilder project).
  • * Double-click Foo.app.

The window should appear containing our static text and button (Figure 3).

Figure 3. Foo.app, before localization.

  • Quit Foo.app.

In the workspace, select Foo.app, then select Open as Folder from the File menu.

  • In the Foo.app file viewer, open the Resources directory, select English.lproj, then select Duplicate from the File menu.
  • Rename the duplicate to German.lproj.
  • Inside the German.lproj directory, Double-click NEXTSTEP_foo.nib.

You'll find yourself in InterfaceBuilder, editing the version of the nib file that lives in German.proj.

  • In InterfaceBuilder, edit the static text in the main window and change it to read:
Diese anwendung erlaubt es ihnen ein fahrzeug auf einem anderen planeten

Big thanks to Andreas Hommel, compiler writer extraordinaire, for the German translation! ;)

  • Save, then Quit InterfaceBuilder.

Note that we didn't change the button text. As it turns out, OK in German is OK! Our next step is to run the preferences application and change the order of preferred languages so that German is first.

  • Double-click on the Preferences application (it's the icon in the dock that looks like a clock).
  • In the Preferences window, click on the left-most icon (the one that looks like a series of flags).
  • In the scrolling list of Languages, click on Deutsch and drag it to the top of the list (Figure 4).

Figure 4. The Localization Preferences, with German (Deutsch) selected as the preferred language.

The scrolling list of languages allow you to order the set of languages on your machine. On my machine, I have it set to German first (just for this demo), then English, French, Italian, and Swedish. When I run an application on my machine, the order of languages in my preferences determine which .lproj directory is used to fetch the application's nib files. In this case, the directory German.lproj is used first, then English.lproj, French.lproj, etc.

  • Quit the Preferences application.
  • Go back into the file viewer and run Foo.App.

This time, the text should appear in German (Figure 5). Wunderbar!

Figure 5. Foo.app running in German. Cool!

The Localization Functions

The sample program we just created was relatively simple. All localization was done directly in the nib file. Earlier in the column, we explored the TextEdit application and saw that the TextEdit text strings were stored in a set of .strings files. Instead of editing the TextEdit nib files, localization was done on these .strings files. This is made possible by a set of localization functions called by your program any time it needs to access a localized string. The functions go out to the appropriate .strings file and retrieve the localized version of the specified string.

The three localization functions we're referring to all start with the name NSLocalizedString. Here's a cool trick you can use to search for routines in the precompiled headers used by your projects.

  • Launch the Edit application.
  • Type the text NSLocalizedString.
  • select the text, then select the Services menu, Header Viewer submenu, Find item (Alt-Shift-H).

The HeaderViewer app will do a search and find the selected routine in the various precompiled headers (in HeaderViewer, select Info/Preferences to see the list of precompiled headers to be searched). When we used this technique to search for NSLocalizedString we get:

#define NSLocalizedString(key, comment) \
_  [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:nil]
#define NSLocalizedStringFromTable(key, tbl, comment) \
_  [[NSBundle mainBundle] localizedStringForKey:(key) value:@"" table:(tbl)]
#define NSLocalizedStringFromTableInBundle(key, tbl, bundle, comment) \
_  [bundle localizedStringForKey:(key) value:@"" table:(tbl)]

These three routines are the keys to localizing your strings.

NSLocalizedString takes a key and a comment, both of which are NSStrings. When ProjectBuilder encounters a call of NSLocalizedString, it uses the key and comment to build an entry in the file Localizable.strings. Here's an example:

NSString *untitled = NSLocalizedString(@"UNTITLED",
		@"Name of new, untitled document");

This piece of code defines an NSString pointer named untitled, which gets the string retrieved by the call of NSLocalizedString. The NSLocalizedString call takes two parameters, both of them NSStrings. The first one is the default value of the string. In this case, the default value is "UNTITLED". The second NSString is the comment that leads off the entry. ProjectBuilder will use this line of code to generate this entry in the file Localizable.strings:

/* Name of new, untitled document */
"&UNTITLED" = "&UNTITLED";

Note that the first parameter to NSLocalizedString serves as both the left and right side of the pseudo-assignment statement. Instead of embedding the string @"UNTITLED" directly in your code, pass it as a parameter to NSLocalizedString (or one of the other routines we'll look at in a sec), then use the NSString returned by NSLocalizedString instead. Think of NSLocalizedString as a bottleneck routine. By using it, your strings will automatically be exported into a .strings file. Once your strings are exported into a .strings file, you can hand the file to your translator, then place the localized copy in the appropriate XXX.lproj directory. Remember to tell your translator to translate the right hand side of all the assignment statements only. The left side provides the link to the NSLocalizedString call in your code. If your default language is English, the left side of the assignment statement in each .strings file will also be in English, as will all the first parameters to NSLocalizedString. The right side of each assignment statement might be in German, French, Swedish, Kanji, whatever.

By the way, though the comment and assignment statement might look like straight C code, it is actually intended as an NSStringTable. Just thought you'd like to know.

The function NSLocalizedStringFromTable takes a key, table name, and comment. key and comment serve the same purpose they did with NSLocalizedString. The table name is an NSString that specifies the name of an NSStringTable in which you'd like this entry stored. For example, this call will create an entry in the file FindPanel.strings.

NSString *untitled = NSLocalizedStringFromTable(
	@"Enter Find String:",
	@"FindPanel",
	@"Prompt for Find panel");

Why not stick all your strings in Localizable.strings? One approach used by OPENSTEP programmers is to create one .strings file for each panel/window in their interface. If your application supported a Find panel, an Info panel, and a main window, you might have three .strings files: FindPanel.strings, InfoPanel.strings, and MainPanel.strings. You might choose to keep all your strings in Localizable.strings or not use Localizable.strings at all. The point is, NSLocalizedStringFromTable is designed to let you store strings in the .strings file you choose.

The second parameter to NSLocalizedStringFromTable assumes the .strings suffix. So passing in the NSString @"FindPanel" will store the string in the file FindPanel.strings. Of course, if you create more than one .strings file, you'll have more files to manage and to pass on to your translator, so make the design choice that's right for your situation.

Terminology note: @"mystring" asks the runtime to create a temporary NSString object with the specified string and pass the reference to wherever it is used.

Finally, NSLocalizedStringFromTableInBundle lets you do the above but from a table associated with a bundle. Bundles are like plugins -- we'll get to them in a future column.

Till Next Month...

Your homework for this month: Add some NSLocalizedString calls to the VerySimpleText application that we built two months ago. You can add the code to the AboutWindowController class, inside the show method. Check out the .strings files generated by ProjectBuilder in response to your additional code. Do you see when these files get generated?

In Digital Librarian, open the bookshelf /NextLibrary/Bookshelves/DevTools.bshlf. Spend some time with this bookshelf, and pay special attention to Part 2: Creating the Interface. It has documents that describe creating a nib file, creating menus, initializing text, and tons more.

See you next month!

 

Community Search:
MacTech Search:

Software Updates via MacUpdate

Latest Forum Discussions

See All

Tokkun Studio unveils alpha trailer for...
We are back on the MMORPG news train, and this time it comes from the sort of international developers Tokkun Studio. They are based in France and Japan, so it counts. Anyway, semantics aside, they have released an alpha trailer for the upcoming... | Read more »
Win a host of exclusive in-game Honor of...
To celebrate its latest Jujutsu Kaisen crossover event, Honor of Kings is offering a bounty of login and achievement rewards kicking off the holiday season early. [Read more] | Read more »
Miraibo GO comes out swinging hard as it...
Having just launched what feels like yesterday, Dreamcube Studio is wasting no time adding events to their open-world survival Miraibo GO. Abyssal Souls arrives relatively in time for the spooky season and brings with it horrifying new partners to... | Read more »
Ditch the heavy binders and high price t...
As fun as the real-world equivalent and the very old Game Boy version are, the Pokemon Trading Card games have historically been received poorly on mobile. It is a very strange and confusing trend, but one that The Pokemon Company is determined to... | Read more »
Peace amongst mobile gamers is now shatt...
Some of the crazy folk tales from gaming have undoubtedly come from the EVE universe. Stories of spying, betrayal, and epic battles have entered history, and now the franchise expands as CCP Games launches EVE Galaxy Conquest, a free-to-play 4x... | Read more »
Lord of Nazarick, the turn-based RPG bas...
Crunchyroll and A PLUS JAPAN have just confirmed that Lord of Nazarick, their turn-based RPG based on the popular OVERLORD anime, is now available for iOS and Android. Starting today at 2PM CET, fans can download the game from Google Play and the... | Read more »
Digital Extremes' recent Devstream...
If you are anything like me you are impatiently waiting for Warframe: 1999 whilst simultaneously cursing the fact Excalibur Prime is permanently Vault locked. To keep us fed during our wait, Digital Extremes hosted a Double Devstream to dish out a... | Read more »
The Frozen Canvas adds a splash of colou...
It is time to grab your gloves and layer up, as Torchlight: Infinite is diving into the frozen tundra in its sixth season. The Frozen Canvas is a colourful new update that brings a stylish flair to the Netherrealm and puts creativity in the... | Read more »
Back When AOL WAS the Internet – The Tou...
In Episode 606 of The TouchArcade Show we kick things off talking about my plans for this weekend, which has resulted in this week’s show being a bit shorter than normal. We also go over some more updates on our Patreon situation, which has been... | Read more »
Creative Assembly's latest mobile p...
The Total War series has been slowly trickling onto mobile, which is a fantastic thing because most, if not all, of them are incredibly great fun. Creative Assembly's latest to get the Feral Interactive treatment into portable form is Total War:... | Read more »

Price Scanner via MacPrices.net

Early Black Friday Deal: Apple’s newly upgrad...
Amazon has Apple 13″ MacBook Airs with M2 CPUs and 16GB of RAM on early Black Friday sale for $200 off MSRP, only $799. Their prices are the lowest currently available for these newly upgraded 13″ M2... Read more
13-inch 8GB M2 MacBook Airs for $749, $250 of...
Best Buy has Apple 13″ MacBook Airs with M2 CPUs and 8GB of RAM in stock and on sale on their online store for $250 off MSRP. Prices start at $749. Their prices are the lowest currently available for... Read more
Amazon is offering an early Black Friday $100...
Amazon is offering early Black Friday discounts on Apple’s new 2024 WiFi iPad minis ranging up to $100 off MSRP, each with free shipping. These are the lowest prices available for new minis anywhere... Read more
Price Drop! Clearance 14-inch M3 MacBook Pros...
Best Buy is offering a $500 discount on clearance 14″ M3 MacBook Pros on their online store this week with prices available starting at only $1099. Prices valid for online orders only, in-store... Read more
Apple AirPods Pro with USB-C on early Black F...
A couple of Apple retailers are offering $70 (28%) discounts on Apple’s AirPods Pro with USB-C (and hearing aid capabilities) this weekend. These are early AirPods Black Friday discounts if you’re... Read more
Price drop! 13-inch M3 MacBook Airs now avail...
With yesterday’s across-the-board MacBook Air upgrade to 16GB of RAM standard, Apple has dropped prices on clearance 13″ 8GB M3 MacBook Airs, Certified Refurbished, to a new low starting at only $829... Read more
Price drop! Apple 15-inch M3 MacBook Airs now...
With yesterday’s release of 15-inch M3 MacBook Airs with 16GB of RAM standard, Apple has dropped prices on clearance Certified Refurbished 15″ 8GB M3 MacBook Airs to a new low starting at only $999.... Read more
Apple has clearance 15-inch M2 MacBook Airs a...
Apple has clearance, Certified Refurbished, 15″ M2 MacBook Airs now available starting at $929 and ranging up to $410 off original MSRP. These are the cheapest 15″ MacBook Airs for sale today at... Read more
Apple drops prices on 13-inch M2 MacBook Airs...
Apple has dropped prices on 13″ M2 MacBook Airs to a new low of only $749 in their Certified Refurbished store. These are the cheapest M2-powered MacBooks for sale at Apple. Apple’s one-year warranty... Read more
Clearance 13-inch M1 MacBook Airs available a...
Apple has clearance 13″ M1 MacBook Airs, Certified Refurbished, now available for $679 for 8-Core CPU/7-Core GPU/256GB models. Apple’s one-year warranty is included, shipping is free, and each... Read more

Jobs Board

Seasonal Cashier - *Apple* Blossom Mall - J...
Seasonal Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Read more
Seasonal Fine Jewelry Commission Associate -...
…Fine Jewelry Commission Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) Read more
Seasonal Operations Associate - *Apple* Blo...
Seasonal Operations Associate - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Read more
Hair Stylist - *Apple* Blossom Mall - JCPen...
Hair Stylist - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Read more
Cashier - *Apple* Blossom Mall - JCPenney (...
Cashier - Apple Blossom Mall Location:Winchester, VA, United States (https://jobs.jcp.com/jobs/location/191170/winchester-va-united-states) - Apple Blossom Mall Read more
All contents are Copyright 1984-2011 by Xplain Corporation. All rights reserved. Theme designed by Icreon.