File: NSFontCollection.m

package info (click to toggle)
gnustep-gui 0.32.0-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 15,348 kB
  • sloc: objc: 178,763; ansic: 24,089; cpp: 664; yacc: 464; sh: 90; makefile: 72
file content (625 lines) | stat: -rw-r--r-- 17,998 bytes parent folder | download | duplicates (4)
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
/* Implementation of class NSFontCollection
   Copyright (C) 2019, 2020 Free Software Foundation, Inc.

   By: Gregory John Casamento
   Date: Tue Dec 10 11:51:33 EST 2019

   Author: Fred Kiefer <fredkiefer@gmx.de>
   Date:   March 2020

   This file is part of the GNUstep 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; if not, write to the Free
   Software Foundation, Inc., 51 Franklin Street, Fifth Floor,
   Boston, MA 02110 USA.
*/

#import <Foundation/NSArray.h>
#import <Foundation/NSData.h>
#import <Foundation/NSDebug.h>
#import <Foundation/NSDictionary.h>
#import <Foundation/NSError.h>
#import <Foundation/NSException.h>
#import <Foundation/NSFileManager.h>
#import <Foundation/NSKeyedArchiver.h>
#import <Foundation/NSLocale.h>
#import <Foundation/NSLock.h>
#import <Foundation/NSPathUtilities.h>
#import <Foundation/NSString.h>
#import <Foundation/NSValue.h>

#import <AppKit/NSFontCollection.h>
#import <AppKit/NSFontDescriptor.h>
#import <GNUstepGUI/GSFontInfo.h>

static NSMutableDictionary *_availableFontCollections = nil;
static NSLock *_fontCollectionLock = nil;

/*
 * Private functions...
 */
@interface NSFontCollection (Private)

+ (NSFontCollection *) _readFileAtPath: (NSString *)path;
+ (void) _loadAvailableFontCollections;
- (BOOL) _writeToFileAtPath: (NSString *)path;
- (BOOL) _writeToFile;
- (BOOL) _removeFile;
- (NSMutableDictionary *) _fontCollectionDictionary;
- (void) _setFontCollectionDictionary: (NSMutableDictionary *)dict;
- (void) _setQueryDescriptors: (NSArray *)queryDescriptors;
- (void) _setFullFileName: (NSString *)fn;
- (NSString *) _fullFileName;
- (void) _setName: (NSString *)n;
- (NSString *) _name;
@end

/*
 * Private functions...
 */
@implementation NSFontCollection (Private)

/**
 * Load all font collections....
 */
+ (void) _loadAvailableFontCollections
{
  [_fontCollectionLock lock];

  if (_availableFontCollections != nil)
    {
      // Nothing to do ... already loaded
      [_fontCollectionLock unlock];
    }
  else
    {
      NSString      *dir = nil;
      NSEnumerator  *e = nil;
      NSFileManager *fm = [NSFileManager defaultManager];

      // Create the global array of font collections...
      _availableFontCollections = [[NSMutableDictionary alloc] init];

      /*
       * Load font lists found in standard paths into the array
       */
      e = [NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
                                               NSAllDomainsMask, YES) objectEnumerator];

      while ((dir = (NSString *)[e nextObject]))
	{
	  BOOL flag;
          NSDirectoryEnumerator *de = nil;
          NSString *file = nil;

	  dir = [dir stringByAppendingPathComponent: @"FontCollections"];
	  if (![fm fileExistsAtPath: dir isDirectory: &flag] || !flag)
	    {
	      // Only process existing directories
	      continue;
	    }

	  de = [fm enumeratorAtPath: dir];
	  while ((file = [de nextObject]))
	    {
	      if ([[file pathExtension] isEqualToString: @"collection"])
		{
		  NSString *name = [file stringByDeletingPathExtension];
                  NSString *path = [dir stringByAppendingPathComponent: file];
                  NSFontCollection *newCollection = [self _readFileAtPath: path];

                  if (newCollection != nil && name != nil)
                    {
                      [newCollection _setFullFileName: path];
                      [newCollection _setName: name];
                      [_availableFontCollections setObject: newCollection
                                                    forKey: name];
                    }
                }
	    }
	}

      [_fontCollectionLock unlock];
    }
}

+ (NSFontCollection *) _readFileAtPath: (NSString *)path
{
  NSData *d = [NSData dataWithContentsOfFile: path];
  NSKeyedUnarchiver *u = [[NSKeyedUnarchiver alloc] initForReadingWithData: d];
  NSFontCollection *fc = [[NSFontCollection alloc] initWithCoder: u];

  RELEASE(u);

  return AUTORELEASE(fc);
}

/*
 * Writing and Removing Files
 */
