File: NSFontManager.m

package info (click to toggle)
gnustep-gui 0.25.0-4
  • links: PTS, VCS
  • area: main
  • in suites: stretch
  • size: 13,088 kB
  • ctags: 3,417
  • sloc: objc: 153,800; ansic: 18,239; cpp: 579; yacc: 462; makefile: 143; sh: 5
file content (1203 lines) | stat: -rw-r--r-- 32,121 bytes parent folder | download | duplicates (8)
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
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
/** <title>NSFontManager</title>

   <abstract>Manages system and user fonts</abstract>

   Copyright (C) 1996 Free Software Foundation, Inc.

   Author: Fred Kiefer <FredKiefer@gmx.de>
   Date: January 2000
   Almost complete rewrite.
   
   This file is part of the GNUstep GUI Library.

   This library is free software; you can redistribute it and/or
   modify it under the terms of the GNU Lesser General Public
   License as published by the Free Software Foundation; either
   version 2 of the License, or (at your option) any later version.

   This library is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	 See the GNU
   Lesser General Public License for more details.

   You should have received a copy of the GNU Lesser General Public
   License along with this library; see the file COPYING.LIB.
   If not, see <http://www.gnu.org/licenses/> or write to the 
   Free Software Foundation, 51 Franklin Street, Fifth Floor, 
   Boston, MA 02110-1301, USA.
*/ 

#include "config.h"
#import <Foundation/NSArray.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSSet.h>
#import <Foundation/NSString.h>
#import <Foundation/NSValue.h>
#import <Foundation/NSDebug.h>
#import "AppKit/NSFontDescriptor.h"
#import "AppKit/NSFontManager.h"
#import "AppKit/NSApplication.h"
#import "AppKit/NSFont.h"
#import "AppKit/NSFontPanel.h"
#import "AppKit/NSMenu.h"
#import "AppKit/NSMenuItem.h"
#import "GNUstepGUI/GSFontInfo.h"


/*
 * Class variables
 */
static NSFontManager *sharedFontManager = nil;
static NSFontPanel   *fontPanel = nil;
static Class         fontManagerClass = Nil;
static Class         fontPanelClass = Nil;


@implementation NSFontManager

/*
 * Class methods
 */
+ (void) initialize
{
  if (self == [NSFontManager class])
    {
      // Initial version
      [self setVersion: 1];

      // Set the factories
      [self setFontManagerFactory: [NSFontManager class]];
      [self setFontPanelFactory: [NSFontPanel class]];
    }
}

/**<p>Sets the class used to create the NSFontManager to <var>aClass</var>.
   By default it is a NSFontManager class. You can change this behavour by
   implementing your own class ( a subclass of NSFontManager ) </p>
   <p>This class is init into +sharedFontManager</p>
   <p>See Also: +sharedFontManager</p>
 */
+ (void) setFontManagerFactory: (Class)aClass
{
  fontManagerClass = aClass;
}

/**<p>Sets the class used to create a NSFontPanel. If you want to use
   a custom class it should be NSFontPanel subclass</p>
   <p>See Also: -fontPanel:</p>
 */
+ (void) setFontPanelFactory: (Class)aClass
{
  fontPanelClass = aClass;
}

/**<p>Creates ( if needed ) and returns the NSFontManager shared instance.
   This method init the font manager class defined in +setFontManagerFactory:
   ( it is usally a NSFontManager class ) </p>
 */
+ (NSFontManager*) sharedFontManager
{
  if (!sharedFontManager)
    {
      sharedFontManager = [[fontManagerClass alloc] init];
    }
  return sharedFontManager;
}

/*
 * Instance methods
 */
- (id) init
{
  if (sharedFontManager && self != sharedFontManager)
    {
      RELEASE(self);
      return sharedFontManager;
    }
  self = [super init];

  _action = @selector(changeFont:);
  _storedTag = NSNoFontChangeAction;
  _fontEnumerator = RETAIN([GSFontEnumerator sharedEnumerator]);
  _collections = [[NSMutableDictionary alloc] initWithCapacity: 3];

  return self;
}

- (void) dealloc
{
  TEST_RELEASE(_selectedFont);
  TEST_RELEASE(_selectedAttributes);
  TEST_RELEASE(_fontMenu);
  TEST_RELEASE(_fontEnumerator);
  RELEASE(_collections);
  [super dealloc];
}

