source: trunk/macosx/NSStringAdditions.m @ 12899

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

whoops, comment

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