- (BOOL) _writeToFileAtPath: (NSString *)path
{
  BOOL success = NO;
  NSMutableData *m = [[NSMutableData alloc] initWithCapacity: 1024];
  NSKeyedArchiver *a = [[NSKeyedArchiver alloc] initForWritingWithMutableData: m];

  [self encodeWithCoder: a];
  [a finishEncoding];
  RELEASE(a);

  // Write the file....
  NSDebugLLog(@"NSFontCollection", @"Writing to %@", path);
  success = [m writeToFile: path atomically: YES];
  RELEASE(m);
  return success;
}

- (BOOL) _writeToFile
{
  NSFileManager *fm = [NSFileManager defaultManager];
  BOOL           success = NO;
  NSString      *path = [self _fullFileName];

  /*
   * We need to initialize before saving, to avoid the new file being
   * counted as a different collection thus making it appear twice
   */
  [NSFontCollection _loadAvailableFontCollections];

  if (path == nil)
    {
      // Find library....
      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
                                                           NSUserDomainMask, YES);

      if ([paths count] == 0)
        {
          NSLog(@"Failed to find Library directory for user");
          return NO;
        }

      path = [[paths objectAtIndex: 0]
               stringByAppendingPathComponent: @"FontCollections"];
      if ([fm fileExistsAtPath: path] == NO)
        {
          if ([fm createDirectoryAtPath: path
                  withIntermediateDirectories: YES
                             attributes: nil
                                  error: NULL])
            {
              NSDebugLLog(@"NSFontCollection", @"Created standard directory %@", path);
            }
          else
            {
              NSLog(@"Failed attempt to create directory %@", path);
              return NO;
            }
        }

      NSDebugLLog(@"NSFontCollection", @"Font collection name = %@", [self _name]);
      path = [path stringByAppendingPathComponent:
                     [[self _name] stringByAppendingPathExtension: @"collection"]];

      [self _setFullFileName: path];
    }

  // Create the archive...
  success = [self _writeToFileAtPath: path];
  if (success)
    {
      [_fontCollectionLock lock];
      if ([[_availableFontCollections allValues] containsObject: self] == NO)
        {
          [_availableFontCollections setObject: self forKey: [self _name]];
        }
      [_fontCollectionLock unlock];
    }

  return success;
}

- (BOOL) _removeFile
{
  NSFileManager *fm = [NSFileManager defaultManager];
  BOOL           isDir;
  NSString      *path = [self _fullFileName];
  BOOL           result = NO;

  /*
   * We need to initialize before saving, to avoid the new file being
   * counted as a different collection thus making it appear twice
   */
  [NSFontCollection _loadAvailableFontCollections];

  if (path == nil)
    {
      // the standard path for saving font collections
      NSArray *paths = NSSearchPathForDirectoriesInDomains(NSLibraryDirectory,
                                                           NSUserDomainMask, YES);
      if ([paths count] == 0)
	{
	  NSLog(@"Failed to find Library directory for user");
	  return NO;
	}
      path = [[[[paths objectAtIndex: 0]
                 stringByAppendingPathComponent: @"FontCollections"]
                stringByAppendingPathComponent: [self _name]]
               stringByAppendingPathExtension: @"collection"];
    }

  if (![fm fileExistsAtPath: path isDirectory: &isDir] || isDir)
    {
      NSLog(@"Failed to find font collection file to delete");
      return NO;
    }
  else
    {
      // Remove the file
      result = [[NSFileManager defaultManager] removeFileAtPath: path
                                                        handler: nil];

      // Remove the collection from the global list of font collections
      [_fontCollectionLock lock];
      [_availableFontCollections removeObjectForKey: [self _name]];
      [_fontCollectionLock unlock];

      // Reset file name
      [self _setFullFileName: nil];
    }

  return result;
}

- (NSMutableDictionary *) _fontCollectionDictionary
{
  return _fontCollectionDictionary;
}

- (void) _setFontCollectionDictionary: (NSMutableDictionary *)dict
{
  ASSIGNCOPY(_fontCollectionDictionary, dict);
}

- (void) _setQueryDescriptors: (NSArray *)queryDescriptors
{
  return [_fontCollectionDictionary setObject: queryDescriptors
                                       forKey: @"NSFontCollectionFontDescriptors"];
}

- (NSMutableDictionary *) _fontCollectionAttributes
{
  NSMutableDictionary *attrs = [_fontCollectionDictionary objectForKey:
                                                            @"NSFontCollectionAttributes"];

  if (attrs == nil)
    {
      attrs = [NSMutableDictionary dictionary];
      [_fontCollectionDictionary setObject: attrs
                                    forKey: @"NSFontCollectionAttributes"];
    }
  return attrs;
}

- (void) _setName: (NSString *)n
{
  [[self _fontCollectionAttributes] setObject: n
                                       forKey: @"NSFontCollectionName"];
}