/**<p>Returns an array of available fonts.</p>
 */
- (NSArray*) availableFonts
{
  return [_fontEnumerator availableFonts];
}

- (NSArray*) availableFontFamilies
{
  return [_fontEnumerator availableFontFamilies];
}

- (NSArray*) availableFontNamesWithTraits: (NSFontTraitMask)fontTraitMask
{
  unsigned int i, j;
  NSArray *fontFamilies = [self availableFontFamilies];
  NSMutableArray *fontNames = [NSMutableArray array];
  NSFontTraitMask traits;

  if (fontTraitMask == (NSUnitalicFontMask | NSUnboldFontMask))
    {
      fontTraitMask = 0;
    }

  for (i = 0; i < [fontFamilies count]; i++)
    {
      NSArray *fontDefs = [self availableMembersOfFontFamily: 
                                 [fontFamilies objectAtIndex: i]];
      
      for (j = 0; j < [fontDefs count]; j++)
        {
          NSArray *fontDef = [fontDefs objectAtIndex: j];

          traits = [[fontDef objectAtIndex: 3] unsignedIntValue];
          // Check if the font has exactly the given mask
          if (traits == fontTraitMask)
            [fontNames addObject: [fontDef objectAtIndex: 0]];
        }
    }

  return fontNames;
}

- (NSArray*) availableMembersOfFontFamily: (NSString*)family
{
  return [_fontEnumerator availableMembersOfFontFamily: family];
}

- (NSArray *) availableFontNamesMatchingFontDescriptor: (NSFontDescriptor *)descriptor
{
  return [_fontEnumerator availableFontNamesMatchingFontDescriptor: descriptor];
}

// GNUstep extension
- (NSArray *) matchingFontDescriptorsFor: (NSDictionary *)attributes
{
  return [_fontEnumerator matchingFontDescriptorsFor: attributes];
}

- (NSString*) localizedNameForFamily: (NSString*)family 
                                face: (NSString*)face
{
  // TODO
  return [NSString stringWithFormat: @"%@-%@", family, face];
}

/**
 */
- (void) setSelectedFont: (NSFont*)fontObject
              isMultiple: (BOOL)flag
{
  if (_selectedFont == fontObject)
    {
      if (flag != _multiple)
        {
          _multiple = flag;
          // The panel should also know if multiple changed
          if (fontPanel != nil)
            {
              [fontPanel setPanelFont: fontObject isMultiple: flag];
            }
        }
      return;
    }

  _multiple = flag;
  ASSIGN(_selectedFont, fontObject);
  DESTROY(_selectedAttributes);

  if (fontPanel != nil)
    {
      [fontPanel setPanelFont: fontObject isMultiple: flag];
    }
  
  if (_fontMenu != nil)
    {
      id <NSMenuItem> menuItem;
      NSFontTraitMask trait = [self traitsOfFont: fontObject];

      /*
       * FIXME: We should check if that trait is available
       * We keep the tag, to mark the item
       */
      if (trait & NSItalicFontMask)
        {
          menuItem = [_fontMenu itemWithTag: NSItalicFontMask];
          if (menuItem != nil)
            {
              [menuItem setTitle: @"Unitalic"];
              [menuItem setAction: @selector(removeFontTrait:)];
            }
        }
      else
        {
          menuItem = [_fontMenu itemWithTag: NSItalicFontMask];
          if (menuItem != nil)
            {
              [menuItem setTitle: @"Italic"];
              [menuItem setAction: @selector(addFontTrait:)];
            }
        }

      if (trait & NSBoldFontMask)
        {
          menuItem = [_fontMenu itemWithTag: NSBoldFontMask];
          if (menuItem != nil)
            {
              [menuItem setTitle: @"Unbold"];
              [menuItem setAction: @selector(removeFontTrait:)];
            }
        }
      else
        {
          menuItem = [_fontMenu itemWithTag: NSBoldFontMask];
          if (menuItem != nil)
            {
              [menuItem setTitle: @"Bold"];
              [menuItem setAction: @selector(addFontTrait:)];
            }
        }

      // TODO Update the rest of the font menu to reflect this font
    }
}

/**<p>Returns the selected font</p>
   <p>See Also: -setSelectedFont:isMultiple:</p>
 */
