source: trunk/macosx/NSStringAdditions.m @ 12898

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

roll my own method to separate a string into components

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