File: StringsFile.m

package info (click to toggle)
gnustep-base 1.31.1-4
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 26,580 kB
  • sloc: objc: 239,446; ansic: 36,519; cpp: 122; sh: 112; makefile: 100; xml: 32
file content (652 lines) | stat: -rw-r--r-- 16,615 bytes parent folder | download | duplicates (2)
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
/* StringsFile

   Copyright (C) 2002 Free Software Foundation, Inc.

   Written by:  Alexander Malmberg <alexander@malmberg.org>
   Created: 2002

   This file is part of the GNUstep Project

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

   You should have received a copy of the GNU General Public
   License along with this program; see the file COPYINGv3.
   If not, write to the Free Software Foundation,
   31 Milk Street #960789 Boston, MA 02196 USA.

*/

#import "common.h"
#import "Foundation/NSString.h"
#import "Foundation/NSArray.h"
#import "Foundation/NSFileManager.h"
#import "Foundation/NSData.h"
#import "Foundation/NSDate.h"

#include "StringsFile.h"

#include "StringsEntry.h"
#include "SourceEntry.h"

#include "make_strings.h"


static NSString *parse_string(NSString **ptr)
{
  NSString *str = *ptr;
  NSString *ret;
  int i,c;
  unichar ch;

  c = [str length];
  for (i = 0; i < c; i++)
    {
      ch = [str characterAtIndex: i];
      if (ch == '\\')
	{
	  if (i == c)
	    {
	      fprintf(stderr,"parse error, \\ without second character\n");
	      exit(1);
	    }
	  i++;
	}
      if (ch == '\"')
	break;
    }
  if (i == c)
    {
      fprintf(stderr,"parse error, unterminated string\n");
      exit(1);
    }
  ret = [str substringToIndex: i];
  str = [str substringFromIndex: i+1];
  *ptr = str;

  return ret;
}


#define DUMMY @"<dummy>"

@implementation StringsFile

- (BOOL) isTranslated: (NSString *)key
{
  return [keys_translated containsObject: key];
}

- (void) addTranslated: (NSString *)key
{
  if (![self isTranslated: key])
    [keys_translated addObject: key];
}


- (BOOL) isMatched: (NSString *)key
{
  return [keys_matched containsObject: key];
}

- (void) addMatched: (NSString *)key
{
  if (![self isMatched: key])
    [keys_matched addObject: key];
}


- init
{
  self = [super init];
  strings = [[NSMutableArray alloc] init];
  keys_translated = [[NSMutableArray alloc] init];
  keys_matched = [[NSMutableArray alloc] init];
  return self;
}

- (void) dealloc
{
  DESTROY(global_comment);
  DESTROY(strings);
  [super dealloc];
}