- (NSFont*) selectedFont
{
  return _selectedFont;
}

/**<p>Returns whether the current selection contains multiple fonts</p>
 */
- (BOOL) isMultiple
{
  return _multiple;
}

/*
 * Action methods
 */
- (void) addFontTrait: (id)sender
{
  _storedTag = NSAddTraitFontAction;
  _trait = [sender tag];
  [self sendAction];

  // We update our own selected font
  if (_selectedFont != nil)
    {
      NSFont *newFont = [self convertFont: _selectedFont];

      if (newFont != nil)
        {
          [self setSelectedFont: newFont isMultiple: _multiple];
        }
    }
}

- (void) removeFontTrait: (id)sender
{
  _storedTag = NSRemoveTraitFontAction;
  _trait = [sender tag];
  [self sendAction];

  // We update our own selected font
  if (_selectedFont != nil)
    {
      NSFont *newFont = [self convertFont: _selectedFont];

      if (newFont != nil)
        {
          [self setSelectedFont: newFont isMultiple: _multiple];
        }
    }
}

- (void) modifyFont: (id)sender
{
  _storedTag = [sender tag];
  [self sendAction];

  // We update our own selected font
  if (_selectedFont != nil)
    {
      NSFont *newFont = [self convertFont: _selectedFont];

      if (newFont != nil)
        {
          [self setSelectedFont: newFont isMultiple: _multiple];
        }
    }
}

- (void) modifyFontViaPanel: (id)sender
{
  _storedTag = NSViaPanelFontAction;
  [self sendAction];

  // We update our own selected font
  if (_selectedFont != nil)
    {
      NSFont *newFont = [self convertFont: _selectedFont];

      if (newFont != nil)
        {
          [self setSelectedFont: newFont isMultiple: _multiple];
        }
    }
}

/**<p>Converts the NSFont <var>fontObject</var> according to user changes
   in the Font panel or the font menu</p>
   <p>See Also: -addFontTrait: -removeFontTrait: -modifyFont: 
   -modifyFontViaPanel: -convertFont:toHaveTrait: -convertFont:toNotHaveTrait:
   -convertFont:toSize: -convertFont:toFamily: -convertWeight:ofFont:</p>
 */
- (NSFont*) convertFont: (NSFont*)fontObject
{
  NSFont *newFont = fontObject;
  int i;
  float size;
  float sizes[] = {4.0, 6.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 
                   14.0, 16.0, 18.0, 24.0, 36.0, 48.0, 64.0};

  if (fontObject == nil)
    return nil;

  switch (_storedTag)
    {
      case NSNoFontChangeAction: 
        break;
      case NSViaPanelFontAction: 
        if (fontPanel != nil)
          {
            newFont = [fontPanel panelConvertFont: fontObject];
          }
        break;
      case NSAddTraitFontAction: 
        newFont = [self convertFont: fontObject toHaveTrait: _trait];
        break;
      case NSRemoveTraitFontAction: 
         newFont = [self convertFont: fontObject toNotHaveTrait: _trait];
        break;
      case NSSizeUpFontAction: 
        size = [fontObject pointSize];
        for (i = 0; i < sizeof(sizes)/sizeof(float); i++)
          {
            if (sizes[i] > size)
              {
                size = sizes[i];
                break;
              }
          }
        newFont = [self convertFont: fontObject 
                        toSize: size];
        break;
      case NSSizeDownFontAction: 
        size = [fontObject pointSize];
        for (i = sizeof(sizes)/sizeof(float) -1; i >= 0; i--)
          {
            if (sizes[i] < size)
              {
                size = sizes[i];
                break;
              }
          }
        newFont = [self convertFont: fontObject 
                        toSize: size];
        break;
      case NSHeavierFontAction: 
        newFont = [self convertWeight: YES ofFont: fontObject]; 
        break;
      case NSLighterFontAction: 
        newFont = [self convertWeight: NO ofFont: fontObject]; 
        break;
    }

  return newFont;
}


- (NSFont*) convertFont: (NSFont*)fontObject
               toFamily: (NSString*)family
{
  if ([family isEqualToString: [fontObject familyName]])
    {
      // If already of that family then just return it
      return fontObject;
    }
  else
    {
      // Else convert it
      NSFont *newFont;
      NSFontTraitMask trait = [self traitsOfFont: fontObject];
      int weight = [self weightOfFont: fontObject];
      float size = [fontObject pointSize];

      newFont = [self fontWithFamily: family 
                              traits: trait
                              weight: weight
                                size: size];
      if (newFont == nil)
        return fontObject;
      else 
        return newFont;
    }
}