- (NSString *) _name
{
  return [[self _fontCollectionAttributes] objectForKey: @"NSFontCollectionName"];
}

- (void) _setFullFileName: (NSString *)fn
{
  [[self _fontCollectionAttributes] setObject: fn
                                forKey: @"NSFontCollectionFileName"];
}

- (NSString *) _fullFileName
{
  return [[self _fontCollectionAttributes] objectForKey: @"NSFontCollectionFileName"];
}

@end

/*
 * NSFontCollection
 */
@implementation NSFontCollection

+ (void) initialize
{
  if (self == [NSFontCollection class])
    {
      [self _loadAvailableFontCollections];
    }
}

// Initializers...
- (instancetype) initWithDescriptors: (NSArray *)queryDescriptors
{
  self = [super init];
  if (self != nil)
    {
      _fontCollectionDictionary = [[NSMutableDictionary alloc] initWithCapacity: 10];
      [self _setQueryDescriptors: queryDescriptors];
    }
  return self;
}

- (instancetype) init
{
  return [self initWithDescriptors: [NSArray array]];
}

- (void) dealloc
{
  RELEASE(_fontCollectionDictionary);
  [super dealloc];
}

+ (NSFontCollection *) fontCollectionWithDescriptors: (NSArray *)queryDescriptors
{
  NSFontCollection *fc = [[NSFontCollection alloc] initWithDescriptors: queryDescriptors];
  return AUTORELEASE(fc);
}

+ (NSFontCollection *) fontCollectionWithAllAvailableDescriptors
{
  NSFontCollection *fc = [_availableFontCollections objectForKey: NSFontCollectionAllFonts];
  if (fc == nil)
    {
      NSDictionary *fa = [NSDictionary dictionary];
      NSFontDescriptor *fd = [NSFontDescriptor fontDescriptorWithFontAttributes: fa];
      fc =  [self fontCollectionWithDescriptors: [NSArray arrayWithObject: fd]];
      if (fc != nil)
        {
          [fc _setName: NSFontCollectionAllFonts];
          [fc _writeToFile];
        }
    }
  return fc;
}

+ (NSFontCollection *) fontCollectionWithLocale: (NSLocale *)locale
{
  NSDictionary *fa = [NSDictionary dictionaryWithObject: [locale languageCode]
                                                 forKey: @"NSCTFontDesignLanguagesAttribute"];
  NSFontDescriptor *fd = [NSFontDescriptor fontDescriptorWithFontAttributes: fa];
  return [self fontCollectionWithDescriptors: [NSArray arrayWithObject: fd]];
}

+ (BOOL) showFontCollection: (NSFontCollection *)collection
                   withName: (NSFontCollectionName)name
                 visibility: (NSFontCollectionVisibility)visibility
                      error: (NSError **)error
{
  [collection _setName: name];
  return [collection _writeToFile];
}

+ (BOOL) hideFontCollectionWithName: (NSFontCollectionName)name
                         visibility: (NSFontCollectionVisibility)visibility
                              error: (NSError **)error
{
  NSFontCollection *collection = [_availableFontCollections objectForKey: name];

  return [collection _removeFile];
}

+ (BOOL) renameFontCollectionWithName: (NSFontCollectionName)aname
                           visibility: (NSFontCollectionVisibility)visibility
                               toName: (NSFontCollectionName)name
                                error: (NSError **)error
{
  NSFontCollection *collection = [_availableFontCollections objectForKey: aname];
  BOOL rv = [collection _removeFile];

  if (rv == YES)
    {
      [collection _setName: name];
      [collection _writeToFile];
    }

  return rv;
}

+ (NSArray *) allFontCollectionNames
{
  return [_availableFontCollections allKeys];
}

+ (NSFontCollection *) fontCollectionWithName: (NSFontCollectionName)name
{
  NSFontCollection *fc = [_availableFontCollections objectForKey: name];
  if (fc == nil)
    {
      fc = [[NSFontCollection alloc] init];
      [fc _setName: name];
      AUTORELEASE(fc);
    }
  return fc;
}

+ (NSFontCollection *) fontCollectionWithName: (NSFontCollectionName)name
                                   visibility: (NSFontCollectionVisibility)visibility
{
  return [self fontCollectionWithName: name];
}

// Descriptors
- (NSArray *) queryDescriptors
{
  return [_fontCollectionDictionary objectForKey: @"NSFontCollectionFontDescriptors"];
}

- (NSArray *) exclusionDescriptors
{
  return [_fontCollectionDictionary objectForKey: @"NSFontExclusionDescriptorAttributes"];
}

- (NSArray *) matchingDescriptors
{
  return [self matchingDescriptorsWithOptions: nil];
}