- initWithFile: (NSString *)filename
{
  NSString *str;

  self = [self init];

  str = [NSString stringWithContentsOfFile: filename];
  if (!str) return self;

  {
    StringsEntry *se = nil;
    NSMutableArray *update_list = [[NSMutableArray alloc] init];
    NSArray *lines;
    NSString *l;
    NSUInteger i,c,pos; 	
    NSMutableDictionary *dummy_entries = [[NSMutableDictionary alloc] init];

    NSMutableString *user_comment = [[NSMutableString alloc] init];

    NSString *key,*trans;

    /* this is a bit yucky, but it works */
    lines = [str componentsSeparatedByString: @"/*"];
    c = [lines count];
    for (i = 0; i < c; i++)
      {
	l = [lines objectAtIndex: i];
	/* First entry has everything before the first comment and needs
	   to be handled specially. */
	if (i)
	  {
	    /* Parse special comments. */
	    if ([l hasPrefix: @"**"])
	      { /* It's one of our banners, just ignore it. If it's the first
		   one we put all comments so far in the global user comment. */
		if (user_comment)
		  {
		    if (![user_comment isEqual: @""])
		      global_comment = [user_comment copy];
		    DESTROY(user_comment);
		  }
	      }
	    else if ([l hasPrefix: @" File: "])
	      {
		se = [[StringsEntry alloc] init];
		[se addFlag: FLAG_UNMATCHED];  /* TODO: ? */
		[update_list addObject: se];
		[se release];

		l = [l substringFromIndex: 7];
		pos = [l rangeOfString: @":"].location;
		[se setFile: [l substringToIndex: pos]];
		l = [l substringFromIndex: pos+1];
		[se setLine: [l intValue]];
	      }
	    else if ([l hasPrefix: @" Flag: untranslated */"])
	      [se addFlag: FLAG_UNTRANSLATED];
	    else if ([l hasPrefix: @" Flag: unmatched */"])
	      [se addFlag: FLAG_UNMATCHED];  /* this is essentially a noop */
	    else if ([l hasPrefix: @" Comment: "])
	      {
		l = [l substringFromIndex: 10];
		pos = [l rangeOfString: @" */"].location;
                if (pos == NSNotFound) continue;
		[se setComment: [l substringToIndex: pos]];
	      }
	    else
	      {
		pos = [l rangeOfString: @"*/"].location;
                if (pos == NSNotFound)
                  {
                    fprintf(stderr,"parse error in '%s', missing '*/'\n",
                      [filename cString]);
                    pos = [l length];
                  }
		if ([user_comment length])
		  [user_comment appendString: @"\n"];
		[user_comment appendString: [l substringToIndex: pos]];
	      }

	    pos = [l rangeOfString: @"*/"].location;
	    if (pos == NSNotFound) continue;
	    l = [l substringFromIndex: pos+2];
	  }

	while (1)
	  {
	    pos = [l rangeOfString: @"\""].location;
	    if (pos == NSNotFound) break;

	    l = [l substringFromIndex: pos+1];
	    key = parse_string(&l);

	    pos = [l rangeOfString: @"="].location;
	    if (pos == NSNotFound)
	      {
		fprintf(stderr,"parse error in '%s', expecting '='\n",
                  [filename cString]);
		exit(1);
	      }
	    l = [l substringFromIndex: pos+1];
	    pos = [l rangeOfString: @"\""].location;
	    if (pos == NSNotFound)
	      {
		fprintf(stderr,"parse error in '%s', expecting second string\n",
                  [filename cString]);
		exit(1);
	      }
	    l = [l substringFromIndex: pos+1];
	    trans = parse_string(&l);

	    pos = [l rangeOfString: @";"].location;
	    if (pos == NSNotFound)
	      {
		fprintf(stderr,"parse error in '%s', expecting ';'\n",
                  [filename cString]);
		exit(1);
	      }
	    l = [l substringFromIndex: pos+1];

	    if (![update_list count])
	      { /* we're probably parsing a file not created by us */
		if (![dummy_entries objectForKey: key])
		  {
		    se = [[StringsEntry alloc] init];
		    [se setFile: DUMMY];
		    [se setFlags: FLAG_UNMATCHED];
		    [update_list addObject: se];
		    [se release];
		    [dummy_entries setObject: se forKey: key];
		  }
	      }

	    [update_list makeObjectsPerformSelector: @selector(setKey:)
                                         withObject: key];
	    [update_list makeObjectsPerformSelector: @selector(setTranslated:)
                                         withObject: trans];

	    {
	      int i,c = [update_list count];
              for (i = 0; i < c; i++)
                {
//		    printf("%4i : %@\n",i,[update_list objectAtIndex: i]);
                  se = [update_list objectAtIndex: i];
                  if (!([se flags] & FLAG_UNTRANSLATED))
                    {
                      [self addTranslated: key];
                      break;
                    }
                }
	    }


	    [strings addObjectsFromArray: update_list];

	    [update_list removeAllObjects];
	    se = nil;
	  }
      }

    DESTROY(user_comment);
    DESTROY(dummy_entries);
    DESTROY(update_list);
  }

  return self;
}


- (void) _writeTo: (NSMutableString *)str  entryHead: (StringsEntry *)se
{
  if ([se file])
    {
      [str appendString: @"/* File: "];
      [str appendString: [se file]];
      [str appendString: [NSString stringWithFormat: @":%i */\n",[se line]]];
    }
  if ([se comment])
    {
      [str appendString: @"/* Comment: "];
      [str appendString: [se comment]];
      [str appendString: @" */\n"];
    }
}

- (void) _writeTo: (NSMutableString *)str  entryFlags: (StringsEntry *)se
{
  int flags = [se flags];
  if (!flags) return;
  if (flags & FLAG_UNMATCHED)
    [str appendString: @"/* Flag: unmatched */\n"];
  else
    if (flags & FLAG_UNTRANSLATED)
      [str appendString: @"/* Flag: untranslated */\n"];
    else
      {
	fprintf(stderr,"unknown flag %08x\n",flags);
      }
}

- (void) _writeTo: (NSMutableString *)str  entryKey: (StringsEntry *)se
{
  [str appendString: @"\""];
  [str appendString: [se key]];

  /* Try to write a nice readable output ... key and value with whitrespace
   * around the '=' charactger, or wrap to a new line with a two space indent.
   */
  if ([[se key] length] + [[se translated] length] < 70)
    [str appendString: @"\" = \""];
  else
    [str appendString: @"\"\n  = \""];

  [str appendString: [se translated]];
  [str appendString: @"\";\n"];
}