- (NSFont*) convertFont: (NSFont*)fontObject
                 toFace: (NSString*)typeface
{
  NSFont *newFont;

  // This conversion just retains the point size
  if ([[fontObject fontName] isEqualToString: typeface])
    {
      return fontObject;
    }

  newFont = [NSFont fontWithName: typeface size: [fontObject pointSize]];
  if (newFont == nil)
    return fontObject;
  else 
    return newFont;
}

- (NSFont*) convertFont: (NSFont*)fontObject
            toHaveTrait: (NSFontTraitMask)trait
{
  NSFontTraitMask t = [self traitsOfFont: fontObject];

  if (t & trait)
    {
      // If already have that trait then just return it
      return fontObject;
    }
  else
    {
      // Else convert it
      NSFont *newFont;

      int weight = [self weightOfFont: fontObject];
      float size = [fontObject pointSize];
      NSString *family = [fontObject familyName];

      if (trait & NSBoldFontMask)
        {
          // We cannot reuse the weight in a bold
          weight = 9;
          t = t & ~NSUnboldFontMask;
        }
      else if (trait & NSUnboldFontMask)
        {
          // We cannot reuse the weight in an unbold
          weight = 5;
          t = t & ~NSBoldFontMask;
        }
      if (trait == NSItalicFontMask)
        {
          t = t & ~NSUnitalicFontMask;
        }
      else if (trait & NSUnitalicFontMask)
        {
          t = t & ~NSItalicFontMask;
        }

      t = t | trait;

      newFont = [self fontWithFamily: family 
                              traits: t
                              weight: weight
                                size: size];

      if (newFont == nil)
        return fontObject;
      else 
        return newFont;
    }
}

- (NSFont*) convertFont: (NSFont*)fontObject
         toNotHaveTrait: (NSFontTraitMask)trait
{
  NSFontTraitMask t = [self traitsOfFont: fontObject];

  if (!(t & trait))
    {
      // If already do not have that trait then just return it
      return fontObject;
    }
  else
    {
      // Else convert it
      NSFont *newFont;

      int weight = [self weightOfFont: fontObject];
      float size = [fontObject pointSize];
      NSString *family = [fontObject familyName];

      if (trait & NSBoldFontMask)
        {
          // We cannot reuse the weight in an unbold
          weight = 5;
          t = (t | NSUnboldFontMask);
        }
      else if (trait & NSUnboldFontMask)
        {
          // We cannot reuse the weight in a bold
          weight = 9;
          t = (t | NSBoldFontMask);
        }
      if (trait & NSItalicFontMask)
        {
          t = (t | NSUnitalicFontMask);
        }
      else if (trait & NSUnitalicFontMask)
        {
          t = (t | NSItalicFontMask);
        }
 
      t &= ~trait;
      newFont = [self fontWithFamily: family 
                              traits: t
                              weight: weight
                                size: size];
      if (newFont == nil)
        return fontObject;
      else 
        return newFont;
    }
}

- (NSFont*) convertFont: (NSFont*)fontObject
                 toSize: (float)size
{
  if ([fontObject pointSize] == size)
    {
      // If already that size then just return it
      return fontObject;
    }
  else
    {
      // Else convert it
      NSFont *newFont;

      newFont = [NSFont fontWithName: [fontObject fontName] 
                        size: size];
      if (newFont == nil)
        return fontObject;
      else 
        return newFont;
    }
}

