source: trunk/macosx/NSStringAdditions.m @ 12901

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

even more work on betterComponentsSeparatedByCharactersInSet:

  • Property svn:keywords set to Date Rev Author Id
File size: 10.5 KB
Line 
1/******************************************************************************
2 * $Id: NSStringAdditions.m 12901 2011-09-19 02:00:52Z 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 != i)
195        {
196            if (range.location == NSNotFound)
197            {
198                [components addObject: [self substringFromIndex: i]];
199                break;
200            }
201            else
202            {
203                const NSUInteger length = range.location - i;
204                [components addObject: [self substringWithRange: NSMakeRange(i, length)]];
205               
206                i += length;
207            }
208        }
209        i += range.length;
210    }
211   
212    return components;
213}
214
215@end
216
217@implementation NSString (Private)
218
219+ (NSString *) stringForFileSize: (uint64_t) size showUnitUnless: (NSString *) notAllowedUnit
220    unitsUsed: (NSString **) unitUsed
221{
222    const float baseFloat = [NSApp isOnSnowLeopardOrBetter] ? 1000.0 : 1024.0;
223    const NSUInteger baseInt = [NSApp isOnSnowLeopardOrBetter] ? 1000 : 1024;
224   
225    double convertedSize;
226    NSString * unit;
227    NSUInteger decimals;
228    if (size < pow(baseInt, 2))
229    {
230        convertedSize = size / baseFloat;
231        unit = NSLocalizedString(@"KB", "File size - kilobytes");
232        decimals = convertedSize >= 10.0 ? 0 : 1;
233    }
234    else if (size < pow(baseInt, 3))
235    {
236        convertedSize = size / powf(baseFloat, 2);
237        unit = NSLocalizedString(@"MB", "File size - megabytes");
238        decimals = 1;
239    }
240    else if (size < pow(baseInt, 4))
241    {
242        convertedSize = size / powf(baseFloat, 3);
243        unit = NSLocalizedString(@"GB", "File size - gigabytes");
244        decimals = 2;
245    }
246    else
247    {
248        convertedSize = size / powf(baseFloat, 4);
249        unit = NSLocalizedString(@"TB", "File size - terabytes");
250        decimals = 3; //guessing on this one
251    }
252   
253    //match Finder's behavior
254    NSNumberFormatter * numberFormatter = [[NSNumberFormatter alloc] init];
255    [numberFormatter setNumberStyle: NSNumberFormatterDecimalStyle];
256    [numberFormatter setMinimumFractionDigits: 0];
257    [numberFormatter setMaximumFractionDigits: decimals];
258   
259    NSString * fileSizeString = [numberFormatter stringFromNumber: [NSNumber numberWithFloat: convertedSize]];
260    [numberFormatter release];
261   
262    if (!notAllowedUnit || ![unit isEqualToString: notAllowedUnit])
263        fileSizeString = [fileSizeString stringByAppendingFormat: @" %@", unit];
264   
265    if (unitUsed)
266        *unitUsed = unit;
267   
268    return fileSizeString;
269}
270
271+ (NSString *) stringForSpeed: (CGFloat) speed kb: (NSString *) kb mb: (NSString *) mb gb: (NSString *) gb
272{
273    const CGFloat baseFloat = [NSApp isOnSnowLeopardOrBetter] ? 1000.0 : 1024.0;
274   
275    if (speed <= 999.95) //0.0 KB/s to 999.9 KB/s
276        return [NSString localizedStringWithFormat: @"%.1f %@", speed, kb];
277   
278    speed /= baseFloat;
279   
280    if (speed <= 99.995) //1.00 MB/s to 99.99 MB/s
281        return [NSString localizedStringWithFormat: @"%.2f %@", speed, mb];
282    else if (speed <= 999.95) //100.0 MB/s to 999.9 MB/s
283        return [NSString localizedStringWithFormat: @"%.1f %@", speed, mb];
284    else //insane speeds
285        return [NSString localizedStringWithFormat: @"%.2f %@", (speed / baseFloat), gb];
286}
287
288@end
Note: See TracBrowser for help on using the repository browser.