- (void) _writeTo: (NSMutableString *)str  manyEntries: (NSMutableArray *)list
{
  int i,c;
  StringsEntry *tr,*cur;

  [list sortUsingSelector: @selector(compareFileLine:)];
  c = [list count];
  if (!c) return;
  cur = tr = nil;
  for (i = 0; i < c; i++)
    {
      cur = [list objectAtIndex: i];
      [self _writeTo: str  entryHead: cur];
      if ([cur flags])
	[self _writeTo: str  entryFlags: cur];

      if (!([cur flags] & FLAG_UNTRANSLATED))
	tr = cur;
    }
  if (tr)
    [self _writeTo: str  entryKey: tr];
  else
    [self _writeTo: str  entryKey: cur];
}

- (BOOL) _shouldIgnore: (StringsEntry *)se
{
  if (([se flags] & (FLAG_UNMATCHED|FLAG_UNTRANSLATED))
    == (FLAG_UNMATCHED|FLAG_UNTRANSLATED))
    return YES;

  if (aggressive_import && [[se file] isEqual: DUMMY]
    && [self isMatched: [se key]])
    return YES;

  if (aggressive_remove && ([se flags] & FLAG_UNMATCHED)
    && [self isMatched: [se key]])
    return YES;

  return NO;
}

- (BOOL) _writeString: (NSString *)str toFile: (NSString *)filename
{
  BOOL isAscii = YES;
  NSUInteger len = [str length];
  NSUInteger i;

  for (i = 0; i < len; i++)
    {
      unichar u = [str characterAtIndex: i];
      if (u > 127)
        {
          isAscii = NO;
          break;
        }
    }

  if (isAscii)
    {
      return [str writeToFile: filename atomically: YES];
    }
  else
    {
      NSData *d = [str dataUsingEncoding: NSUTF8StringEncoding];
      NSMutableData *md = [[NSMutableData alloc] initWithCapacity: [d length] + 3];
      // Add BOM at the beginning of the file
      char bytes[] = {0xEF, 0xBB, 0xBF};
      BOOL result;

      [md appendBytes: bytes length: 3];
      [md appendData: d];
      result = [md writeToFile: filename atomically: YES];
      [md release];
      return result;
    }
}