- (NSFont*) convertWeight: (BOOL)upFlag
                   ofFont: (NSFont*)fontObject
{
  NSFont *newFont = nil;
  NSString *fontName = nil;
  NSFontTraitMask trait = [self traitsOfFont: fontObject];
  float size = [fontObject pointSize];
  NSString *family = [fontObject familyName];
  int w = [self weightOfFont: fontObject];
  // We check what weights we have for this family. We must
  // also check to see if that font has the correct traits!
  NSArray *fontDefs = [self availableMembersOfFontFamily: family];

  if (upFlag)
    {
      unsigned int i;
      // The documentation is a bit unclear about the range of weights
      // sometimes it says 0 to 9 and sometimes 0 to 15
      int next_w = 15;

      for (i = 0; i < [fontDefs count]; i++)
        {
          NSArray *fontDef = [fontDefs objectAtIndex: i];
          int w1 = [[fontDef objectAtIndex: 2] intValue];

          if (w1 > w && w1 < next_w && 
              [[fontDef objectAtIndex: 3] unsignedIntValue] == trait)
            {
              next_w = w1;
              fontName = [fontDef objectAtIndex: 0];
            }
        }

      if (fontName == nil)
        {
          // Not found, try again with changed trait
          trait |= NSBoldFontMask;
          
          for (i = 0; i < [fontDefs count]; i++)
            { 
              NSArray *fontDef = [fontDefs objectAtIndex: i];
              int w1 = [[fontDef objectAtIndex: 2] intValue];

              if (w1 > w && w1 < next_w && 
                  [[fontDef objectAtIndex: 3] unsignedIntValue] == trait)
                {
                  next_w = w1;
                  fontName = [fontDef objectAtIndex: 0];
                }
            }
        }
    }
  else
    {
      unsigned int i;
      int next_w = 0;

      for (i = 0; i < [fontDefs count]; i++)
        {
          NSArray *fontDef = [fontDefs objectAtIndex: i];
          int w1 = [[fontDef objectAtIndex: 2] intValue];

          if (w1 < w && w1 > next_w
            && [[fontDef objectAtIndex: 3] unsignedIntValue] == trait)
            {
              next_w = w1;
              fontName = [fontDef objectAtIndex: 0];
            }
        }

      if (fontName == nil)
        {
          // Not found, try again with changed trait
          trait &= ~NSBoldFontMask;

          for (i = 0; i < [fontDefs count]; i++)
            {
              NSArray *fontDef = [fontDefs objectAtIndex: i];
              int w1 = [[fontDef objectAtIndex: 2] intValue];
              
              if (w1 < w && w1 > next_w
                && [[fontDef objectAtIndex: 3] unsignedIntValue] == trait)
                {
                  next_w = w1;
                  fontName = [fontDef objectAtIndex: 0];
                }
            }
        }
    }

  if (fontName != nil)
    {
      newFont = [NSFont fontWithName: fontName
                                size: size];
    }
  if (newFont == nil)
    return fontObject;
  else 
    return newFont;
}

/*
 * Getting a font
 */
- (NSFont*) fontWithFamily: (NSString*)family
                    traits: (NSFontTraitMask)traits
                    weight: (int)weight
                      size: (float)size
{
  NSArray *fontDefs = [self availableMembersOfFontFamily: family];
  unsigned int i;

  //NSLog(@"Searching font %@: %i: %i size %.0f", family, weight, traits, size);

  // First do an exact match search
  for (i = 0; i < [fontDefs count]; i++)
    {
      NSArray *fontDef = [fontDefs objectAtIndex: i];

      //NSLog(@"Testing font %@: %i: %i", [fontDef objectAtIndex: 0], 
      //          [[fontDef objectAtIndex: 2] intValue], 
      //          [[fontDef objectAtIndex: 3] unsignedIntValue]);  
      if (([[fontDef objectAtIndex: 2] intValue] == weight) &&
          ([[fontDef objectAtIndex: 3] unsignedIntValue] == traits))
        {
            //NSLog(@"Found font");
          return [NSFont fontWithName: [fontDef objectAtIndex: 0] 
                         size: size];
        }
    }

  // Try to find something close by ignoring some trait flags
  traits &= ~(NSNonStandardCharacterSetFontMask | NSFixedPitchFontMask
              | NSUnitalicFontMask | NSUnboldFontMask);
  for (i = 0; i < [fontDefs count]; i++)
    {
      NSArray *fontDef = [fontDefs objectAtIndex: i];
      NSFontTraitMask t = [[fontDef objectAtIndex: 3] unsignedIntValue];

      t &= ~(NSNonStandardCharacterSetFontMask | NSFixedPitchFontMask
             | NSUnitalicFontMask | NSUnboldFontMask);
      if (([[fontDef objectAtIndex: 2] intValue] == weight) &&
          (t == traits))
        {
            //NSLog(@"Found font");
          return [NSFont fontWithName: [fontDef objectAtIndex: 0] 
                         size: size];
        }
    }

  if (traits & NSBoldFontMask)
    {
      //NSLog(@"Trying ignore weights for bold font");
      for (i = 0; i < [fontDefs count]; i++)
        {
          NSArray *fontDef = [fontDefs objectAtIndex: i];
          NSFontTraitMask t = [[fontDef objectAtIndex: 3] unsignedIntValue];

          t &= ~(NSNonStandardCharacterSetFontMask | NSFixedPitchFontMask
                 | NSUnitalicFontMask | NSUnboldFontMask);
          if (t == traits)
            {
              //NSLog(@"Found font");
              return [NSFont fontWithName: [fontDef objectAtIndex: 0] 
                             size: size];
            }
        }
    }
  
  if (weight == 5 || weight == 6)
    {
      //NSLog(@"Trying alternate non-bold weights for non-bold font");
      for (i = 0; i < [fontDefs count]; i++)
        {
          NSArray *fontDef = [fontDefs objectAtIndex: i];
          NSFontTraitMask t = [[fontDef objectAtIndex: 3] unsignedIntValue];

          t &= ~(NSNonStandardCharacterSetFontMask | NSFixedPitchFontMask
                 | NSUnitalicFontMask | NSUnboldFontMask);
          if ((([[fontDef objectAtIndex: 2] intValue] == 5) ||
               ([[fontDef objectAtIndex: 2] intValue] == 6)) &&
              (t == traits))
            {
              //NSLog(@"Found font");
              return [NSFont fontWithName: [fontDef objectAtIndex: 0] 
                             size: size];
            }
        }
    }

  //NSLog(@"Didnt find font");  
  return nil;
}