- (NSArray *) matchingDescriptorsWithOptions: (NSDictionary *)options
{
  return [self matchingDescriptorsForFamily: nil options: options];
}

- (NSArray *) matchingDescriptorsForFamily: (NSString *)family
{
  return [self matchingDescriptorsForFamily: family options: nil];
}

- (NSArray *) matchingDescriptorsForFamily: (NSString *)family options: (NSDictionary *)options
{
  GSFontEnumerator *fen = [GSFontEnumerator sharedEnumerator];

  return [fen matchingDescriptorsForFamily: family
                                   options: options
                                 inclusion: [self queryDescriptors]
                                 exculsion: [self exclusionDescriptors]];
}

- (instancetype) copyWithZone: (NSZone *)zone
{
  NSFontCollection *fc = [[NSFontCollection allocWithZone: zone] init];
  [fc _setFontCollectionDictionary: _fontCollectionDictionary];
  return fc;
}

- (instancetype) mutableCopyWithZone: (NSZone *)zone
{
  NSMutableFontCollection *fc = [[NSMutableFontCollection allocWithZone: zone] init];

  [fc _setFontCollectionDictionary: [_fontCollectionDictionary mutableCopyWithZone: zone]];

  return fc;
}

- (void) encodeWithCoder: (NSCoder *)coder
{
  if ([coder allowsKeyedCoding])
    {
      [coder encodeObject: _fontCollectionDictionary
                   forKey: @"NSFontCollectionDictionary"];
    }
  else
    {
      [coder encodeObject: _fontCollectionDictionary];
    }
}

- (instancetype) initWithCoder: (NSCoder *)coder
{
  self = [super init];
  if (self != nil)
    {
      if ([coder allowsKeyedCoding])
        {
          ASSIGN(_fontCollectionDictionary,
                 [coder decodeObjectForKey: @"NSFontCollectionDictionary"]);
        }
    }
  else
    {
      [coder decodeValueOfObjCType: @encode(id) at: &_fontCollectionDictionary];
    }
  return self;
}

@end


@implementation NSMutableFontCollection

+ (NSMutableFontCollection *) fontCollectionWithDescriptors: (NSArray *)queryDescriptors
{
  return [[NSFontCollection fontCollectionWithDescriptors: queryDescriptors] mutableCopy];
}

+ (NSMutableFontCollection *) fontCollectionWithAllAvailableDescriptors
{
  return [[NSFontCollection fontCollectionWithAllAvailableDescriptors] mutableCopy];
}

+ (NSMutableFontCollection *) fontCollectionWithLocale: (NSLocale *)locale
{
  return [[NSFontCollection fontCollectionWithLocale: locale] mutableCopy];
}

+ (NSMutableFontCollection *) fontCollectionWithName: (NSFontCollectionName)name
{
  return [[NSFontCollection fontCollectionWithName: name] mutableCopy];
}

+ (NSMutableFontCollection *) fontCollectionWithName: (NSFontCollectionName)name
                                          visibility: (NSFontCollectionVisibility)visibility
{
  return [[NSFontCollection fontCollectionWithName: name visibility: visibility] mutableCopy];
}

- (NSArray *) queryDescriptors
{
  return [super queryDescriptors];
}

- (void) setQueryDescriptors: (NSArray *)queryDescriptors
{
  [super _setQueryDescriptors: [queryDescriptors mutableCopy]];
}

- (NSArray *) exclusionDescriptors
{
  return [_fontCollectionDictionary objectForKey: @"NSFontExclusionDescriptorAttributes"];
}

- (void) setExclusionDescriptors: (NSArray *)exclusionDescriptors
{
  [_fontCollectionDictionary setObject: [exclusionDescriptors mutableCopy]
                                forKey: @"NSFontExclusionDescriptorAttributes"];

}

- (void) addQueryForDescriptors: (NSArray *)descriptors
{
  NSMutableArray *arr = [[self queryDescriptors] mutableCopy];
  NSMutableArray *ed = [[self exclusionDescriptors] mutableCopy];

  [ed removeObjectsInArray: descriptors];
  [arr addObjectsFromArray: descriptors];
  [self setQueryDescriptors: arr];
  [self setExclusionDescriptors: ed];
  RELEASE(arr);
  RELEASE(ed);
}

- (void) removeQueryForDescriptors: (NSArray *)descriptors
{
  NSMutableArray *arr = [[self queryDescriptors] mutableCopy];
  NSMutableArray *ed = [[self exclusionDescriptors] mutableCopy];

  [ed addObjectsFromArray: descriptors];
  [arr removeObjectsInArray: descriptors];
  [self setQueryDescriptors: arr];
  [self setExclusionDescriptors: ed];
  RELEASE(arr);
  RELEASE(ed);
}

@end