summaryrefslogtreecommitdiffstats
path: root/chrome/browser/cocoa/font_language_settings_controller.mm
blob: 1aaa548038eb766923c4cb149ec1dddc307e857b (plain)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
// Copyright (c) 2009 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

#import "chrome/browser/cocoa/font_language_settings_controller.h"

#import <Cocoa/Cocoa.h>
#import "base/mac_util.h"
#include "base/sys_string_conversions.h"
#include "chrome/browser/character_encoding.h"
#include "chrome/browser/profile.h"
#include "chrome/common/pref_names.h"
#include "chrome/common/pref_service.h"

NSString* const kCharacterInfoEncoding = @"encoding";
NSString* const kCharacterInfoName = @"name";
NSString* const kCharacterInfoID = @"id";

@interface FontLanguageSettingsController (Private)
- (void)updateDisplayField:(NSTextField*)field withFont:(NSFont*)font;
@end

@implementation FontLanguageSettingsController

- (id)initWithProfile:(Profile*)profile {
  DCHECK(profile);
  NSString* nibpath = [mac_util::MainAppBundle()
                        pathForResource:@"FontLanguageSettings"
                                 ofType:@"nib"];
  if ((self = [super initWithWindowNibPath:nibpath owner:self])) {
    profile_ = profile;

    // Convert the name/size preference values to NSFont objects.
    serifName_.Init(prefs::kWebKitSerifFontFamily, profile->GetPrefs(), NULL);
    serifSize_.Init(prefs::kWebKitDefaultFontSize, profile->GetPrefs(), NULL);
    NSString* serif = base::SysWideToNSString(serifName_.GetValue());
    serifFont_.reset(
        [[NSFont fontWithName:serif size:serifSize_.GetValue()] retain]);

    sansSerifName_.Init(prefs::kWebKitSansSerifFontFamily, profile->GetPrefs(),
                        NULL);
    sansSerifSize_.Init(prefs::kWebKitDefaultFontSize, profile->GetPrefs(),
                        NULL);
    NSString* sansSerif = base::SysWideToNSString(sansSerifName_.GetValue());
    sansSerifFont_.reset(
        [[NSFont fontWithName:sansSerif
                         size:sansSerifSize_.GetValue()] retain]);

    fixedWidthName_.Init(prefs::kWebKitFixedFontFamily, profile->GetPrefs(),
                         NULL);
    fixedWidthSize_.Init(prefs::kWebKitDefaultFixedFontSize,
                         profile->GetPrefs(), NULL);
    NSString* fixedWidth = base::SysWideToNSString(fixedWidthName_.GetValue());
    fixedWidthFont_.reset(
        [[NSFont fontWithName:fixedWidth
                         size:fixedWidthSize_.GetValue()] retain]);

    // Generate a list of encodings.
    NSInteger count = CharacterEncoding::GetSupportCanonicalEncodingCount();
    NSMutableArray* encodings = [NSMutableArray arrayWithCapacity:count];
    for (NSInteger i = 0; i < count; ++i) {
      int commandId = CharacterEncoding::GetEncodingCommandIdByIndex(i);
      string16 name = CharacterEncoding::\
          GetCanonicalEncodingDisplayNameByCommandId(commandId);
      std::string encoding =
          CharacterEncoding::GetCanonicalEncodingNameByCommandId(commandId);
      NSDictionary* strings = [NSDictionary dictionaryWithObjectsAndKeys:
          base::SysUTF16ToNSString(name), kCharacterInfoName,
          base::SysUTF8ToNSString(encoding), kCharacterInfoEncoding,
          [NSNumber numberWithInt:commandId], kCharacterInfoID,
          nil
      ];
      [encodings addObject:strings];
    }

    // Sort the encodings.
    scoped_nsobject<NSSortDescriptor> sorter(
        [[NSSortDescriptor alloc] initWithKey:kCharacterInfoName
                                    ascending:YES]);
    NSArray* sorterArray = [NSArray arrayWithObject:sorter.get()];
    encodings_.reset(
        [[encodings sortedArrayUsingDescriptors:sorterArray] retain]);

    // Find and set the default encoding.
    defaultEncoding_.Init(prefs::kDefaultCharset, profile->GetPrefs(), NULL);
    NSString* defaultEncoding =
        base::SysWideToNSString(defaultEncoding_.GetValue());
    NSUInteger index = 0;
    for (NSDictionary* entry in encodings_.get()) {
      NSString* encoding = [entry objectForKey:kCharacterInfoEncoding];
      if ([encoding isEqualToString:defaultEncoding]) {
        defaultEncodingIndex_ = index;
        break;
      }
      ++index;
    }

    // Register as a KVO observer so we can receive updates when the encoding
    // changes.
    [self addObserver:self
           forKeyPath:@"defaultEncodingIndex_"
              options:NSKeyValueObservingOptionNew
              context:NULL];
  }
  return self;
}