//
// Examining a font
//
- (NSFontTraitMask) traitsOfFont: (NSFont*)aFont
{
  return [[aFont fontInfo] traits];
}

/**<p>Returns the weight of the NSFont <var>fontObject</var></p>
 */
- (int) weightOfFont: (NSFont*)fontObject
{
  return [[fontObject fontInfo] weight];
}

- (BOOL) fontNamed: (NSString*)typeface 
         hasTraits: (NSFontTraitMask)fontTraitMask
{
  // TODO: This method is implemented very slow, but I dont 
  // see any use for it, so why change it?
  unsigned int i, j;
  NSArray *fontFamilies = [self availableFontFamilies];
  NSFontTraitMask traits;
  
  for (i = 0; i < [fontFamilies count]; i++)
    {
      NSArray *fontDefs = [self availableMembersOfFontFamily: 
                                  [fontFamilies objectAtIndex: i]];
      
      for (j = 0; j < [fontDefs count]; j++)
        {
          NSArray *fontDef = [fontDefs objectAtIndex: j];
          
          if ([[fontDef objectAtIndex: 0] isEqualToString: typeface])
            {
              traits = [[fontDef objectAtIndex: 3] unsignedIntValue];
              // FIXME: This is not exactly the right condition
              if ((traits & fontTraitMask) == fontTraitMask)
                {
                  return YES;
                }
              else
                return NO;
            }
        }
    }
  
  return NO;
}

/**<p>Returns whether the NSFontPanel is enabled ( if exists )</p> 
 */
- (BOOL) isEnabled
{
  if (fontPanel != nil)
    {
      return [fontPanel isEnabled];
    }
  else
    return NO;
}

/**<p>Enables/disables the NSFontPanel and the font menu ( if they exist )</p> 
   <p>See Also: -isEnabled</p>
 */
- (void) setEnabled: (BOOL)flag
{
  int i;

  if (_fontMenu != nil)
    {
      for (i = 0; i < [_fontMenu numberOfItems]; i++)
        {
          [[_fontMenu itemAtIndex: i] setEnabled: flag];
        }
    }

  if (fontPanel != nil)
    [fontPanel setEnabled: flag];
}

/**<p>Returns the font menu, creates it (if needed ) if <var>create</var> 
   is YES.</p><p>See Also: -setFontMenu:</p>
 */