- (BOOL) writeToFile: (NSString *)filename
{
  unsigned int i,c;
  BOOL result;
  NSMutableString *str = [[NSMutableString alloc] initWithCapacity: 32*1024];
  StringsEntry *se;

  NSMutableArray *strings_left = [strings mutableCopy];
  NSMutableArray *str_list = [[NSMutableArray alloc] init];
  NSMutableArray *dup_list = [[NSMutableArray alloc] init];
  NSMutableArray *un_list = [[NSMutableArray alloc] init];

  StringsEntry *cur,*c2;

  int single_file,wrote_banner,unflags;
  int un_count = 0;

  if (global_comment && ![global_comment isEqual: @""])
    {
      [str appendString: @"/*"];
      [str appendString: global_comment];
      [str appendString: @"*/\n\n"];
    }

  [str appendString:
	 [NSString stringWithFormat:
		     @"/***\n"
		   @"%@\n"
		   @"updated by make_strings %@\n"
		   @"add comments above this one\n"
		   @"***/\n",
		   filename,[NSDate dateWithTimeIntervalSinceNow: 0]]];

  wrote_banner = 0;

  /* First, output all keys that appear in multiple places (unless all
     appearances are in one file and none are marked unmatched or untranslated).
     Collect unmatched or untranslated single entries in un_list and matched
     translated (single/multiple in one file) entries in str_list. */
  while ([strings_left count])
    {
      cur = [strings_left objectAtIndex: 0];
      if ([self _shouldIgnore: cur])
	{
	  [strings_left removeObjectAtIndex: 0];
	  continue;
	}
      [dup_list addObject: cur];
      [strings_left removeObjectAtIndex: 0];

      single_file = 1;
      unflags = [cur flags];
      for (i = 0; i < [strings_left count]; i++)
	{
	  c2 = [strings_left objectAtIndex: i];

	  if ([self _shouldIgnore: c2])
	    {
	      [strings_left removeObjectAtIndex: i];
	      i--;
	      continue;
	    }

	  if ([[cur key] isEqual: [c2 key]])
	    {
	      unflags |= [c2 flags];
	      [dup_list addObject: c2];
	      [strings_left removeObjectAtIndex: i];
	      if (single_file)
		if (![[cur file] isEqual: [c2 file]])
		  single_file = 0;
	      i--;
	    }
	}
      if (single_file && !unflags)
	{
	  [str_list addObjectsFromArray: dup_list];
	  [dup_list removeAllObjects];
	  continue;
	}
      if ([dup_list count] == 1)
	{
	  [un_list addObjectsFromArray: dup_list];
	  [dup_list removeAllObjects];
	  continue;
	}

      if (unflags)
	un_count += [dup_list count];

      if (!wrote_banner)
	{
	  [str appendString: @"\n\n/*** Keys found in multiple places ***/\n"];
	  wrote_banner = 1;
	}

      [str appendString: @"\n"];
      [self _writeTo: str  manyEntries: dup_list];
      [dup_list removeAllObjects];
    }

  DESTROY(strings_left);

  /* Now output all single unmatched or untranslated entries. Order by line
     and file so key changes and movements are easy to spot and fix. */
  if ([un_list count])
    {
      [str appendString: @"\n\n/*** Unmatched/untranslated keys ***/\n"];
      [un_list sortUsingSelector: @selector(compareFileLine:)];
      c = [un_list count];
      un_count += c;
      for (i = 0; i < c; i++)
	{
	  se = [un_list objectAtIndex: i];
	  [str appendString: @"\n"];
	  [self _writeTo: str  entryHead: se];
	  [self _writeTo: str  entryFlags: se];
	  [self _writeTo: str  entryKey: se];
	}
    }

  /* Finally, output all matched and translated entries ordered by file. The
     translator should never have to touch these strings (unless there are typos
     or something). */
  if ([str_list count])
    {
      NSString *last_filename = nil;

      [str_list sortUsingSelector: @selector(compareFileKeyComment:)];
      c = [str_list count];
      for (i = 0; i < c; i++)
	{
	  se = [str_list objectAtIndex: i];
	  if (!last_filename || ![last_filename isEqual: [se file]])
	    {
	      last_filename = [se file];
	      [str appendString:
                [NSString stringWithFormat: @"\n\n/*** Strings from %@ ***/\n",
                  last_filename]];
	    }
	  [self _writeTo: str  entryHead: se];
	  if (i == c - 1
            || ![[se key] isEqual: [[str_list objectAtIndex: i + 1] key]])
	    [self _writeTo: str  entryKey: se];
	}
    }
  DESTROY(str_list);
  DESTROY(dup_list);

  {
    NSString *backupname = [filename stringByAppendingString: @"~"];
    [[NSFileManager defaultManager] removeFileAtPath: backupname handler: nil];
    [[NSFileManager defaultManager] movePath: filename
                                      toPath: backupname
                                     handler: nil];
    result = [self _writeString: str toFile: filename];

    if (!result)
      fprintf(stderr,"Error saving '%s'!\n",[filename cString]);
  }

  DESTROY(str);
  DESTROY(un_list);

  if (un_count)
    fprintf(stderr,"'%s': %i untranslated or unmatched messages\n",
      [filename cString],un_count);

  return result;
}


- (void) addSourceEntry: (SourceEntry *)e
{
  /* First try to find a match among our unmatched strings. We consider
     two entries to match if they have the same key, file and comment. This
     could be extended, but the risk of errors increases. */
  int i,c;
  StringsEntry *se;

  c = [strings count];

  [self addMatched: [e key]];

  /* Look for exact matches. If we find an exact match (same file, key, and
     comment) we mark the StringsEntry matched and don't add the SourceEntry.
  */
  for (i = 0; i < c; i++)
    {
      se = [strings objectAtIndex: i];
      if (!([se flags] & FLAG_UNMATCHED))
	continue;

      if (![[se key] isEqual: [e key]])
	continue;

      if (([se flags] & FLAG_UNMATCHED) && [[se file] isEqual: [e file]])
	{
	  if ((![se comment] && ![e comment])
            || ([[se comment] isEqual: [e comment]]))
	    {
	      [se setFlags: [se flags] & ~FLAG_UNMATCHED];
	      [se setLine: [e line]];
	      return;
	    }
	}
    }

  if (aggressive_match)
    {
      /* If aggressive match is enabled, we try to find an existing and
	 translated StringsEntry. If we find we add a new StringsEntry from
	 the SourceEntry with the same translation and marked as translated.
      */
      for (i = 0; i < c; i++)
	{
	  se = [strings objectAtIndex: i];

	  if ([se flags] & FLAG_UNTRANSLATED)
	    continue;

	  if (![[se key] isEqual: [e key]])
	    continue;

	  {
	    StringsEntry *se2 = [StringsEntry stringsEntryFromSourceEntry: e];
	    [se2 setFlags: 0];
	    [se2 setTranslated: [se translated]];
	    [strings addObject: se2];
	    return;
	  }
	}
    }

  /* No match, add a new, untranslated StringsEntry. */
  [strings addObject: [StringsEntry stringsEntryFromSourceEntry: e]];
}

@end