1 // Copyright (c) 2011 The Chromium Authors. All rights reserved.
2 // Use of this source code is governed by a BSD-style license that can be
3 // found in the LICENSE file.
5 #import "chrome/browser/ui/cocoa/ui_localizer.h"
7 #import <Foundation/Foundation.h>
11 #include "base/logging.h"
12 #include "base/strings/sys_string_conversions.h"
13 #include "grit/chromium_strings.h"
14 #include "grit/generated_resources.h"
15 #include "grit/ui_strings.h"
16 #include "ui/base/l10n/l10n_util.h"
17 #include "ui/base/l10n/l10n_util_mac.h"
19 struct UILocalizerResourceMap {
20 const char* const name;
21 unsigned int label_id;
22 unsigned int label_arg_id;
28 // Utility function for bsearch on a ResourceMap table
29 int ResourceMapCompare(const void* utf8Void,
30 const void* resourceMapVoid) {
31 const char* utf8_key = reinterpret_cast<const char*>(utf8Void);
32 const UILocalizerResourceMap* res_map =
33 reinterpret_cast<const UILocalizerResourceMap*> (resourceMapVoid);
34 return strcmp(utf8_key, res_map->name);
39 @interface GTMUILocalizer (PrivateAdditions)
40 - (void)localizedObjects;
43 @implementation GTMUILocalizer (PrivateAdditions)
44 - (void)localizedObjects {
45 // The ivars are private, so this method lets us trigger the localization
46 // from -[ChromeUILocalizer awakeFromNib].
47 [self localizeObject:owner_ recursively:YES];
48 [self localizeObject:otherObjectToLocalize_ recursively:YES];
49 [self localizeObject:yetAnotherObjectToLocalize_ recursively:YES];
53 @implementation ChromeUILocalizer
55 - (void)awakeFromNib {
56 // The GTM base is bundle based, since don't need the bundle, use this
57 // override to bypass the bundle lookup and directly do the localization
59 [self localizedObjects];
62 - (NSString *)localizedStringForString:(NSString *)string {
64 // Include the table here so it is a local static. This header provides
65 // kUIResources and kUIResourcesSize.
66 #include "ui_localizer_table.h"
68 // Look up the string for the resource id to fetch.
69 const char* utf8_key = [string UTF8String];
71 const void* valVoid = bsearch(utf8_key,
74 sizeof(UILocalizerResourceMap),
76 const UILocalizerResourceMap* val =
77 reinterpret_cast<const UILocalizerResourceMap*>(valVoid);
79 // Do we need to build the string, or just fetch it?
80 if (val->label_arg_id != 0) {
81 const base::string16 label_arg(
82 l10n_util::GetStringUTF16(val->label_arg_id));
83 return l10n_util::GetNSStringFWithFixup(val->label_id, label_arg);
86 return l10n_util::GetNSStringWithFixup(val->label_id);
89 // Sanity check, there shouldn't be any strings with this id that aren't
91 DLOG_IF(WARNING, [string hasPrefix:@"^ID"]) << "Key '" << utf8_key
92 << "' wasn't in the resource map?";
95 // If we didn't find anything, this string doesn't need localizing.