- (NSMenu*) fontMenu: (BOOL)create
{
  if (create && _fontMenu == nil)
    {
      id <NSMenuItem> menuItem;
      
      // As the font menu is stored in a instance variable we 
      // dont autorelease it
      _fontMenu = [NSMenu new];
      [_fontMenu setTitle: @"Font Menu"];

      // First an entry to start the font panel
      menuItem = [_fontMenu addItemWithTitle: @"Font Panel"
                            action: @selector(orderFrontFontPanel:)
                            keyEquivalent: @"t"];
      [menuItem setTarget: self];

      // Entry for italic
      menuItem = [_fontMenu addItemWithTitle: @"Italic"
                            action: @selector(addFontTrait:)
                            keyEquivalent: @"i"];
      [menuItem setTag: NSItalicFontMask];
      [menuItem setTarget: self];

      // Entry for bold
      menuItem = [_fontMenu addItemWithTitle: @"Bold"
                            action: @selector(addFontTrait:)
                            keyEquivalent: @"b"];
      [menuItem setTag: NSBoldFontMask];
      [menuItem setTarget: self];

      // Entry to increase weight
      menuItem = [_fontMenu addItemWithTitle: @"Heavier"
                            action: @selector(modifyFont:)
                            keyEquivalent: @""];
      [menuItem setTag: NSHeavierFontAction];
      [menuItem setTarget: self];
 
      // Entry to decrease weight
      menuItem = [_fontMenu addItemWithTitle: @"Lighter"
                            action: @selector(modifyFont:)
                            keyEquivalent: @""];
      [menuItem setTag: NSLighterFontAction];
      [menuItem setTarget: self];
 
      // Entry to increase size
      menuItem = [_fontMenu addItemWithTitle: @"Larger"
                            action: @selector(modifyFont:)
                            keyEquivalent: @"+"];
      [menuItem setTag: NSSizeUpFontAction];
      [menuItem setTarget: self];

      // Entry to decrease size
      menuItem = [_fontMenu addItemWithTitle: @"Smaller"
                            action: @selector(modifyFont:)
                            keyEquivalent: @"-"];
      [menuItem setTag: NSSizeDownFontAction];
      [menuItem setTarget: self];
    }
  return _fontMenu;
}

/**<p>Sets the font menu to <var>newMenu</var></p>
   <p>See Also: -fontMenu:</p>
 */
- (void) setFontMenu: (NSMenu*)newMenu
{
  ASSIGN(_fontMenu, newMenu); 
}

/**<p>Returns the NSFontPanel, creates it ( if needed ) if <var>create</var>
   is YES.</p>
   <p>See Also: +setFontPanelFactory:</p>
 */
- (NSFontPanel*) fontPanel: (BOOL)create
{
  if ((fontPanel == nil) && (create))
    {
      fontPanel = [[fontPanelClass alloc] init];
    }
  return fontPanel;
}

- (void) orderFrontFontPanel: (id)sender
{
  if (fontPanel == nil)
    fontPanel = [self fontPanel: YES];
  [fontPanel orderFront: sender];
}

/**<p>Returns the NSFontManager's delegate</p>
 */
- (id) delegate
{
  return _delegate;
}

/**<p>Sets the NSFontManager's delegate to <var>anObject</var></p>
 * FIXME: This is extremely unclear.  At the moment, the
 * NSFontManager's delegate is never used.  This can't be right.
 */
- (void) setDelegate: (id)anObject
{
  _delegate = anObject;
}

/** <p>Returns the action sents by the NSFontManager.</p>
    <p>See Also: -setAction:</p>
 */
- (SEL) action
{
  return _action;
}

/** <p>Sents the action sents by the NSFontManager to <var>aSelector</var>.</p>
    <p>See Also: -action</p>
 */
- (void) setAction: (SEL)aSelector
{
  _action = aSelector;
}

- (BOOL) sendAction
{
  NSApplication *theApp = [NSApplication sharedApplication];

  if (_action)
    {
      /* FIXME - shouldn't we try our own delegate first ??  It seems
       * what every programmer would expect, but it looks like Apple
       * doesn't do it!  Or maybe they fixed it in recent releases ?
       */
      return [theApp sendAction: _action to: nil from: self];
    }
  else
    {
      return NO;
    }
}

- (BOOL) addCollection: (NSString *)name options: (int)options
{
  [_collections setObject: [NSMutableArray arrayWithCapacity: 10] forKey: name];
  return YES;
}

- (BOOL) removeCollection:(NSString *) collection
{
  if ([_collections objectForKey: collection])
    {
      [_collections removeObjectForKey: collection];
      return YES;
    }
  else
    {
      return NO;
    }
}

