source: trunk/macosx/NSStringAdditions.m @ 12910

Last change on this file since 12910 was 12910, checked in by livings124, 10 years ago

trivial tweak to betterComponentsSeparatedByCharactersInSet:

  • Property svn:keywords set to Date Rev Author Id
File size: 10.4 KB
Line 
1/******************************************************************************
2 * $Id: NSStringAdditions.m 12910 2011-09-24 19:38:04Z livings124 $
3 *
4 * Copyright (c) 2005-2011 Transmission authors and contributors
5 *
6 * Permission is hereby granted, free of charge, to any person obtaining a
7 * copy of this software and associated documentation files (the "Software"),
8 * to deal in the Software without restriction, including without limitation
9 * the rights to use, copy, modify, merge, publish, distribute, sublicense,
10 * and/or sell copies of the Software, and to permit persons to whom the
11 * Software is furnished to do so, subject to the following conditions:
12 *
13 * The above copyright notice and this permission notice shall be included in
14 * all copies or substantial portions of the Software.
15 *
16 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
17 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
18 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
19 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
20 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
21 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
22 * DEALINGS IN THE SOFTWARE.
23 *****************************************************************************/
24
25#import "NSStringAdditions.h"
26#import "NSApplicationAdditions.h"
27
28#import <transmission.h>
29#import "utils.h"
30
31@interface NSString (Private)
32
33+ (NSString *) stringForFileSize: (uint64_t) size showUnitUnless: (NSString *) notAllowedUnit
34    unitsUsed: (NSString **) unitUsed;
35
36+ (NSString *) stringForSpeed: (CGFloat) speed kb: (NSString *) kb mb: (NSString *) mb gb: (NSString *) gb;
37
38@end
39
40@implementation NSString (NSStringAdditions)
41
42+ (NSString *) ellipsis
43{
44        return [NSString stringWithUTF8String: "\xE2\x80\xA6"];
45}
46
47- (NSString *) stringByAppendingEllipsis
48{
49        return [self stringByAppendingString: [NSString ellipsis]];
50}
51
52+ (NSString *) formattedUInteger: (NSUInteger) value
53{
54    NSNumberFormatter * numberFormatter = [[[NSNumberFormatter alloc] init] autorelease];
55    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
56    [numberFormatter setMaximumFractionDigits: 0];
57   
58    return [numberFormatter stringFromNumber: [NSNumber numberWithUnsignedInteger: value]];
59}
60
61+ (NSString *) stringForFileSize: (uint64_t) size
62{
63    return [self stringForFileSize: size showUnitUnless: nil unitsUsed: nil];
64}
65
66+ (NSString *) stringForFilePartialSize: (uint64_t) partialSize fullSize: (uint64_t) fullSize
67{
68    NSString * units;
69    NSString * fullString = [self stringForFileSize: fullSize showUnitUnless: nil unitsUsed: &units];
70    NSString * partialString = [self stringForFileSize: partialSize showUnitUnless: units unitsUsed: nil];
71   
72    return [NSString stringWithFormat: NSLocalizedString(@"%@ of %@", "file size string"), partialString, fullString];
73}
74
75+ (NSString *) stringForSpeed: (CGFloat) speed
76{
77    return [self stringForSpeed: speed
78                kb: NSLocalizedString(@"KB/s", "Transfer speed (kilobytes per second)")
79                mb: NSLocalizedString(@"MB/s", "Transfer speed (megabytes per second)")
80                gb: NSLocalizedString(@"GB/s", "Transfer speed (gigabytes per second)")];
81}
82
83+ (NSString *) stringForSpeedAbbrev: (CGFloat) speed
84{
85    return [self stringForSpeed: speed kb: @"K" mb: @"M" gb: @"G"];
86}
87
88+ (NSString *) stringForRatio: (CGFloat) ratio
89{
90    //N/A is different than libtransmission's
91    if ((int)ratio == TR_RATIO_NA)
92        return NSLocalizedString(@"N/A", "No Ratio");
93    else if ((int)ratio == TR_RATIO_INF)
94        return [NSString stringWithUTF8String: "\xE2\x88\x9E"];
95    else
96    {
97        if (ratio < 10.0)
98            return [NSString localizedStringWithFormat: @"%.2f", tr_truncd(ratio, 2)];
99        else if (ratio < 100.0)
100            return [NSString localizedStringWithFormat: @"%.1f", tr_truncd(ratio, 1)];
101        else
102            return [NSString localizedStringWithFormat: @"%.0f", tr_truncd(ratio, 0)];
103    }
104}
105
106+ (NSString *) percentString: (CGFloat) progress longDecimals: (BOOL) longDecimals
107{
108    if (progress >= 1.0)
109        return @"100%";
110    else if (longDecimals)
111        return [NSString localizedStringWithFormat: @"%.2f%%", tr_truncd(progress * 100.0, 2)];
112    else
113        return [NSString localizedStringWithFormat: @"%.1f%%", tr_truncd(progress * 100.0, 1)];
114}
115
116+ (NSString *) timeString: (uint64_t) seconds showSeconds: (BOOL) showSeconds
117{
118    return [NSString timeString: seconds showSeconds: showSeconds maxFields: NSUIntegerMax];
119}
120
121+ (NSString *) timeString: (uint64_t) seconds showSeconds: (BOOL) showSeconds maxFields: (NSUInteger) max
122{
123    NSAssert(max > 0, @"Cannot generate a time string with no fields");
124   
125    NSMutableArray * timeArray = [NSMutableArray arrayWithCapacity: MIN(max, 5)];
126    NSUInteger remaining = seconds; //causes problems for some users when it's a uint64_t
127   
128    if (seconds >= 31557600) //official amount of seconds in one year
129    {
130        const NSUInteger years = remaining / 31557600;
131        if (years == 1)
132            [timeArray addObject: NSLocalizedString(@"1 year", "time string")];
133        else
134            [timeArray addObject: [NSString stringWithFormat: NSLocalizedString(@"%u years", "time string"), years]];
135        remaining %= 31557600;
136        --max;
137    }
138    if (max > 0 && seconds >= (24 * 60 * 60))
139    {
140        const NSUInteger days = remaining / (24 * 60 * 60);
141        if (days == 1)
142            [timeArray addObject: NSLocalizedString(@"1 day", "time string")];
143        else
144            [timeArray addObject: [NSString stringWithFormat: NSLocalizedString(@"%u days", "time string"), days]];
145        remaining %= (24 * 60 * 60);
146        --max;
147    }
148    if (max > 0 && seconds >= (60 * 60))
149    {
150        [timeArray addObject: [NSString stringWithFormat: NSLocalizedString(@"%u hr", "time string"), remaining / (60 * 60)]];
151        remaining %= (60 * 60);
152        --max;
153    }
154    if (max > 0 && (!showSeconds || seconds >= 60))
155    {
156        [timeArray addObject: [NSString stringWithFormat: NSLocalizedString(@"%u min", "time string"), remaining / 60]];
157        remaining %= 60;
158        --max;
159    }
160    if (max > 0 && showSeconds)
161        [timeArray addObject: [NSString stringWithFormat: NSLocalizedString(@"%u sec", "time string"), remaining]];
162   
163    return [timeArray componentsJoinedByString: @" "];
164}
165
166//also used in InfoWindow.xib and MessageWindow.xib
167- (NSComparisonResult) compareFinder: (NSString *) string
168{
169    if ([NSApp isOnSnowLeopardOrBetter])
170        return [self localizedStandardCompare: string];
171    else
172    {
173        const NSStringCompareOptions comparisonOptions = NSCaseInsensitiveSearch | NSNumericSearch | NSWidthInsensitiveSearch
174                                                            | NSForcedOrderingSearch;
175        return [self compare: string options: comparisonOptions range: NSMakeRange(0, [self length]) locale: [NSLocale currentLocale]];
176    }
177}
178
179- (NSComparisonResult) compareNumeric: (NSString *) string
180{
181    const NSStringCompareOptions comparisonOptions = NSNumericSearch | NSForcedOrderingSearch;
182    return [self compare: string options: comparisonOptions range: NSMakeRange(0, [self length]) locale: [NSLocale currentLocale]];
183}
184
185- (NSArray *) betterComponentsSeparatedByCharactersInSet: (NSCharacterSet *) separator
186{
187    NSMutableArray * components = [NSMutableArray array];
188   
189    NSUInteger i = 0;
190    while (i < [self length])
191    {
192        const NSRange range = [self rangeOfCharacterFromSet: separator options: 0 range: NSMakeRange(i, [self length]-i)];
193       
194        if (range.location == NSNotFound)
195        {
196            [components addObject: [self substringFromIndex: i]];
197            break;
198        }
199        else if (range.location != i)
200        {
201            const NSUInteger length = range.location - i;
202            [components addObject: [self substringWithRange: NSMakeRange(i, length)]];
203           
204            i += length;
205        }
206       
207        i += range.length;
208    }
209   
210    return components;
211}
212
213@end
214
215@implementation NSString (Private)
216
217+ (NSString *) stringForFileSize: (uint64_t) size showUnitUnless: (NSString *) notAllowedUnit
218    unitsUsed: (NSString **) unitUsed
219{
220    const float baseFloat = [NSApp isOnSnowLeopardOrBetter] ? 1000.0 : 1024.0;
221    const NSUInteger baseInt = [NSApp isOnSnowLeopardOrBetter] ? 1000 : 1024;
222   
223    double convertedSize;
224    NSString * unit;
225    NSUInteger decimals;
226    if (size < pow(baseInt, 2))
227    {
228        convertedSize = size / baseFloat;
229        unit = NSLocalizedString(@"KB", "File size - kilobytes");
230        decimals = convertedSize >= 10.0 ? 0 : 1;
231    }
232    else if (size < pow(baseInt, 3))
233    {
234        convertedSize = size / powf(baseFloat, 2);
235        unit = NSLocalizedString(@"MB", "File size - megabytes");
236        decimals = 1;
237    }
238    else if (size < pow(baseInt, 4))
239    {
240        convertedSize = size / powf(baseFloat, 3);
241        unit = NSLocalizedString(@"GB", "File size - gigabytes");
242        decimals = 2;
243    }
244    else
245    {
246        convertedSize = size / powf(baseFloat, 4);
247        unit = NSLocalizedString(@"TB", "File size - terabytes");
248        decimals = 3; //guessing on this one
249    }
250   
251    //match Finder's behavior
252    NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
253    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
254    [numberFormatter setMinimumFractionDigits: 0];
255    [numberFormatter setMaximumFractionDigits: decimals];
256   
257    NSString * fileSizeString = [numberFormatter stringFromNumber: [NSNumber numberWithFloat: convertedSize]];
258    [numberFormatter release];
259   
260    if (!notAllowedUnit || ![unit isEqualToString: notAllowedUnit])
261        fileSizeString = [fileSizeString stringByAppendingFormat: @" %@", unit];
262   
263    if (unitUsed)
264        *unitUsed = unit;
265   
266    return fileSizeString;
267}
268
269+ (NSString *) stringForSpeed: (CGFloat) speed kb: (NSString *) kb mb: (NSString *) mb gb: (NSString *) gb
270{
271    const CGFloat baseFloat = [NSApp isOnSnowLeopardOrBetter] ? 1000.0 : 1024.0;
272   
273    if (speed <= 999.95) //0.0 KB/s to 999.9 KB/s
274        return [NSString localizedStringWithFormat: @"%.1f %@", speed, kb];
275   
276    speed /= baseFloat;
277   
278    if (speed <= 99.995) //1.00 MB/s to 99.99 MB/s
279        return [NSString localizedStringWithFormat: @"%.2f %@", speed, mb];
280    else if (speed <= 999.95) //100.0 MB/s to 999.9 MB/s
281        return [NSString localizedStringWithFormat: @"%.1f %@", speed, mb];
282    else //insane speeds
283        return [NSString localizedStringWithFormat: @"%.2f %@", (speed / baseFloat), gb];
284}
285
286@end
Note: See TracBrowser for help on using the repository browser.