- (void)dealloc {
  [self removeObserver:self forKeyPath:@"defaultEncodingIndex_"];
  [super dealloc];
}

- (void)awakeFromNib {
  DCHECK([self window]);
  [[self window] setDelegate:self];

  // Set up the font display.
  [self updateDisplayField:serifField_ withFont:serifFont_.get()];
  [self updateDisplayField:sansSerifField_ withFont:sansSerifFont_.get()];
  [self updateDisplayField:fixedWidthField_ withFont:fixedWidthFont_.get()];
}

- (void)windowWillClose:(NSNotification*)notif {
  [self autorelease];
}

- (IBAction)selectFont:(id)sender {
  if (sender == serifButton_) {
    currentFont_ = serifFont_.get();
    currentType_ = FontSettingSerif;
  } else if (sender == sansSerifButton_) {
    currentFont_ = sansSerifFont_.get();
    currentType_ = FontSettingSansSerif;
  } else if (sender == fixedWidthButton_) {
    currentFont_ = fixedWidthFont_.get();
    currentType_ = FontSettingFixed;
  } else {
    NOTREACHED();
  }

  // Validate whatever editing is currently happening.
  if ([[self window] makeFirstResponder:nil]) {
    NSFontManager* manager = [NSFontManager sharedFontManager];
    [manager setSelectedFont:currentFont_ isMultiple:NO];
    [manager orderFrontFontPanel:self];
  }
}

// Called by the font manager when the user has selected a new font. We should
// then persist those changes into the preference system.
- (void)changeFont:(id)fontManager {
  switch (currentType_) {
    case FontSettingSerif:
      serifFont_.reset([[fontManager convertFont:serifFont_] retain]);
      [self updateDisplayField:serifField_ withFont:serifFont_.get()];
      changedSerif_ = YES;
      break;
    case FontSettingSansSerif:
      sansSerifFont_.reset([[fontManager convertFont:sansSerifFont_] retain]);
      [self updateDisplayField:sansSerifField_ withFont:sansSerifFont_.get()];
      changedSansSerif_ = YES;
      break;
    case FontSettingFixed:
      fixedWidthFont_.reset(
          [[fontManager convertFont:fixedWidthFont_] retain]);
      [self updateDisplayField:fixedWidthField_
                      withFont:fixedWidthFont_.get()];
      changedFixedWidth_ = YES;
      break;
    default:
      NOTREACHED();
  }
}

- (IBAction)closeSheet:(id)sender {
  NSFontPanel* panel = [[NSFontManager sharedFontManager] fontPanel:NO];
  [panel close];
  [NSApp endSheet:[self window]];
}

- (IBAction)save:(id)sender {
  if (changedSerif_) {
    serifName_.SetValue(base::SysNSStringToWide([serifFont_ fontName]));
    serifSize_.SetValue([serifFont_ pointSize]);
  }
  if (changedSansSerif_) {
    sansSerifName_.SetValue(
        base::SysNSStringToWide([sansSerifFont_ fontName]));
    sansSerifSize_.SetValue([sansSerifFont_ pointSize]);
  }
  if (changedFixedWidth_) {
    fixedWidthName_.SetValue(
        base::SysNSStringToWide([fixedWidthFont_ fontName]));
    fixedWidthSize_.SetValue([fixedWidthFont_ pointSize]);
  }
  if (changedEncoding_) {
    NSDictionary* object = [encodings_ objectAtIndex:defaultEncodingIndex_];
    NSString* newEncoding = [object objectForKey:kCharacterInfoEncoding];
    std::wstring encoding = base::SysNSStringToWide(newEncoding);
    defaultEncoding_.SetValue(encoding);
  }
  [self closeSheet:sender];
}

- (NSArray*)encodings {
  return encodings_.get();
}

// KVO notification.
- (void)observeValueForKeyPath:(NSString*)keyPath
                      ofObject:(id)object
                        change:(NSDictionary*)change
                       context:(void*)context {
  // If this is the default encoding, then set the flag to persist the value.
  if ([keyPath isEqual:@"defaultEncodingIndex_"]) {
    changedEncoding_ = YES;
    return;
  }

  [super observeValueForKeyPath:keyPath
                       ofObject:object
                         change:change
                        context:context];
}

#pragma mark Private

// This will set the font on |field| to be |font|, and will set the string
// value to something human-readable.
- (void)updateDisplayField:(NSTextField*)field withFont:(NSFont*)font {
  if (!font) {
    // Something has gone really wrong. Don't make things worse by showing the
    // user "(null)".
    return;
  }
  [field setFont:font];
  NSString* value =
      [NSString stringWithFormat:@"%@, %g", [font fontName], [font pointSize]];
  [field setStringValue:value];
}

@end