- (NSArray *) collectionNames
{
  return [_collections allKeys];
}

- (void) addFontDescriptors: (NSArray *)descriptors 
               toCollection: (NSString *)collection
{
  NSMutableArray *a = [_collections objectForKey: collection];

  if (a)
    {
      [a addObjectsFromArray: descriptors];
    }
}

- (void) removeFontDescriptor: (NSFontDescriptor *)descriptor 
               fromCollection: (NSString *)collection
{
  NSMutableArray *a = [_collections objectForKey: collection];

  if (a)
    {
      [a removeObject: descriptor];
    }
}

- (NSArray *) fontDescriptorsInCollection: (NSString *)collection
{
  return [_collections objectForKey: collection];
}

- (NSDictionary *) convertAttributes: (NSDictionary *)attributes
{
  NSMutableDictionary *newAttributes;
  int i;
  float size;
  float sizes[] = {4.0, 6.0, 8.0, 9.0, 10.0, 11.0, 12.0, 13.0, 
                   14.0, 16.0, 18.0, 24.0, 36.0, 48.0, 64.0};
  NSFontTraitMask t;

  if (attributes == nil)
    return nil;

  newAttributes = AUTORELEASE([attributes mutableCopy]);
  switch (_storedTag)
    {
      case NSNoFontChangeAction: 
        break;
      case NSViaPanelFontAction: 
        // FIXME
        break;
      case NSAddTraitFontAction: 
        t = [[attributes objectForKey: NSFontSymbolicTrait] unsignedIntValue];
        
        if (t & _trait)
          {
            return newAttributes;
          }
        else if (_trait == NSUnboldFontMask)
          {
            t &= ~NSBoldFontMask;
          }
        else if (_trait == NSUnitalicFontMask)
          {
            t &= ~NSItalicFontMask;
          }
        else
          {
            t &= _trait;
            // FIXME: What about weight for NSBoldFontMask?
          }
        [newAttributes setObject: [NSNumber numberWithUnsignedInt: t]
                       forKey: NSFontSymbolicTrait];
        break;
      case NSRemoveTraitFontAction: 
        t = [[attributes objectForKey: NSFontSymbolicTrait] unsignedIntValue];
        
        if (!(t & _trait))
          {
            return newAttributes;
          }
        else if (_trait == NSUnboldFontMask)
          {
            t = (t | NSBoldFontMask) & ~NSUnboldFontMask;
          }
        else if (_trait == NSUnitalicFontMask)
          {
            t = (t | NSItalicFontMask) & ~NSUnitalicFontMask;
          }
        else
          {
            t &= ~_trait;
            // FIXME: What about weight for NSBoldFontMask?
          }
        [newAttributes setObject: [NSNumber numberWithUnsignedInt: t]
                       forKey: NSFontSymbolicTrait];
        break;
      case NSSizeUpFontAction: 
        size = [[attributes objectForKey: NSFontSizeAttribute] floatValue];
        for (i = 0; i < sizeof(sizes)/sizeof(float); i++)
          {
            if (sizes[i] > size)
              {
                size = sizes[i];
                break;
              }
          }
        [newAttributes setObject: [NSString stringWithFormat: @"%f", size]
                       forKey: NSFontSizeAttribute];
        break;
      case NSSizeDownFontAction: 
        size = [[attributes objectForKey: NSFontSizeAttribute] floatValue];
        for (i = sizeof(sizes)/sizeof(float) -1; i >= 0; i--)
          {
            if (sizes[i] < size)
              {
                size = sizes[i];
                break;
              }
          }
        [newAttributes setObject: [NSString stringWithFormat: @"%f", size]
                       forKey: NSFontSizeAttribute];
        break;
      case NSHeavierFontAction: 
        // FIXME
        break;
      case NSLighterFontAction: 
        // FIXME
        break;
    }

  return newAttributes;
}

- (void) setSelectedAttributes: (NSDictionary *)attributes 
                    isMultiple: (BOOL)flag
{
  ASSIGN(_selectedAttributes, attributes);
  _multiple = flag;
  DESTROY(_selectedFont);
}

@end

@implementation NSApplication(NSFontPanel)

- (void) orderFrontFontPanel: (id)sender
{
  [[NSFontManager sharedFontManager] orderFrontFontPanel: sender];
}

@end