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 "chrome/grit/chromium_strings.h"
14 #include "chrome/grit/generated_resources.h"
15 #include "grit/components_strings.h"
16 #include "ui/base/l10n/l10n_util.h"
17 #include "ui/base/l10n/l10n_util_mac.h"
18 #include "ui/strings/grit/ui_strings.h"
20 struct UILocalizerResourceMap {
21 const char* const name;
22 unsigned int label_id;
23 unsigned int label_arg_id;
29 // Utility function for bsearch on a ResourceMap table
30 int ResourceMapCompare(const void* utf8Void,
31 const void* resourceMapVoid) {
32 const char* utf8_key = reinterpret_cast<const char*>(utf8Void);
33 const UILocalizerResourceMap* res_map =
34 reinterpret_cast<const UILocalizerResourceMap*> (resourceMapVoid);
35 return strcmp(utf8_key, res_map->name);
40 @interface GTMUILocalizer (PrivateAdditions)
41 - (void)localizedObjects;
44 @implementation GTMUILocalizer (PrivateAdditions)
45 - (void)localizedObjects {
46 // The ivars are private, so this method lets us trigger the localization
47 // from -[ChromeUILocalizer awakeFromNib].
48 [self localizeObject:owner_ recursively:YES];
49 [self localizeObject:otherObjectToLocalize_ recursively:YES];
50 [self localizeObject:yetAnotherObjectToLocalize_ recursively:YES];
54 @implementation ChromeUILocalizer
56 - (void)awakeFromNib {
57 // The GTM base is bundle based, since don't need the bundle, use this
58 // override to bypass the bundle lookup and directly do the localization
60 [self localizedObjects];
63 - (NSString *)localizedStringForString:(NSString *)string {
65 // Include the table here so it is a local static. This header provides
66 // kUIResources and kUIResourcesSize.
67 #include "ui_localizer_table.h"
69 // Look up the string for the resource id to fetch.
70 const char* utf8_key = [string UTF8String];
72 const void* valVoid = bsearch(utf8_key,
75 sizeof(UILocalizerResourceMap),
77 const UILocalizerResourceMap* val =
78 reinterpret_cast<const UILocalizerResourceMap*>(valVoid);
80 // Do we need to build the string, or just fetch it?
81 if (val->label_arg_id != 0) {
82 const base::string16 label_arg(
83 l10n_util::GetStringUTF16(val->label_arg_id));
84 return l10n_util::GetNSStringFWithFixup(val->label_id, label_arg);
87 return l10n_util::GetNSStringWithFixup(val->label_id);
90 // Sanity check, there shouldn't be any strings with this id that aren't
92 DLOG_IF(WARNING, [string hasPrefix:@"^ID"]) << "Key '" << utf8_key
93 << "' wasn't in the resource map?";
96 // If we didn't find anything, this string doesn't need localizing.