]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Fixed slightly corrupted English localization -- but is this string ever used?
[cydia.git] / MobileCydia.mm
1 /* Cydia - iPhone UIKit Front-End for Debian APT
2 * Copyright (C) 2008-2010 Jay Freeman (saurik)
3 */
4
5 /* Modified BSD License {{{ */
6 /*
7 * Redistribution and use in source and binary
8 * forms, with or without modification, are permitted
9 * provided that the following conditions are met:
10 *
11 * 1. Redistributions of source code must retain the
12 * above copyright notice, this list of conditions
13 * and the following disclaimer.
14 * 2. Redistributions in binary form must reproduce the
15 * above copyright notice, this list of conditions
16 * and the following disclaimer in the documentation
17 * and/or other materials provided with the
18 * distribution.
19 * 3. The name of the author may not be used to endorse
20 * or promote products derived from this software
21 * without specific prior written permission.
22 *
23 * THIS SOFTWARE IS PROVIDED BY THE AUTHOR ``AS IS''
24 * AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING,
25 * BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF
26 * MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
27 * ARE DISCLAIMED. IN NO EVENT SHALL THE AUTHOR BE
28 * LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL,
29 * EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT
30 * NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR
31 * SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
32 * INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF
33 * LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR
34 * TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN
35 * ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF
36 * ADVISED OF THE POSSIBILITY OF SUCH DAMAGE.
37 */
38 /* }}} */
39
40 // XXX: wtf/FastMalloc.h... wtf?
41 #define USE_SYSTEM_MALLOC 1
42
43 /* #include Directives {{{ */
44 #include "UICaboodle/UCPlatform.h"
45 #include "UICaboodle/UCLocalize.h"
46
47 #include <objc/objc.h>
48 #include <objc/runtime.h>
49
50 #include <CoreGraphics/CoreGraphics.h>
51 #include <Foundation/Foundation.h>
52
53 #if 0
54 #define DEPLOYMENT_TARGET_MACOSX 1
55 #define CF_BUILDING_CF 1
56 #include <CoreFoundation/CFInternal.h>
57 #endif
58
59 #include <CoreFoundation/CFPriv.h>
60 #include <CoreFoundation/CFUniChar.h>
61
62 #include <SystemConfiguration/SystemConfiguration.h>
63
64 #include <UIKit/UIKit.h>
65 #include "iPhonePrivate.h"
66
67 #include <IOKit/IOKitLib.h>
68
69 #include <WebCore/WebCoreThread.h>
70
71 #include <algorithm>
72 #include <iomanip>
73 #include <sstream>
74 #include <string>
75
76 #include <ext/stdio_filebuf.h>
77
78 #undef ABS
79
80 #include <apt-pkg/acquire.h>
81 #include <apt-pkg/acquire-item.h>
82 #include <apt-pkg/algorithms.h>
83 #include <apt-pkg/cachefile.h>
84 #include <apt-pkg/clean.h>
85 #include <apt-pkg/configuration.h>
86 #include <apt-pkg/debindexfile.h>
87 #include <apt-pkg/debmetaindex.h>
88 #include <apt-pkg/error.h>
89 #include <apt-pkg/init.h>
90 #include <apt-pkg/mmap.h>
91 #include <apt-pkg/pkgrecords.h>
92 #include <apt-pkg/sha1.h>
93 #include <apt-pkg/sourcelist.h>
94 #include <apt-pkg/sptr.h>
95 #include <apt-pkg/strutl.h>
96 #include <apt-pkg/tagfile.h>
97
98 #include <apr-1/apr_pools.h>
99
100 #include <sys/types.h>
101 #include <sys/stat.h>
102 #include <sys/sysctl.h>
103 #include <sys/param.h>
104 #include <sys/mount.h>
105 #include <sys/reboot.h>
106
107 #include <fcntl.h>
108 #include <notify.h>
109 #include <dlfcn.h>
110
111 extern "C" {
112 #include <mach-o/nlist.h>
113 }
114
115 #include <cstdio>
116 #include <cstdlib>
117 #include <cstring>
118
119 #include <errno.h>
120 #include <pcre.h>
121
122 #include <Cytore.hpp>
123
124 #include "UICaboodle/BrowserView.h"
125 #include "SDURLCache/SDURLCache.h"
126
127 #include "substrate.h"
128 /* }}} */
129
130 /* Profiler {{{ */
131 struct timeval _ltv;
132 bool _itv;
133
134 #define _timestamp ({ \
135 struct timeval tv; \
136 gettimeofday(&tv, NULL); \
137 tv.tv_sec * 1000000 + tv.tv_usec; \
138 })
139
140 typedef std::vector<class ProfileTime *> TimeList;
141 TimeList times_;
142
143 class ProfileTime {
144 private:
145 const char *name_;
146 uint64_t total_;
147 uint64_t count_;
148
149 public:
150 ProfileTime(const char *name) :
151 name_(name),
152 total_(0)
153 {
154 times_.push_back(this);
155 }
156
157 void AddTime(uint64_t time) {
158 total_ += time;
159 ++count_;
160 }
161
162 void Print() {
163 if (total_ != 0)
164 std::cerr << std::setw(5) << count_ << ", " << std::setw(7) << total_ << " : " << name_ << std::endl;
165 total_ = 0;
166 count_ = 0;
167 }
168 };
169
170 class ProfileTimer {
171 private:
172 ProfileTime &time_;
173 uint64_t start_;
174
175 public:
176 ProfileTimer(ProfileTime &time) :
177 time_(time),
178 start_(_timestamp)
179 {
180 }
181
182 ~ProfileTimer() {
183 time_.AddTime(_timestamp - start_);
184 }
185 };
186
187 void PrintTimes() {
188 for (TimeList::const_iterator i(times_.begin()); i != times_.end(); ++i)
189 (*i)->Print();
190 std::cerr << "========" << std::endl;
191 }
192
193 #define _profile(name) { \
194 static ProfileTime name(#name); \
195 ProfileTimer _ ## name(name);
196
197 #define _end }
198 /* }}} */
199
200 #define _pooled _H<NSAutoreleasePool> _pool([[NSAutoreleasePool alloc] init], true);
201
202 #define CYPoolStart() \
203 NSAutoreleasePool *_pool([[NSAutoreleasePool alloc] init]); \
204 do
205 #define CYPoolEnd() \
206 while (false); \
207 [_pool release];
208
209 // Hash Functions/Structures {{{
210 extern "C" uint32_t hashlittle(const void *key, size_t length, uint32_t initval = 0);
211
212 union SplitHash {
213 uint32_t u32;
214 uint16_t u16[2];
215 };
216 // }}}
217
218 static const NSUInteger UIViewAutoresizingFlexibleBoth(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleHeight);
219
220 void NSLogPoint(const char *fix, const CGPoint &point) {
221 NSLog(@"%s(%g,%g)", fix, point.x, point.y);
222 }
223
224 void NSLogRect(const char *fix, const CGRect &rect) {
225 NSLog(@"%s(%g,%g)+(%g,%g)", fix, rect.origin.x, rect.origin.y, rect.size.width, rect.size.height);
226 }
227
228 static _finline NSString *CydiaURL(NSString *path) {
229 char page[25];
230 page[0] = 'h'; page[1] = 't'; page[2] = 't'; page[3] = 'p'; page[4] = ':';
231 page[5] = '/'; page[6] = '/'; page[7] = 'c'; page[8] = 'y'; page[9] = 'd';
232 page[10] = 'i'; page[11] = 'a'; page[12] = '.'; page[13] = 's'; page[14] = 'a';
233 page[15] = 'u'; page[16] = 'r'; page[17] = 'i'; page[18] = 'k'; page[19] = '.';
234 page[20] = 'c'; page[21] = 'o'; page[22] = 'm'; page[23] = '/'; page[24] = '\0';
235 return [[NSString stringWithUTF8String:page] stringByAppendingString:path];
236 }
237
238 static _finline void UpdateExternalStatus(uint64_t newStatus) {
239 int notify_token;
240 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
241 notify_set_state(notify_token, newStatus);
242 notify_cancel(notify_token);
243 }
244 notify_post("com.saurik.Cydia.status");
245 }
246
247 /* [NSObject yieldToSelector:(withObject:)] {{{*/
248 @interface NSObject (Cydia)
249 - (id) yieldToSelector:(SEL)selector withObject:(id)object;
250 - (id) yieldToSelector:(SEL)selector;
251 @end
252
253 @implementation NSObject (Cydia)
254
255 - (void) doNothing {
256 }
257
258 - (void) _yieldToContext:(NSMutableArray *)context { _pooled
259 SEL selector(reinterpret_cast<SEL>([[context objectAtIndex:0] pointerValue]));
260 id object([[context objectAtIndex:1] nonretainedObjectValue]);
261 volatile bool &stopped(*reinterpret_cast<bool *>([[context objectAtIndex:2] pointerValue]));
262
263 /* XXX: deal with exceptions */
264 id value([self performSelector:selector withObject:object]);
265
266 NSMethodSignature *signature([self methodSignatureForSelector:selector]);
267 [context removeAllObjects];
268 if ([signature methodReturnLength] != 0 && value != nil)
269 [context addObject:value];
270
271 stopped = true;
272
273 [self
274 performSelectorOnMainThread:@selector(doNothing)
275 withObject:nil
276 waitUntilDone:NO
277 ];
278 }
279
280 - (id) yieldToSelector:(SEL)selector withObject:(id)object {
281 volatile bool stopped(false);
282
283 NSMutableArray *context([NSMutableArray arrayWithObjects:
284 [NSValue valueWithPointer:selector],
285 [NSValue valueWithNonretainedObject:object],
286 [NSValue valueWithPointer:const_cast<bool *>(&stopped)],
287 nil]);
288
289 NSThread *thread([[[NSThread alloc]
290 initWithTarget:self
291 selector:@selector(_yieldToContext:)
292 object:context
293 ] autorelease]);
294
295 [thread start];
296
297 NSRunLoop *loop([NSRunLoop currentRunLoop]);
298 NSDate *future([NSDate distantFuture]);
299
300 while (!stopped && [loop runMode:NSDefaultRunLoopMode beforeDate:future]);
301
302 return [context count] == 0 ? nil : [context objectAtIndex:0];
303 }
304
305 - (id) yieldToSelector:(SEL)selector {
306 return [self yieldToSelector:selector withObject:nil];
307 }
308
309 @end
310 /* }}} */
311
312 /* Cydia Action Sheet {{{ */
313 @interface CYActionSheet : UIAlertView {
314 unsigned button_;
315 }
316
317 - (int) yieldToPopupAlertAnimated:(BOOL)animated;
318 @end
319
320 @implementation CYActionSheet
321
322 - (id) initWithTitle:(NSString *)title buttons:(NSArray *)buttons defaultButtonIndex:(int)index {
323 if ((self = [super init])) {
324 [self setTitle:title];
325 [self setDelegate:self];
326 for (NSString *button in buttons) [self addButtonWithTitle:button];
327 [self setCancelButtonIndex:index];
328 } return self;
329 }
330
331 - (void) _updateFrameForDisplay {
332 [super _updateFrameForDisplay];
333 if ([self cancelButtonIndex] == -1) {
334 NSArray *buttons = [self buttons];
335 if ([buttons count]) {
336 UIImage *background = [[buttons objectAtIndex:0] backgroundForState:0];
337 for (UIThreePartButton *button in buttons)
338 [button setBackground:background forState:0];
339 }
340 }
341 }
342
343 - (void) alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex {
344 button_ = buttonIndex + 1;
345 }
346
347 - (void) dismiss {
348 [self dismissWithClickedButtonIndex:-1 animated:YES];
349 }
350
351 - (int) yieldToPopupAlertAnimated:(BOOL)animated {
352 [self setRunsModal:YES];
353 button_ = 0;
354 [self show];
355 return button_;
356 }
357
358 @end
359 /* }}} */
360
361 /* NSForcedOrderingSearch doesn't work on the iPhone */
362 static const NSStringCompareOptions MatchCompareOptions_ = NSLiteralSearch | NSCaseInsensitiveSearch;
363 static const NSStringCompareOptions LaxCompareOptions_ = NSNumericSearch | NSDiacriticInsensitiveSearch | NSWidthInsensitiveSearch | NSCaseInsensitiveSearch;
364 static const CFStringCompareFlags LaxCompareFlags_ = kCFCompareCaseInsensitive | kCFCompareNonliteral | kCFCompareLocalized | kCFCompareNumerically | kCFCompareWidthInsensitive | kCFCompareForcedOrdering;
365
366 /* Information Dictionaries {{{ */
367 @interface NSMutableArray (Cydia)
368 - (void) addInfoDictionary:(NSDictionary *)info;
369 @end
370
371 @implementation NSMutableArray (Cydia)
372
373 - (void) addInfoDictionary:(NSDictionary *)info {
374 [self addObject:info];
375 }
376
377 @end
378
379 @interface NSMutableDictionary (Cydia)
380 - (void) addInfoDictionary:(NSDictionary *)info;
381 @end
382
383 @implementation NSMutableDictionary (Cydia)
384
385 - (void) addInfoDictionary:(NSDictionary *)info {
386 [self setObject:info forKey:[info objectForKey:@"CFBundleIdentifier"]];
387 }
388
389 @end
390 /* }}} */
391
392 #define lprintf(args...) fprintf(stderr, args)
393
394 #define ForRelease 1
395 #define TraceLogging (1 && !ForRelease)
396 #define HistogramInsertionSort (!ForRelease ? 0 : 0)
397 #define ProfileTimes (0 && !ForRelease)
398 #define ForSaurik (0 && !ForRelease)
399 #define LogBrowser (0 && !ForRelease)
400 #define TrackResize (0 && !ForRelease)
401 #define ManualRefresh (1 && !ForRelease)
402 #define ShowInternals (0 && !ForRelease)
403 #define IgnoreInstall (0 && !ForRelease)
404 #define AlwaysReload (0 && !ForRelease)
405 #define TryIndexedCollation (0 && !ForRelease)
406
407 #if !TraceLogging
408 #undef _trace
409 #define _trace(args...)
410 #endif
411
412 #if !ProfileTimes
413 #undef _profile
414 #define _profile(name) {
415 #undef _end
416 #define _end }
417 #define PrintTimes() do {} while (false)
418 #endif
419
420 /* Radix Sort {{{ */
421 typedef uint32_t (*SKRadixFunction)(id, void *);
422
423 @interface NSMutableArray (Radix)
424 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
425 @end
426
427 struct RadixItem_ {
428 size_t index;
429 uint32_t key;
430 };
431
432 @implementation NSMutableArray (Radix)
433
434 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
435 size_t count([self count]);
436 struct RadixItem_ *swap(new RadixItem_[count * 2]);
437
438 for (size_t i(0); i != count; ++i) {
439 RadixItem_ &item(swap[i]);
440 item.index = i;
441
442 id object([self objectAtIndex:i]);
443 item.key = function(object, argument);
444 }
445
446 struct RadixItem_ *lhs(swap), *rhs(swap + count);
447
448 static const size_t width = 32;
449 static const size_t bits = 11;
450 static const size_t slots = 1 << bits;
451 static const size_t passes = (width + (bits - 1)) / bits;
452
453 size_t *hist(new size_t[slots]);
454
455 for (size_t pass(0); pass != passes; ++pass) {
456 memset(hist, 0, sizeof(size_t) * slots);
457
458 for (size_t i(0); i != count; ++i) {
459 uint32_t key(lhs[i].key);
460 key >>= pass * bits;
461 key &= _not(uint32_t) >> width - bits;
462 ++hist[key];
463 }
464
465 size_t offset(0);
466 for (size_t i(0); i != slots; ++i) {
467 size_t local(offset);
468 offset += hist[i];
469 hist[i] = local;
470 }
471
472 for (size_t i(0); i != count; ++i) {
473 uint32_t key(lhs[i].key);
474 key >>= pass * bits;
475 key &= _not(uint32_t) >> width - bits;
476 rhs[hist[key]++] = lhs[i];
477 }
478
479 RadixItem_ *tmp(lhs);
480 lhs = rhs;
481 rhs = tmp;
482 }
483
484 delete [] hist;
485
486 const void **values(new const void *[count]);
487 for (size_t i(0); i != count; ++i)
488 values[i] = [self objectAtIndex:lhs[i].index];
489 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
490 delete [] values;
491
492 delete [] swap;
493 }
494
495 @end
496 /* }}} */
497 /* Insertion Sort {{{ */
498
499 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
500 const char *ptr = (const char *)list;
501 while (0 < count) {
502 CFIndex half = count / 2;
503 const char *probe = ptr + elementSize * half;
504 CFComparisonResult cr = comparator(element, probe, context);
505 if (0 == cr) return (probe - (const char *)list) / elementSize;
506 ptr = (cr < 0) ? ptr : probe + elementSize;
507 count = (cr < 0) ? half : (half + (count & 1) - 1);
508 }
509 return (ptr - (const char *)list) / elementSize;
510 }
511
512 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
513 const char *ptr = (const char *)list;
514 while (0 < count) {
515 CFIndex half = count / 2;
516 const char *probe = ptr + elementSize * half;
517 CFComparisonResult cr = comparator(element, probe, context);
518 if (0 == cr) return (probe - (const char *)list) / elementSize;
519 ptr = (cr < 0) ? ptr : probe + elementSize;
520 count = (cr < 0) ? half : (half + (count & 1) - 1);
521 }
522 return (ptr - (const char *)list) / elementSize;
523 }
524
525 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
526 if (range.length == 0)
527 return;
528 const void **values(new const void *[range.length]);
529 CFArrayGetValues(array, range, values);
530
531 #if HistogramInsertionSort > 0
532 uint32_t total(0), *offsets(new uint32_t[range.length]);
533 #endif
534
535 for (CFIndex index(1); index != range.length; ++index) {
536 const void *value(values[index]);
537 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
538 CFIndex correct(index);
539 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
540 #if HistogramInsertionSort > 1
541 NSLog(@"%@ < %@", value, values[correct - 1]);
542 #endif
543 if (--correct == 0)
544 break;
545 }
546 if (correct != index) {
547 size_t offset(index - correct);
548 #if HistogramInsertionSort
549 total += offset;
550 ++offsets[offset];
551 if (offset > 10)
552 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
553 #endif
554 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
555 values[correct] = value;
556 }
557 }
558
559 CFArrayReplaceValues(array, range, values, range.length);
560 delete [] values;
561
562 #if HistogramInsertionSort > 0
563 for (CFIndex index(0); index != range.length; ++index)
564 if (offsets[index] != 0)
565 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
566 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
567 delete [] offsets;
568 #endif
569 }
570
571 /* }}} */
572
573 /* Apple Bug Fixes {{{ */
574 @implementation UIWebDocumentView (Cydia)
575
576 - (void) _setScrollerOffset:(CGPoint)offset {
577 UIScroller *scroller([self _scroller]);
578
579 CGSize size([scroller contentSize]);
580 CGSize bounds([scroller bounds].size);
581
582 CGPoint max;
583 max.x = size.width - bounds.width;
584 max.y = size.height - bounds.height;
585
586 // wtf Apple?!
587 if (max.x < 0)
588 max.x = 0;
589 if (max.y < 0)
590 max.y = 0;
591
592 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
593 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
594
595 [scroller setOffset:offset];
596 }
597
598 @end
599 /* }}} */
600
601 @implementation WebScriptObject (NSFastEnumeration)
602
603 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
604 size_t length([self count] - state->state);
605 if (length <= 0)
606 return 0;
607 else if (length > count)
608 length = count;
609 for (size_t i(0); i != length; ++i)
610 objects[i] = [self objectAtIndex:state->state++];
611 state->itemsPtr = objects;
612 state->mutationsPtr = (unsigned long *) self;
613 return length;
614 }
615
616 @end
617
618 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
619 size_t length([self length] - state->state);
620 if (length <= 0)
621 return 0;
622 else if (length > count)
623 length = count;
624 for (size_t i(0); i != length; ++i)
625 objects[i] = [self item:state->state++];
626 state->itemsPtr = objects;
627 state->mutationsPtr = (unsigned long *) self;
628 return length;
629 }
630
631 /* Cydia NSString Additions {{{ */
632 @interface NSString (Cydia)
633 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
634 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
635 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
636 - (NSComparisonResult) compareByPath:(NSString *)other;
637 - (NSString *) stringByCachingURLWithCurrentCDN;
638 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
639 @end
640
641 @implementation NSString (Cydia)
642
643 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
644 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
645 }
646
647 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
648 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
649 memcpy(data, bytes, length);
650 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
651 }
652
653 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
654 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
655 }
656
657 - (NSComparisonResult) compareByPath:(NSString *)other {
658 NSString *prefix = [self commonPrefixWithString:other options:0];
659 size_t length = [prefix length];
660
661 NSRange lrange = NSMakeRange(length, [self length] - length);
662 NSRange rrange = NSMakeRange(length, [other length] - length);
663
664 lrange = [self rangeOfString:@"/" options:0 range:lrange];
665 rrange = [other rangeOfString:@"/" options:0 range:rrange];
666
667 NSComparisonResult value;
668
669 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
670 value = NSOrderedSame;
671 else if (lrange.location == NSNotFound)
672 value = NSOrderedAscending;
673 else if (rrange.location == NSNotFound)
674 value = NSOrderedDescending;
675 else
676 value = NSOrderedSame;
677
678 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
679 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
680 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
681 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
682
683 NSComparisonResult result = [lpath compare:rpath];
684 return result == NSOrderedSame ? value : result;
685 }
686
687 - (NSString *) stringByCachingURLWithCurrentCDN {
688 return [self
689 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
690 withString:@"://cache.cydia.saurik.com/"
691 ];
692 }
693
694 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
695 return [(id)CFURLCreateStringByAddingPercentEscapes(
696 kCFAllocatorDefault,
697 (CFStringRef) self,
698 NULL,
699 CFSTR(";/?:@&=+$,"),
700 kCFStringEncodingUTF8
701 ) autorelease];
702 }
703
704 @end
705 /* }}} */
706
707 /* C++ NSString Wrapper Cache {{{ */
708 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
709 return size == 0 ? NULL :
710 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
711 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
712 }
713
714 static _finline CFStringRef CYStringCreate(const char *data) {
715 return CYStringCreate(data, strlen(data));
716 }
717
718 class CYString {
719 private:
720 char *data_;
721 size_t size_;
722 CFStringRef cache_;
723
724 _finline void clear_() {
725 if (cache_ != NULL) {
726 CFRelease(cache_);
727 cache_ = NULL;
728 }
729 }
730
731 public:
732 _finline bool empty() const {
733 return size_ == 0;
734 }
735
736 _finline size_t size() const {
737 return size_;
738 }
739
740 _finline char *data() const {
741 return data_;
742 }
743
744 _finline void clear() {
745 size_ = 0;
746 clear_();
747 }
748
749 _finline CYString() :
750 data_(0),
751 size_(0),
752 cache_(NULL)
753 {
754 }
755
756 _finline ~CYString() {
757 clear_();
758 }
759
760 void operator =(const CYString &rhs) {
761 data_ = rhs.data_;
762 size_ = rhs.size_;
763
764 if (rhs.cache_ == nil)
765 cache_ = NULL;
766 else
767 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
768 }
769
770 void copy(apr_pool_t *pool) {
771 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
772 memcpy(temp, data_, size_);
773 temp[size_] = '\0';
774 data_ = temp;
775 }
776
777 void set(apr_pool_t *pool, const char *data, size_t size) {
778 if (size == 0)
779 clear();
780 else {
781 clear_();
782
783 data_ = const_cast<char *>(data);
784 size_ = size;
785
786 if (pool != NULL)
787 copy(pool);
788 }
789 }
790
791 _finline void set(apr_pool_t *pool, const char *data) {
792 set(pool, data, data == NULL ? 0 : strlen(data));
793 }
794
795 _finline void set(apr_pool_t *pool, const std::string &rhs) {
796 set(pool, rhs.data(), rhs.size());
797 }
798
799 bool operator ==(const CYString &rhs) const {
800 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
801 }
802
803 _finline operator CFStringRef() {
804 if (cache_ == NULL)
805 cache_ = CYStringCreate(data_, size_);
806 return cache_;
807 }
808
809 _finline operator id() {
810 return (NSString *) static_cast<CFStringRef>(*this);
811 }
812
813 _finline operator const char *() {
814 return reinterpret_cast<const char *>(data_);
815 }
816 };
817 /* }}} */
818 /* C++ NSString Algorithm Adapters {{{ */
819 extern "C" {
820 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
821 }
822
823 struct NSStringMapHash :
824 std::unary_function<NSString *, size_t>
825 {
826 _finline size_t operator ()(NSString *value) const {
827 return CFStringHashNSString((CFStringRef) value);
828 }
829 };
830
831 struct NSStringMapLess :
832 std::binary_function<NSString *, NSString *, bool>
833 {
834 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
835 return [lhs compare:rhs] == NSOrderedAscending;
836 }
837 };
838
839 struct NSStringMapEqual :
840 std::binary_function<NSString *, NSString *, bool>
841 {
842 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
843 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
844 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
845 //[lhs isEqualToString:rhs];
846 }
847 };
848 /* }}} */
849
850 /* Perl-Compatible RegEx {{{ */
851 class Pcre {
852 private:
853 pcre *code_;
854 pcre_extra *study_;
855 int capture_;
856 int *matches_;
857 const char *data_;
858
859 public:
860 Pcre(const char *regex) :
861 study_(NULL)
862 {
863 const char *error;
864 int offset;
865 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
866
867 if (code_ == NULL) {
868 lprintf("%d:%s\n", offset, error);
869 _assert(false);
870 }
871
872 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
873 matches_ = new int[(capture_ + 1) * 3];
874 }
875
876 ~Pcre() {
877 pcre_free(code_);
878 delete matches_;
879 }
880
881 NSString *operator [](size_t match) {
882 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
883 }
884
885 bool operator ()(NSString *data) {
886 // XXX: length is for characters, not for bytes
887 return operator ()([data UTF8String], [data length]);
888 }
889
890 bool operator ()(const char *data, size_t size) {
891 data_ = data;
892 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
893 }
894 };
895 /* }}} */
896 /* Mime Addresses {{{ */
897 @interface Address : NSObject {
898 NSString *name_;
899 NSString *address_;
900 }
901
902 - (NSString *) name;
903 - (NSString *) address;
904
905 - (void) setAddress:(NSString *)address;
906
907 + (Address *) addressWithString:(NSString *)string;
908 - (Address *) initWithString:(NSString *)string;
909 @end
910
911 @implementation Address
912
913 - (void) dealloc {
914 [name_ release];
915 if (address_ != nil)
916 [address_ release];
917 [super dealloc];
918 }
919
920 - (NSString *) name {
921 return name_;
922 }
923
924 - (NSString *) address {
925 return address_;
926 }
927
928 - (void) setAddress:(NSString *)address {
929 if (address_ != nil)
930 [address_ autorelease];
931 if (address == nil)
932 address_ = nil;
933 else
934 address_ = [address retain];
935 }
936
937 + (Address *) addressWithString:(NSString *)string {
938 return [[[Address alloc] initWithString:string] autorelease];
939 }
940
941 + (NSArray *) _attributeKeys {
942 return [NSArray arrayWithObjects:@"address", @"name", nil];
943 }
944
945 - (NSArray *) attributeKeys {
946 return [[self class] _attributeKeys];
947 }
948
949 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
950 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
951 }
952
953 - (Address *) initWithString:(NSString *)string {
954 if ((self = [super init]) != nil) {
955 const char *data = [string UTF8String];
956 size_t size = [string length];
957
958 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
959
960 if (address_r(data, size)) {
961 name_ = [address_r[1] retain];
962 address_ = [address_r[2] retain];
963 } else {
964 name_ = [string retain];
965 address_ = nil;
966 }
967 } return self;
968 }
969
970 @end
971 /* }}} */
972 /* CoreGraphics Primitives {{{ */
973 class CYColor {
974 private:
975 CGColorRef color_;
976
977 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
978 CGFloat color[] = {red, green, blue, alpha};
979 return CGColorCreate(space, color);
980 }
981
982 public:
983 CYColor() :
984 color_(NULL)
985 {
986 }
987
988 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
989 color_(Create_(space, red, green, blue, alpha))
990 {
991 Set(space, red, green, blue, alpha);
992 }
993
994 void Clear() {
995 if (color_ != NULL)
996 CGColorRelease(color_);
997 }
998
999 ~CYColor() {
1000 Clear();
1001 }
1002
1003 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1004 Clear();
1005 color_ = Create_(space, red, green, blue, alpha);
1006 }
1007
1008 operator CGColorRef() {
1009 return color_;
1010 }
1011 };
1012 /* }}} */
1013
1014 /* Random Global Variables {{{ */
1015 static const int PulseInterval_ = 50000;
1016
1017 static int Finish_;
1018 static NSArray *Finishes_;
1019
1020 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1021 #define NotifyConfig_ "/etc/notify.conf"
1022
1023 static bool Queuing_;
1024
1025 static CYColor Blue_;
1026 static CYColor Blueish_;
1027 static CYColor Black_;
1028 static CYColor Off_;
1029 static CYColor White_;
1030 static CYColor Gray_;
1031 static CYColor Green_;
1032 static CYColor Purple_;
1033 static CYColor Purplish_;
1034
1035 static UIColor *InstallingColor_;
1036 static UIColor *RemovingColor_;
1037
1038 static NSString *App_;
1039 static NSString *Home_;
1040
1041 static BOOL Advanced_;
1042 static BOOL Ignored_;
1043
1044 static UIFont *Font12_;
1045 static UIFont *Font12Bold_;
1046 static UIFont *Font14_;
1047 static UIFont *Font18Bold_;
1048 static UIFont *Font22Bold_;
1049
1050 static const char *Machine_ = NULL;
1051 static NSString *System_ = nil;
1052 static NSString *SerialNumber_ = nil;
1053 static NSString *ChipID_ = nil;
1054 static NSString *Token_ = nil;
1055 static NSString *UniqueID_ = nil;
1056 static NSString *PLMN_ = nil;
1057 static NSString *Build_ = nil;
1058 static NSString *Product_ = nil;
1059 static NSString *Safari_ = nil;
1060
1061 static CFLocaleRef Locale_;
1062 static NSArray *Languages_;
1063 static CGColorSpaceRef space_;
1064
1065 static NSDictionary *SectionMap_;
1066 static NSMutableDictionary *Metadata_;
1067 static _transient NSMutableDictionary *Settings_;
1068 static _transient NSString *Role_;
1069 static _transient NSMutableDictionary *Packages_;
1070 static _transient NSMutableDictionary *Sections_;
1071 static _transient NSMutableDictionary *Sources_;
1072 static bool Changed_;
1073 static time_t now_;
1074
1075 bool IsWildcat_;
1076 /* }}} */
1077
1078 /* Display Helpers {{{ */
1079 inline float Interpolate(float begin, float end, float fraction) {
1080 return (end - begin) * fraction + begin;
1081 }
1082
1083 /* XXX: localize this! */
1084 NSString *SizeString(double size) {
1085 bool negative = size < 0;
1086 if (negative)
1087 size = -size;
1088
1089 unsigned power = 0;
1090 while (size > 1024) {
1091 size /= 1024;
1092 ++power;
1093 }
1094
1095 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1096
1097 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1098 }
1099
1100 static _finline const char *StripVersion_(const char *version) {
1101 const char *colon(strchr(version, ':'));
1102 return colon == NULL ? version : colon + 1;
1103 }
1104
1105 NSString *LocalizeSection(NSString *section) {
1106 static Pcre title_r("^(.*?) \\((.*)\\)$");
1107 if (title_r(section)) {
1108 NSString *parent(title_r[1]);
1109 NSString *child(title_r[2]);
1110
1111 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1112 LocalizeSection(parent),
1113 LocalizeSection(child)
1114 ];
1115 }
1116
1117 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1118 }
1119
1120 NSString *Simplify(NSString *title) {
1121 const char *data = [title UTF8String];
1122 size_t size = [title length];
1123
1124 static Pcre square_r("^\\[(.*)\\]$");
1125 if (square_r(data, size))
1126 return Simplify(square_r[1]);
1127
1128 static Pcre paren_r("^\\((.*)\\)$");
1129 if (paren_r(data, size))
1130 return Simplify(paren_r[1]);
1131
1132 static Pcre title_r("^(.*?) \\((.*)\\)$");
1133 if (title_r(data, size))
1134 return Simplify(title_r[1]);
1135
1136 return title;
1137 }
1138 /* }}} */
1139
1140 NSString *GetLastUpdate() {
1141 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1142
1143 if (update == nil)
1144 return UCLocalize("NEVER_OR_UNKNOWN");
1145
1146 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1147 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1148
1149 CFRelease(formatter);
1150
1151 return [(NSString *) formatted autorelease];
1152 }
1153
1154 bool isSectionVisible(NSString *section) {
1155 NSDictionary *metadata([Sections_ objectForKey:section]);
1156 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1157 return hidden == nil || ![hidden boolValue];
1158 }
1159
1160 @class Cydia;
1161
1162 /* Delegate Prototypes {{{ */
1163 @class Package;
1164 @class Source;
1165
1166 @interface NSObject (ProgressDelegate)
1167 @end
1168
1169 @protocol ProgressDelegate
1170 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1171 - (void) setProgressTitle:(NSString *)title;
1172 - (void) setProgressPercent:(float)percent;
1173 - (void) startProgress;
1174 - (void) addProgressOutput:(NSString *)output;
1175 - (bool) isCancelling:(size_t)received;
1176 @end
1177
1178 @protocol ConfigurationDelegate
1179 - (void) repairWithSelector:(SEL)selector;
1180 - (void) setConfigurationData:(NSString *)data;
1181 @end
1182
1183 @class CYPackageController;
1184
1185 @protocol CydiaDelegate
1186 - (void) retainNetworkActivityIndicator;
1187 - (void) releaseNetworkActivityIndicator;
1188 - (void) clearPackage:(Package *)package;
1189 - (void) installPackage:(Package *)package;
1190 - (void) installPackages:(NSArray *)packages;
1191 - (void) removePackage:(Package *)package;
1192 - (void) beginUpdate;
1193 - (BOOL) updating;
1194 - (void) distUpgrade;
1195 - (void) loadData;
1196 - (void) updateData;
1197 - (void) syncData;
1198 - (void) showSettings;
1199 - (UIProgressHUD *) addProgressHUD;
1200 - (void) removeProgressHUD:(UIProgressHUD *)hud;
1201 - (CYViewController *) pageForPackage:(NSString *)name;
1202 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item;
1203 @end
1204
1205 static id<CydiaDelegate> CydiaApp;
1206 /* }}} */
1207
1208 /* Status Delegation {{{ */
1209 class Status :
1210 public pkgAcquireStatus
1211 {
1212 private:
1213 _transient NSObject<ProgressDelegate> *delegate_;
1214
1215 public:
1216 Status() :
1217 delegate_(nil)
1218 {
1219 }
1220
1221 void setDelegate(id delegate) {
1222 delegate_ = delegate;
1223 }
1224
1225 NSObject<ProgressDelegate> *getDelegate() const {
1226 return delegate_;
1227 }
1228
1229 virtual bool MediaChange(std::string media, std::string drive) {
1230 return false;
1231 }
1232
1233 virtual void IMSHit(pkgAcquire::ItemDesc &item) {
1234 }
1235
1236 virtual void Fetch(pkgAcquire::ItemDesc &item) {
1237 //NSString *name([NSString stringWithUTF8String:item.ShortDesc.c_str()]);
1238 [delegate_ setProgressTitle:[NSString stringWithFormat:UCLocalize("DOWNLOADING_"), [NSString stringWithUTF8String:item.ShortDesc.c_str()]]];
1239 }
1240
1241 virtual void Done(pkgAcquire::ItemDesc &item) {
1242 }
1243
1244 virtual void Fail(pkgAcquire::ItemDesc &item) {
1245 if (
1246 item.Owner->Status == pkgAcquire::Item::StatIdle ||
1247 item.Owner->Status == pkgAcquire::Item::StatDone
1248 )
1249 return;
1250
1251 std::string &error(item.Owner->ErrorText);
1252 if (error.empty())
1253 return;
1254
1255 NSString *description([NSString stringWithUTF8String:item.Description.c_str()]);
1256 NSArray *fields([description componentsSeparatedByString:@" "]);
1257 NSString *source([fields count] == 0 ? nil : [fields objectAtIndex:0]);
1258
1259 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
1260 withObject:[NSArray arrayWithObjects:
1261 [NSString stringWithUTF8String:error.c_str()],
1262 source,
1263 nil]
1264 waitUntilDone:YES
1265 ];
1266 }
1267
1268 virtual bool Pulse(pkgAcquire *Owner) {
1269 bool value = pkgAcquireStatus::Pulse(Owner);
1270
1271 float percent(
1272 double(CurrentBytes + CurrentItems) /
1273 double(TotalBytes + TotalItems)
1274 );
1275
1276 [delegate_ setProgressPercent:percent];
1277 return [delegate_ isCancelling:CurrentBytes] ? false : value;
1278 }
1279
1280 virtual void Start() {
1281 [delegate_ startProgress];
1282 }
1283
1284 virtual void Stop() {
1285 }
1286 };
1287 /* }}} */
1288 /* Progress Delegation {{{ */
1289 class Progress :
1290 public OpProgress
1291 {
1292 private:
1293 _transient id<ProgressDelegate> delegate_;
1294 float percent_;
1295
1296 protected:
1297 virtual void Update() {
1298 /*if (abs(Percent - percent_) > 2)
1299 //NSLog(@"%s:%s:%f", Op.c_str(), SubOp.c_str(), Percent);
1300 percent_ = Percent;
1301 }*/
1302
1303 /*[delegate_ setProgressTitle:[NSString stringWithUTF8String:Op.c_str()]];
1304 [delegate_ setProgressPercent:(Percent / 100)];*/
1305 }
1306
1307 public:
1308 Progress() :
1309 delegate_(nil),
1310 percent_(0)
1311 {
1312 }
1313
1314 void setDelegate(id delegate) {
1315 delegate_ = delegate;
1316 }
1317
1318 id getDelegate() const {
1319 return delegate_;
1320 }
1321
1322 virtual void Done() {
1323 //NSLog(@"DONE");
1324 //[delegate_ setProgressPercent:1];
1325 }
1326 };
1327 /* }}} */
1328
1329 /* Database Interface {{{ */
1330 typedef std::map< unsigned long, _H<Source> > SourceMap;
1331
1332 @interface Database : NSObject {
1333 NSZone *zone_;
1334 apr_pool_t *pool_;
1335
1336 unsigned era_;
1337
1338 pkgCacheFile cache_;
1339 pkgDepCache::Policy *policy_;
1340 pkgRecords *records_;
1341 pkgProblemResolver *resolver_;
1342 pkgAcquire *fetcher_;
1343 FileFd *lock_;
1344 SPtr<pkgPackageManager> manager_;
1345 pkgSourceList *list_;
1346
1347 SourceMap sources_;
1348 CFMutableArrayRef deadSources_;
1349 CFMutableArrayRef packages_;
1350
1351 _transient NSObject<ConfigurationDelegate, ProgressDelegate> *delegate_;
1352 Status status_;
1353 Progress progress_;
1354
1355 int cydiafd_;
1356 int statusfd_;
1357 FILE *input_;
1358
1359 std::map<const char *, _H<NSString> > sections_;
1360 }
1361
1362 + (Database *) sharedInstance;
1363 - (unsigned) era;
1364
1365 - (void) _readCydia:(NSNumber *)fd;
1366 - (void) _readStatus:(NSNumber *)fd;
1367 - (void) _readOutput:(NSNumber *)fd;
1368
1369 - (FILE *) input;
1370
1371 - (Package *) packageWithName:(NSString *)name;
1372
1373 - (pkgCacheFile &) cache;
1374 - (pkgDepCache::Policy *) policy;
1375 - (pkgRecords *) records;
1376 - (pkgProblemResolver *) resolver;
1377 - (pkgAcquire &) fetcher;
1378 - (pkgSourceList &) list;
1379 - (NSArray *) packages;
1380 - (NSArray *) sources;
1381 - (void) reloadData;
1382
1383 - (void) configure;
1384 - (bool) prepare;
1385 - (void) perform;
1386 - (bool) upgrade;
1387 - (void) update;
1388
1389 - (void) updateWithStatus:(Status &)status;
1390
1391 - (void) setDelegate:(id)delegate;
1392 - (Source *) getSource:(pkgCache::PkgFileIterator)file;
1393
1394 - (NSString *) mappedSectionForPointer:(const char *)pointer;
1395
1396 @end
1397 /* }}} */
1398 /* Delegate Helpers {{{ */
1399 @implementation NSObject (ProgressDelegate)
1400
1401 - (void) _setProgressErrorPackage:(NSArray *)args {
1402 [self performSelector:@selector(setProgressError:forPackage:)
1403 withObject:[args objectAtIndex:0]
1404 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1405 ];
1406 }
1407
1408 - (void) _setProgressErrorTitle:(NSArray *)args {
1409 [self performSelector:@selector(setProgressError:withTitle:)
1410 withObject:[args objectAtIndex:0]
1411 withObject:([args count] == 1 ? nil : [args objectAtIndex:1])
1412 ];
1413 }
1414
1415 - (void) _setProgressError:(NSString *)error withTitle:(NSString *)title {
1416 [self performSelectorOnMainThread:@selector(_setProgressErrorTitle:)
1417 withObject:[NSArray arrayWithObjects:error, title, nil]
1418 waitUntilDone:YES
1419 ];
1420 }
1421
1422 - (void) setProgressError:(NSString *)error forPackage:(NSString *)id {
1423 Package *package = id == nil ? nil : [[Database sharedInstance] packageWithName:id];
1424
1425 [self performSelector:@selector(setProgressError:withTitle:)
1426 withObject:error
1427 withObject:(package == nil ? id : [package name])
1428 ];
1429 }
1430
1431 @end
1432 /* }}} */
1433
1434 // Cytore Definitions {{{
1435 struct PackageValue :
1436 Cytore::Block
1437 {
1438 Cytore::Offset<PackageValue> next_;
1439
1440 uint32_t index_ : 23;
1441 uint32_t subscribed_ : 1;
1442 uint32_t : 8;
1443
1444 int32_t first_;
1445 int32_t last_;
1446
1447 uint16_t vhash_;
1448 uint16_t nhash_;
1449
1450 char version_[8];
1451 char name_[];
1452 };
1453
1454 struct MetaValue :
1455 Cytore::Block
1456 {
1457 uint32_t active_;
1458 Cytore::Offset<PackageValue> packages_[1 << 16];
1459 };
1460
1461 static Cytore::File<MetaValue> MetaFile_;
1462 // }}}
1463 // Cytore Helper Functions {{{
1464 static PackageValue *PackageFind(const char *name, size_t length) {
1465 SplitHash nhash = { hashlittle(name, length) };
1466
1467 PackageValue *metadata;
1468
1469 Cytore::Offset<PackageValue> *offset(&MetaFile_->packages_[nhash.u16[0]]);
1470 offset: if (offset->IsNull()) {
1471 *offset = MetaFile_.New<PackageValue>(length + 1);
1472 metadata = &MetaFile_.Get(*offset);
1473
1474 memcpy(metadata->name_, name, length + 1);
1475 metadata->nhash_ = nhash.u16[1];
1476 } else {
1477 metadata = &MetaFile_.Get(*offset);
1478
1479 if (metadata->nhash_ != nhash.u16[1] || strncmp(metadata->name_, name, length + 1) != 0) {
1480 offset = &metadata->next_;
1481 goto offset;
1482 }
1483 }
1484
1485 return metadata;
1486 }
1487
1488 static void PackageImport(const void *key, const void *value, void *context) {
1489 char buffer[1024];
1490 if (!CFStringGetCString((CFStringRef) key, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1491 NSLog(@"failed to import package %@", key);
1492 return;
1493 }
1494
1495 PackageValue *metadata(PackageFind(buffer, strlen(buffer)));
1496 NSDictionary *package((NSDictionary *) value);
1497
1498 if (NSNumber *subscribed = [package objectForKey:@"IsSubscribed"])
1499 if ([subscribed boolValue] && !metadata->subscribed_)
1500 metadata->subscribed_ = true;
1501
1502 if (NSDate *date = [package objectForKey:@"FirstSeen"]) {
1503 time_t time([date timeIntervalSince1970]);
1504 if (metadata->first_ > time || metadata->first_ == 0)
1505 metadata->first_ = time;
1506 }
1507
1508 NSDate *date([package objectForKey:@"LastSeen"]);
1509 NSString *version([package objectForKey:@"LastVersion"]);
1510
1511 if (date != nil && version != nil) {
1512 time_t time([date timeIntervalSince1970]);
1513 if (metadata->last_ < time || metadata->last_ == 0)
1514 if (CFStringGetCString((CFStringRef) version, buffer, sizeof(buffer), kCFStringEncodingUTF8)) {
1515 size_t length(strlen(buffer));
1516 uint16_t vhash(hashlittle(buffer, length));
1517
1518 size_t capped(std::min<size_t>(8, length));
1519 char *latest(buffer + length - capped);
1520
1521 strncpy(metadata->version_, latest, sizeof(metadata->version_));
1522 metadata->vhash_ = vhash;
1523
1524 metadata->last_ = time;
1525 }
1526 }
1527 }
1528 // }}}
1529
1530 /* Source Class {{{ */
1531 @interface Source : NSObject {
1532 CYString depiction_;
1533 CYString description_;
1534 CYString label_;
1535 CYString origin_;
1536 CYString support_;
1537
1538 CYString uri_;
1539 CYString distribution_;
1540 CYString type_;
1541 CYString version_;
1542
1543 NSString *host_;
1544 NSString *authority_;
1545
1546 CYString defaultIcon_;
1547
1548 NSDictionary *record_;
1549 BOOL trusted_;
1550 }
1551
1552 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool;
1553
1554 - (NSComparisonResult) compareByNameAndType:(Source *)source;
1555
1556 - (NSString *) depictionForPackage:(NSString *)package;
1557 - (NSString *) supportForPackage:(NSString *)package;
1558
1559 - (NSDictionary *) record;
1560 - (BOOL) trusted;
1561
1562 - (NSString *) uri;
1563 - (NSString *) distribution;
1564 - (NSString *) type;
1565 - (NSString *) key;
1566 - (NSString *) host;
1567
1568 - (NSString *) name;
1569 - (NSString *) description;
1570 - (NSString *) label;
1571 - (NSString *) origin;
1572 - (NSString *) version;
1573
1574 - (NSString *) defaultIcon;
1575
1576 @end
1577
1578 @implementation Source
1579
1580 - (void) _clear {
1581 uri_.clear();
1582 distribution_.clear();
1583 type_.clear();
1584
1585 description_.clear();
1586 label_.clear();
1587 origin_.clear();
1588 depiction_.clear();
1589 support_.clear();
1590 version_.clear();
1591 defaultIcon_.clear();
1592
1593 if (record_ != nil) {
1594 [record_ release];
1595 record_ = nil;
1596 }
1597
1598 if (host_ != nil) {
1599 [host_ release];
1600 host_ = nil;
1601 }
1602
1603 if (authority_ != nil) {
1604 [authority_ release];
1605 authority_ = nil;
1606 }
1607 }
1608
1609 - (void) dealloc {
1610 // XXX: this is a very inefficient way to call these deconstructors
1611 [self _clear];
1612 [super dealloc];
1613 }
1614
1615 + (NSArray *) _attributeKeys {
1616 return [NSArray arrayWithObjects:@"description", @"distribution", @"host", @"key", @"label", @"name", @"origin", @"trusted", @"type", @"uri", @"version", nil];
1617 }
1618
1619 - (NSArray *) attributeKeys {
1620 return [[self class] _attributeKeys];
1621 }
1622
1623 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
1624 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
1625 }
1626
1627 - (void) setMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1628 [self _clear];
1629
1630 trusted_ = index->IsTrusted();
1631
1632 uri_.set(pool, index->GetURI());
1633 distribution_.set(pool, index->GetDist());
1634 type_.set(pool, index->GetType());
1635
1636 debReleaseIndex *dindex(dynamic_cast<debReleaseIndex *>(index));
1637 if (dindex != NULL) {
1638 FileFd fd;
1639 if (!fd.Open(dindex->MetaIndexFile("Release"), FileFd::ReadOnly))
1640 _error->Discard();
1641 else {
1642 pkgTagFile tags(&fd);
1643
1644 pkgTagSection section;
1645 tags.Step(section);
1646
1647 struct {
1648 const char *name_;
1649 CYString *value_;
1650 } names[] = {
1651 {"default-icon", &defaultIcon_},
1652 {"depiction", &depiction_},
1653 {"description", &description_},
1654 {"label", &label_},
1655 {"origin", &origin_},
1656 {"support", &support_},
1657 {"version", &version_},
1658 };
1659
1660 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
1661 const char *start, *end;
1662
1663 if (section.Find(names[i].name_, start, end)) {
1664 CYString &value(*names[i].value_);
1665 value.set(pool, start, end - start);
1666 }
1667 }
1668 }
1669 }
1670
1671 record_ = [Sources_ objectForKey:[self key]];
1672 if (record_ != nil)
1673 record_ = [record_ retain];
1674
1675 NSURL *url([NSURL URLWithString:uri_]);
1676
1677 host_ = [url host];
1678 if (host_ != nil)
1679 host_ = [[host_ lowercaseString] retain];
1680
1681 if (host_ != nil)
1682 authority_ = host_;
1683 else
1684 authority_ = [url path];
1685
1686 if (authority_ != nil)
1687 authority_ = [authority_ retain];
1688 }
1689
1690 - (Source *) initWithMetaIndex:(metaIndex *)index inPool:(apr_pool_t *)pool {
1691 if ((self = [super init]) != nil) {
1692 [self setMetaIndex:index inPool:pool];
1693 } return self;
1694 }
1695
1696 - (NSComparisonResult) compareByNameAndType:(Source *)source {
1697 NSDictionary *lhr = [self record];
1698 NSDictionary *rhr = [source record];
1699
1700 if (lhr != rhr)
1701 return lhr == nil ? NSOrderedDescending : NSOrderedAscending;
1702
1703 NSString *lhs = [self name];
1704 NSString *rhs = [source name];
1705
1706 if ([lhs length] != 0 && [rhs length] != 0) {
1707 unichar lhc = [lhs characterAtIndex:0];
1708 unichar rhc = [rhs characterAtIndex:0];
1709
1710 if (isalpha(lhc) && !isalpha(rhc))
1711 return NSOrderedAscending;
1712 else if (!isalpha(lhc) && isalpha(rhc))
1713 return NSOrderedDescending;
1714 }
1715
1716 return [lhs compare:rhs options:LaxCompareOptions_];
1717 }
1718
1719 - (NSString *) depictionForPackage:(NSString *)package {
1720 return depiction_.empty() ? nil : [static_cast<id>(depiction_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1721 }
1722
1723 - (NSString *) supportForPackage:(NSString *)package {
1724 return support_.empty() ? nil : [static_cast<id>(support_) stringByReplacingOccurrencesOfString:@"*" withString:package];
1725 }
1726
1727 - (NSDictionary *) record {
1728 return record_;
1729 }
1730
1731 - (BOOL) trusted {
1732 return trusted_;
1733 }
1734
1735 - (NSString *) uri {
1736 return uri_;
1737 }
1738
1739 - (NSString *) distribution {
1740 return distribution_;
1741 }
1742
1743 - (NSString *) type {
1744 return type_;
1745 }
1746
1747 - (NSString *) key {
1748 return [NSString stringWithFormat:@"%@:%@:%@", (NSString *) type_, (NSString *) uri_, (NSString *) distribution_];
1749 }
1750
1751 - (NSString *) host {
1752 return host_;
1753 }
1754
1755 - (NSString *) name {
1756 return origin_.empty() ? authority_ : origin_;
1757 }
1758
1759 - (NSString *) description {
1760 return description_;
1761 }
1762
1763 - (NSString *) label {
1764 return label_.empty() ? authority_ : label_;
1765 }
1766
1767 - (NSString *) origin {
1768 return origin_;
1769 }
1770
1771 - (NSString *) version {
1772 return version_;
1773 }
1774
1775 - (NSString *) defaultIcon {
1776 return defaultIcon_;
1777 }
1778
1779 @end
1780 /* }}} */
1781 /* Relationship Class {{{ */
1782 @interface Relationship : NSObject {
1783 NSString *type_;
1784 NSString *id_;
1785 }
1786
1787 - (NSString *) type;
1788 - (NSString *) id;
1789 - (NSString *) name;
1790
1791 @end
1792
1793 @implementation Relationship
1794
1795 - (void) dealloc {
1796 [type_ release];
1797 [id_ release];
1798 [super dealloc];
1799 }
1800
1801 - (NSString *) type {
1802 return type_;
1803 }
1804
1805 - (NSString *) id {
1806 return id_;
1807 }
1808
1809 - (NSString *) name {
1810 _assert(false);
1811 return nil;
1812 }
1813
1814 @end
1815 /* }}} */
1816 /* Package Class {{{ */
1817 struct ParsedPackage {
1818 CYString tagline_;
1819
1820 CYString icon_;
1821
1822 CYString depiction_;
1823 CYString homepage_;
1824
1825 CYString sponsor_;
1826 CYString author_;
1827
1828 CYString bugs_;
1829 CYString support_;
1830 };
1831
1832 @interface Package : NSObject {
1833 uint32_t era_ : 26;
1834 uint32_t role_ : 3;
1835 uint32_t essential_ : 1;
1836 uint32_t obsolete_ : 1;
1837 uint32_t ignored_ : 1;
1838
1839 apr_pool_t *pool_;
1840
1841 _transient Database *database_;
1842
1843 pkgCache::VerIterator version_;
1844 pkgCache::PkgIterator iterator_;
1845 pkgCache::VerFileIterator file_;
1846
1847 CYString id_;
1848 CYString name_;
1849
1850 CYString latest_;
1851 CYString installed_;
1852
1853 const char *section_;
1854 _transient NSString *section$_;
1855
1856 Source *source_;
1857
1858 PackageValue *metadata_;
1859 ParsedPackage *parsed_;
1860
1861 NSMutableArray *tags_;
1862 }
1863
1864 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1865 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database;
1866
1867 - (pkgCache::PkgIterator) iterator;
1868 - (void) parse;
1869
1870 - (NSString *) section;
1871 - (NSString *) simpleSection;
1872
1873 - (NSString *) longSection;
1874 - (NSString *) shortSection;
1875
1876 - (NSString *) uri;
1877
1878 - (Address *) maintainer;
1879 - (size_t) size;
1880 - (NSString *) longDescription;
1881 - (NSString *) shortDescription;
1882 - (unichar) index;
1883
1884 - (PackageValue *) metadata;
1885 - (time_t) seen;
1886
1887 - (bool) subscribed;
1888 - (bool) setSubscribed:(bool)subscribed;
1889
1890 - (BOOL) ignored;
1891
1892 - (NSString *) latest;
1893 - (NSString *) installed;
1894 - (BOOL) uninstalled;
1895
1896 - (BOOL) valid;
1897 - (BOOL) upgradableAndEssential:(BOOL)essential;
1898 - (BOOL) essential;
1899 - (BOOL) broken;
1900 - (BOOL) unfiltered;
1901 - (BOOL) visible;
1902
1903 - (BOOL) half;
1904 - (BOOL) halfConfigured;
1905 - (BOOL) halfInstalled;
1906 - (BOOL) hasMode;
1907 - (NSString *) mode;
1908
1909 - (NSString *) id;
1910 - (NSString *) name;
1911 - (UIImage *) icon;
1912 - (NSString *) homepage;
1913 - (NSString *) depiction;
1914 - (Address *) author;
1915
1916 - (NSString *) support;
1917
1918 - (NSArray *) files;
1919 - (NSArray *) warnings;
1920 - (NSArray *) applications;
1921
1922 - (Source *) source;
1923
1924 - (BOOL) matches:(NSString *)text;
1925
1926 - (bool) hasSupportingRole;
1927 - (BOOL) hasTag:(NSString *)tag;
1928 - (NSString *) primaryPurpose;
1929 - (NSArray *) purposes;
1930 - (bool) isCommercial;
1931
1932 - (void) setIndex:(size_t)index;
1933
1934 - (CYString &) cyname;
1935
1936 - (uint32_t) compareBySection:(NSArray *)sections;
1937
1938 - (void) install;
1939 - (void) remove;
1940
1941 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search;
1942 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search;
1943 - (bool) isInstalledAndUnfiltered:(NSNumber *)number;
1944 - (bool) isVisibleInSection:(NSString *)section;
1945 - (bool) isVisibleInSource:(Source *)source;
1946
1947 @end
1948
1949 uint32_t PackageChangesRadix(Package *self, void *) {
1950 union {
1951 uint32_t key;
1952
1953 struct {
1954 uint32_t timestamp : 30;
1955 uint32_t ignored : 1;
1956 uint32_t upgradable : 1;
1957 } bits;
1958 } value;
1959
1960 bool upgradable([self upgradableAndEssential:YES]);
1961 value.bits.upgradable = upgradable ? 1 : 0;
1962
1963 if (upgradable) {
1964 value.bits.timestamp = 0;
1965 value.bits.ignored = [self ignored] ? 0 : 1;
1966 value.bits.upgradable = 1;
1967 } else {
1968 value.bits.timestamp = [self seen] >> 2;
1969 value.bits.ignored = 0;
1970 value.bits.upgradable = 0;
1971 }
1972
1973 return _not(uint32_t) - value.key;
1974 }
1975
1976 uint32_t PackagePrefixRadix(Package *self, void *context) {
1977 size_t offset(reinterpret_cast<size_t>(context));
1978 CYString &name([self cyname]);
1979
1980 size_t size(name.size());
1981 if (size == 0)
1982 return 0;
1983 char *text(name.data());
1984
1985 size_t zeros;
1986 if (!isdigit(text[0]))
1987 zeros = 0;
1988 else {
1989 size_t digits(1);
1990 while (size != digits && isdigit(text[digits]))
1991 if (++digits == 4)
1992 break;
1993 zeros = 4 - digits;
1994 }
1995
1996 uint8_t data[4];
1997
1998 if (offset == 0 && zeros != 0) {
1999 memset(data, '0', zeros);
2000 memcpy(data + zeros, text, 4 - zeros);
2001 } else {
2002 /* XXX: there's some danger here if you request a non-zero offset < 4 and it gets zero padded */
2003 if (size <= offset - zeros)
2004 return 0;
2005
2006 text += offset - zeros;
2007 size -= offset - zeros;
2008
2009 if (size >= 4)
2010 memcpy(data, text, 4);
2011 else {
2012 memcpy(data, text, size);
2013 memset(data + size, 0, 4 - size);
2014 }
2015
2016 for (size_t i(0); i != 4; ++i)
2017 if (isalpha(data[i]))
2018 data[i] |= 0x20;
2019 }
2020
2021 if (offset == 0)
2022 if (data[0] == '@')
2023 data[0] = 0x7f;
2024 else
2025 data[0] = (data[0] & 0x1f) | "\x80\x00\xc0\x40"[data[0] >> 6];
2026
2027 /* XXX: ntohl may be more honest */
2028 return OSSwapInt32(*reinterpret_cast<uint32_t *>(data));
2029 }
2030
2031 CYString &(*PackageName)(Package *self, SEL sel);
2032
2033 CFComparisonResult PackageNameCompare(Package *lhs, Package *rhs, void *arg) {
2034 _profile(PackageNameCompare)
2035 CYString &lhi(PackageName(lhs, @selector(cyname)));
2036 CYString &rhi(PackageName(rhs, @selector(cyname)));
2037 CFStringRef lhn(lhi), rhn(rhi);
2038
2039 if (lhn == NULL)
2040 return rhn == NULL ? NSOrderedSame : NSOrderedAscending;
2041 else if (rhn == NULL)
2042 return NSOrderedDescending;
2043
2044 _profile(PackageNameCompare$NumbersLast)
2045 if (!lhi.empty() && !rhi.empty()) {
2046 UniChar lhc(CFStringGetCharacterAtIndex(lhn, 0));
2047 UniChar rhc(CFStringGetCharacterAtIndex(rhn, 0));
2048 bool lha(CFUniCharIsMemberOf(lhc, kCFUniCharLetterCharacterSet));
2049 if (lha != CFUniCharIsMemberOf(rhc, kCFUniCharLetterCharacterSet))
2050 return lha ? NSOrderedAscending : NSOrderedDescending;
2051 }
2052 _end
2053
2054 CFIndex length = CFStringGetLength(lhn);
2055
2056 _profile(PackageNameCompare$Compare)
2057 return CFStringCompareWithOptionsAndLocale(lhn, rhn, CFRangeMake(0, length), LaxCompareFlags_, Locale_);
2058 _end
2059 _end
2060 }
2061
2062 CFComparisonResult PackageNameCompare_(Package **lhs, Package **rhs, void *context) {
2063 return PackageNameCompare(*lhs, *rhs, context);
2064 }
2065
2066 struct PackageNameOrdering :
2067 std::binary_function<Package *, Package *, bool>
2068 {
2069 _finline bool operator ()(Package *lhs, Package *rhs) const {
2070 return PackageNameCompare(lhs, rhs, NULL) == NSOrderedAscending;
2071 }
2072 };
2073
2074 @implementation Package
2075
2076 - (NSString *) description {
2077 return [NSString stringWithFormat:@"<Package:%@>", static_cast<NSString *>(name_)];
2078 }
2079
2080 - (void) dealloc {
2081 if (parsed_ != NULL)
2082 delete parsed_;
2083 if (source_ != nil)
2084 [source_ release];
2085 if (tags_ != nil)
2086 [tags_ release];
2087 [super dealloc];
2088 }
2089
2090 + (NSString *) webScriptNameForSelector:(SEL)selector {
2091 if (selector == @selector(hasTag:))
2092 return @"hasTag";
2093 else
2094 return nil;
2095 }
2096
2097 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
2098 return [self webScriptNameForSelector:selector] == nil;
2099 }
2100
2101 + (NSArray *) _attributeKeys {
2102 return [NSArray arrayWithObjects:@"applications", @"author", @"depiction", @"longDescription", @"essential", @"homepage", @"icon", @"id", @"installed", @"latest", @"longSection", @"maintainer", @"mode", @"name", @"purposes", @"section", @"shortDescription", @"shortSection", @"simpleSection", @"size", @"source", @"sponsor", @"support", @"warnings", nil];
2103 }
2104
2105 - (NSArray *) attributeKeys {
2106 return [[self class] _attributeKeys];
2107 }
2108
2109 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
2110 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
2111 }
2112
2113 - (void) parse {
2114 if (parsed_ != NULL)
2115 return;
2116 @synchronized (database_) {
2117 if ([database_ era] != era_ || file_.end())
2118 return;
2119
2120 ParsedPackage *parsed(new ParsedPackage);
2121 parsed_ = parsed;
2122
2123 _profile(Package$parse)
2124 pkgRecords::Parser *parser;
2125
2126 _profile(Package$parse$Lookup)
2127 parser = &[database_ records]->Lookup(file_);
2128 _end
2129
2130 CYString website;
2131
2132 _profile(Package$parse$Find)
2133 struct {
2134 const char *name_;
2135 CYString *value_;
2136 } names[] = {
2137 {"icon", &parsed->icon_},
2138 {"depiction", &parsed->depiction_},
2139 {"homepage", &parsed->homepage_},
2140 {"website", &website},
2141 {"bugs", &parsed->bugs_},
2142 {"support", &parsed->support_},
2143 {"sponsor", &parsed->sponsor_},
2144 {"author", &parsed->author_},
2145 };
2146
2147 for (size_t i(0); i != sizeof(names) / sizeof(names[0]); ++i) {
2148 const char *start, *end;
2149
2150 if (parser->Find(names[i].name_, start, end)) {
2151 CYString &value(*names[i].value_);
2152 _profile(Package$parse$Value)
2153 value.set(pool_, start, end - start);
2154 _end
2155 }
2156 }
2157 _end
2158
2159 _profile(Package$parse$Tagline)
2160 const char *start, *end;
2161 if (parser->ShortDesc(start, end)) {
2162 const char *stop(reinterpret_cast<const char *>(memchr(start, '\n', end - start)));
2163 if (stop == NULL)
2164 stop = end;
2165 while (stop != start && stop[-1] == '\r')
2166 --stop;
2167 parsed->tagline_.set(pool_, start, stop - start);
2168 }
2169 _end
2170
2171 _profile(Package$parse$Retain)
2172 if (parsed->homepage_.empty())
2173 parsed->homepage_ = website;
2174 if (parsed->homepage_ == parsed->depiction_)
2175 parsed->homepage_.clear();
2176 _end
2177 _end
2178 } }
2179
2180 - (Package *) initWithVersion:(pkgCache::VerIterator)version withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2181 if ((self = [super init]) != nil) {
2182 _profile(Package$initWithVersion)
2183 pool_ = pool;
2184
2185 database_ = database;
2186 era_ = [database era];
2187
2188 version_ = version;
2189
2190 pkgCache::PkgIterator iterator(version.ParentPkg());
2191 iterator_ = iterator;
2192
2193 _profile(Package$initWithVersion$Version)
2194 if (!version_.end())
2195 file_ = version_.FileList();
2196 else {
2197 pkgCache &cache([database_ cache]);
2198 file_ = pkgCache::VerFileIterator(cache, cache.VerFileP);
2199 }
2200 _end
2201
2202 _profile(Package$initWithVersion$Cache)
2203 name_.set(NULL, iterator.Display());
2204
2205 latest_.set(NULL, StripVersion_(version_.VerStr()));
2206
2207 pkgCache::VerIterator current(iterator.CurrentVer());
2208 if (!current.end())
2209 installed_.set(NULL, StripVersion_(current.VerStr()));
2210 _end
2211
2212 _profile(Package$initWithVersion$Tags)
2213 pkgCache::TagIterator tag(iterator.TagList());
2214 if (!tag.end()) {
2215 tags_ = [[NSMutableArray alloc] initWithCapacity:8];
2216 do {
2217 const char *name(tag.Name());
2218 [tags_ addObject:[(NSString *)CYStringCreate(name) autorelease]];
2219
2220 if (role_ == 0 && strncmp(name, "role::", 6) == 0 /*&& strcmp(name, "role::leaper") != 0*/) {
2221 if (strcmp(name + 6, "enduser") == 0)
2222 role_ = 1;
2223 else if (strcmp(name + 6, "hacker") == 0)
2224 role_ = 2;
2225 else if (strcmp(name + 6, "developer") == 0)
2226 role_ = 3;
2227 else if (strcmp(name + 6, "cydia") == 0)
2228 role_ = 7;
2229 else
2230 role_ = 4;
2231 }
2232
2233 if (strncmp(name, "cydia::", 7) == 0) {
2234 if (strcmp(name + 7, "essential") == 0)
2235 essential_ = true;
2236 else if (strcmp(name + 7, "obsolete") == 0)
2237 obsolete_ = true;
2238 }
2239
2240 ++tag;
2241 } while (!tag.end());
2242 }
2243 _end
2244
2245 _profile(Package$initWithVersion$Metadata)
2246 const char *mixed(iterator.Name());
2247 size_t size(strlen(mixed));
2248 char lower[size + 1];
2249
2250 for (size_t i(0); i != size; ++i)
2251 lower[i] = mixed[i] | 0x20;
2252 lower[size] = '\0';
2253
2254 PackageValue *metadata(PackageFind(lower, size));
2255 metadata_ = metadata;
2256
2257 id_.set(NULL, metadata->name_, size);
2258
2259 const char *latest(version_.VerStr());
2260 size_t length(strlen(latest));
2261
2262 uint16_t vhash(hashlittle(latest, length));
2263
2264 size_t capped(std::min<size_t>(8, length));
2265 latest = latest + length - capped;
2266
2267 if (metadata->first_ == 0)
2268 metadata->first_ = now_;
2269
2270 if (metadata->vhash_ != vhash || strncmp(metadata->version_, latest, sizeof(metadata->version_)) != 0) {
2271 strncpy(metadata->version_, latest, sizeof(metadata->version_));
2272 metadata->vhash_ = vhash;
2273 metadata->last_ = now_;
2274 } else if (metadata->last_ == 0)
2275 metadata->last_ = metadata->first_;
2276 _end
2277
2278 _profile(Package$initWithVersion$Section)
2279 section_ = iterator.Section();
2280 _end
2281
2282 _profile(Package$initWithVersion$Flags)
2283 essential_ |= ((iterator->Flags & pkgCache::Flag::Essential) == 0 ? NO : YES);
2284 ignored_ = iterator->SelectedState == pkgCache::State::Hold;
2285 _end
2286 _end } return self;
2287 }
2288
2289 + (Package *) packageWithIterator:(pkgCache::PkgIterator)iterator withZone:(NSZone *)zone inPool:(apr_pool_t *)pool database:(Database *)database {
2290 pkgCache::VerIterator version;
2291
2292 _profile(Package$packageWithIterator$GetCandidateVer)
2293 version = [database policy]->GetCandidateVer(iterator);
2294 _end
2295
2296 if (version.end())
2297 return nil;
2298
2299 Package *package;
2300
2301 _profile(Package$packageWithIterator$Allocate)
2302 package = [Package allocWithZone:zone];
2303 _end
2304
2305 _profile(Package$packageWithIterator$Initialize)
2306 package = [package
2307 initWithVersion:version
2308 withZone:zone
2309 inPool:pool
2310 database:database
2311 ];
2312 _end
2313
2314 _profile(Package$packageWithIterator$Autorelease)
2315 package = [package autorelease];
2316 _end
2317
2318 return package;
2319 }
2320
2321 - (pkgCache::PkgIterator) iterator {
2322 return iterator_;
2323 }
2324
2325 - (NSString *) section {
2326 if (section$_ == nil) {
2327 if (section_ == NULL)
2328 return nil;
2329
2330 _profile(Package$section$mappedSectionForPointer)
2331 section$_ = [database_ mappedSectionForPointer:section_];
2332 _end
2333 } return section$_;
2334 }
2335
2336 - (NSString *) simpleSection {
2337 if (NSString *section = [self section])
2338 return Simplify(section);
2339 else
2340 return nil;
2341 }
2342
2343 - (NSString *) longSection {
2344 return LocalizeSection([self section]);
2345 }
2346
2347 - (NSString *) shortSection {
2348 return [[NSBundle mainBundle] localizedStringForKey:[self simpleSection] value:nil table:@"Sections"];
2349 }
2350
2351 - (NSString *) uri {
2352 return nil;
2353 #if 0
2354 pkgIndexFile *index;
2355 pkgCache::PkgFileIterator file(file_.File());
2356 if (![database_ list].FindIndex(file, index))
2357 return nil;
2358 return [NSString stringWithUTF8String:iterator_->Path];
2359 //return [NSString stringWithUTF8String:file.Site()];
2360 //return [NSString stringWithUTF8String:index->ArchiveURI(file.FileName()).c_str()];
2361 #endif
2362 }
2363
2364 - (Address *) maintainer {
2365 @synchronized (database_) {
2366 if ([database_ era] != era_ || file_.end())
2367 return nil;
2368
2369 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2370 const std::string &maintainer(parser->Maintainer());
2371 return maintainer.empty() ? nil : [Address addressWithString:[NSString stringWithUTF8String:maintainer.c_str()]];
2372 } }
2373
2374 - (size_t) size {
2375 @synchronized (database_) {
2376 if ([database_ era] != era_ || version_.end())
2377 return 0;
2378
2379 return version_->InstalledSize;
2380 } }
2381
2382 - (NSString *) longDescription {
2383 @synchronized (database_) {
2384 if ([database_ era] != era_ || file_.end())
2385 return nil;
2386
2387 pkgRecords::Parser *parser = &[database_ records]->Lookup(file_);
2388 NSString *description([NSString stringWithUTF8String:parser->LongDesc().c_str()]);
2389
2390 NSArray *lines = [description componentsSeparatedByString:@"\n"];
2391 NSMutableArray *trimmed = [NSMutableArray arrayWithCapacity:([lines count] - 1)];
2392 if ([lines count] < 2)
2393 return nil;
2394
2395 NSCharacterSet *whitespace = [NSCharacterSet whitespaceCharacterSet];
2396 for (size_t i(1), e([lines count]); i != e; ++i) {
2397 NSString *trim = [[lines objectAtIndex:i] stringByTrimmingCharactersInSet:whitespace];
2398 [trimmed addObject:trim];
2399 }
2400
2401 return [trimmed componentsJoinedByString:@"\n"];
2402 } }
2403
2404 - (NSString *) shortDescription {
2405 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->tagline_);
2406 }
2407
2408 - (unichar) index {
2409 _profile(Package$index)
2410 CFStringRef name((CFStringRef) [self name]);
2411 if (CFStringGetLength(name) == 0)
2412 return '#';
2413 UniChar character(CFStringGetCharacterAtIndex(name, 0));
2414 if (!CFUniCharIsMemberOf(character, kCFUniCharLetterCharacterSet))
2415 return '#';
2416 return toupper(character);
2417 _end
2418 }
2419
2420 - (PackageValue *) metadata {
2421 return metadata_;
2422 }
2423
2424 - (time_t) seen {
2425 PackageValue *metadata([self metadata]);
2426 return metadata->subscribed_ ? metadata->last_ : metadata->first_;
2427 }
2428
2429 - (bool) subscribed {
2430 return [self metadata]->subscribed_;
2431 }
2432
2433 - (bool) setSubscribed:(bool)subscribed {
2434 PackageValue *metadata([self metadata]);
2435 if (metadata->subscribed_ == subscribed)
2436 return false;
2437 metadata->subscribed_ = subscribed;
2438 return true;
2439 }
2440
2441 - (BOOL) ignored {
2442 return ignored_;
2443 }
2444
2445 - (NSString *) latest {
2446 return latest_;
2447 }
2448
2449 - (NSString *) installed {
2450 return installed_;
2451 }
2452
2453 - (BOOL) uninstalled {
2454 return installed_.empty();
2455 }
2456
2457 - (BOOL) valid {
2458 return !version_.end();
2459 }
2460
2461 - (BOOL) upgradableAndEssential:(BOOL)essential {
2462 _profile(Package$upgradableAndEssential)
2463 pkgCache::VerIterator current(iterator_.CurrentVer());
2464 if (current.end())
2465 return essential && essential_;
2466 else
2467 return !version_.end() && version_ != current;
2468 _end
2469 }
2470
2471 - (BOOL) essential {
2472 return essential_;
2473 }
2474
2475 - (BOOL) broken {
2476 return [database_ cache][iterator_].InstBroken();
2477 }
2478
2479 - (BOOL) unfiltered {
2480 _profile(Package$unfiltered$obsolete)
2481 if (_unlikely(obsolete_))
2482 return false;
2483 _end
2484
2485 _profile(Package$unfiltered$hasSupportingRole)
2486 if (_unlikely(![self hasSupportingRole]))
2487 return false;
2488 _end
2489
2490 return true;
2491 }
2492
2493 - (BOOL) visible {
2494 if (![self unfiltered])
2495 return false;
2496
2497 NSString *section;
2498
2499 _profile(Package$visible$section)
2500 section = [self section];
2501 _end
2502
2503 _profile(Package$visible$isSectionVisible)
2504 if (section != nil && !isSectionVisible(section))
2505 return false;
2506 _end
2507
2508 return true;
2509 }
2510
2511 - (BOOL) half {
2512 unsigned char current(iterator_->CurrentState);
2513 return current == pkgCache::State::HalfConfigured || current == pkgCache::State::HalfInstalled;
2514 }
2515
2516 - (BOOL) halfConfigured {
2517 return iterator_->CurrentState == pkgCache::State::HalfConfigured;
2518 }
2519
2520 - (BOOL) halfInstalled {
2521 return iterator_->CurrentState == pkgCache::State::HalfInstalled;
2522 }
2523
2524 - (BOOL) hasMode {
2525 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2526 return state.Mode != pkgDepCache::ModeKeep;
2527 }
2528
2529 - (NSString *) mode {
2530 pkgDepCache::StateCache &state([database_ cache][iterator_]);
2531
2532 switch (state.Mode) {
2533 case pkgDepCache::ModeDelete:
2534 if ((state.iFlags & pkgDepCache::Purge) != 0)
2535 return @"PURGE";
2536 else
2537 return @"REMOVE";
2538 case pkgDepCache::ModeKeep:
2539 if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2540 return @"REINSTALL";
2541 /*else if ((state.iFlags & pkgDepCache::AutoKept) != 0)
2542 return nil;*/
2543 else
2544 return nil;
2545 case pkgDepCache::ModeInstall:
2546 /*if ((state.iFlags & pkgDepCache::ReInstall) != 0)
2547 return @"REINSTALL";
2548 else*/ switch (state.Status) {
2549 case -1:
2550 return @"DOWNGRADE";
2551 case 0:
2552 return @"INSTALL";
2553 case 1:
2554 return @"UPGRADE";
2555 case 2:
2556 return @"NEW_INSTALL";
2557 _nodefault
2558 }
2559 _nodefault
2560 }
2561 }
2562
2563 - (NSString *) id {
2564 return id_;
2565 }
2566
2567 - (NSString *) name {
2568 return name_.empty() ? id_ : name_;
2569 }
2570
2571 - (UIImage *) icon {
2572 NSString *section = [self simpleSection];
2573
2574 UIImage *icon(nil);
2575 if (parsed_ != NULL)
2576 if (NSString *href = parsed_->icon_)
2577 if ([href hasPrefix:@"file:///"])
2578 // XXX: correct escaping
2579 icon = [UIImage imageAtPath:[href substringFromIndex:7]];
2580 if (icon == nil) if (section != nil)
2581 icon = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]];
2582 if (icon == nil) if (Source *source = [self source]) if (NSString *dicon = [source defaultIcon])
2583 if ([dicon hasPrefix:@"file:///"])
2584 // XXX: correct escaping
2585 icon = [UIImage imageAtPath:[dicon substringFromIndex:7]];
2586 if (icon == nil)
2587 icon = [UIImage applicationImageNamed:@"unknown.png"];
2588 return icon;
2589 }
2590
2591 - (NSString *) homepage {
2592 return parsed_ == NULL ? nil : static_cast<NSString *>(parsed_->homepage_);
2593 }
2594
2595 - (NSString *) depiction {
2596 return parsed_ != NULL && !parsed_->depiction_.empty() ? parsed_->depiction_ : [[self source] depictionForPackage:id_];
2597 }
2598
2599 - (Address *) sponsor {
2600 return parsed_ == NULL || parsed_->sponsor_.empty() ? nil : [Address addressWithString:parsed_->sponsor_];
2601 }
2602
2603 - (Address *) author {
2604 return parsed_ == NULL || parsed_->author_.empty() ? nil : [Address addressWithString:parsed_->author_];
2605 }
2606
2607 - (NSString *) support {
2608 return parsed_ != NULL && !parsed_->bugs_.empty() ? parsed_->bugs_ : [[self source] supportForPackage:id_];
2609 }
2610
2611 - (NSArray *) files {
2612 NSString *path = [NSString stringWithFormat:@"/var/lib/dpkg/info/%@.list", static_cast<NSString *>(id_)];
2613 NSMutableArray *files = [NSMutableArray arrayWithCapacity:128];
2614
2615 std::ifstream fin;
2616 fin.open([path UTF8String]);
2617 if (!fin.is_open())
2618 return nil;
2619
2620 std::string line;
2621 while (std::getline(fin, line))
2622 [files addObject:[NSString stringWithUTF8String:line.c_str()]];
2623
2624 return files;
2625 }
2626
2627 - (NSArray *) warnings {
2628 NSMutableArray *warnings([NSMutableArray arrayWithCapacity:4]);
2629 const char *name(iterator_.Name());
2630
2631 size_t length(strlen(name));
2632 if (length < 2) invalid:
2633 [warnings addObject:UCLocalize("ILLEGAL_PACKAGE_IDENTIFIER")];
2634 else for (size_t i(0); i != length; ++i)
2635 if (
2636 /* XXX: technically this is not allowed */
2637 (name[i] < 'A' || name[i] > 'Z') &&
2638 (name[i] < 'a' || name[i] > 'z') &&
2639 (name[i] < '0' || name[i] > '9') &&
2640 (i == 0 || name[i] != '+' && name[i] != '-' && name[i] != '.')
2641 ) goto invalid;
2642
2643 if (strcmp(name, "cydia") != 0) {
2644 bool cydia = false;
2645 bool user = false;
2646 bool _private = false;
2647 bool stash = false;
2648
2649 bool repository = [[self section] isEqualToString:@"Repositories"];
2650
2651 if (NSArray *files = [self files])
2652 for (NSString *file in files)
2653 if (!cydia && [file isEqualToString:@"/Applications/Cydia.app"])
2654 cydia = true;
2655 else if (!user && [file isEqualToString:@"/User"])
2656 user = true;
2657 else if (!_private && [file isEqualToString:@"/private"])
2658 _private = true;
2659 else if (!stash && [file isEqualToString:@"/var/stash"])
2660 stash = true;
2661
2662 /* XXX: this is not sensitive enough. only some folders are valid. */
2663 if (cydia && !repository)
2664 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"Cydia.app"]];
2665 if (user)
2666 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/User"]];
2667 if (_private)
2668 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/private"]];
2669 if (stash)
2670 [warnings addObject:[NSString stringWithFormat:UCLocalize("FILES_INSTALLED_TO"), @"/var/stash"]];
2671 }
2672
2673 return [warnings count] == 0 ? nil : warnings;
2674 }
2675
2676 - (NSArray *) applications {
2677 NSString *me([[NSBundle mainBundle] bundleIdentifier]);
2678
2679 NSMutableArray *applications([NSMutableArray arrayWithCapacity:2]);
2680
2681 static Pcre application_r("^/Applications/(.*)\\.app/Info.plist$");
2682 if (NSArray *files = [self files])
2683 for (NSString *file in files)
2684 if (application_r(file)) {
2685 NSDictionary *info([NSDictionary dictionaryWithContentsOfFile:file]);
2686 NSString *id([info objectForKey:@"CFBundleIdentifier"]);
2687 if ([id isEqualToString:me])
2688 continue;
2689
2690 NSString *display([info objectForKey:@"CFBundleDisplayName"]);
2691 if (display == nil)
2692 display = application_r[1];
2693
2694 NSString *bundle([file stringByDeletingLastPathComponent]);
2695 NSString *icon([info objectForKey:@"CFBundleIconFile"]);
2696 if (icon == nil || [icon length] == 0)
2697 icon = @"icon.png";
2698 NSURL *url([NSURL fileURLWithPath:[bundle stringByAppendingPathComponent:icon]]);
2699
2700 NSMutableArray *application([NSMutableArray arrayWithCapacity:2]);
2701 [applications addObject:application];
2702
2703 [application addObject:id];
2704 [application addObject:display];
2705 [application addObject:url];
2706 }
2707
2708 return [applications count] == 0 ? nil : applications;
2709 }
2710
2711 - (Source *) source {
2712 if (source_ == nil) {
2713 @synchronized (database_) {
2714 if ([database_ era] != era_ || file_.end())
2715 source_ = (Source *) [NSNull null];
2716 else
2717 source_ = [([database_ getSource:file_.File()] ?: (Source *) [NSNull null]) retain];
2718 }
2719 }
2720
2721 return source_ == (Source *) [NSNull null] ? nil : source_;
2722 }
2723
2724 - (BOOL) matches:(NSString *)text {
2725 if (text == nil)
2726 return NO;
2727
2728 NSRange range;
2729
2730 range = [[self id] rangeOfString:text options:MatchCompareOptions_];
2731 if (range.location != NSNotFound)
2732 return YES;
2733
2734 range = [[self name] rangeOfString:text options:MatchCompareOptions_];
2735 if (range.location != NSNotFound)
2736 return YES;
2737
2738 [self parse];
2739
2740 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2741 if (range.location != NSNotFound)
2742 return YES;
2743
2744 return NO;
2745 }
2746
2747 - (bool) hasSupportingRole {
2748 if (role_ == 0)
2749 return true;
2750 if (role_ == 1)
2751 return true;
2752 if ([Role_ isEqualToString:@"User"])
2753 return false;
2754 if (role_ == 2)
2755 return true;
2756 if ([Role_ isEqualToString:@"Hacker"])
2757 return false;
2758 if (role_ == 3)
2759 return true;
2760 if ([Role_ isEqualToString:@"Developer"])
2761 return false;
2762 _assert(false);
2763 }
2764
2765 - (BOOL) hasTag:(NSString *)tag {
2766 return tags_ == nil ? NO : [tags_ containsObject:tag];
2767 }
2768
2769 - (NSString *) primaryPurpose {
2770 for (NSString *tag in tags_)
2771 if ([tag hasPrefix:@"purpose::"])
2772 return [tag substringFromIndex:9];
2773 return nil;
2774 }
2775
2776 - (NSArray *) purposes {
2777 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2778 for (NSString *tag in tags_)
2779 if ([tag hasPrefix:@"purpose::"])
2780 [purposes addObject:[tag substringFromIndex:9]];
2781 return [purposes count] == 0 ? nil : purposes;
2782 }
2783
2784 - (bool) isCommercial {
2785 return [self hasTag:@"cydia::commercial"];
2786 }
2787
2788 - (void) setIndex:(size_t)index {
2789 if (metadata_->index_ != index)
2790 metadata_->index_ = index;
2791 }
2792
2793 - (CYString &) cyname {
2794 return name_.empty() ? id_ : name_;
2795 }
2796
2797 - (uint32_t) compareBySection:(NSArray *)sections {
2798 NSString *section([self section]);
2799 for (size_t i(0), e([sections count]); i != e; ++i) {
2800 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2801 return i;
2802 }
2803
2804 return _not(uint32_t);
2805 }
2806
2807 - (void) clear {
2808 @synchronized (database_) {
2809 pkgProblemResolver *resolver = [database_ resolver];
2810 resolver->Clear(iterator_);
2811
2812 pkgCacheFile &cache([database_ cache]);
2813 cache->SetReInstall(iterator_, false);
2814 cache->MarkKeep(iterator_, false);
2815 } }
2816
2817 - (void) install {
2818 @synchronized (database_) {
2819 pkgProblemResolver *resolver = [database_ resolver];
2820 resolver->Clear(iterator_);
2821 resolver->Protect(iterator_);
2822
2823 pkgCacheFile &cache([database_ cache]);
2824 cache->SetReInstall(iterator_, false);
2825 cache->MarkInstall(iterator_, false);
2826
2827 pkgDepCache::StateCache &state((*cache)[iterator_]);
2828 if (!state.Install())
2829 cache->SetReInstall(iterator_, true);
2830 } }
2831
2832 - (void) remove {
2833 @synchronized (database_) {
2834 pkgProblemResolver *resolver = [database_ resolver];
2835 resolver->Clear(iterator_);
2836 resolver->Remove(iterator_);
2837 resolver->Protect(iterator_);
2838
2839 pkgCacheFile &cache([database_ cache]);
2840 cache->SetReInstall(iterator_, false);
2841 cache->MarkDelete(iterator_, true);
2842 } }
2843
2844 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2845 _profile(Package$isUnfilteredAndSearchedForBy)
2846 bool value(true);
2847
2848 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2849 value &= [self unfiltered];
2850 _end
2851
2852 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2853 value &= [self matches:search];
2854 _end
2855
2856 return value;
2857 _end
2858 }
2859
2860 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2861 if ([search length] == 0)
2862 return false;
2863
2864 _profile(Package$isUnfilteredAndSelectedForBy)
2865 bool value(true);
2866
2867 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2868 value &= [self unfiltered];
2869 _end
2870
2871 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2872 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2873 _end
2874
2875 return value;
2876 _end
2877 }
2878
2879 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2880 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2881 }
2882
2883 - (bool) isVisibleInSection:(NSString *)name {
2884 NSString *section([self section]);
2885
2886 return (
2887 name == nil ||
2888 section == nil && [name length] == 0 ||
2889 [name isEqualToString:section]
2890 ) && [self visible];
2891 }
2892
2893 - (bool) isVisibleInSource:(Source *)source {
2894 return [self source] == source && [self visible];
2895 }
2896
2897 @end
2898 /* }}} */
2899 /* Section Class {{{ */
2900 @interface Section : NSObject {
2901 NSString *name_;
2902 unichar index_;
2903 size_t row_;
2904 size_t count_;
2905 NSString *localized_;
2906 }
2907
2908 - (NSComparisonResult) compareByLocalized:(Section *)section;
2909 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2910 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2911 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2912 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2913 - (NSString *) name;
2914 - (unichar) index;
2915
2916 - (size_t) row;
2917 - (size_t) count;
2918
2919 - (void) addToRow;
2920 - (void) addToCount;
2921
2922 - (void) setCount:(size_t)count;
2923 - (NSString *) localized;
2924
2925 @end
2926
2927 @implementation Section
2928
2929 - (void) dealloc {
2930 [name_ release];
2931 if (localized_ != nil)
2932 [localized_ release];
2933 [super dealloc];
2934 }
2935
2936 - (NSComparisonResult) compareByLocalized:(Section *)section {
2937 NSString *lhs(localized_);
2938 NSString *rhs([section localized]);
2939
2940 /*if ([lhs length] != 0 && [rhs length] != 0) {
2941 unichar lhc = [lhs characterAtIndex:0];
2942 unichar rhc = [rhs characterAtIndex:0];
2943
2944 if (isalpha(lhc) && !isalpha(rhc))
2945 return NSOrderedAscending;
2946 else if (!isalpha(lhc) && isalpha(rhc))
2947 return NSOrderedDescending;
2948 }*/
2949
2950 return [lhs compare:rhs options:LaxCompareOptions_];
2951 }
2952
2953 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2954 if ((self = [self initWithName:name localize:NO]) != nil) {
2955 if (localized != nil)
2956 localized_ = [localized retain];
2957 } return self;
2958 }
2959
2960 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2961 return [self initWithName:name row:0 localize:localize];
2962 }
2963
2964 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2965 if ((self = [super init]) != nil) {
2966 name_ = [name retain];
2967 index_ = '\0';
2968 row_ = row;
2969 if (localize)
2970 localized_ = [LocalizeSection(name_) retain];
2971 } return self;
2972 }
2973
2974 /* XXX: localize the index thingees */
2975 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2976 if ((self = [super init]) != nil) {
2977 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2978 index_ = index;
2979 row_ = row;
2980 } return self;
2981 }
2982
2983 - (NSString *) name {
2984 return name_;
2985 }
2986
2987 - (unichar) index {
2988 return index_;
2989 }
2990
2991 - (size_t) row {
2992 return row_;
2993 }
2994
2995 - (size_t) count {
2996 return count_;
2997 }
2998
2999 - (void) addToRow {
3000 ++row_;
3001 }
3002
3003 - (void) addToCount {
3004 ++count_;
3005 }
3006
3007 - (void) setCount:(size_t)count {
3008 count_ = count;
3009 }
3010
3011 - (NSString *) localized {
3012 return localized_;
3013 }
3014
3015 @end
3016 /* }}} */
3017
3018 static NSString *Colon_;
3019 static NSString *Elision_;
3020 static NSString *Error_;
3021 static NSString *Warning_;
3022
3023 /* Database Implementation {{{ */
3024 @implementation Database
3025
3026 + (Database *) sharedInstance {
3027 static Database *instance;
3028 if (instance == nil)
3029 instance = [[Database alloc] init];
3030 return instance;
3031 }
3032
3033 - (unsigned) era {
3034 return era_;
3035 }
3036
3037 - (void) releasePackages {
3038 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3039 CFArrayRemoveAllValues(packages_);
3040 }
3041
3042 - (void) dealloc {
3043 // XXX: actually implement this thing
3044 _assert(false);
3045 if (deadSources_)
3046 CFRelease(deadSources_);
3047 [self releasePackages];
3048 apr_pool_destroy(pool_);
3049 NSRecycleZone(zone_);
3050 [super dealloc];
3051 }
3052
3053 - (void) _readCydia:(NSNumber *)fd { _pooled
3054 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3055 std::istream is(&ib);
3056 std::string line;
3057
3058 static Pcre finish_r("^finish:([^:]*)$");
3059
3060 while (std::getline(is, line)) {
3061 const char *data(line.c_str());
3062 size_t size = line.size();
3063 lprintf("C:%s\n", data);
3064
3065 if (finish_r(data, size)) {
3066 NSString *finish = finish_r[1];
3067 int index = [Finishes_ indexOfObject:finish];
3068 if (index != INT_MAX && index > Finish_)
3069 Finish_ = index;
3070 }
3071 }
3072
3073 _assume(false);
3074 }
3075
3076 - (void) _readStatus:(NSNumber *)fd { _pooled
3077 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3078 std::istream is(&ib);
3079 std::string line;
3080
3081 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3082 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3083
3084 while (std::getline(is, line)) {
3085 const char *data(line.c_str());
3086 size_t size(line.size());
3087 lprintf("S:%s\n", data);
3088
3089 if (conffile_r(data, size)) {
3090 [delegate_ setConfigurationData:conffile_r[1]];
3091 } else if (strncmp(data, "status: ", 8) == 0) {
3092 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3093 [delegate_ setProgressTitle:string];
3094 } else if (pmstatus_r(data, size)) {
3095 std::string type([pmstatus_r[1] UTF8String]);
3096 NSString *id = pmstatus_r[2];
3097
3098 float percent([pmstatus_r[3] floatValue]);
3099 [delegate_ setProgressPercent:(percent / 100)];
3100
3101 NSString *string = pmstatus_r[4];
3102
3103 if (type == "pmerror")
3104 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3105 withObject:[NSArray arrayWithObjects:string, id, nil]
3106 waitUntilDone:YES
3107 ];
3108 else if (type == "pmstatus") {
3109 [delegate_ setProgressTitle:string];
3110 } else if (type == "pmconffile")
3111 [delegate_ setConfigurationData:string];
3112 else
3113 lprintf("E:unknown pmstatus\n");
3114 } else
3115 lprintf("E:unknown status\n");
3116 }
3117
3118 _assume(false);
3119 }
3120
3121 - (void) _readOutput:(NSNumber *)fd { _pooled
3122 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3123 std::istream is(&ib);
3124 std::string line;
3125
3126 while (std::getline(is, line)) {
3127 lprintf("O:%s\n", line.c_str());
3128 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3129 }
3130
3131 _assume(false);
3132 }
3133
3134 - (FILE *) input {
3135 return input_;
3136 }
3137
3138 - (Package *) packageWithName:(NSString *)name {
3139 @synchronized (self) {
3140 if (static_cast<pkgDepCache *>(cache_) == NULL)
3141 return nil;
3142 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3143 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3144 } }
3145
3146 - (id) init {
3147 if ((self = [super init]) != nil) {
3148 policy_ = NULL;
3149 records_ = NULL;
3150 resolver_ = NULL;
3151 fetcher_ = NULL;
3152 lock_ = NULL;
3153
3154 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3155 apr_pool_create(&pool_, NULL);
3156
3157 size_t capacity(MetaFile_->active_);
3158 if (capacity == 0)
3159 capacity = 16384;
3160 else
3161 capacity += 1024;
3162
3163 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3164 deadSources_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
3165
3166 int fds[2];
3167
3168 _assert(pipe(fds) != -1);
3169 cydiafd_ = fds[1];
3170
3171 _config->Set("APT::Keep-Fds::", cydiafd_);
3172 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3173
3174 [NSThread
3175 detachNewThreadSelector:@selector(_readCydia:)
3176 toTarget:self
3177 withObject:[NSNumber numberWithInt:fds[0]]
3178 ];
3179
3180 _assert(pipe(fds) != -1);
3181 statusfd_ = fds[1];
3182
3183 [NSThread
3184 detachNewThreadSelector:@selector(_readStatus:)
3185 toTarget:self
3186 withObject:[NSNumber numberWithInt:fds[0]]
3187 ];
3188
3189 _assert(pipe(fds) != -1);
3190 _assert(dup2(fds[0], 0) != -1);
3191 _assert(close(fds[0]) != -1);
3192
3193 input_ = fdopen(fds[1], "a");
3194
3195 _assert(pipe(fds) != -1);
3196 _assert(dup2(fds[1], 1) != -1);
3197 _assert(close(fds[1]) != -1);
3198
3199 [NSThread
3200 detachNewThreadSelector:@selector(_readOutput:)
3201 toTarget:self
3202 withObject:[NSNumber numberWithInt:fds[0]]
3203 ];
3204 } return self;
3205 }
3206
3207 - (pkgCacheFile &) cache {
3208 return cache_;
3209 }
3210
3211 - (pkgDepCache::Policy *) policy {
3212 return policy_;
3213 }
3214
3215 - (pkgRecords *) records {
3216 return records_;
3217 }
3218
3219 - (pkgProblemResolver *) resolver {
3220 return resolver_;
3221 }
3222
3223 - (pkgAcquire &) fetcher {
3224 return *fetcher_;
3225 }
3226
3227 - (pkgSourceList &) list {
3228 return *list_;
3229 }
3230
3231 - (NSArray *) packages {
3232 return (NSArray *) packages_;
3233 }
3234
3235 - (NSArray *) sources {
3236 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3237 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3238 [sources addObject:i->second];
3239 [sources addObjectsFromArray:(NSArray *)deadSources_];
3240 return sources;
3241 }
3242
3243 - (NSArray *) issues {
3244 if (cache_->BrokenCount() == 0)
3245 return nil;
3246
3247 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3248
3249 for (Package *package in [self packages]) {
3250 if (![package broken])
3251 continue;
3252 pkgCache::PkgIterator pkg([package iterator]);
3253
3254 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3255 [entry addObject:[package name]];
3256 [issues addObject:entry];
3257
3258 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3259 if (ver.end())
3260 continue;
3261
3262 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3263 pkgCache::DepIterator start;
3264 pkgCache::DepIterator end;
3265 dep.GlobOr(start, end); // ++dep
3266
3267 if (!cache_->IsImportantDep(end))
3268 continue;
3269 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3270 continue;
3271
3272 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3273 [entry addObject:failure];
3274 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3275
3276 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3277 if (Package *package = [self packageWithName:name])
3278 name = [package name];
3279 [failure addObject:name];
3280
3281 pkgCache::PkgIterator target(start.TargetPkg());
3282 if (target->ProvidesList != 0)
3283 [failure addObject:@"?"];
3284 else {
3285 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3286 if (!ver.end())
3287 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3288 else if (!cache_[target].CandidateVerIter(cache_).end())
3289 [failure addObject:@"-"];
3290 else if (target->ProvidesList == 0)
3291 [failure addObject:@"!"];
3292 else
3293 [failure addObject:@"%"];
3294 }
3295
3296 _forever {
3297 if (start.TargetVer() != 0)
3298 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3299 if (start == end)
3300 break;
3301 ++start;
3302 }
3303 }
3304 }
3305
3306 return issues;
3307 }
3308
3309 - (bool) popErrorWithTitle:(NSString *)title {
3310 bool fatal(false);
3311 std::string message;
3312
3313 while (!_error->empty()) {
3314 std::string error;
3315 bool warning(!_error->PopMessage(error));
3316 if (!warning)
3317 fatal = true;
3318 for (;;) {
3319 size_t size(error.size());
3320 if (size == 0 || error[size - 1] != '\n')
3321 break;
3322 error.resize(size - 1);
3323 }
3324 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3325
3326 if (!message.empty())
3327 message += "\n\n";
3328 message += error;
3329 }
3330
3331 if (fatal && !message.empty())
3332 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3333
3334 return fatal;
3335 }
3336
3337 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3338 return [self popErrorWithTitle:title] || !success;
3339 }
3340
3341 - (void) reloadData { CYPoolStart() {
3342 @synchronized (self) {
3343 ++era_;
3344
3345 [self releasePackages];
3346
3347 sources_.clear();
3348 CFArrayRemoveAllValues(deadSources_);
3349
3350 _error->Discard();
3351
3352 delete list_;
3353 list_ = NULL;
3354 manager_ = NULL;
3355 delete lock_;
3356 lock_ = NULL;
3357 delete fetcher_;
3358 fetcher_ = NULL;
3359 delete resolver_;
3360 resolver_ = NULL;
3361 delete records_;
3362 records_ = NULL;
3363 delete policy_;
3364 policy_ = NULL;
3365
3366 cache_.Close();
3367
3368 apr_pool_clear(pool_);
3369
3370 NSRecycleZone(zone_);
3371 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3372
3373 int chk(creat("/tmp/cydia.chk", 0644));
3374 if (chk != -1)
3375 close(chk);
3376
3377 NSString *title(UCLocalize("DATABASE"));
3378
3379 _trace();
3380 if (!cache_.Open(progress_, true)) { pop:
3381 std::string error;
3382 bool warning(!_error->PopMessage(error));
3383 lprintf("cache_.Open():[%s]\n", error.c_str());
3384
3385 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3386 [delegate_ repairWithSelector:@selector(configure)];
3387 else if (error == "The package lists or status file could not be parsed or opened.")
3388 [delegate_ repairWithSelector:@selector(update)];
3389 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3390 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3391 // else if (error == "The list of sources could not be read.")
3392 else
3393 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3394
3395 if (warning)
3396 goto pop;
3397 _error->Discard();
3398 return;
3399 }
3400 _trace();
3401
3402 unlink("/tmp/cydia.chk");
3403
3404 now_ = [[NSDate date] timeIntervalSince1970];
3405
3406 policy_ = new pkgDepCache::Policy();
3407 records_ = new pkgRecords(cache_);
3408 resolver_ = new pkgProblemResolver(cache_);
3409 fetcher_ = new pkgAcquire(&status_);
3410 lock_ = NULL;
3411
3412 list_ = new pkgSourceList();
3413 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3414 return;
3415
3416 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3417 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3418 return;
3419 }
3420
3421 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3422 return;
3423
3424 if (cache_->BrokenCount() != 0) {
3425 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3426 return;
3427
3428 if (cache_->BrokenCount() != 0) {
3429 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3430 return;
3431 }
3432
3433 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3434 return;
3435 }
3436
3437 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3438 bool found = false;
3439 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3440 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3441 // XXX: this could be more intelligent
3442 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3443 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3444 if (!cached.end()) {
3445 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3446 found = true;
3447 }
3448 }
3449 if (!found)
3450 CFArrayAppendValue(deadSources_, [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3451 }
3452
3453 {
3454 /*std::vector<Package *> packages;
3455 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3456 [packages_ release];
3457 packages_ = nil;*/
3458
3459 _trace();
3460
3461 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3462 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3463 //packages.push_back(package);
3464 CFArrayAppendValue(packages_, [package retain]);
3465
3466 _trace();
3467
3468 /*if (packages.empty())
3469 packages_ = [[NSArray alloc] init];
3470 else
3471 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3472 _trace();*/
3473
3474 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3475 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3476 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3477
3478 /*_trace();
3479 PrintTimes();
3480 _trace();*/
3481
3482 _trace();
3483
3484 /*if (!packages.empty())
3485 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3486 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3487
3488 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3489
3490 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3491
3492 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3493
3494 _trace();
3495
3496 size_t count(CFArrayGetCount(packages_));
3497 MetaFile_->active_ = count;
3498
3499 for (size_t index(0); index != count; ++index)
3500 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3501
3502 _trace();
3503 }
3504 } } CYPoolEnd() _trace(); }
3505
3506 - (void) clear {
3507 @synchronized (self) {
3508 delete resolver_;
3509 resolver_ = new pkgProblemResolver(cache_);
3510
3511 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3512 if (!cache_[iterator].Keep()) {
3513 cache_->MarkKeep(iterator, false);
3514 cache_->SetReInstall(iterator, false);
3515 }
3516 }
3517 } }
3518
3519 - (void) configure {
3520 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3521 _trace();
3522 system([dpkg UTF8String]);
3523 _trace();
3524 }
3525
3526 - (bool) clean {
3527 // XXX: I don't remember this condition
3528 if (lock_ != NULL)
3529 return false;
3530
3531 FileFd Lock;
3532 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3533
3534 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3535
3536 if ([self popErrorWithTitle:title])
3537 return false;
3538
3539 pkgAcquire fetcher;
3540 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3541
3542 class LogCleaner :
3543 public pkgArchiveCleaner
3544 {
3545 protected:
3546 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3547 unlink(File);
3548 }
3549 } cleaner;
3550
3551 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3552 return false;
3553
3554 return true;
3555 }
3556
3557 - (bool) prepare {
3558 fetcher_->Shutdown();
3559
3560 pkgRecords records(cache_);
3561
3562 lock_ = new FileFd();
3563 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3564
3565 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3566
3567 if ([self popErrorWithTitle:title])
3568 return false;
3569
3570 pkgSourceList list;
3571 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3572 return false;
3573
3574 manager_ = (_system->CreatePM(cache_));
3575 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3576 return false;
3577
3578 return true;
3579 }
3580
3581 - (void) perform {
3582 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3583
3584 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3585 pkgSourceList list;
3586 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3587 return;
3588 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3589 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3590 }
3591
3592 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3593 _trace();
3594 return;
3595 }
3596
3597 [CydiaApp retainNetworkActivityIndicator];
3598
3599 bool failed = false;
3600 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3601 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3602 continue;
3603 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3604 continue;
3605
3606 std::string uri = (*item)->DescURI();
3607 std::string error = (*item)->ErrorText;
3608
3609 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3610 failed = true;
3611
3612 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3613 withObject:[NSArray arrayWithObjects:
3614 [NSString stringWithUTF8String:error.c_str()],
3615 nil]
3616 waitUntilDone:YES
3617 ];
3618 }
3619
3620 [CydiaApp releaseNetworkActivityIndicator];
3621
3622 if (failed) {
3623 _trace();
3624 return;
3625 }
3626
3627 _system->UnLock();
3628 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3629
3630 if (_error->PendingError()) {
3631 _trace();
3632 return;
3633 }
3634
3635 if (result == pkgPackageManager::Failed) {
3636 _trace();
3637 return;
3638 }
3639
3640 if (result != pkgPackageManager::Completed) {
3641 _trace();
3642 return;
3643 }
3644
3645 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3646 pkgSourceList list;
3647 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3648 return;
3649 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3650 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3651 }
3652
3653 if (![before isEqualToArray:after])
3654 [self update];
3655 }
3656
3657 - (bool) upgrade {
3658 NSString *title(UCLocalize("UPGRADE"));
3659 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3660 return false;
3661 return true;
3662 }
3663
3664 - (void) update {
3665 [self updateWithStatus:status_];
3666 }
3667
3668 - (void) updateWithStatus:(Status &)status {
3669 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3670 NSString *title(UCLocalize("REFRESHING_DATA"));
3671
3672 pkgSourceList list;
3673 if (!list.ReadMainList())
3674 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3675
3676 FileFd lock;
3677 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3678 if ([self popErrorWithTitle:title])
3679 return;
3680
3681 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3682 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3683 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3684
3685 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3686 Changed_ = true;
3687 }
3688
3689 - (void) setDelegate:(id)delegate {
3690 delegate_ = delegate;
3691 status_.setDelegate(delegate);
3692 progress_.setDelegate(delegate);
3693 }
3694
3695 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3696 SourceMap::const_iterator i(sources_.find(file->ID));
3697 return i == sources_.end() ? nil : i->second;
3698 }
3699
3700 - (NSString *) mappedSectionForPointer:(const char *)section {
3701 _H<NSString> *mapped;
3702
3703 _profile(Database$mappedSectionForPointer$Cache)
3704 mapped = &sections_[section];
3705 _end
3706
3707 if (*mapped == NULL) {
3708 size_t length(strlen(section));
3709 char spaced[length + 1];
3710
3711 _profile(Database$mappedSectionForPointer$Replace)
3712 for (size_t index(0); index != length; ++index)
3713 spaced[index] = section[index] == '_' ? ' ' : section[index];
3714 spaced[length] = '\0';
3715 _end
3716
3717 NSString *string;
3718
3719 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3720 string = [NSString stringWithUTF8String:spaced];
3721 _end
3722
3723 _profile(Database$mappedSectionForPointer$Map)
3724 string = [SectionMap_ objectForKey:string] ?: string;
3725 _end
3726
3727 *mapped = string;
3728 } return *mapped;
3729 }
3730
3731 @end
3732 /* }}} */
3733
3734 /* Web Scripting {{{ */
3735 @interface CydiaObject : NSObject {
3736 id indirect_;
3737 _transient id delegate_;
3738 }
3739
3740 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3741 @end
3742
3743 @implementation CydiaObject
3744
3745 - (void) dealloc {
3746 [indirect_ release];
3747 [super dealloc];
3748 }
3749
3750 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3751 if ((self = [super init]) != nil) {
3752 indirect_ = [indirect retain];
3753 } return self;
3754 }
3755
3756 - (void) setDelegate:(id)delegate {
3757 delegate_ = delegate;
3758 }
3759
3760 + (NSArray *) _attributeKeys {
3761 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3762 }
3763
3764 - (NSArray *) attributeKeys {
3765 return [[self class] _attributeKeys];
3766 }
3767
3768 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3769 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3770 }
3771
3772 - (NSString *) device {
3773 return [[UIDevice currentDevice] uniqueIdentifier];
3774 }
3775
3776 #if 0 // XXX: implement!
3777 - (NSString *) mac {
3778 if (![indirect_ promptForSensitive:@"Mac Address"])
3779 return nil;
3780 }
3781
3782 - (NSString *) serial {
3783 if (![indirect_ promptForSensitive:@"Serial #"])
3784 return nil;
3785 }
3786
3787 - (NSString *) firewire {
3788 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3789 return nil;
3790 }
3791
3792 - (NSString *) imei {
3793 if (![indirect_ promptForSensitive:@"IMEI"])
3794 return nil;
3795 }
3796 #endif
3797
3798 + (NSString *) webScriptNameForSelector:(SEL)selector {
3799 if (selector == @selector(close))
3800 return @"close";
3801 else if (selector == @selector(getInstalledPackages))
3802 return @"getInstalledPackages";
3803 else if (selector == @selector(getPackageById:))
3804 return @"getPackageById";
3805 else if (selector == @selector(installPackages:))
3806 return @"installPackages";
3807 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3808 return @"setButtonImage";
3809 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3810 return @"setButtonTitle";
3811 else if (selector == @selector(setPopupHook:))
3812 return @"setPopupHook";
3813 else if (selector == @selector(setSpecial:))
3814 return @"setSpecial";
3815 else if (selector == @selector(setToken:))
3816 return @"setToken";
3817 else if (selector == @selector(setViewportWidth:))
3818 return @"setViewportWidth";
3819 else if (selector == @selector(supports:))
3820 return @"supports";
3821 else if (selector == @selector(stringWithFormat:arguments:))
3822 return @"format";
3823 else if (selector == @selector(localizedStringForKey:value:table:))
3824 return @"localize";
3825 else if (selector == @selector(du:))
3826 return @"du";
3827 else if (selector == @selector(statfs:))
3828 return @"statfs";
3829 else
3830 return nil;
3831 }
3832
3833 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3834 return [self webScriptNameForSelector:selector] == nil;
3835 }
3836
3837 - (BOOL) supports:(NSString *)feature {
3838 return [feature isEqualToString:@"window.open"];
3839 }
3840
3841 - (NSArray *) getInstalledPackages {
3842 NSArray *packages([[Database sharedInstance] packages]);
3843 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3844 for (Package *package in packages)
3845 if ([package installed] != nil)
3846 [installed addObject:package];
3847 return installed;
3848 }
3849
3850 - (Package *) getPackageById:(NSString *)id {
3851 Package *package([[Database sharedInstance] packageWithName:id]);
3852 [package parse];
3853 return package;
3854 }
3855
3856 - (NSArray *) statfs:(NSString *)path {
3857 struct statfs stat;
3858
3859 if (path == nil || statfs([path UTF8String], &stat) == -1)
3860 return nil;
3861
3862 return [NSArray arrayWithObjects:
3863 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3864 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3865 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3866 nil];
3867 }
3868
3869 - (NSNumber *) du:(NSString *)path {
3870 NSNumber *value(nil);
3871
3872 int fds[2];
3873 _assert(pipe(fds) != -1);
3874
3875 pid_t pid(ExecFork());
3876 if (pid == 0) {
3877 _assert(dup2(fds[1], 1) != -1);
3878 _assert(close(fds[0]) != -1);
3879 _assert(close(fds[1]) != -1);
3880 /* XXX: this should probably not use du */
3881 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3882 exit(1);
3883 _assert(false);
3884 }
3885
3886 _assert(close(fds[1]) != -1);
3887
3888 if (FILE *du = fdopen(fds[0], "r")) {
3889 char line[1024];
3890 while (fgets(line, sizeof(line), du) != NULL) {
3891 size_t length(strlen(line));
3892 while (length != 0 && line[length - 1] == '\n')
3893 line[--length] = '\0';
3894 if (char *tab = strchr(line, '\t')) {
3895 *tab = '\0';
3896 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3897 }
3898 }
3899
3900 fclose(du);
3901 } else _assert(close(fds[0]));
3902
3903 int status;
3904 wait:
3905 if (waitpid(pid, &status, 0) == -1)
3906 if (errno == EINTR)
3907 goto wait;
3908 else _assert(false);
3909
3910 return value;
3911 }
3912
3913 - (void) close {
3914 [indirect_ close];
3915 }
3916
3917 - (void) installPackages:(NSArray *)packages {
3918 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3919 }
3920
3921 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3922 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3923 }
3924
3925 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3926 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3927 }
3928
3929 - (void) setSpecial:(id)function {
3930 [indirect_ setSpecial:function];
3931 }
3932
3933 - (void) setToken:(NSString *)token {
3934 if (Token_ != nil)
3935 [Token_ release];
3936 Token_ = [token retain];
3937
3938 [Metadata_ setObject:Token_ forKey:@"Token"];
3939 Changed_ = true;
3940 }
3941
3942 - (void) setPopupHook:(id)function {
3943 [indirect_ setPopupHook:function];
3944 }
3945
3946 - (void) setViewportWidth:(float)width {
3947 [indirect_ setViewportWidth:width];
3948 }
3949
3950 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3951 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3952 unsigned count([arguments count]);
3953 id values[count];
3954 for (unsigned i(0); i != count; ++i)
3955 values[i] = [arguments objectAtIndex:i];
3956 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3957 }
3958
3959 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3960 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3961 value = nil;
3962 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3963 table = nil;
3964 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3965 }
3966
3967 @end
3968 /* }}} */
3969
3970 /* @ Loading... Indicator {{{ */
3971 @interface CYLoadingIndicator : UIView {
3972 UIActivityIndicatorView *spinner_;
3973 UILabel *label_;
3974 UIView *container_;
3975 }
3976
3977 @property (readonly, nonatomic) UILabel *label;
3978 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3979
3980 @end
3981
3982 @implementation CYLoadingIndicator
3983
3984 - (id)initWithFrame:(CGRect)frame {
3985 if ((self = [super initWithFrame:frame])) {
3986 container_ = [[[UIView alloc] init] autorelease];
3987 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
3988
3989 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
3990 [spinner_ startAnimating];
3991 [container_ addSubview:spinner_];
3992
3993 label_ = [[[UILabel alloc] init] autorelease];
3994 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
3995 [label_ setBackgroundColor:[UIColor clearColor]];
3996 [label_ setTextColor:[UIColor blackColor]];
3997 [label_ setShadowColor:[UIColor whiteColor]];
3998 [label_ setShadowOffset:CGSizeMake(0, 1)];
3999 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
4000 [container_ addSubview:label_];
4001
4002 CGSize viewsize = frame.size;
4003 CGSize spinnersize = [spinner_ bounds].size;
4004 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4005 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4006
4007 CGRect containrect = {
4008 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4009 CGSizeMake(bothwidth, spinnersize.height)
4010 };
4011 CGRect textrect = {
4012 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4013 textsize
4014 };
4015 CGRect spinrect = {
4016 CGPointZero,
4017 spinnersize
4018 };
4019
4020 [container_ setFrame:containrect];
4021 [spinner_ setFrame:spinrect];
4022 [label_ setFrame:textrect];
4023 [self addSubview:container_];
4024 }
4025
4026 return self;
4027 }
4028
4029 - (UILabel *)label { return label_; }
4030 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
4031
4032 @end
4033 /* }}} */
4034 /* Emulated Loading Controller {{{ */
4035 @interface CYEmulatedLoadingController : CYViewController {
4036 CYLoadingIndicator *indicator_;
4037 UITabBar *tabbar_;
4038 UINavigationBar *navbar_;
4039 }
4040 @end
4041
4042 @implementation CYEmulatedLoadingController
4043
4044 - (CYEmulatedLoadingController *) init {
4045 if ((self = [super init])) {
4046 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4047
4048 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4049 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4050 [[self view] addSubview:indicator_];
4051 [indicator_ release];
4052
4053 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4054 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4055 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4056 [[self view] addSubview:tabbar_];
4057 [tabbar_ release];
4058
4059 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4060 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4061 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4062 [[self view] addSubview:navbar_];
4063 [navbar_ release];
4064 } return self;
4065 }
4066
4067 @end
4068 /* }}} */
4069
4070 /* Cydia Browser Controller {{{ */
4071 @interface CYBrowserController : BrowserController {
4072 CydiaObject *cydia_;
4073 }
4074
4075 @end
4076
4077 @implementation CYBrowserController
4078
4079 - (void) dealloc {
4080 [cydia_ release];
4081 [super dealloc];
4082 }
4083
4084 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4085 }
4086
4087 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4088 [super webView:view didClearWindowObject:window forFrame:frame];
4089
4090 WebDataSource *source([frame dataSource]);
4091 NSURLResponse *response([source response]);
4092
4093 NSURL *url([response URL]);
4094 NSString *scheme([url scheme]);
4095 NSString *host([url host]);
4096
4097 if ([response isKindOfClass:[NSHTTPURLResponse class]]) {
4098 NSHTTPURLResponse *http((NSHTTPURLResponse *) response);
4099 NSDictionary *headers([http allHeaderFields]);
4100 [self setHeaders:headers forHost:host];
4101 }
4102
4103 if (
4104 [host isEqualToString:@"cydia.saurik.com"] ||
4105 [host hasSuffix:@".cydia.saurik.com"] ||
4106 [scheme isEqualToString:@"file"]
4107 )
4108 [window setValue:cydia_ forKey:@"cydia"];
4109 }
4110
4111 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
4112 if (System_ != NULL)
4113 [request setValue:System_ forHTTPHeaderField:@"X-System"];
4114 if (Machine_ != NULL)
4115 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
4116 if (Token_ != nil)
4117 [request setValue:Token_ forHTTPHeaderField:@"X-Cydia-Token"];
4118 if (Role_ != nil)
4119 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
4120 }
4121
4122 - (NSURLRequest *) webView:(WebView *)view resource:(id)resource willSendRequest:(NSURLRequest *)request redirectResponse:(NSURLResponse *)response fromDataSource:(WebDataSource *)source {
4123 NSMutableURLRequest *copy([[super webView:view resource:resource willSendRequest:request redirectResponse:response fromDataSource:source] mutableCopy]);
4124 [self _setMoreHeaders:copy];
4125 return copy;
4126 }
4127
4128 - (void) setDelegate:(id)delegate {
4129 [super setDelegate:delegate];
4130 [cydia_ setDelegate:delegate];
4131 }
4132
4133 - (id) init {
4134 if ((self = [super initWithWidth:0 ofClass:[CYBrowserController class]]) != nil) {
4135 cydia_ = [[CydiaObject alloc] initWithDelegate:indirect_];
4136
4137 WebView *webview([[webview_ _documentView] webView]);
4138
4139 Package *package([[Database sharedInstance] packageWithName:@"cydia"]);
4140
4141 NSString *application = package == nil ? @"Cydia" : [NSString
4142 stringWithFormat:@"Cydia/%@",
4143 [package installed]
4144 ];
4145
4146 if (Safari_ != nil)
4147 application = [NSString stringWithFormat:@"Safari/%@ %@", Safari_, application];
4148 if (Build_ != nil)
4149 application = [NSString stringWithFormat:@"Mobile/%@ %@", Build_, application];
4150 if (Product_ != nil)
4151 application = [NSString stringWithFormat:@"Version/%@ %@", Product_, application];
4152
4153 [webview setApplicationNameForUserAgent:application];
4154 } return self;
4155 }
4156
4157 @end
4158 /* }}} */
4159
4160 /* Confirmation Controller {{{ */
4161 bool DepSubstrate(const pkgCache::VerIterator &iterator) {
4162 if (!iterator.end())
4163 for (pkgCache::DepIterator dep(iterator.DependsList()); !dep.end(); ++dep) {
4164 if (dep->Type != pkgCache::Dep::Depends && dep->Type != pkgCache::Dep::PreDepends)
4165 continue;
4166 pkgCache::PkgIterator package(dep.TargetPkg());
4167 if (package.end())
4168 continue;
4169 if (strcmp(package.Name(), "mobilesubstrate") == 0)
4170 return true;
4171 }
4172
4173 return false;
4174 }
4175
4176 @protocol ConfirmationControllerDelegate
4177 - (void) cancelAndClear:(bool)clear;
4178 - (void) confirmWithNavigationController:(UINavigationController *)navigation;
4179 - (void) queue;
4180 @end
4181
4182 @interface ConfirmationController : CYBrowserController {
4183 _transient Database *database_;
4184 UIAlertView *essential_;
4185 NSArray *changes_;
4186 NSArray *issues_;
4187 NSArray *sizes_;
4188 BOOL substrate_;
4189 }
4190
4191 - (id) initWithDatabase:(Database *)database;
4192
4193 @end
4194
4195 @implementation ConfirmationController
4196
4197 - (void) dealloc {
4198 [changes_ release];
4199 if (issues_ != nil)
4200 [issues_ release];
4201 [sizes_ release];
4202 if (essential_ != nil)
4203 [essential_ release];
4204 [super dealloc];
4205 }
4206
4207 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4208 NSString *context([alert context]);
4209
4210 if ([context isEqualToString:@"remove"]) {
4211 if (button == [alert cancelButtonIndex]) {
4212 [self dismissModalViewControllerAnimated:YES];
4213 } else if (button == [alert firstOtherButtonIndex]) {
4214 if (substrate_)
4215 Finish_ = 2;
4216 [delegate_ confirmWithNavigationController:[self navigationController]];
4217 }
4218
4219 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4220 } else if ([context isEqualToString:@"unable"]) {
4221 [self dismissModalViewControllerAnimated:YES];
4222 [alert dismissWithClickedButtonIndex:-1 animated:YES];
4223 } else {
4224 [super alertView:alert clickedButtonAtIndex:button];
4225 }
4226 }
4227
4228 - (void) _doContinue {
4229 [self dismissModalViewControllerAnimated:YES];
4230 [delegate_ cancelAndClear:NO];
4231 }
4232
4233 - (id) invokeDefaultMethodWithArguments:(NSArray *)args {
4234 [self performSelectorOnMainThread:@selector(_doContinue) withObject:nil waitUntilDone:NO];
4235 return nil;
4236 }
4237
4238 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4239 [super webView:view didClearWindowObject:window forFrame:frame];
4240 [window setValue:changes_ forKey:@"changes"];
4241 [window setValue:issues_ forKey:@"issues"];
4242 [window setValue:sizes_ forKey:@"sizes"];
4243 [window setValue:self forKey:@"queue"];
4244 }
4245
4246 - (id) initWithDatabase:(Database *)database {
4247 if ((self = [super init]) != nil) {
4248 database_ = database;
4249
4250 [[self navigationItem] setTitle:UCLocalize("CONFIRM")];
4251
4252 NSMutableArray *installing = [NSMutableArray arrayWithCapacity:16];
4253 NSMutableArray *reinstalling = [NSMutableArray arrayWithCapacity:16];
4254 NSMutableArray *upgrading = [NSMutableArray arrayWithCapacity:16];
4255 NSMutableArray *downgrading = [NSMutableArray arrayWithCapacity:16];
4256 NSMutableArray *removing = [NSMutableArray arrayWithCapacity:16];
4257
4258 bool remove(false);
4259
4260 pkgDepCache::Policy *policy([database_ policy]);
4261
4262 pkgCacheFile &cache([database_ cache]);
4263 NSArray *packages = [database_ packages];
4264 for (Package *package in packages) {
4265 pkgCache::PkgIterator iterator = [package iterator];
4266 pkgDepCache::StateCache &state(cache[iterator]);
4267
4268 NSString *name([package name]);
4269
4270 if (state.NewInstall())
4271 [installing addObject:name];
4272 else if (!state.Delete() && (state.iFlags & pkgDepCache::ReInstall) == pkgDepCache::ReInstall)
4273 [reinstalling addObject:name];
4274 else if (state.Upgrade())
4275 [upgrading addObject:name];
4276 else if (state.Downgrade())
4277 [downgrading addObject:name];
4278 else if (state.Delete()) {
4279 if ([package essential])
4280 remove = true;
4281 [removing addObject:name];
4282 } else continue;
4283
4284 substrate_ |= DepSubstrate(policy->GetCandidateVer(iterator));
4285 substrate_ |= DepSubstrate(iterator.CurrentVer());
4286 }
4287
4288 if (!remove)
4289 essential_ = nil;
4290 else if (Advanced_) {
4291 NSString *parenthetical(UCLocalize("PARENTHETICAL"));
4292
4293 essential_ = [[UIAlertView alloc]
4294 initWithTitle:UCLocalize("REMOVING_ESSENTIALS")
4295 message:UCLocalize("REMOVING_ESSENTIALS_EX")
4296 delegate:self
4297 cancelButtonTitle:[NSString stringWithFormat:parenthetical, UCLocalize("CANCEL_OPERATION"), UCLocalize("SAFE")]
4298 otherButtonTitles:[NSString stringWithFormat:parenthetical, UCLocalize("FORCE_REMOVAL"), UCLocalize("UNSAFE")], nil
4299 ];
4300
4301 [essential_ setContext:@"remove"];
4302 } else {
4303 essential_ = [[UIAlertView alloc]
4304 initWithTitle:UCLocalize("UNABLE_TO_COMPLY")
4305 message:UCLocalize("UNABLE_TO_COMPLY_EX")
4306 delegate:self
4307 cancelButtonTitle:UCLocalize("OKAY")
4308 otherButtonTitles:nil
4309 ];
4310
4311 [essential_ setContext:@"unable"];
4312 }
4313
4314 changes_ = [[NSArray alloc] initWithObjects:
4315 installing,
4316 reinstalling,
4317 upgrading,
4318 downgrading,
4319 removing,
4320 nil];
4321
4322 issues_ = [database_ issues];
4323 if (issues_ != nil)
4324 issues_ = [issues_ retain];
4325
4326 sizes_ = [[NSArray alloc] initWithObjects:
4327 SizeString([database_ fetcher].FetchNeeded()),
4328 SizeString([database_ fetcher].PartialPresent()),
4329 nil];
4330
4331 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"confirm" ofType:@"html"]]];
4332
4333 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
4334 initWithTitle:UCLocalize("CANCEL")
4335 // OLD: [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("CANCEL"), UCLocalize("QUEUE")]
4336 style:UIBarButtonItemStylePlain
4337 target:self
4338 action:@selector(cancelButtonClicked)
4339 ] autorelease]];
4340 } return self;
4341 }
4342
4343 - (void) applyRightButton {
4344 #if !AlwaysReload && !IgnoreInstall
4345 if (issues_ == nil && ![self isLoading])
4346 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
4347 initWithTitle:UCLocalize("CONFIRM")
4348 style:UIBarButtonItemStylePlain
4349 target:self
4350 action:@selector(confirmButtonClicked)
4351 ] autorelease]];
4352 else
4353 [super applyRightButton];
4354 #else
4355 [[self navigationItem] setRightBarButtonItem:nil];
4356 #endif
4357 }
4358
4359 - (void) cancelButtonClicked {
4360 [self dismissModalViewControllerAnimated:YES];
4361 [delegate_ cancelAndClear:YES];
4362 }
4363
4364 #if !AlwaysReload
4365 - (void) confirmButtonClicked {
4366 #if IgnoreInstall
4367 return;
4368 #endif
4369 if (essential_ != nil)
4370 [essential_ show];
4371 else {
4372 if (substrate_)
4373 Finish_ = 2;
4374 [delegate_ confirmWithNavigationController:[self navigationController]];
4375 }
4376 }
4377 #endif
4378
4379 @end
4380 /* }}} */
4381
4382 /* Progress Data {{{ */
4383 @interface ProgressData : NSObject {
4384 SEL selector_;
4385 // XXX: should these really both be _transient?
4386 _transient id target_;
4387 _transient id object_;
4388 }
4389
4390 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object;
4391
4392 - (SEL) selector;
4393 - (id) target;
4394 - (id) object;
4395 @end
4396
4397 @implementation ProgressData
4398
4399 - (ProgressData *) initWithSelector:(SEL)selector target:(id)target object:(id)object {
4400 if ((self = [super init]) != nil) {
4401 selector_ = selector;
4402 target_ = target;
4403 object_ = object;
4404 } return self;
4405 }
4406
4407 - (SEL) selector {
4408 return selector_;
4409 }
4410
4411 - (id) target {
4412 return target_;
4413 }
4414
4415 - (id) object {
4416 return object_;
4417 }
4418
4419 @end
4420 /* }}} */
4421 /* Progress Controller {{{ */
4422 @interface ProgressController : CYViewController <
4423 ConfigurationDelegate,
4424 ProgressDelegate
4425 > {
4426 _transient Database *database_;
4427 UIProgressBar *progress_;
4428 UITextView *output_;
4429 UITextLabel *status_;
4430 UIPushButton *close_;
4431 BOOL running_;
4432 SHA1SumValue springlist_;
4433 SHA1SumValue notifyconf_;
4434 NSString *title_;
4435 }
4436
4437 - (id) initWithDatabase:(Database *)database delegate:(id)delegate;
4438
4439 - (void) _retachThread;
4440 - (void) _detachNewThreadData:(ProgressData *)data;
4441 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title;
4442
4443 - (BOOL) isRunning;
4444
4445 @end
4446
4447 @protocol ProgressControllerDelegate
4448 - (void) progressControllerIsComplete:(ProgressController *)sender;
4449 @end
4450
4451 @implementation ProgressController
4452
4453 - (void) dealloc {
4454 [database_ setDelegate:nil];
4455 [progress_ release];
4456 [output_ release];
4457 [status_ release];
4458 [close_ release];
4459 if (title_ != nil)
4460 [title_ release];
4461 [super dealloc];
4462 }
4463
4464 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
4465 if ((self = [super init]) != nil) {
4466 database_ = database;
4467 [database_ setDelegate:self];
4468 delegate_ = delegate;
4469
4470 [[self view] setBackgroundColor:[UIColor colorWithRed:0.0f green:0.0f blue:0.0f alpha:1.0f]];
4471
4472 progress_ = [[UIProgressBar alloc] init];
4473 [progress_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4474 [progress_ setStyle:0];
4475
4476 status_ = [[UITextLabel alloc] init];
4477 [status_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4478 [status_ setColor:[UIColor whiteColor]];
4479 [status_ setBackgroundColor:[UIColor clearColor]];
4480 [status_ setCentersHorizontally:YES];
4481 //[status_ setFont:font];
4482
4483 output_ = [[UITextView alloc] init];
4484 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4485 //[output_ setTextFont:@"Courier New"];
4486 [output_ setFont:[[output_ font] fontWithSize:12]];
4487 [output_ setTextColor:[UIColor whiteColor]];
4488 [output_ setBackgroundColor:[UIColor clearColor]];
4489 [output_ setMarginTop:0];
4490 [output_ setAllowsRubberBanding:YES];
4491 [output_ setEditable:NO];
4492 [[self view] addSubview:output_];
4493
4494 close_ = [[UIPushButton alloc] init];
4495 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4496 [close_ setAutosizesToFit:NO];
4497 [close_ setDrawsShadow:YES];
4498 [close_ setStretchBackground:YES];
4499 [close_ setEnabled:YES];
4500 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4501 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4502 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4503 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4504 } return self;
4505 }
4506
4507 - (void) positionViews {
4508 CGRect bounds = [[self view] bounds];
4509 CGSize prgsize = [UIProgressBar defaultSize];
4510
4511 CGRect prgrect = {{
4512 (bounds.size.width - prgsize.width) / 2,
4513 bounds.size.height - prgsize.height - 20
4514 }, prgsize};
4515
4516 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4517
4518 [progress_ setFrame:prgrect];
4519 [status_ setFrame:CGRectMake(
4520 10,
4521 bounds.size.height - prgsize.height - 50,
4522 bounds.size.width - 20,
4523 24
4524 )];
4525 [output_ setFrame:CGRectMake(
4526 10,
4527 20,
4528 bounds.size.width - 20,
4529 bounds.size.height - 96
4530 )];
4531 [close_ setFrame:CGRectMake(
4532 (bounds.size.width - closewidth) / 2,
4533 bounds.size.height - prgsize.height - 50,
4534 closewidth,
4535 32 + prgsize.height
4536 )];
4537 }
4538
4539 - (void) viewWillAppear:(BOOL)animated {
4540 [super viewDidAppear:animated];
4541 [[self navigationItem] setHidesBackButton:YES];
4542 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4543
4544 [self positionViews];
4545 }
4546
4547 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4548 [self positionViews];
4549 }
4550
4551 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4552 NSString *context([alert context]);
4553
4554 if ([context isEqualToString:@"conffile"]) {
4555 FILE *input = [database_ input];
4556 if (button == [alert cancelButtonIndex])
4557 fprintf(input, "N\n");
4558 else if (button == [alert firstOtherButtonIndex])
4559 fprintf(input, "Y\n");
4560 fflush(input);
4561 }
4562 }
4563
4564 - (void) closeButtonPushed {
4565 running_ = NO;
4566
4567 UpdateExternalStatus(0);
4568
4569 switch (Finish_) {
4570 case 0:
4571 [self dismissModalViewControllerAnimated:YES];
4572 break;
4573
4574 case 1:
4575 [delegate_ terminateWithSuccess];
4576 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4577 [delegate_ suspendWithAnimation:YES];
4578 else
4579 [delegate_ suspend];*/
4580 break;
4581
4582 case 2:
4583 _trace();
4584 goto reload;
4585
4586 case 3:
4587 _trace();
4588 goto reload;
4589
4590 reload:
4591 system("/usr/bin/sbreload");
4592 _trace();
4593 break;
4594
4595 case 4:
4596 _trace();
4597 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4598 SBReboot(SBSSpringBoardServerPort());
4599 else
4600 reboot2(RB_AUTOBOOT);
4601 break;
4602 }
4603 }
4604
4605 - (void) _retachThread {
4606 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4607
4608 [[self view] addSubview:close_];
4609 [progress_ removeFromSuperview];
4610 [status_ removeFromSuperview];
4611
4612 [database_ popErrorWithTitle:title_];
4613 [delegate_ progressControllerIsComplete:self];
4614
4615 if (Finish_ < 4) {
4616 FileFd file;
4617 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4618 _error->Discard();
4619 else {
4620 MMap mmap(file, MMap::ReadOnly);
4621 SHA1Summation sha1;
4622 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4623 if (!(notifyconf_ == sha1.Result()))
4624 Finish_ = 4;
4625 }
4626 }
4627
4628 if (Finish_ < 3) {
4629 FileFd file;
4630 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4631 _error->Discard();
4632 else {
4633 MMap mmap(file, MMap::ReadOnly);
4634 SHA1Summation sha1;
4635 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4636 if (!(springlist_ == sha1.Result()))
4637 Finish_ = 3;
4638 }
4639 }
4640
4641 switch (Finish_) {
4642 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4643 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4644 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4645 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4646 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4647 }
4648
4649 _trace();
4650 system("su -c /usr/bin/uicache mobile");
4651 _trace();
4652
4653 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4654
4655 [delegate_ setStatusBarShowsProgress:NO];
4656 }
4657
4658 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4659 [[data target] performSelector:[data selector] withObject:[data object]];
4660 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4661 }
4662
4663 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4664 UpdateExternalStatus(1);
4665
4666 if (title_ != nil)
4667 [title_ release];
4668 if (title == nil)
4669 title_ = nil;
4670 else
4671 title_ = [title retain];
4672
4673 [[self navigationItem] setTitle:title_];
4674
4675 [status_ setText:nil];
4676 [output_ setText:@""];
4677 [progress_ setProgress:0];
4678
4679 [close_ removeFromSuperview];
4680 [[self view] addSubview:progress_];
4681 [[self view] addSubview:status_];
4682
4683 [delegate_ setStatusBarShowsProgress:YES];
4684 running_ = YES;
4685
4686 {
4687 FileFd file;
4688 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4689 _error->Discard();
4690 else {
4691 MMap mmap(file, MMap::ReadOnly);
4692 SHA1Summation sha1;
4693 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4694 notifyconf_ = sha1.Result();
4695 }
4696 }
4697
4698 {
4699 FileFd file;
4700 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4701 _error->Discard();
4702 else {
4703 MMap mmap(file, MMap::ReadOnly);
4704 SHA1Summation sha1;
4705 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4706 springlist_ = sha1.Result();
4707 }
4708 }
4709
4710 [NSThread
4711 detachNewThreadSelector:@selector(_detachNewThreadData:)
4712 toTarget:self
4713 withObject:[[[ProgressData alloc]
4714 initWithSelector:selector
4715 target:target
4716 object:object
4717 ] autorelease]
4718 ];
4719 }
4720
4721 - (void) repairWithSelector:(SEL)selector {
4722 [self
4723 detachNewThreadSelector:selector
4724 toTarget:database_
4725 withObject:nil
4726 title:UCLocalize("REPAIRING")
4727 ];
4728 }
4729
4730 - (void) setConfigurationData:(NSString *)data {
4731 [self
4732 performSelectorOnMainThread:@selector(_setConfigurationData:)
4733 withObject:data
4734 waitUntilDone:YES
4735 ];
4736 }
4737
4738 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4739 CYActionSheet *sheet([[[CYActionSheet alloc]
4740 initWithTitle:title
4741 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4742 defaultButtonIndex:0
4743 ] autorelease]);
4744
4745 [sheet setMessage:error];
4746 [sheet yieldToPopupAlertAnimated:YES];
4747 [sheet dismiss];
4748 }
4749
4750 - (void) setProgressTitle:(NSString *)title {
4751 [self
4752 performSelectorOnMainThread:@selector(_setProgressTitle:)
4753 withObject:title
4754 waitUntilDone:YES
4755 ];
4756 }
4757
4758 - (void) setProgressPercent:(float)percent {
4759 [self
4760 performSelectorOnMainThread:@selector(_setProgressPercent:)
4761 withObject:[NSNumber numberWithFloat:percent]
4762 waitUntilDone:YES
4763 ];
4764 }
4765
4766 - (void) startProgress {
4767 }
4768
4769 - (void) addProgressOutput:(NSString *)output {
4770 [self
4771 performSelectorOnMainThread:@selector(_addProgressOutput:)
4772 withObject:output
4773 waitUntilDone:YES
4774 ];
4775 }
4776
4777 - (bool) isCancelling:(size_t)received {
4778 return false;
4779 }
4780
4781 - (void) _setConfigurationData:(NSString *)data {
4782 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4783
4784 if (!conffile_r(data)) {
4785 lprintf("E:invalid conffile\n");
4786 return;
4787 }
4788
4789 NSString *ofile = conffile_r[1];
4790 //NSString *nfile = conffile_r[2];
4791
4792 UIAlertView *alert = [[[UIAlertView alloc]
4793 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4794 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4795 delegate:self
4796 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4797 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4798 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4799 nil
4800 ] autorelease];
4801
4802 [alert setContext:@"conffile"];
4803 [alert show];
4804 }
4805
4806 - (void) _setProgressTitle:(NSString *)title {
4807 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4808 for (size_t i(0), e([words count]); i != e; ++i) {
4809 NSString *word([words objectAtIndex:i]);
4810 if (Package *package = [database_ packageWithName:word])
4811 [words replaceObjectAtIndex:i withObject:[package name]];
4812 }
4813
4814 [status_ setText:[words componentsJoinedByString:@" "]];
4815 }
4816
4817 - (void) _setProgressPercent:(NSNumber *)percent {
4818 [progress_ setProgress:[percent floatValue]];
4819 }
4820
4821 - (void) _addProgressOutput:(NSString *)output {
4822 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4823 CGSize size = [output_ contentSize];
4824 CGPoint offset = [output_ contentOffset];
4825 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4826 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4827 [output_ scrollRectToVisible:rect animated:YES];
4828 }
4829 }
4830
4831 - (BOOL) isRunning {
4832 return running_;
4833 }
4834
4835 @end
4836 /* }}} */
4837
4838 /* Cell Content View {{{ */
4839 @protocol ContentDelegate
4840 - (void) drawContentRect:(CGRect)rect;
4841 @end
4842
4843 @interface ContentView : UIView {
4844 _transient id<ContentDelegate> delegate_;
4845 }
4846
4847 @end
4848
4849 @implementation ContentView
4850
4851 - (id) initWithFrame:(CGRect)frame {
4852 if ((self = [super initWithFrame:frame]) != nil) {
4853 [self setNeedsDisplayOnBoundsChange:YES];
4854 } return self;
4855 }
4856
4857 - (void) setDelegate:(id<ContentDelegate>)delegate {
4858 delegate_ = delegate;
4859 }
4860
4861 - (void) drawRect:(CGRect)rect {
4862 [super drawRect:rect];
4863 [delegate_ drawContentRect:rect];
4864 }
4865
4866 @end
4867 /* }}} */
4868 /* Cydia TableView Cell {{{ */
4869 @interface CYTableViewCell : UITableViewCell {
4870 ContentView *content_;
4871 bool highlighted_;
4872 }
4873
4874 @end
4875
4876 @implementation CYTableViewCell
4877
4878 - (void) dealloc {
4879 [content_ release];
4880 [super dealloc];
4881 }
4882
4883 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4884 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4885
4886 if (view == content_) {
4887 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4888 highlighted_ = highlighted;
4889 }
4890
4891 [super _updateHighlightColorsForView:view highlighted:highlighted];
4892 }
4893
4894 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4895 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4896 highlighted_ = selected;
4897
4898 [super setSelected:selected animated:animated];
4899 [content_ setNeedsDisplay];
4900 }
4901
4902 @end
4903 /* }}} */
4904
4905 /* Package Cell {{{ */
4906 @interface PackageCell : CYTableViewCell <
4907 ContentDelegate
4908 > {
4909 UIImage *icon_;
4910 NSString *name_;
4911 NSString *description_;
4912 bool commercial_;
4913 NSString *source_;
4914 UIImage *badge_;
4915 Package *package_;
4916 UIImage *placard_;
4917 }
4918
4919 - (PackageCell *) init;
4920 - (void) setPackage:(Package *)package;
4921
4922 - (void) drawContentRect:(CGRect)rect;
4923
4924 @end
4925
4926 @implementation PackageCell
4927
4928 - (void) clearPackage {
4929 if (icon_ != nil) {
4930 [icon_ release];
4931 icon_ = nil;
4932 }
4933
4934 if (name_ != nil) {
4935 [name_ release];
4936 name_ = nil;
4937 }
4938
4939 if (description_ != nil) {
4940 [description_ release];
4941 description_ = nil;
4942 }
4943
4944 if (source_ != nil) {
4945 [source_ release];
4946 source_ = nil;
4947 }
4948
4949 if (badge_ != nil) {
4950 [badge_ release];
4951 badge_ = nil;
4952 }
4953
4954 if (placard_ != nil) {
4955 [placard_ release];
4956 placard_ = nil;
4957 }
4958
4959 [package_ release];
4960 package_ = nil;
4961 }
4962
4963 - (void) dealloc {
4964 [self clearPackage];
4965 [super dealloc];
4966 }
4967
4968 - (PackageCell *) init {
4969 CGRect frame(CGRectMake(0, 0, 320, 74));
4970 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4971 UIView *content([self contentView]);
4972 CGRect bounds([content bounds]);
4973
4974 content_ = [[ContentView alloc] initWithFrame:bounds];
4975 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4976 [content addSubview:content_];
4977
4978 [content_ setDelegate:self];
4979 [content_ setOpaque:YES];
4980 } return self;
4981 }
4982
4983 - (void) _setBackgroundColor {
4984 UIColor *color;
4985 if (NSString *mode = [package_ mode]) {
4986 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4987 color = remove ? RemovingColor_ : InstallingColor_;
4988 } else
4989 color = [UIColor whiteColor];
4990
4991 [content_ setBackgroundColor:color];
4992 [self setNeedsDisplay];
4993 }
4994
4995 - (NSString *) accessibilityLabel {
4996 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
4997 }
4998
4999 - (void) setPackage:(Package *)package {
5000 [self clearPackage];
5001 [package parse];
5002
5003 Source *source = [package source];
5004
5005 icon_ = [[package icon] retain];
5006 name_ = [[package name] retain];
5007
5008 if (IsWildcat_)
5009 description_ = [package longDescription];
5010 if (description_ == nil)
5011 description_ = [package shortDescription];
5012 if (description_ != nil)
5013 description_ = [description_ retain];
5014
5015 commercial_ = [package isCommercial];
5016
5017 package_ = [package retain];
5018
5019 NSString *label = nil;
5020 bool trusted = false;
5021
5022 if (source != nil) {
5023 label = [source label];
5024 trusted = [source trusted];
5025 } else if ([[package id] isEqualToString:@"firmware"])
5026 label = UCLocalize("APPLE");
5027 else
5028 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5029
5030 NSString *from(label);
5031
5032 NSString *section = [package simpleSection];
5033 if (section != nil && ![section isEqualToString:label]) {
5034 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5035 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5036 }
5037
5038 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5039 source_ = [from retain];
5040
5041 if (NSString *purpose = [package primaryPurpose])
5042 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5043 badge_ = [badge_ retain];
5044
5045 if ([package installed] != nil)
5046 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
5047 placard_ = [placard_ retain];
5048
5049 [self _setBackgroundColor];
5050 [content_ setNeedsDisplay];
5051 }
5052
5053 - (void) drawContentRect:(CGRect)rect {
5054 bool highlighted(highlighted_);
5055 float width([self bounds].size.width);
5056
5057 #if 0
5058 CGContextRef context(UIGraphicsGetCurrentContext());
5059 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5060 CGContextFillRect(context, rect);
5061 #endif
5062
5063 if (icon_ != nil) {
5064 CGRect rect;
5065 rect.size = [icon_ size];
5066
5067 rect.size.width /= 2;
5068 rect.size.height /= 2;
5069
5070 rect.origin.x = 25 - rect.size.width / 2;
5071 rect.origin.y = 25 - rect.size.height / 2;
5072
5073 [icon_ drawInRect:rect];
5074 }
5075
5076 if (badge_ != nil) {
5077 CGRect rect;
5078 rect.size = [badge_ size];
5079
5080 rect.size.width /= 2;
5081 rect.size.height /= 2;
5082
5083 rect.origin.x = 36 - rect.size.width / 2;
5084 rect.origin.y = 36 - rect.size.height / 2;
5085
5086 [badge_ drawInRect:rect];
5087 }
5088
5089 if (highlighted)
5090 UISetColor(White_);
5091
5092 if (!highlighted)
5093 UISetColor(commercial_ ? Purple_ : Black_);
5094 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5095 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5096
5097 if (!highlighted)
5098 UISetColor(commercial_ ? Purplish_ : Gray_);
5099 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5100
5101 if (placard_ != nil)
5102 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5103 }
5104
5105 @end
5106 /* }}} */
5107 /* Section Cell {{{ */
5108 @interface SectionCell : CYTableViewCell <
5109 ContentDelegate
5110 > {
5111 NSString *basic_;
5112 NSString *section_;
5113 NSString *name_;
5114 NSString *count_;
5115 UIImage *icon_;
5116 UISwitch *switch_;
5117 BOOL editing_;
5118 }
5119
5120 - (void) setSection:(Section *)section editing:(BOOL)editing;
5121
5122 @end
5123
5124 @implementation SectionCell
5125
5126 - (void) clearSection {
5127 if (basic_ != nil) {
5128 [basic_ release];
5129 basic_ = nil;
5130 }
5131
5132 if (section_ != nil) {
5133 [section_ release];
5134 section_ = nil;
5135 }
5136
5137 if (name_ != nil) {
5138 [name_ release];
5139 name_ = nil;
5140 }
5141
5142 if (count_ != nil) {
5143 [count_ release];
5144 count_ = nil;
5145 }
5146 }
5147
5148 - (void) dealloc {
5149 [self clearSection];
5150 [icon_ release];
5151 [switch_ release];
5152 [super dealloc];
5153 }
5154
5155 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5156 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5157 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5158 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5159 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5160
5161 UIView *content([self contentView]);
5162 CGRect bounds([content bounds]);
5163
5164 content_ = [[ContentView alloc] initWithFrame:bounds];
5165 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5166 [content addSubview:content_];
5167 [content_ setBackgroundColor:[UIColor whiteColor]];
5168
5169 [content_ setDelegate:self];
5170 } return self;
5171 }
5172
5173 - (void) onSwitch:(id)sender {
5174 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5175 if (metadata == nil) {
5176 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5177 [Sections_ setObject:metadata forKey:basic_];
5178 }
5179
5180 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5181 Changed_ = true;
5182 }
5183
5184 - (void) setSection:(Section *)section editing:(BOOL)editing {
5185 if (editing != editing_) {
5186 if (editing_)
5187 [switch_ removeFromSuperview];
5188 else
5189 [self addSubview:switch_];
5190 editing_ = editing;
5191 }
5192
5193 [self clearSection];
5194
5195 if (section == nil) {
5196 name_ = [UCLocalize("ALL_PACKAGES") retain];
5197 count_ = nil;
5198 } else {
5199 basic_ = [section name];
5200 if (basic_ != nil)
5201 basic_ = [basic_ retain];
5202
5203 section_ = [section localized];
5204 if (section_ != nil)
5205 section_ = [section_ retain];
5206
5207 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5208 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5209
5210 if (editing_)
5211 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5212 }
5213
5214 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5215 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5216
5217 [content_ setNeedsDisplay];
5218 }
5219
5220 - (void) setFrame:(CGRect)frame {
5221 [super setFrame:frame];
5222
5223 CGRect rect([switch_ frame]);
5224 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5225 }
5226
5227 - (NSString *) accessibilityLabel {
5228 return name_;
5229 }
5230
5231 - (void) drawContentRect:(CGRect)rect {
5232 bool highlighted(highlighted_ && !editing_);
5233
5234 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5235
5236 if (highlighted)
5237 UISetColor(White_);
5238
5239 float width(rect.size.width);
5240 if (editing_)
5241 width -= 87;
5242
5243 if (!highlighted)
5244 UISetColor(Black_);
5245 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5246
5247 CGSize size = [count_ sizeWithFont:Font14_];
5248
5249 UISetColor(White_);
5250 if (count_ != nil)
5251 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5252 }
5253
5254 @end
5255 /* }}} */
5256
5257 /* File Table {{{ */
5258 @interface FileTable : CYViewController <
5259 UITableViewDataSource,
5260 UITableViewDelegate
5261 > {
5262 _transient Database *database_;
5263 Package *package_;
5264 NSString *name_;
5265 NSMutableArray *files_;
5266 UITableView *list_;
5267 }
5268
5269 - (id) initWithDatabase:(Database *)database;
5270 - (void) setPackage:(Package *)package;
5271
5272 @end
5273
5274 @implementation FileTable
5275
5276 - (void) dealloc {
5277 if (package_ != nil)
5278 [package_ release];
5279 if (name_ != nil)
5280 [name_ release];
5281 [files_ release];
5282 [list_ release];
5283 [super dealloc];
5284 }
5285
5286 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5287 return files_ == nil ? 0 : [files_ count];
5288 }
5289
5290 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5291 return 24.0f;
5292 }*/
5293
5294 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5295 static NSString *reuseIdentifier = @"Cell";
5296
5297 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5298 if (cell == nil) {
5299 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5300 [cell setFont:[UIFont systemFontOfSize:16]];
5301 }
5302 [cell setText:[files_ objectAtIndex:indexPath.row]];
5303 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5304
5305 return cell;
5306 }
5307
5308 - (id) initWithDatabase:(Database *)database {
5309 if ((self = [super init]) != nil) {
5310 database_ = database;
5311
5312 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5313
5314 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5315
5316 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5317 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5318 [list_ setRowHeight:24.0f];
5319 [[self view] addSubview:list_];
5320
5321 [list_ setDataSource:self];
5322 [list_ setDelegate:self];
5323 } return self;
5324 }
5325
5326 - (void) setPackage:(Package *)package {
5327 if (package_ != nil) {
5328 [package_ autorelease];
5329 package_ = nil;
5330 }
5331
5332 if (name_ != nil) {
5333 [name_ release];
5334 name_ = nil;
5335 }
5336
5337 [files_ removeAllObjects];
5338
5339 if (package != nil) {
5340 package_ = [package retain];
5341 name_ = [[package id] retain];
5342
5343 if (NSArray *files = [package files])
5344 [files_ addObjectsFromArray:files];
5345
5346 if ([files_ count] != 0) {
5347 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5348 [files_ removeObjectAtIndex:0];
5349 [files_ sortUsingSelector:@selector(compareByPath:)];
5350
5351 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5352 [stack addObject:@"/"];
5353
5354 for (int i(0), e([files_ count]); i != e; ++i) {
5355 NSString *file = [files_ objectAtIndex:i];
5356 while (![file hasPrefix:[stack lastObject]])
5357 [stack removeLastObject];
5358 NSString *directory = [stack lastObject];
5359 [stack addObject:[file stringByAppendingString:@"/"]];
5360 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5361 ([stack count] - 2) * 3, "",
5362 [file substringFromIndex:[directory length]]
5363 ]];
5364 }
5365 }
5366 }
5367
5368 [list_ reloadData];
5369 }
5370
5371 - (void) reloadData {
5372 [self setPackage:[database_ packageWithName:name_]];
5373 }
5374
5375 @end
5376 /* }}} */
5377 /* Package Controller {{{ */
5378 @interface CYPackageController : CYBrowserController <
5379 UIActionSheetDelegate
5380 > {
5381 _transient Database *database_;
5382 Package *package_;
5383 NSString *name_;
5384 bool commercial_;
5385 NSMutableArray *buttons_;
5386 UIBarButtonItem *button_;
5387 }
5388
5389 - (id) initWithDatabase:(Database *)database;
5390 - (void) setPackage:(Package *)package;
5391
5392 @end
5393
5394 @implementation CYPackageController
5395
5396 - (void) dealloc {
5397 if (package_ != nil)
5398 [package_ release];
5399 if (name_ != nil)
5400 [name_ release];
5401
5402 [buttons_ release];
5403
5404 if (button_ != nil)
5405 [button_ release];
5406
5407 [super dealloc];
5408 }
5409
5410 - (void) release {
5411 [super release];
5412 }
5413
5414 /* XXX: this is not safe at all... localization of /fail/ */
5415 - (void) _clickButtonWithName:(NSString *)name {
5416 if ([name isEqualToString:UCLocalize("CLEAR")])
5417 [delegate_ clearPackage:package_];
5418 else if ([name isEqualToString:UCLocalize("INSTALL")])
5419 [delegate_ installPackage:package_];
5420 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5421 [delegate_ installPackage:package_];
5422 else if ([name isEqualToString:UCLocalize("REMOVE")])
5423 [delegate_ removePackage:package_];
5424 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5425 [delegate_ installPackage:package_];
5426 else _assert(false);
5427 }
5428
5429 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5430 NSString *context([sheet context]);
5431
5432 if ([context isEqualToString:@"modify"]) {
5433 if (button != [sheet cancelButtonIndex]) {
5434 NSString *buttonName = [buttons_ objectAtIndex:button];
5435 [self _clickButtonWithName:buttonName];
5436 }
5437
5438 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5439 }
5440 }
5441
5442 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5443 [super webView:view didClearWindowObject:window forFrame:frame];
5444 [window setValue:package_ forKey:@"package"];
5445 }
5446
5447 - (bool) _allowJavaScriptPanel {
5448 return commercial_;
5449 }
5450
5451 #if !AlwaysReload
5452 - (void) _customButtonClicked {
5453 int count([buttons_ count]);
5454 if (count == 0)
5455 return;
5456
5457 if (count == 1)
5458 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5459 else {
5460 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5461 [buttons addObjectsFromArray:buttons_];
5462
5463 UIActionSheet *sheet = [[[UIActionSheet alloc]
5464 initWithTitle:nil
5465 delegate:self
5466 cancelButtonTitle:nil
5467 destructiveButtonTitle:nil
5468 otherButtonTitles:nil
5469 ] autorelease];
5470
5471 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5472 if (!IsWildcat_) {
5473 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5474 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5475 }
5476 [sheet setContext:@"modify"];
5477
5478 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5479 }
5480 }
5481
5482 // We don't want to allow non-commercial packages to do custom things to the install button,
5483 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5484 - (void) customButtonClicked {
5485 if (commercial_)
5486 [super customButtonClicked];
5487 else
5488 [self _customButtonClicked];
5489 }
5490
5491 - (void) reloadButtonClicked {
5492 // Don't reload a commerical package by tapping the loading button,
5493 // but if it's not an Install button, we should forward it on.
5494 if (![package_ uninstalled])
5495 [self _customButtonClicked];
5496 }
5497
5498 - (void) applyLoadingTitle {
5499 // Don't show "Loading" as the title. Ever.
5500 }
5501
5502 - (UIBarButtonItem *) rightButton {
5503 return button_;
5504 }
5505 #endif
5506
5507 - (id) initWithDatabase:(Database *)database {
5508 if ((self = [super init]) != nil) {
5509 database_ = database;
5510 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5511 [self loadURL:[NSURL URLWithString:CydiaURL(@"ui/package/")]];
5512 } return self;
5513 }
5514
5515 - (void) setPackage:(Package *)package {
5516 if (package_ != nil) {
5517 [package_ autorelease];
5518 package_ = nil;
5519 }
5520
5521 if (name_ != nil) {
5522 [name_ release];
5523 name_ = nil;
5524 }
5525
5526 [buttons_ removeAllObjects];
5527
5528 if (package != nil) {
5529 [package parse];
5530
5531 package_ = [package retain];
5532 name_ = [[package id] retain];
5533 commercial_ = [package isCommercial];
5534
5535 if ([package_ mode] != nil)
5536 [buttons_ addObject:UCLocalize("CLEAR")];
5537 if ([package_ source] == nil);
5538 else if ([package_ upgradableAndEssential:NO])
5539 [buttons_ addObject:UCLocalize("UPGRADE")];
5540 else if ([package_ uninstalled])
5541 [buttons_ addObject:UCLocalize("INSTALL")];
5542 else
5543 [buttons_ addObject:UCLocalize("REINSTALL")];
5544 if (![package_ uninstalled])
5545 [buttons_ addObject:UCLocalize("REMOVE")];
5546 }
5547
5548 if (button_ != nil)
5549 [button_ release];
5550
5551 NSString *title;
5552 switch ([buttons_ count]) {
5553 case 0: title = nil; break;
5554 case 1: title = [buttons_ objectAtIndex:0]; break;
5555 default: title = UCLocalize("MODIFY"); break;
5556 }
5557
5558 button_ = [[UIBarButtonItem alloc]
5559 initWithTitle:title
5560 style:UIBarButtonItemStylePlain
5561 target:self
5562 action:@selector(customButtonClicked)
5563 ];
5564
5565 [self reloadURL];
5566 }
5567
5568 - (bool) isLoading {
5569 return commercial_ ? [super isLoading] : false;
5570 }
5571
5572 - (void) reloadData {
5573 [self setPackage:[database_ packageWithName:name_]];
5574 }
5575
5576 @end
5577 /* }}} */
5578
5579 /* Package Table {{{ */
5580 @interface PackageTable : UIView <
5581 UITableViewDataSource,
5582 UITableViewDelegate
5583 > {
5584 _transient Database *database_;
5585 unsigned era_;
5586 NSMutableArray *packages_;
5587 NSMutableArray *sections_;
5588 UITableView *list_;
5589 NSMutableArray *index_;
5590 NSMutableDictionary *indices_;
5591 // XXX: this target_ seems to be delegate_. :(
5592 _transient id target_;
5593 SEL action_;
5594 // XXX: why do we even have this delegate_?
5595 _transient id delegate_;
5596 }
5597
5598 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5599
5600 - (void) setDelegate:(id)delegate;
5601
5602 - (void) reloadData;
5603 - (void) resetCursor;
5604
5605 - (UITableView *) list;
5606
5607 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5608
5609 - (void) deselectWithAnimation:(BOOL)animated;
5610
5611 @end
5612
5613 @implementation PackageTable
5614
5615 - (void) dealloc {
5616 [packages_ release];
5617 [sections_ release];
5618 [list_ release];
5619 [index_ release];
5620 [indices_ release];
5621
5622 [super dealloc];
5623 }
5624
5625 #if TryIndexedCollation
5626 + (BOOL) hasIndexedCollation {
5627 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5628 }
5629 #endif
5630
5631 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5632 NSInteger count([sections_ count]);
5633 return count == 0 ? 1 : count;
5634 }
5635
5636 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5637 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5638 return nil;
5639 return [[sections_ objectAtIndex:section] name];
5640 }
5641
5642 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5643 if ([sections_ count] == 0)
5644 return 0;
5645 return [[sections_ objectAtIndex:section] count];
5646 }
5647
5648 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5649 @synchronized (database_) {
5650 if ([database_ era] != era_)
5651 return nil;
5652
5653 Section *section([sections_ objectAtIndex:[path section]]);
5654 NSInteger row([path row]);
5655 Package *package([packages_ objectAtIndex:([section row] + row)]);
5656 return [[package retain] autorelease];
5657 } }
5658
5659 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5660 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5661 if (cell == nil)
5662 cell = [[[PackageCell alloc] init] autorelease];
5663 [cell setPackage:[self packageAtIndexPath:path]];
5664 return cell;
5665 }
5666
5667 - (void) deselectWithAnimation:(BOOL)animated {
5668 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5669 }
5670
5671 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5672 Package *package([self packageAtIndexPath:path]);
5673 package = [database_ packageWithName:[package id]];
5674 [target_ performSelector:action_ withObject:package];
5675 return path;
5676 }
5677
5678 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5679 // XXX: is 20 the most optimal number here?
5680 return [packages_ count] > 20 ? index_ : nil;
5681 }
5682
5683 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5684 #if TryIndexedCollation
5685 if ([[self class] hasIndexedCollation]) {
5686 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5687 }
5688 #endif
5689
5690 return index;
5691 }
5692
5693 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5694 if ((self = [super initWithFrame:frame]) != nil) {
5695 database_ = database;
5696
5697 target_ = target;
5698 action_ = action;
5699
5700 #if TryIndexedCollation
5701 if ([[self class] hasIndexedCollation])
5702 index_ = [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
5703 else
5704 #endif
5705 index_ = [[NSMutableArray alloc] initWithCapacity:32];
5706
5707 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5708
5709 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5710 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5711
5712 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5713 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5714 [list_ setRowHeight:73];
5715 [self addSubview:list_];
5716
5717 [list_ setDataSource:self];
5718 [list_ setDelegate:self];
5719 } return self;
5720 }
5721
5722 - (void) setDelegate:(id)delegate {
5723 delegate_ = delegate;
5724 }
5725
5726 - (bool) hasPackage:(Package *)package {
5727 return true;
5728 }
5729
5730 - (void) reloadData {
5731 era_ = [database_ era];
5732 NSArray *packages = [database_ packages];
5733
5734 [packages_ removeAllObjects];
5735 [sections_ removeAllObjects];
5736
5737 _profile(PackageTable$reloadData$Filter)
5738 for (Package *package in packages)
5739 if ([self hasPackage:package])
5740 [packages_ addObject:package];
5741 _end
5742
5743 [indices_ removeAllObjects];
5744
5745 Section *section = nil;
5746
5747 #if TryIndexedCollation
5748 if ([[self class] hasIndexedCollation]) {
5749 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5750 NSArray *titles = [collation sectionIndexTitles];
5751 int secidx = -1;
5752
5753 _profile(PackageTable$reloadData$Section)
5754 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5755 Package *package;
5756 int index;
5757
5758 _profile(PackageTable$reloadData$Section$Package)
5759 package = [packages_ objectAtIndex:offset];
5760 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5761 _end
5762
5763 while (secidx < index) {
5764 secidx += 1;
5765
5766 _profile(PackageTable$reloadData$Section$Allocate)
5767 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5768 _end
5769
5770 _profile(PackageTable$reloadData$Section$Add)
5771 [sections_ addObject:section];
5772 _end
5773 }
5774
5775 [section addToCount];
5776 }
5777 _end
5778 } else
5779 #endif
5780 {
5781 [index_ removeAllObjects];
5782
5783 _profile(PackageTable$reloadData$Section)
5784 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5785 Package *package;
5786 unichar index;
5787
5788 _profile(PackageTable$reloadData$Section$Package)
5789 package = [packages_ objectAtIndex:offset];
5790 index = [package index];
5791 _end
5792
5793 if (section == nil || [section index] != index) {
5794 _profile(PackageTable$reloadData$Section$Allocate)
5795 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5796 _end
5797
5798 [index_ addObject:[section name]];
5799 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5800
5801 _profile(PackageTable$reloadData$Section$Add)
5802 [sections_ addObject:section];
5803 _end
5804 }
5805
5806 [section addToCount];
5807 }
5808 _end
5809 }
5810
5811 _profile(PackageTable$reloadData$List)
5812 [list_ reloadData];
5813 _end
5814 }
5815
5816 - (void) resetCursor {
5817 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5818 }
5819
5820 - (UITableView *) list {
5821 return list_;
5822 }
5823
5824 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5825 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5826 }
5827
5828 @end
5829 /* }}} */
5830 /* Filtered Package Table {{{ */
5831 @interface FilteredPackageTable : PackageTable {
5832 SEL filter_;
5833 IMP imp_;
5834 id object_;
5835 }
5836
5837 - (void) setObject:(id)object;
5838 - (void) setObject:(id)object forFilter:(SEL)filter;
5839
5840 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5841
5842 @end
5843
5844 @implementation FilteredPackageTable
5845
5846 - (void) dealloc {
5847 if (object_ != nil)
5848 [object_ release];
5849 [super dealloc];
5850 }
5851
5852 - (void) setFilter:(SEL)filter {
5853 filter_ = filter;
5854
5855 /* XXX: this is an unsafe optimization of doomy hell */
5856 Method method(class_getInstanceMethod([Package class], filter));
5857 _assert(method != NULL);
5858 imp_ = method_getImplementation(method);
5859 _assert(imp_ != NULL);
5860 }
5861
5862 - (void) setObject:(id)object {
5863 if (object_ != nil)
5864 [object_ release];
5865 if (object == nil)
5866 object_ = nil;
5867 else
5868 object_ = [object retain];
5869 }
5870
5871 - (void) setObject:(id)object forFilter:(SEL)filter {
5872 [self setFilter:filter];
5873 [self setObject:object];
5874 }
5875
5876 - (bool) hasPackage:(Package *)package {
5877 _profile(FilteredPackageTable$hasPackage)
5878 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5879 _end
5880 }
5881
5882 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5883 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5884 [self setFilter:filter];
5885 object_ = [object retain];
5886 [self reloadData];
5887 } return self;
5888 }
5889
5890 @end
5891 /* }}} */
5892 /* Filtered Package Controller {{{ */
5893 @interface FilteredPackageController : CYViewController {
5894 _transient Database *database_;
5895 FilteredPackageTable *packages_;
5896 NSString *title_;
5897 }
5898
5899 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5900
5901 @end
5902
5903 @implementation FilteredPackageController
5904
5905 - (void) dealloc {
5906 [packages_ release];
5907 [title_ release];
5908
5909 [super dealloc];
5910 }
5911
5912 - (void) viewDidAppear:(BOOL)animated {
5913 [super viewDidAppear:animated];
5914 [packages_ deselectWithAnimation:animated];
5915 }
5916
5917 - (void) didSelectPackage:(Package *)package {
5918 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
5919 [view setPackage:package];
5920 [view setDelegate:delegate_];
5921 [[self navigationController] pushViewController:view animated:YES];
5922 }
5923
5924 - (NSString *) title { return title_; }
5925
5926 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5927 if ((self = [super init]) != nil) {
5928 database_ = database;
5929 title_ = [title copy];
5930 [[self navigationItem] setTitle:title_];
5931
5932 packages_ = [[FilteredPackageTable alloc]
5933 initWithFrame:[[self view] bounds]
5934 database:database
5935 target:self
5936 action:@selector(didSelectPackage:)
5937 filter:filter
5938 with:object
5939 ];
5940
5941 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5942 [[self view] addSubview:packages_];
5943 } return self;
5944 }
5945
5946 - (void) reloadData {
5947 [packages_ reloadData];
5948 }
5949
5950 - (void) setDelegate:(id)delegate {
5951 [super setDelegate:delegate];
5952 [packages_ setDelegate:delegate];
5953 }
5954
5955 @end
5956
5957 /* }}} */
5958
5959 /* Home Controller {{{ */
5960 @interface HomeController : CYBrowserController {
5961 }
5962 @end
5963
5964 @implementation HomeController
5965
5966 + (BOOL)shouldHideNavigationBar {
5967 return NO;
5968 }
5969
5970 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
5971 [super _setMoreHeaders:request];
5972
5973 if (ChipID_ != nil)
5974 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
5975 if (UniqueID_ != nil)
5976 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5977 if (PLMN_ != nil)
5978 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
5979 }
5980
5981 - (void) aboutButtonClicked {
5982 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
5983
5984 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
5985 [alert addButtonWithTitle:UCLocalize("CLOSE")];
5986 [alert setCancelButtonIndex:0];
5987
5988 [alert setMessage:
5989 @"Copyright (C) 2008-2010\n"
5990 "Jay Freeman (saurik)\n"
5991 "saurik@saurik.com\n"
5992 "http://www.saurik.com/"
5993 ];
5994
5995 [alert show];
5996 }
5997
5998 - (void) viewWillAppear:(BOOL)animated {
5999 [super viewWillAppear:animated];
6000
6001 if ([[self class] shouldHideNavigationBar])
6002 [[self navigationController] setNavigationBarHidden:YES animated:animated];
6003 }
6004
6005 - (void) viewWillDisappear:(BOOL)animated {
6006 [super viewWillDisappear:animated];
6007
6008 if ([[self class] shouldHideNavigationBar])
6009 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6010 }
6011
6012 - (id) init {
6013 if ((self = [super init]) != nil) {
6014 [self loadURL:[NSURL URLWithString:CydiaURL(@"ui/home/")]];
6015
6016 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6017 initWithTitle:UCLocalize("ABOUT")
6018 style:UIBarButtonItemStylePlain
6019 target:self
6020 action:@selector(aboutButtonClicked)
6021 ] autorelease]];
6022 } return self;
6023 }
6024
6025 @end
6026 /* }}} */
6027 /* Manage Controller {{{ */
6028 @interface ManageController : CYBrowserController {
6029 }
6030
6031 - (void) queueStatusDidChange;
6032 @end
6033
6034 @implementation ManageController
6035
6036 - (id) init {
6037 if ((self = [super init]) != nil) {
6038 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6039
6040 [self loadURL:[NSURL URLWithString:CydiaURL(@"ui/manage/")]];
6041
6042 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6043 initWithTitle:UCLocalize("SETTINGS")
6044 style:UIBarButtonItemStylePlain
6045 target:self
6046 action:@selector(settingsButtonClicked)
6047 ] autorelease]];
6048
6049 [self queueStatusDidChange];
6050 } return self;
6051 }
6052
6053 - (void) settingsButtonClicked {
6054 [delegate_ showSettings];
6055 }
6056
6057 #if !AlwaysReload
6058 - (void) queueButtonClicked {
6059 [delegate_ queue];
6060 }
6061
6062 - (void) applyLoadingTitle {
6063 // No "Loading" title.
6064 }
6065
6066 - (void) applyRightButton {
6067 // No right button.
6068 }
6069 #endif
6070
6071 - (void) queueStatusDidChange {
6072 #if !AlwaysReload
6073 if (!IsWildcat_ && Queuing_) {
6074 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6075 initWithTitle:UCLocalize("QUEUE")
6076 style:UIBarButtonItemStyleDone
6077 target:self
6078 action:@selector(queueButtonClicked)
6079 ] autorelease]];
6080 } else {
6081 [[self navigationItem] setRightBarButtonItem:nil];
6082 }
6083 #endif
6084 }
6085
6086 - (bool) isLoading {
6087 return false;
6088 }
6089
6090 @end
6091 /* }}} */
6092
6093 /* Refresh Bar {{{ */
6094 @interface RefreshBar : UINavigationBar {
6095 UIProgressIndicator *indicator_;
6096 UITextLabel *prompt_;
6097 UIProgressBar *progress_;
6098 UINavigationButton *cancel_;
6099 }
6100
6101 @end
6102
6103 @implementation RefreshBar
6104
6105 - (void) dealloc {
6106 [indicator_ release];
6107 [prompt_ release];
6108 [progress_ release];
6109 [cancel_ release];
6110 [super dealloc];
6111 }
6112
6113 - (void) positionViews {
6114 CGRect frame = [cancel_ frame];
6115 frame.size = [cancel_ sizeThatFits:frame.size];
6116 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6117 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6118 [cancel_ setFrame:frame];
6119
6120 CGSize prgsize = {75, 100};
6121 CGRect prgrect = {{
6122 [self frame].size.width - prgsize.width - 10,
6123 ([self frame].size.height - prgsize.height) / 2
6124 } , prgsize};
6125 [progress_ setFrame:prgrect];
6126
6127 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6128 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6129 CGRect indrect = {{indoffset, indoffset}, indsize};
6130 [indicator_ setFrame:indrect];
6131
6132 CGSize prmsize = {215, indsize.height + 4};
6133 CGRect prmrect = {{
6134 indoffset * 2 + indsize.width,
6135 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6136 }, prmsize};
6137 [prompt_ setFrame:prmrect];
6138 }
6139
6140 - (void)setFrame:(CGRect)frame {
6141 [super setFrame:frame];
6142
6143 [self positionViews];
6144 }
6145
6146 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6147 if ((self = [super initWithFrame:frame])) {
6148 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6149
6150 [self setBarStyle:UIBarStyleBlack];
6151
6152 UIBarStyle barstyle([self _barStyle:NO]);
6153 bool ugly(barstyle == UIBarStyleDefault);
6154
6155 UIProgressIndicatorStyle style = ugly ?
6156 UIProgressIndicatorStyleMediumBrown :
6157 UIProgressIndicatorStyleMediumWhite;
6158
6159 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6160 [indicator_ setStyle:style];
6161 [indicator_ startAnimation];
6162 [self addSubview:indicator_];
6163
6164 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6165 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6166 [prompt_ setBackgroundColor:[UIColor clearColor]];
6167 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6168 [self addSubview:prompt_];
6169
6170 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6171 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6172 [progress_ setStyle:0];
6173 [self addSubview:progress_];
6174
6175 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6176 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6177 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6178 [cancel_ setBarStyle:barstyle];
6179
6180 [self positionViews];
6181 } return self;
6182 }
6183
6184 - (void) cancel {
6185 [cancel_ removeFromSuperview];
6186 }
6187
6188 - (void) start {
6189 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6190 [progress_ setProgress:0];
6191 [self addSubview:cancel_];
6192 }
6193
6194 - (void) stop {
6195 [cancel_ removeFromSuperview];
6196 }
6197
6198 - (void) setPrompt:(NSString *)prompt {
6199 [prompt_ setText:prompt];
6200 }
6201
6202 - (void) setProgress:(float)progress {
6203 [progress_ setProgress:progress];
6204 }
6205
6206 @end
6207 /* }}} */
6208
6209 @class CYNavigationController;
6210
6211 /* Cydia Tab Bar Controller {{{ */
6212 @interface CYTabBarController : UITabBarController <
6213 ProgressDelegate
6214 > {
6215 _transient Database *database_;
6216 RefreshBar *refreshbar_;
6217
6218 bool dropped_;
6219 bool updating_;
6220 // XXX: ok, "updatedelegate_"?...
6221 _transient NSObject<CydiaDelegate> *updatedelegate_;
6222
6223 id root_;
6224 }
6225
6226 - (void) dropBar:(BOOL)animated;
6227 - (void) beginUpdate;
6228 - (void) raiseBar:(BOOL)animated;
6229 - (BOOL) updating;
6230
6231 @end
6232
6233 @implementation CYTabBarController
6234
6235 - (void) reloadData {
6236 size_t count([[self viewControllers] count]);
6237 for (size_t i(0); i != count; ++i) {
6238 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6239 [page reloadData];
6240 }
6241
6242 [(CYNavigationController *)[self transientViewController] reloadData];
6243 }
6244
6245 - (id) initWithDatabase:(Database *)database {
6246 if ((self = [super init]) != nil) {
6247 database_ = database;
6248
6249 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6250 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6251
6252 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6253 } return self;
6254 }
6255
6256 - (void) setUpdate:(NSDate *)date {
6257 [self beginUpdate];
6258 }
6259
6260 - (void) beginUpdate {
6261 [refreshbar_ start];
6262 [self dropBar:YES];
6263
6264 [updatedelegate_ retainNetworkActivityIndicator];
6265 updating_ = true;
6266
6267 [NSThread
6268 detachNewThreadSelector:@selector(performUpdate)
6269 toTarget:self
6270 withObject:nil
6271 ];
6272 }
6273
6274 - (void) performUpdate { _pooled
6275 Status status;
6276 status.setDelegate(self);
6277 [database_ updateWithStatus:status];
6278
6279 [self
6280 performSelectorOnMainThread:@selector(completeUpdate)
6281 withObject:nil
6282 waitUntilDone:NO
6283 ];
6284 }
6285
6286 - (void) stopUpdateWithSelector:(SEL)selector {
6287 updating_ = false;
6288 [updatedelegate_ releaseNetworkActivityIndicator];
6289
6290 [self raiseBar:YES];
6291 [refreshbar_ stop];
6292
6293 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6294 }
6295
6296 - (void) completeUpdate {
6297 if (!updating_)
6298 return;
6299 [self stopUpdateWithSelector:@selector(reloadData)];
6300 }
6301
6302 - (void) cancelUpdate {
6303 [self stopUpdateWithSelector:@selector(updateData)];
6304 }
6305
6306 - (void) cancelPressed {
6307 [self cancelUpdate];
6308 }
6309
6310 - (BOOL) updating {
6311 return updating_;
6312 }
6313
6314 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6315 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6316 }
6317
6318 - (void) startProgress {
6319 }
6320
6321 - (void) setProgressTitle:(NSString *)title {
6322 [self
6323 performSelectorOnMainThread:@selector(_setProgressTitle:)
6324 withObject:title
6325 waitUntilDone:YES
6326 ];
6327 }
6328
6329 - (bool) isCancelling:(size_t)received {
6330 return !updating_;
6331 }
6332
6333 - (void) setProgressPercent:(float)percent {
6334 [self
6335 performSelectorOnMainThread:@selector(_setProgressPercent:)
6336 withObject:[NSNumber numberWithFloat:percent]
6337 waitUntilDone:YES
6338 ];
6339 }
6340
6341 - (void) addProgressOutput:(NSString *)output {
6342 [self
6343 performSelectorOnMainThread:@selector(_addProgressOutput:)
6344 withObject:output
6345 waitUntilDone:YES
6346 ];
6347 }
6348
6349 - (void) _setProgressTitle:(NSString *)title {
6350 [refreshbar_ setPrompt:title];
6351 }
6352
6353 - (void) _setProgressPercent:(NSNumber *)percent {
6354 [refreshbar_ setProgress:[percent floatValue]];
6355 }
6356
6357 - (void) _addProgressOutput:(NSString *)output {
6358 }
6359
6360 - (void) setUpdateDelegate:(id)delegate {
6361 updatedelegate_ = delegate;
6362 }
6363
6364 - (CGFloat) statusBarHeight {
6365 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6366 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6367 } else {
6368 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6369 }
6370 }
6371
6372 - (UIView *) transitionView {
6373 if ([self respondsToSelector:@selector(_transitionView)])
6374 return [self _transitionView];
6375 else
6376 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6377 }
6378
6379 - (void) dropBar:(BOOL)animated {
6380 if (dropped_)
6381 return;
6382 dropped_ = true;
6383
6384 UIView *transition([self transitionView]);
6385 [[self view] addSubview:refreshbar_];
6386
6387 CGRect barframe([refreshbar_ frame]);
6388
6389 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6390 barframe.origin.y = [self statusBarHeight];
6391 else
6392 barframe.origin.y = 0;
6393
6394 [refreshbar_ setFrame:barframe];
6395
6396 if (animated)
6397 [UIView beginAnimations:nil context:NULL];
6398
6399 CGRect viewframe = [transition frame];
6400 viewframe.origin.y += barframe.size.height;
6401 viewframe.size.height -= barframe.size.height;
6402 [transition setFrame:viewframe];
6403
6404 if (animated)
6405 [UIView commitAnimations];
6406
6407 // Ensure bar has the proper width for our view, it might have changed
6408 barframe.size.width = viewframe.size.width;
6409 [refreshbar_ setFrame:barframe];
6410
6411 // XXX: fix Apple's layout bug
6412 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6413 }
6414
6415 - (void) raiseBar:(BOOL)animated {
6416 if (!dropped_)
6417 return;
6418 dropped_ = false;
6419
6420 UIView *transition([self transitionView]);
6421 [refreshbar_ removeFromSuperview];
6422
6423 CGRect barframe([refreshbar_ frame]);
6424
6425 if (animated)
6426 [UIView beginAnimations:nil context:NULL];
6427
6428 CGRect viewframe = [transition frame];
6429 viewframe.origin.y -= barframe.size.height;
6430 viewframe.size.height += barframe.size.height;
6431 [transition setFrame:viewframe];
6432
6433 if (animated)
6434 [UIView commitAnimations];
6435
6436 // XXX: fix Apple's layout bug
6437 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6438 }
6439
6440 #if 0
6441 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6442 // XXX: fix Apple's layout bug
6443 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6444 }
6445 #endif
6446
6447 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6448 bool dropped(dropped_);
6449
6450 if (dropped)
6451 [self raiseBar:NO];
6452
6453 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6454
6455 if (dropped)
6456 [self dropBar:NO];
6457
6458 // XXX: fix Apple's layout bug
6459 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6460 }
6461
6462 - (void) statusBarFrameChanged:(NSNotification *)notification {
6463 if (dropped_) {
6464 [self raiseBar:NO];
6465 [self dropBar:NO];
6466 }
6467 }
6468
6469 - (void) dealloc {
6470 [refreshbar_ release];
6471 [[NSNotificationCenter defaultCenter] removeObserver:self];
6472 [super dealloc];
6473 }
6474
6475 @end
6476 /* }}} */
6477 /* Cydia Navigation Controller {{{ */
6478 @interface CYNavigationController : UINavigationController {
6479 _transient Database *database_;
6480 _transient id<UINavigationControllerDelegate> delegate_;
6481 }
6482
6483 - (id) initWithDatabase:(Database *)database;
6484 - (void) reloadData;
6485
6486 @end
6487
6488
6489 @implementation CYNavigationController
6490
6491 - (void) dealloc {
6492 [super dealloc];
6493 }
6494
6495 - (void) reloadData {
6496 size_t count([[self viewControllers] count]);
6497 for (size_t i(0); i != count; ++i) {
6498 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6499 [page reloadData];
6500 }
6501 }
6502
6503 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6504 delegate_ = delegate;
6505 }
6506
6507 - (id) initWithDatabase:(Database *)database {
6508 if ((self = [super init]) != nil) {
6509 database_ = database;
6510 } return self;
6511 }
6512
6513 @end
6514 /* }}} */
6515
6516 /* Cydia:// Protocol {{{ */
6517 @interface CydiaURLProtocol : NSURLProtocol {
6518 }
6519
6520 @end
6521
6522 @implementation CydiaURLProtocol
6523
6524 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6525 NSURL *url([request URL]);
6526 if (url == nil)
6527 return NO;
6528 NSString *scheme([[url scheme] lowercaseString]);
6529 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6530 return NO;
6531 return YES;
6532 }
6533
6534 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6535 return request;
6536 }
6537
6538 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6539 id<NSURLProtocolClient> client([self client]);
6540 if (icon == nil)
6541 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6542 else {
6543 NSData *data(UIImagePNGRepresentation(icon));
6544
6545 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6546 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6547 [client URLProtocol:self didLoadData:data];
6548 [client URLProtocolDidFinishLoading:self];
6549 }
6550 }
6551
6552 - (void) startLoading {
6553 id<NSURLProtocolClient> client([self client]);
6554 NSURLRequest *request([self request]);
6555
6556 NSURL *url([request URL]);
6557 NSString *href([url absoluteString]);
6558
6559 NSString *path([href substringFromIndex:8]);
6560 NSRange slash([path rangeOfString:@"/"]);
6561
6562 NSString *command;
6563 if (slash.location == NSNotFound) {
6564 command = path;
6565 path = nil;
6566 } else {
6567 command = [path substringToIndex:slash.location];
6568 path = [path substringFromIndex:(slash.location + 1)];
6569 }
6570
6571 Database *database([Database sharedInstance]);
6572
6573 if ([command isEqualToString:@"package-icon"]) {
6574 if (path == nil)
6575 goto fail;
6576 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6577 Package *package([database packageWithName:path]);
6578 if (package == nil)
6579 goto fail;
6580 UIImage *icon([package icon]);
6581 [self _returnPNGWithImage:icon forRequest:request];
6582 } else if ([command isEqualToString:@"source-icon"]) {
6583 if (path == nil)
6584 goto fail;
6585 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6586 NSString *source(Simplify(path));
6587 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6588 if (icon == nil)
6589 icon = [UIImage applicationImageNamed:@"unknown.png"];
6590 [self _returnPNGWithImage:icon forRequest:request];
6591 } else if ([command isEqualToString:@"uikit-image"]) {
6592 if (path == nil)
6593 goto fail;
6594 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6595 UIImage *icon(_UIImageWithName(path));
6596 [self _returnPNGWithImage:icon forRequest:request];
6597 } else if ([command isEqualToString:@"section-icon"]) {
6598 if (path == nil)
6599 goto fail;
6600 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6601 NSString *section(Simplify(path));
6602 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6603 if (icon == nil)
6604 icon = [UIImage applicationImageNamed:@"unknown.png"];
6605 [self _returnPNGWithImage:icon forRequest:request];
6606 } else fail: {
6607 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6608 }
6609 }
6610
6611 - (void) stopLoading {
6612 }
6613
6614 @end
6615 /* }}} */
6616
6617 /* Section Controller {{{ */
6618 @interface SectionController : FilteredPackageController {
6619 }
6620
6621 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6622
6623 @end
6624
6625 @implementation SectionController
6626
6627 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6628 NSString *title;
6629
6630 if (name == nil) {
6631 title = UCLocalize("ALL_PACKAGES");
6632 } else if (![name isEqual:@""]) {
6633 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6634 } else {
6635 title = UCLocalize("NO_SECTION");
6636 }
6637
6638 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6639 } return self;
6640 }
6641
6642 @end
6643 /* }}} */
6644 /* Sections Controller {{{ */
6645 @interface SectionsController : CYViewController <
6646 UITableViewDataSource,
6647 UITableViewDelegate
6648 > {
6649 _transient Database *database_;
6650 NSMutableArray *sections_;
6651 NSMutableArray *filtered_;
6652 UITableView *list_;
6653 BOOL editing_;
6654 }
6655
6656 - (id) initWithDatabase:(Database *)database;
6657 - (void) reloadData;
6658 - (void) resetView;
6659
6660 - (void) editButtonClicked;
6661
6662 @end
6663
6664 @implementation SectionsController
6665
6666 - (void) dealloc {
6667 [list_ setDataSource:nil];
6668 [list_ setDelegate:nil];
6669
6670 [sections_ release];
6671 [filtered_ release];
6672 [list_ release];
6673 [super dealloc];
6674 }
6675
6676 - (void) updateNavigationItem {
6677 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6678 if ([sections_ count] == 0) {
6679 [[self navigationItem] setRightBarButtonItem:nil];
6680 } else {
6681 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6682 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6683 target:self
6684 action:@selector(editButtonClicked)
6685 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6686 }
6687 }
6688
6689 - (void) setEditing:(BOOL)editing {
6690 if ((editing_ = editing))
6691 [list_ reloadData];
6692 else
6693 [delegate_ updateData];
6694
6695 [self updateNavigationItem];
6696 }
6697
6698 - (void) viewDidAppear:(BOOL)animated {
6699 [super viewDidAppear:animated];
6700 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6701 }
6702
6703 - (void) viewWillDisappear:(BOOL)animated {
6704 [super viewWillDisappear:animated];
6705 if (editing_) [self setEditing:NO];
6706 }
6707
6708 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6709 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6710 return section;
6711 }
6712
6713 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6714 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6715 }
6716
6717 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6718 return 45.0f;
6719 }*/
6720
6721 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6722 static NSString *reuseIdentifier = @"SectionCell";
6723
6724 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6725 if (cell == nil)
6726 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6727
6728 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6729
6730 return cell;
6731 }
6732
6733 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6734 if (editing_)
6735 return;
6736
6737 Section *section = [self sectionAtIndexPath:indexPath];
6738
6739 SectionController *controller = [[[SectionController alloc]
6740 initWithDatabase:database_
6741 section:[section name]
6742 ] autorelease];
6743 [controller setDelegate:delegate_];
6744
6745 [[self navigationController] pushViewController:controller animated:YES];
6746 }
6747
6748 - (id) initWithDatabase:(Database *)database {
6749 if ((self = [super init]) != nil) {
6750 database_ = database;
6751
6752 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6753
6754 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6755 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6756
6757 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6758 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6759 [list_ setRowHeight:45.0f];
6760 [[self view] addSubview:list_];
6761
6762 [list_ setDataSource:self];
6763 [list_ setDelegate:self];
6764
6765 [self reloadData];
6766 } return self;
6767 }
6768
6769 - (void) reloadData {
6770 NSArray *packages = [database_ packages];
6771
6772 [sections_ removeAllObjects];
6773 [filtered_ removeAllObjects];
6774
6775 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6776
6777 _trace();
6778 for (Package *package in packages) {
6779 NSString *name([package section]);
6780 NSString *key(name == nil ? @"" : name);
6781
6782 Section *section;
6783
6784 _profile(SectionsView$reloadData$Section)
6785 section = [sections objectForKey:key];
6786 if (section == nil) {
6787 _profile(SectionsView$reloadData$Section$Allocate)
6788 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6789 [sections setObject:section forKey:key];
6790 _end
6791 }
6792 _end
6793
6794 [section addToCount];
6795
6796 _profile(SectionsView$reloadData$Filter)
6797 if (![package valid] || ![package visible])
6798 continue;
6799 _end
6800
6801 [section addToRow];
6802 }
6803 _trace();
6804
6805 [sections_ addObjectsFromArray:[sections allValues]];
6806
6807 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6808
6809 for (Section *section in sections_) {
6810 size_t count([section row]);
6811 if (count == 0)
6812 continue;
6813
6814 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6815 [section setCount:count];
6816 [filtered_ addObject:section];
6817 }
6818
6819 [self updateNavigationItem];
6820 [list_ reloadData];
6821 _trace();
6822 }
6823
6824 - (void) resetView {
6825 if (editing_)
6826 [self editButtonClicked];
6827 }
6828
6829 - (void)editButtonClicked {
6830 [self setEditing:!editing_];
6831 }
6832
6833 @end
6834 /* }}} */
6835
6836 /* Changes Controller {{{ */
6837 @interface ChangesController : CYViewController <
6838 UITableViewDataSource,
6839 UITableViewDelegate
6840 > {
6841 _transient Database *database_;
6842 unsigned era_;
6843 CFMutableArrayRef packages_;
6844 NSMutableArray *sections_;
6845 UITableView *list_;
6846 unsigned upgrades_;
6847 BOOL hasSentFirstLoad_;
6848 }
6849
6850 - (id) initWithDatabase:(Database *)database;
6851
6852 @end
6853
6854 @implementation ChangesController
6855
6856 - (void) dealloc {
6857 [list_ setDelegate:nil];
6858 [list_ setDataSource:nil];
6859
6860 CFRelease(packages_);
6861
6862 [sections_ release];
6863 [list_ release];
6864 [super dealloc];
6865 }
6866
6867 - (void) viewDidAppear:(BOOL)animated {
6868 [super viewDidAppear:animated];
6869 if (!hasSentFirstLoad_) {
6870 hasSentFirstLoad_ = YES;
6871 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6872 } else {
6873 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6874 }
6875 }
6876
6877 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6878 NSInteger count([sections_ count]);
6879 return count == 0 ? 1 : count;
6880 }
6881
6882 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6883 if ([sections_ count] == 0)
6884 return nil;
6885 return [[sections_ objectAtIndex:section] name];
6886 }
6887
6888 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6889 if ([sections_ count] == 0)
6890 return 0;
6891 return [[sections_ objectAtIndex:section] count];
6892 }
6893
6894 - (Package *) packageAtIndex:(NSUInteger)index {
6895 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6896 }
6897
6898 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6899 @synchronized (database_) {
6900 if ([database_ era] != era_)
6901 return nil;
6902
6903 NSUInteger sectionIndex([path section]);
6904 if (sectionIndex >= [sections_ count])
6905 return nil;
6906 Section *section([sections_ objectAtIndex:sectionIndex]);
6907 NSInteger row([path row]);
6908 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
6909 } }
6910
6911 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6912 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6913 if (cell == nil)
6914 cell = [[[PackageCell alloc] init] autorelease];
6915 [cell setPackage:[self packageAtIndexPath:path]];
6916 return cell;
6917 }
6918
6919 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6920 Package *package([self packageAtIndexPath:path]);
6921 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
6922 [view setDelegate:delegate_];
6923 [view setPackage:package];
6924 [[self navigationController] pushViewController:view animated:YES];
6925 return path;
6926 }
6927
6928 - (void) refreshButtonClicked {
6929 [delegate_ beginUpdate];
6930 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
6931 }
6932
6933 - (void) upgradeButtonClicked {
6934 [delegate_ distUpgrade];
6935 }
6936
6937 - (NSString *) title { return UCLocalize("CHANGES"); }
6938
6939 - (id) initWithDatabase:(Database *)database {
6940 if ((self = [super init]) != nil) {
6941 database_ = database;
6942 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
6943
6944 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
6945 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6946
6947 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6948 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6949 [list_ setRowHeight:73];
6950 [[self view] addSubview:list_];
6951
6952 [list_ setDataSource:self];
6953 [list_ setDelegate:self];
6954 } return self;
6955 }
6956
6957 - (void) _reloadPackages:(NSArray *)packages {
6958 CFRelease(packages_);
6959 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
6960
6961 _trace();
6962 _profile(ChangesController$_reloadPackages$Filter)
6963 for (Package *package in packages)
6964 if ([package upgradableAndEssential:YES] || [package visible])
6965 CFArrayAppendValue(packages_, package);
6966 _end
6967 _trace();
6968 _profile(ChangesController$_reloadPackages$radixSort)
6969 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6970 _end
6971 _trace();
6972 }
6973
6974 - (void) reloadData {
6975 @synchronized (database_) {
6976 era_ = [database_ era];
6977 NSArray *packages = [database_ packages];
6978
6979 [sections_ removeAllObjects];
6980
6981 #if 1
6982 UIProgressHUD *hud([delegate_ addProgressHUD]);
6983 [hud setText:UCLocalize("LOADING")];
6984 //NSLog(@"HUD:%@::%@", delegate_, hud);
6985 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
6986 [delegate_ removeProgressHUD:hud];
6987 #else
6988 [self _reloadPackages:packages];
6989 #endif
6990
6991 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6992 Section *ignored = nil;
6993 Section *section = nil;
6994 time_t last = 0;
6995
6996 upgrades_ = 0;
6997 bool unseens = false;
6998
6999 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
7000
7001 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
7002 Package *package = [self packageAtIndex:offset];
7003
7004 BOOL uae = [package upgradableAndEssential:YES];
7005
7006 if (!uae) {
7007 unseens = true;
7008 time_t seen([package seen]);
7009
7010 if (section == nil || last != seen) {
7011 last = seen;
7012
7013 NSString *name;
7014 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7015 [name autorelease];
7016
7017 _profile(ChangesController$reloadData$Allocate)
7018 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7019 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7020 [sections_ addObject:section];
7021 _end
7022 }
7023
7024 [section addToCount];
7025 } else if ([package ignored]) {
7026 if (ignored == nil) {
7027 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7028 }
7029 [ignored addToCount];
7030 } else {
7031 ++upgrades_;
7032 [upgradable addToCount];
7033 }
7034 }
7035 _trace();
7036
7037 CFRelease(formatter);
7038
7039 if (unseens) {
7040 Section *last = [sections_ lastObject];
7041 size_t count = [last count];
7042 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7043 [sections_ removeLastObject];
7044 }
7045
7046 if ([ignored count] != 0)
7047 [sections_ insertObject:ignored atIndex:0];
7048 if (upgrades_ != 0)
7049 [sections_ insertObject:upgradable atIndex:0];
7050
7051 [list_ reloadData];
7052
7053 if (upgrades_ > 0)
7054 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7055 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7056 style:UIBarButtonItemStylePlain
7057 target:self
7058 action:@selector(upgradeButtonClicked)
7059 ] autorelease]];
7060
7061 if (![delegate_ updating])
7062 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7063 initWithTitle:UCLocalize("REFRESH")
7064 style:UIBarButtonItemStylePlain
7065 target:self
7066 action:@selector(refreshButtonClicked)
7067 ] autorelease]];
7068
7069 PrintTimes();
7070 } }
7071
7072 @end
7073 /* }}} */
7074 /* Search Controller {{{ */
7075 @interface SearchController : FilteredPackageController <
7076 UISearchBarDelegate
7077 > {
7078 UISearchBar *search_;
7079 }
7080
7081 - (id) initWithDatabase:(Database *)database;
7082 - (void) setSearchTerm:(NSString *)term;
7083 - (void) reloadData;
7084
7085 @end
7086
7087 @implementation SearchController
7088
7089 - (void) dealloc {
7090 [search_ release];
7091 [super dealloc];
7092 }
7093
7094 - (void) setSearchTerm:(NSString *)searchTerm {
7095 [search_ setText:searchTerm];
7096 }
7097
7098 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7099 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7100 [search_ resignFirstResponder];
7101 [self reloadData];
7102 }
7103
7104 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7105 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7106 [self reloadData];
7107 }
7108
7109 - (id) initWithDatabase:(Database *)database {
7110 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7111 }
7112
7113 - (void)viewDidAppear:(BOOL)animated {
7114 [super viewDidAppear:animated];
7115 if (!search_) {
7116 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7117 [search_ layoutSubviews];
7118 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7119
7120 UITextField *textField;
7121 if ([search_ respondsToSelector:@selector(searchField)])
7122 textField = [search_ searchField];
7123 else
7124 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7125
7126 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7127 [search_ setDelegate:self];
7128 [textField setEnablesReturnKeyAutomatically:NO];
7129 [[self navigationItem] setTitleView:textField];
7130 }
7131 }
7132
7133 - (void) _reloadData {
7134 }
7135
7136 - (void) reloadData {
7137 _profile(SearchController$reloadData)
7138 [packages_ reloadData];
7139 _end
7140 PrintTimes();
7141 [packages_ resetCursor];
7142 }
7143
7144 - (void) didSelectPackage:(Package *)package {
7145 [search_ resignFirstResponder];
7146 [super didSelectPackage:package];
7147 }
7148
7149 @end
7150 /* }}} */
7151 /* Package Settings Controller {{{ */
7152 @interface PackageSettingsController : CYViewController <
7153 UITableViewDataSource,
7154 UITableViewDelegate
7155 > {
7156 _transient Database *database_;
7157 NSString *name_;
7158 Package *package_;
7159 UITableView *table_;
7160 UISwitch *subscribedSwitch_;
7161 UISwitch *ignoredSwitch_;
7162 UITableViewCell *subscribedCell_;
7163 UITableViewCell *ignoredCell_;
7164 }
7165
7166 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7167
7168 @end
7169
7170 @implementation PackageSettingsController
7171
7172 - (void) dealloc {
7173 [name_ release];
7174 if (package_ != nil)
7175 [package_ release];
7176 [table_ release];
7177 [subscribedSwitch_ release];
7178 [ignoredSwitch_ release];
7179 [subscribedCell_ release];
7180 [ignoredCell_ release];
7181
7182 [super dealloc];
7183 }
7184
7185 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7186 if (package_ == nil)
7187 return 0;
7188
7189 return 1;
7190 }
7191
7192 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7193 if (package_ == nil)
7194 return 0;
7195
7196 return 2;
7197 }
7198
7199 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7200 return UCLocalize("CHANGE_PACKAGE_SETTINGS");
7201 }
7202
7203 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7204 return UCLocalize("SHOW_ALL_CHANGES_EX");
7205 }
7206
7207 - (void) onSubscribed:(id)control {
7208 bool value([control isOn]);
7209 if (package_ == nil)
7210 return;
7211 if ([package_ setSubscribed:value])
7212 [delegate_ updateData];
7213 }
7214
7215 - (void) onIgnored:(id)control {
7216 // TODO: set Held state - possibly call out to dpkg, etc.
7217 }
7218
7219 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7220 if (package_ == nil)
7221 return nil;
7222
7223 switch ([indexPath row]) {
7224 case 0: return subscribedCell_;
7225 case 1: return ignoredCell_;
7226
7227 _nodefault
7228 }
7229
7230 return nil;
7231 }
7232
7233 - (NSString *) title { return UCLocalize("SETTINGS"); }
7234
7235 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7236 if ((self = [super init])) {
7237 database_ = database;
7238 name_ = [package retain];
7239
7240 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7241
7242 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7243 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7244 [[self view] addSubview:table_];
7245
7246 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7247 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7248 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7249
7250 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7251 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7252 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7253 // Disable this switch, since it only reflects (not modifies) the ignored state.
7254 [ignoredSwitch_ setUserInteractionEnabled:NO];
7255
7256 subscribedCell_ = [[UITableViewCell alloc] init];
7257 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7258 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7259 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7260
7261 ignoredCell_ = [[UITableViewCell alloc] init];
7262 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7263 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7264 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7265 // FIXME: Ignored state is not saved.
7266 [ignoredCell_ setUserInteractionEnabled:NO];
7267
7268 [table_ setDataSource:self];
7269 [table_ setDelegate:self];
7270 [self reloadData];
7271 } return self;
7272 }
7273
7274 - (void) reloadData {
7275 if (package_ != nil)
7276 [package_ autorelease];
7277 package_ = [database_ packageWithName:name_];
7278 if (package_ != nil) {
7279 [package_ retain];
7280 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7281 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7282 }
7283
7284 [table_ reloadData];
7285 }
7286
7287 @end
7288 /* }}} */
7289 /* Signature Controller {{{ */
7290 @interface SignatureController : CYBrowserController {
7291 _transient Database *database_;
7292 NSString *package_;
7293 }
7294
7295 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7296
7297 @end
7298
7299 @implementation SignatureController
7300
7301 - (void) dealloc {
7302 [package_ release];
7303 [super dealloc];
7304 }
7305
7306 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7307 // XXX: dude!
7308 [super webView:view didClearWindowObject:window forFrame:frame];
7309 }
7310
7311 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7312 if ((self = [super init]) != nil) {
7313 database_ = database;
7314 package_ = [package retain];
7315 [self reloadData];
7316 } return self;
7317 }
7318
7319 - (void) reloadData {
7320 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7321 }
7322
7323 @end
7324 /* }}} */
7325
7326 /* Installed Controller {{{ */
7327 @interface InstalledController : FilteredPackageController {
7328 BOOL expert_;
7329 }
7330
7331 - (id) initWithDatabase:(Database *)database;
7332
7333 - (void) updateRoleButton;
7334 - (void) queueStatusDidChange;
7335
7336 @end
7337
7338 @implementation InstalledController
7339
7340 - (void) dealloc {
7341 [super dealloc];
7342 }
7343
7344 - (NSString *) title { return UCLocalize("INSTALLED"); }
7345
7346 - (id) initWithDatabase:(Database *)database {
7347 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7348 [self updateRoleButton];
7349 [self queueStatusDidChange];
7350 } return self;
7351 }
7352
7353 #if !AlwaysReload
7354 - (void) queueButtonClicked {
7355 [delegate_ queue];
7356 }
7357 #endif
7358
7359 - (void) queueStatusDidChange {
7360 #if !AlwaysReload
7361 if (IsWildcat_) {
7362 if (Queuing_) {
7363 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7364 initWithTitle:UCLocalize("QUEUE")
7365 style:UIBarButtonItemStyleDone
7366 target:self
7367 action:@selector(queueButtonClicked)
7368 ] autorelease]];
7369 } else {
7370 [[self navigationItem] setLeftBarButtonItem:nil];
7371 }
7372 }
7373 #endif
7374 }
7375
7376 - (void) reloadData {
7377 [packages_ reloadData];
7378 }
7379
7380 - (void) updateRoleButton {
7381 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7382 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7383 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7384 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7385 target:self
7386 action:@selector(roleButtonClicked)
7387 ] autorelease]];
7388 }
7389
7390 - (void) roleButtonClicked {
7391 [packages_ setObject:[NSNumber numberWithBool:expert_]];
7392 [packages_ reloadData];
7393 expert_ = !expert_;
7394
7395 [self updateRoleButton];
7396 }
7397
7398 - (void) setDelegate:(id)delegate {
7399 [super setDelegate:delegate];
7400 [packages_ setDelegate:delegate];
7401 }
7402
7403 @end
7404 /* }}} */
7405
7406 /* Source Cell {{{ */
7407 @interface SourceCell : CYTableViewCell <
7408 ContentDelegate
7409 > {
7410 UIImage *icon_;
7411 NSString *origin_;
7412 NSString *label_;
7413 }
7414
7415 - (void) setSource:(Source *)source;
7416
7417 @end
7418
7419 @implementation SourceCell
7420
7421 - (void) clearSource {
7422 [icon_ release];
7423 [origin_ release];
7424 [label_ release];
7425
7426 icon_ = nil;
7427 origin_ = nil;
7428 label_ = nil;
7429 }
7430
7431 - (void) setSource:(Source *)source {
7432 [self clearSource];
7433
7434 if (icon_ == nil)
7435 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7436 if (icon_ == nil)
7437 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7438 icon_ = [icon_ retain];
7439
7440 origin_ = [[source name] retain];
7441 label_ = [[source uri] retain];
7442
7443 [content_ setNeedsDisplay];
7444 }
7445
7446 - (void) dealloc {
7447 [self clearSource];
7448 [super dealloc];
7449 }
7450
7451 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7452 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7453 UIView *content([self contentView]);
7454 CGRect bounds([content bounds]);
7455
7456 content_ = [[ContentView alloc] initWithFrame:bounds];
7457 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7458 [content_ setBackgroundColor:[UIColor whiteColor]];
7459 [content addSubview:content_];
7460
7461 [content_ setDelegate:self];
7462 [content_ setOpaque:YES];
7463 } return self;
7464 }
7465
7466 - (NSString *) accessibilityLabel {
7467 return label_;
7468 }
7469
7470 - (void) drawContentRect:(CGRect)rect {
7471 bool highlighted(highlighted_);
7472 float width(rect.size.width);
7473
7474 if (icon_ != nil)
7475 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7476
7477 if (highlighted)
7478 UISetColor(White_);
7479
7480 if (!highlighted)
7481 UISetColor(Black_);
7482 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7483
7484 if (!highlighted)
7485 UISetColor(Blue_);
7486 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7487 }
7488
7489 @end
7490 /* }}} */
7491 /* Source Controller {{{ */
7492 @interface SourceController : FilteredPackageController {
7493 }
7494
7495 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7496
7497 @end
7498
7499 @implementation SourceController
7500
7501 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7502 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7503 } return self;
7504 }
7505
7506 @end
7507 /* }}} */
7508 /* Sources Controller {{{ */
7509 @interface SourcesController : CYViewController <
7510 UITableViewDataSource,
7511 UITableViewDelegate
7512 > {
7513 _transient Database *database_;
7514 UITableView *list_;
7515 NSMutableArray *sources_;
7516 int offset_;
7517
7518 NSString *href_;
7519 UIProgressHUD *hud_;
7520 NSError *error_;
7521
7522 //NSURLConnection *installer_;
7523 NSURLConnection *trivial_;
7524 NSURLConnection *trivial_bz2_;
7525 NSURLConnection *trivial_gz_;
7526 //NSURLConnection *automatic_;
7527
7528 BOOL cydia_;
7529 }
7530
7531 - (id) initWithDatabase:(Database *)database;
7532
7533 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7534
7535 @end
7536
7537 @implementation SourcesController
7538
7539 - (void) _releaseConnection:(NSURLConnection *)connection {
7540 if (connection != nil) {
7541 [connection cancel];
7542 //[connection setDelegate:nil];
7543 [connection release];
7544 }
7545 }
7546
7547 - (void) dealloc {
7548 if (href_ != nil)
7549 [href_ release];
7550 if (hud_ != nil)
7551 [hud_ release];
7552 if (error_ != nil)
7553 [error_ release];
7554
7555 //[self _releaseConnection:installer_];
7556 [self _releaseConnection:trivial_];
7557 [self _releaseConnection:trivial_gz_];
7558 [self _releaseConnection:trivial_bz2_];
7559 //[self _releaseConnection:automatic_];
7560
7561 [sources_ release];
7562 [list_ release];
7563 [super dealloc];
7564 }
7565
7566 - (void) viewDidAppear:(BOOL)animated {
7567 [super viewDidAppear:animated];
7568 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7569 }
7570
7571 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7572 return offset_ == 0 ? 1 : 2;
7573 }
7574
7575 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7576 switch (section + (offset_ == 0 ? 1 : 0)) {
7577 case 0: return UCLocalize("ENTERED_BY_USER");
7578 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7579
7580 _nodefault
7581 }
7582 }
7583
7584 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7585 int count = [sources_ count];
7586 switch (section) {
7587 case 0: return (offset_ == 0 ? count : offset_);
7588 case 1: return count - offset_;
7589
7590 _nodefault
7591 }
7592 }
7593
7594 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7595 unsigned idx = 0;
7596 switch (indexPath.section) {
7597 case 0: idx = indexPath.row; break;
7598 case 1: idx = indexPath.row + offset_; break;
7599
7600 _nodefault
7601 }
7602 return [sources_ objectAtIndex:idx];
7603 }
7604
7605 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7606 static NSString *cellIdentifier = @"SourceCell";
7607
7608 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7609 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7610 [cell setSource:[self sourceAtIndexPath:indexPath]];
7611 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7612
7613 return cell;
7614 }
7615
7616 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7617 Source *source = [self sourceAtIndexPath:indexPath];
7618
7619 SourceController *controller = [[[SourceController alloc]
7620 initWithDatabase:database_
7621 source:source
7622 ] autorelease];
7623
7624 [controller setDelegate:delegate_];
7625
7626 [[self navigationController] pushViewController:controller animated:YES];
7627 }
7628
7629 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7630 Source *source = [self sourceAtIndexPath:indexPath];
7631 return [source record] != nil;
7632 }
7633
7634 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7635 Source *source = [self sourceAtIndexPath:indexPath];
7636 [Sources_ removeObjectForKey:[source key]];
7637 [delegate_ syncData];
7638 }
7639
7640 - (void) complete {
7641 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
7642 @"deb", @"Type",
7643 href_, @"URI",
7644 @"./", @"Distribution",
7645 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
7646
7647 [delegate_ syncData];
7648 }
7649
7650 - (NSString *) getWarning {
7651 NSString *href(href_);
7652 NSRange colon([href rangeOfString:@"://"]);
7653 if (colon.location != NSNotFound)
7654 href = [href substringFromIndex:(colon.location + 3)];
7655 href = [href stringByAddingPercentEscapes];
7656 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7657 href = [href stringByCachingURLWithCurrentCDN];
7658
7659 NSURL *url([NSURL URLWithString:href]);
7660
7661 NSStringEncoding encoding;
7662 NSError *error(nil);
7663
7664 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7665 return [warning length] == 0 ? nil : warning;
7666 return nil;
7667 }
7668
7669 - (void) _endConnection:(NSURLConnection *)connection {
7670 // XXX: the memory management in this method is horribly awkward
7671
7672 NSURLConnection **field = NULL;
7673 if (connection == trivial_)
7674 field = &trivial_;
7675 else if (connection == trivial_bz2_)
7676 field = &trivial_bz2_;
7677 else if (connection == trivial_gz_)
7678 field = &trivial_gz_;
7679 _assert(field != NULL);
7680 [connection release];
7681 *field = nil;
7682
7683 if (
7684 trivial_ == nil &&
7685 trivial_bz2_ == nil &&
7686 trivial_gz_ == nil
7687 ) {
7688 bool defer(false);
7689
7690 if (cydia_) {
7691 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7692 defer = true;
7693
7694 UIAlertView *alert = [[[UIAlertView alloc]
7695 initWithTitle:UCLocalize("SOURCE_WARNING")
7696 message:warning
7697 delegate:self
7698 cancelButtonTitle:UCLocalize("CANCEL")
7699 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
7700 ] autorelease];
7701
7702 [alert setContext:@"warning"];
7703 [alert setNumberOfRows:1];
7704 [alert show];
7705 } else
7706 [self complete];
7707 } else if (error_ != nil) {
7708 UIAlertView *alert = [[[UIAlertView alloc]
7709 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7710 message:[error_ localizedDescription]
7711 delegate:self
7712 cancelButtonTitle:UCLocalize("OK")
7713 otherButtonTitles:nil
7714 ] autorelease];
7715
7716 [alert setContext:@"urlerror"];
7717 [alert show];
7718 } else {
7719 UIAlertView *alert = [[[UIAlertView alloc]
7720 initWithTitle:UCLocalize("NOT_REPOSITORY")
7721 message:UCLocalize("NOT_REPOSITORY_EX")
7722 delegate:self
7723 cancelButtonTitle:UCLocalize("OK")
7724 otherButtonTitles:nil
7725 ] autorelease];
7726
7727 [alert setContext:@"trivial"];
7728 [alert show];
7729 }
7730
7731 [delegate_ setStatusBarShowsProgress:NO];
7732 [delegate_ removeProgressHUD:hud_];
7733
7734 [hud_ autorelease];
7735 hud_ = nil;
7736
7737 if (!defer) {
7738 [href_ release];
7739 href_ = nil;
7740 }
7741
7742 if (error_ != nil) {
7743 [error_ release];
7744 error_ = nil;
7745 }
7746 }
7747 }
7748
7749 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7750 switch ([response statusCode]) {
7751 case 200:
7752 cydia_ = YES;
7753 }
7754 }
7755
7756 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7757 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7758 if (error_ != nil)
7759 error_ = [error retain];
7760 [self _endConnection:connection];
7761 }
7762
7763 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7764 [self _endConnection:connection];
7765 }
7766
7767 - (NSString *) title { return UCLocalize("SOURCES"); }
7768
7769 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7770 NSMutableURLRequest *request = [NSMutableURLRequest
7771 requestWithURL:[NSURL URLWithString:href]
7772 cachePolicy:NSURLRequestUseProtocolCachePolicy
7773 timeoutInterval:120.0
7774 ];
7775
7776 [request setHTTPMethod:method];
7777
7778 if (Machine_ != NULL)
7779 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
7780 if (UniqueID_ != nil)
7781 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
7782 if (Role_ != nil)
7783 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
7784
7785 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
7786 }
7787
7788 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7789 NSString *context([alert context]);
7790
7791 if ([context isEqualToString:@"source"]) {
7792 switch (button) {
7793 case 1: {
7794 NSString *href = [[alert textField] text];
7795
7796 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
7797
7798 if (![href hasSuffix:@"/"])
7799 href_ = [href stringByAppendingString:@"/"];
7800 else
7801 href_ = href;
7802 href_ = [href_ retain];
7803
7804 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7805 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
7806 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
7807 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
7808
7809 cydia_ = false;
7810
7811 // XXX: this is stupid
7812 hud_ = [[delegate_ addProgressHUD] retain];
7813 [hud_ setText:UCLocalize("VERIFYING_URL")];
7814 } break;
7815
7816 case 0:
7817 break;
7818
7819 _nodefault
7820 }
7821
7822 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7823 } else if ([context isEqualToString:@"trivial"])
7824 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7825 else if ([context isEqualToString:@"urlerror"])
7826 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7827 else if ([context isEqualToString:@"warning"]) {
7828 switch (button) {
7829 case 1:
7830 [self complete];
7831 break;
7832
7833 case 0:
7834 break;
7835
7836 _nodefault
7837 }
7838
7839 [href_ release];
7840 href_ = nil;
7841
7842 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7843 }
7844 }
7845
7846 - (id) initWithDatabase:(Database *)database {
7847 if ((self = [super init]) != nil) {
7848 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
7849 [self updateButtonsForEditingStatus:NO animated:NO];
7850
7851 database_ = database;
7852 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
7853
7854 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7855 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7856 [list_ setRowHeight:56];
7857 [[self view] addSubview:list_];
7858
7859 [list_ setDataSource:self];
7860 [list_ setDelegate:self];
7861
7862 [self reloadData];
7863 } return self;
7864 }
7865
7866 - (void) reloadData {
7867 pkgSourceList list;
7868 if (!list.ReadMainList())
7869 return;
7870
7871 [sources_ removeAllObjects];
7872 [sources_ addObjectsFromArray:[database_ sources]];
7873 _trace();
7874 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
7875 _trace();
7876
7877 int count([sources_ count]);
7878 offset_ = 0;
7879 for (int i = 0; i != count; i++) {
7880 if ([[sources_ objectAtIndex:i] record] == nil)
7881 break;
7882 offset_++;
7883 }
7884
7885 [list_ setEditing:NO];
7886 [self updateButtonsForEditingStatus:NO animated:NO];
7887 [list_ reloadData];
7888 }
7889
7890 - (void) showAddSourcePrompt {
7891 UIAlertView *alert = [[[UIAlertView alloc]
7892 initWithTitle:UCLocalize("ENTER_APT_URL")
7893 message:nil
7894 delegate:self
7895 cancelButtonTitle:UCLocalize("CANCEL")
7896 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
7897 ] autorelease];
7898
7899 [alert setContext:@"source"];
7900 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
7901
7902 [alert setNumberOfRows:1];
7903 [alert addTextFieldWithValue:@"http://" label:@""];
7904
7905 UITextInputTraits *traits = [[alert textField] textInputTraits];
7906 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7907 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7908 [traits setKeyboardType:UIKeyboardTypeURL];
7909 // XXX: UIReturnKeyDone
7910 [traits setReturnKeyType:UIReturnKeyNext];
7911
7912 [alert show];
7913 }
7914
7915 - (void) addButtonClicked {
7916 [self showAddSourcePrompt];
7917 }
7918
7919 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
7920 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
7921 initWithTitle:UCLocalize("ADD")
7922 style:UIBarButtonItemStylePlain
7923 target:self
7924 action:@selector(addButtonClicked)
7925 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
7926
7927 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7928 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
7929 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7930 target:self
7931 action:@selector(editButtonClicked)
7932 ] autorelease] animated:animated];
7933
7934 if (IsWildcat_ && !editing)
7935 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7936 initWithTitle:UCLocalize("SETTINGS")
7937 style:UIBarButtonItemStylePlain
7938 target:self
7939 action:@selector(settingsButtonClicked)
7940 ] autorelease]];
7941 }
7942
7943 - (void) settingsButtonClicked {
7944 [delegate_ showSettings];
7945 }
7946
7947 - (void) editButtonClicked {
7948 [list_ setEditing:![list_ isEditing] animated:YES];
7949
7950 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
7951 }
7952
7953 @end
7954 /* }}} */
7955
7956 /* Settings Controller {{{ */
7957 @interface SettingsController : CYViewController <
7958 UITableViewDataSource,
7959 UITableViewDelegate
7960 > {
7961 _transient Database *database_;
7962 // XXX: ok, "roledelegate_"?...
7963 _transient id roledelegate_;
7964 UITableView *table_;
7965 UISegmentedControl *segment_;
7966 UIView *container_;
7967 }
7968
7969 - (void) showDoneButton;
7970 - (void) resizeSegmentedControl;
7971
7972 @end
7973
7974 @implementation SettingsController
7975 - (void) dealloc {
7976 [table_ release];
7977 [segment_ release];
7978 [container_ release];
7979
7980 [super dealloc];
7981 }
7982
7983 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7984 if ((self = [super init])) {
7985 database_ = database;
7986 roledelegate_ = delegate;
7987
7988 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7989
7990 NSArray *items = [NSArray arrayWithObjects:
7991 UCLocalize("USER"),
7992 UCLocalize("HACKER"),
7993 UCLocalize("DEVELOPER"),
7994 nil];
7995 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7996 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7997 [container_ addSubview:segment_];
7998
7999 int index = -1;
8000 if ([Role_ isEqualToString:@"User"]) index = 0;
8001 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
8002 if ([Role_ isEqualToString:@"Developer"]) index = 2;
8003 if (index != -1) {
8004 [segment_ setSelectedSegmentIndex:index];
8005 [self showDoneButton];
8006 }
8007
8008 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8009 [self resizeSegmentedControl];
8010
8011 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8012 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8013 [table_ setDelegate:self];
8014 [table_ setDataSource:self];
8015 [[self view] addSubview:table_];
8016 [table_ reloadData];
8017 } return self;
8018 }
8019
8020 - (void) resizeSegmentedControl {
8021 CGFloat width = [[self view] frame].size.width;
8022 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8023 }
8024
8025 - (void) viewWillAppear:(BOOL)animated {
8026 [super viewWillAppear:animated];
8027
8028 [self resizeSegmentedControl];
8029 }
8030
8031 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8032 [self resizeSegmentedControl];
8033 }
8034
8035 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8036 [self resizeSegmentedControl];
8037 }
8038
8039 - (void) save {
8040 NSString *role(nil);
8041
8042 switch ([segment_ selectedSegmentIndex]) {
8043 case 0: role = @"User"; break;
8044 case 1: role = @"Hacker"; break;
8045 case 2: role = @"Developer"; break;
8046
8047 _nodefault
8048 }
8049
8050 if (![role isEqualToString:Role_]) {
8051 bool rolling(Role_ == nil);
8052 Role_ = role;
8053
8054 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8055 Role_, @"Role",
8056 nil];
8057
8058 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8059 Changed_ = true;
8060
8061 if (rolling)
8062 [roledelegate_ loadData];
8063 else
8064 [roledelegate_ updateData];
8065 }
8066 }
8067
8068 - (void) segmentChanged:(UISegmentedControl *)control {
8069 [self showDoneButton];
8070 }
8071
8072 - (void) saveAndClose {
8073 [self save];
8074
8075 [[self navigationItem] setRightBarButtonItem:nil];
8076 [[self navigationController] dismissModalViewControllerAnimated:YES];
8077 }
8078
8079 - (void) doneButtonClicked {
8080 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8081 [spinner startAnimating];
8082 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8083 [[self navigationItem] setRightBarButtonItem:spinItem];
8084
8085 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8086 }
8087
8088 - (void) showDoneButton {
8089 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8090 initWithTitle:UCLocalize("DONE")
8091 style:UIBarButtonItemStyleDone
8092 target:self
8093 action:@selector(doneButtonClicked)
8094 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8095 }
8096
8097 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8098 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8099 return 6;
8100 }
8101
8102 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8103 return 0; // :(
8104 }
8105
8106 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8107 return nil; // This method is required by the protocol.
8108 }
8109
8110 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8111 if (section == 1)
8112 return UCLocalize("ROLE_EX");
8113 if (section == 4)
8114 return [NSString stringWithFormat:
8115 @"%@: %@\n%@: %@\n%@: %@",
8116 UCLocalize("USER"), UCLocalize("USER_EX"),
8117 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8118 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8119 ];
8120 else return nil;
8121 }
8122
8123 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8124 return section == 3 ? 44.0f : 0;
8125 }
8126
8127 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8128 return section == 3 ? container_ : nil;
8129 }
8130
8131 @end
8132 /* }}} */
8133 /* Stash Controller {{{ */
8134 @interface StashController : CYViewController {
8135 // XXX: just delete these things
8136 _transient UIActivityIndicatorView *spinner_;
8137 _transient UILabel *status_;
8138 _transient UILabel *caption_;
8139 }
8140 @end
8141
8142 @implementation StashController
8143 - (id) init {
8144 if ((self = [super init])) {
8145 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8146
8147 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8148 CGRect spinrect = [spinner_ frame];
8149 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8150 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8151 [spinner_ setFrame:spinrect];
8152 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8153 [[self view] addSubview:spinner_];
8154 [spinner_ startAnimating];
8155
8156 CGRect captrect;
8157 captrect.size.width = [[self view] frame].size.width;
8158 captrect.size.height = 40.0f;
8159 captrect.origin.x = 0;
8160 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8161 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8162 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8163 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8164 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8165 [caption_ setTextColor:[UIColor whiteColor]];
8166 [caption_ setBackgroundColor:[UIColor clearColor]];
8167 [caption_ setShadowColor:[UIColor blackColor]];
8168 [caption_ setTextAlignment:UITextAlignmentCenter];
8169 [[self view] addSubview:caption_];
8170
8171 CGRect statusrect;
8172 statusrect.size.width = [[self view] frame].size.width;
8173 statusrect.size.height = 30.0f;
8174 statusrect.origin.x = 0;
8175 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8176 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8177 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8178 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8179 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8180 [status_ setTextColor:[UIColor whiteColor]];
8181 [status_ setBackgroundColor:[UIColor clearColor]];
8182 [status_ setShadowColor:[UIColor blackColor]];
8183 [status_ setTextAlignment:UITextAlignmentCenter];
8184 [[self view] addSubview:status_];
8185 } return self;
8186 }
8187
8188 @end
8189 /* }}} */
8190
8191 @interface Cydia : UIApplication <
8192 ConfirmationControllerDelegate,
8193 ProgressControllerDelegate,
8194 CydiaDelegate,
8195 UINavigationControllerDelegate,
8196 UITabBarControllerDelegate
8197 > {
8198 // XXX: evaluate all fields for _transient
8199
8200 UIWindow *window_;
8201 CYTabBarController *tabbar_;
8202
8203 NSMutableArray *essential_;
8204 NSMutableArray *broken_;
8205
8206 Database *database_;
8207
8208 NSURL *starturl_;
8209
8210 unsigned locked_;
8211 unsigned activity_;
8212
8213 StashController *stash_;
8214
8215 bool loaded_;
8216 }
8217
8218 - (void) loadData;
8219
8220 @end
8221
8222 @implementation Cydia
8223
8224 - (void) beginUpdate {
8225 [tabbar_ beginUpdate];
8226 }
8227
8228 - (BOOL) updating {
8229 return [tabbar_ updating];
8230 }
8231
8232 - (void) _loaded {
8233 if ([broken_ count] != 0) {
8234 int count = [broken_ count];
8235
8236 UIAlertView *alert = [[[UIAlertView alloc]
8237 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8238 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8239 delegate:self
8240 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8241 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8242 ] autorelease];
8243
8244 [alert setContext:@"fixhalf"];
8245 [alert show];
8246 } else if (!Ignored_ && [essential_ count] != 0) {
8247 int count = [essential_ count];
8248
8249 UIAlertView *alert = [[[UIAlertView alloc]
8250 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8251 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8252 delegate:self
8253 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8254 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8255 ] autorelease];
8256
8257 [alert setContext:@"upgrade"];
8258 [alert show];
8259 }
8260 }
8261
8262 - (void) _saveConfig {
8263 _trace();
8264 MetaFile_.Sync();
8265 _trace();
8266
8267 if (Changed_) {
8268 NSString *error(nil);
8269
8270 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8271 _trace();
8272 NSError *error(nil);
8273 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8274 NSLog(@"failure to save metadata data: %@", error);
8275 _trace();
8276
8277 Changed_ = false;
8278 } else {
8279 NSLog(@"failure to serialize metadata: %@", error);
8280 }
8281 }
8282 }
8283
8284 // Navigation controller for the queuing badge.
8285 - (CYNavigationController *) queueNavigationController {
8286 NSArray *controllers = [tabbar_ viewControllers];
8287 return [controllers objectAtIndex:3];
8288 }
8289
8290 - (void) _updateData {
8291 [self _saveConfig];
8292
8293 [tabbar_ reloadData];
8294
8295 CYNavigationController *navigation = [self queueNavigationController];
8296
8297 id queuedelegate = nil;
8298 if ([[navigation viewControllers] count] > 0)
8299 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8300
8301 [queuedelegate queueStatusDidChange];
8302 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8303 }
8304
8305 - (void) _refreshIfPossible {
8306 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8307
8308 bool recently = false;
8309 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8310 if (update != nil) {
8311 NSTimeInterval interval([update timeIntervalSinceNow]);
8312 if (interval <= 0 && interval > -(15*60))
8313 recently = true;
8314 }
8315
8316 // Don't automatic refresh if:
8317 // - We already refreshed recently.
8318 // - We already auto-refreshed this launch.
8319 // - Auto-refresh is disabled.
8320 if (recently || loaded_ || ManualRefresh) {
8321 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8322
8323 // If we are cancelling due to ManualRefresh or a recent refresh
8324 // we need to make sure it knows it's already loaded.
8325 loaded_ = true;
8326 return;
8327 } else {
8328 // We are going to load, so remember that.
8329 loaded_ = true;
8330 }
8331
8332 SCNetworkReachabilityFlags flags; {
8333 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8334 SCNetworkReachabilityGetFlags(reachability, &flags);
8335 CFRelease(reachability);
8336 }
8337
8338 // XXX: this elaborate mess is what Apple is using to determine this? :(
8339 // XXX: do we care if the user has to intervene? maybe that's ok?
8340 bool reachable(
8341 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8342 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8343 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8344 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8345 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8346 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8347 )
8348 );
8349
8350 // If we can reach the server, auto-refresh!
8351 if (reachable)
8352 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8353
8354 [pool release];
8355 }
8356
8357 - (void) refreshIfPossible {
8358 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8359 }
8360
8361 - (void) _reloadData {
8362 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8363 [hud setText:UCLocalize("RELOADING_DATA")];
8364
8365 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8366
8367 if (hud != nil)
8368 [self removeProgressHUD:hud];
8369
8370 size_t changes(0);
8371
8372 [essential_ removeAllObjects];
8373 [broken_ removeAllObjects];
8374
8375 NSArray *packages([database_ packages]);
8376 for (Package *package in packages) {
8377 if ([package half])
8378 [broken_ addObject:package];
8379 if ([package upgradableAndEssential:NO]) {
8380 if ([package essential])
8381 [essential_ addObject:package];
8382 ++changes;
8383 }
8384 }
8385
8386 NSLog(@"changes:#%u", changes);
8387
8388 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8389 if (changes != 0) {
8390 _trace();
8391 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8392 [changesItem setBadgeValue:badge];
8393 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8394 [self setApplicationIconBadgeNumber:changes];
8395 } else {
8396 _trace();
8397 [changesItem setBadgeValue:nil];
8398 [changesItem setAnimatedBadge:NO];
8399 [self setApplicationIconBadgeNumber:0];
8400 }
8401
8402 [self _updateData];
8403
8404 [self refreshIfPossible];
8405 }
8406
8407 - (void) updateData {
8408 [self _updateData];
8409 }
8410
8411 - (void) update_ {
8412 [database_ update];
8413 }
8414
8415 - (void) syncData {
8416 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8417 _assert(file != NULL);
8418
8419 for (NSString *key in [Sources_ allKeys]) {
8420 NSDictionary *source([Sources_ objectForKey:key]);
8421
8422 fprintf(file, "%s %s %s\n",
8423 [[source objectForKey:@"Type"] UTF8String],
8424 [[source objectForKey:@"URI"] UTF8String],
8425 [[source objectForKey:@"Distribution"] UTF8String]
8426 );
8427 }
8428
8429 fclose(file);
8430
8431 [self _saveConfig];
8432
8433 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8434 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8435 if (IsWildcat_)
8436 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8437 [tabbar_ presentModalViewController:navigation animated:YES];
8438
8439 [progress
8440 detachNewThreadSelector:@selector(update_)
8441 toTarget:self
8442 withObject:nil
8443 title:UCLocalize("UPDATING_SOURCES")
8444 ];
8445 }
8446
8447 - (void) reloadData {
8448 @synchronized (self) {
8449 [self _reloadData];
8450 }
8451 }
8452
8453 - (void) resolve {
8454 pkgProblemResolver *resolver = [database_ resolver];
8455
8456 resolver->InstallProtect();
8457 if (!resolver->Resolve(true))
8458 _error->Discard();
8459 }
8460
8461 - (bool) perform {
8462 if (![database_ prepare])
8463 return false;
8464
8465 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8466 [page setDelegate:self];
8467 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8468 [confirm_ setDelegate:self];
8469
8470 if (IsWildcat_)
8471 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8472 [tabbar_ presentModalViewController:confirm_ animated:YES];
8473
8474 return true;
8475 }
8476
8477 - (void) queue {
8478 @synchronized (self) {
8479 [self perform];
8480 }
8481 }
8482
8483 - (void) clearPackage:(Package *)package {
8484 @synchronized (self) {
8485 [package clear];
8486 [self resolve];
8487 [self perform];
8488 }
8489 }
8490
8491 - (void) installPackages:(NSArray *)packages {
8492 @synchronized (self) {
8493 for (Package *package in packages)
8494 [package install];
8495 [self resolve];
8496 [self perform];
8497 }
8498 }
8499
8500 - (void) installPackage:(Package *)package {
8501 @synchronized (self) {
8502 [package install];
8503 [self resolve];
8504 [self perform];
8505 }
8506 }
8507
8508 - (void) removePackage:(Package *)package {
8509 @synchronized (self) {
8510 [package remove];
8511 [self resolve];
8512 [self perform];
8513 }
8514 }
8515
8516 - (void) distUpgrade {
8517 @synchronized (self) {
8518 if (![database_ upgrade])
8519 return;
8520 [self perform];
8521 }
8522 }
8523
8524 - (void) complete {
8525 @synchronized (self) {
8526 [self _reloadData];
8527 }
8528 }
8529
8530 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8531 Queuing_ = false;
8532
8533 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8534
8535 if (navigation != nil) {
8536 [navigation pushViewController:progress animated:YES];
8537 } else {
8538 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8539 if (IsWildcat_)
8540 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8541 [tabbar_ presentModalViewController:navigation animated:YES];
8542 }
8543
8544 [progress
8545 detachNewThreadSelector:@selector(perform)
8546 toTarget:database_
8547 withObject:nil
8548 title:UCLocalize("RUNNING")
8549 ];
8550
8551 ++locked_;
8552 }
8553
8554 - (void) progressControllerIsComplete:(ProgressController *)progress {
8555 --locked_;
8556 [self complete];
8557 }
8558
8559 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8560 CYNavigationController *controller = (CYNavigationController *) viewController;
8561
8562 if ([[controller viewControllers] count] == 0) {
8563 int index = [[tabbar_ viewControllers] indexOfObjectIdenticalTo:controller];
8564 CYViewController *root = nil;
8565
8566 if (index == 0)
8567 root = [[[HomeController alloc] init] autorelease];
8568 else if (index == 1)
8569 root = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8570 else if (index == 2)
8571 root = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8572
8573 if (IsWildcat_) {
8574 if (index == 3)
8575 root = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8576 else if (index == 4)
8577 root = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8578 else if (index == 5)
8579 root = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8580 } else {
8581 if (index == 3)
8582 root = [[[ManageController alloc] init] autorelease];
8583 else if (index == 4)
8584 root = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8585 }
8586
8587 [root setDelegate:self];
8588
8589 if (root != nil)
8590 [controller setViewControllers:[NSArray arrayWithObject:root]];
8591 }
8592 }
8593
8594 - (void) showSettings {
8595 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8596 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8597 if (IsWildcat_)
8598 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8599 [tabbar_ presentModalViewController:nav animated:YES];
8600 }
8601
8602 - (void) retainNetworkActivityIndicator {
8603 if (activity_++ == 0)
8604 [self setNetworkActivityIndicatorVisible:YES];
8605 }
8606
8607 - (void) releaseNetworkActivityIndicator {
8608 if (--activity_ == 0)
8609 [self setNetworkActivityIndicatorVisible:NO];
8610 }
8611
8612 - (void) cancelAndClear:(bool)clear {
8613 @synchronized (self) {
8614 if (clear) {
8615 [database_ clear];
8616 Queuing_ = false;
8617 } else {
8618 Queuing_ = true;
8619 }
8620
8621 [self _updateData];
8622 }
8623 }
8624
8625 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8626 NSString *context([alert context]);
8627
8628 if ([context isEqualToString:@"fixhalf"]) {
8629 if (button == [alert firstOtherButtonIndex]) {
8630 @synchronized (self) {
8631 for (Package *broken in broken_) {
8632 [broken remove];
8633
8634 NSString *id = [broken id];
8635 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8636 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8637 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8638 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8639 }
8640
8641 [self resolve];
8642 [self perform];
8643 }
8644 } else if (button == [alert cancelButtonIndex]) {
8645 [broken_ removeAllObjects];
8646 [self _loaded];
8647 }
8648
8649 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8650 } else if ([context isEqualToString:@"upgrade"]) {
8651 if (button == [alert firstOtherButtonIndex]) {
8652 @synchronized (self) {
8653 for (Package *essential in essential_)
8654 [essential install];
8655
8656 [self resolve];
8657 [self perform];
8658 }
8659 } else if (button == [alert firstOtherButtonIndex] + 1) {
8660 [self distUpgrade];
8661 } else if (button == [alert cancelButtonIndex]) {
8662 Ignored_ = YES;
8663 }
8664
8665 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8666 }
8667 }
8668
8669 - (void) system:(NSString *)command { _pooled
8670 _trace();
8671 system([command UTF8String]);
8672 _trace();
8673 }
8674
8675 - (void) applicationWillSuspend {
8676 [database_ clean];
8677 [super applicationWillSuspend];
8678 }
8679
8680 - (BOOL) isSafeToSuspend {
8681 // Use external process status API internally.
8682 // This is probably a really bad idea.
8683 // XXX: what is the point of this? does this solve anything at all?
8684 uint64_t status = 0;
8685 int notify_token;
8686 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
8687 notify_get_state(notify_token, &status);
8688 notify_cancel(notify_token);
8689 }
8690
8691 return locked_ == 0 && status == 0;
8692 }
8693
8694 - (void) applicationSuspend:(__GSEvent *)event {
8695 if ([self isSafeToSuspend])
8696 [super applicationSuspend:event];
8697 }
8698
8699 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8700 if ([self isSafeToSuspend])
8701 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8702 }
8703
8704 - (void) _setSuspended:(BOOL)value {
8705 if ([self isSafeToSuspend])
8706 [super _setSuspended:value];
8707 }
8708
8709 - (UIProgressHUD *) addProgressHUD {
8710 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8711 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8712
8713 [window_ setUserInteractionEnabled:NO];
8714 [hud show:YES];
8715
8716 UIViewController *target = tabbar_;
8717 while ([target modalViewController] != nil) target = [target modalViewController];
8718 [[target view] addSubview:hud];
8719
8720 ++locked_;
8721 return hud;
8722 }
8723
8724 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8725 [hud show:NO];
8726 [hud removeFromSuperview];
8727 [window_ setUserInteractionEnabled:YES];
8728 --locked_;
8729 }
8730
8731 - (CYViewController *) pageForPackage:(NSString *)name {
8732 if (Package *package = [database_ packageWithName:name]) {
8733 CYPackageController *view = [[[CYPackageController alloc] initWithDatabase:database_] autorelease];
8734 [view setPackage:package];
8735 return view;
8736 } else {
8737 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8738 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8739 CYBrowserController *browser = [[[CYBrowserController alloc] init] autorelease];
8740 [browser loadURL:url];
8741 return browser;
8742 }
8743 }
8744
8745 - (CYViewController *) pageForURL:(NSURL *)url {
8746 NSString *scheme([[url scheme] lowercaseString]);
8747 if ([[url absoluteString] length] <= [scheme length] + 3)
8748 return nil;
8749 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8750 NSArray *components([path pathComponents]);
8751
8752 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
8753 return [self pageForPackage:[components objectAtIndex:1]];
8754
8755 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8756 return nil;
8757
8758 NSString *base([components objectAtIndex:0]);
8759
8760 CYViewController *controller = nil;
8761
8762 if ([base isEqualToString:@"url"]) {
8763 // This kind of URL can contain slashes in the argument, so we can't parse them below.
8764 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
8765 controller = [[[CYBrowserController alloc] init] autorelease];
8766 [(CYBrowserController *)controller loadURL:[NSURL URLWithString:destination]];
8767 } else if ([components count] == 1) {
8768 if ([base isEqualToString:@"sources"]) {
8769 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8770 }
8771
8772 if ([base isEqualToString:@"home"]) {
8773 controller = [[[HomeController alloc] init] autorelease];
8774 }
8775
8776 if ([base isEqualToString:@"sections"]) {
8777 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8778 }
8779
8780 if ([base isEqualToString:@"search"]) {
8781 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8782 }
8783
8784 if ([base isEqualToString:@"changes"]) {
8785 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8786 }
8787
8788 if ([base isEqualToString:@"installed"]) {
8789 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8790 }
8791 } else if ([components count] == 2) {
8792 NSString *argument = [components objectAtIndex:1];
8793
8794 if ([base isEqualToString:@"package"]) {
8795 controller = [self pageForPackage:argument];
8796 }
8797
8798 if ([base isEqualToString:@"search"]) {
8799 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8800 [(SearchController *)controller setSearchTerm:argument];
8801 }
8802
8803 if ([base isEqualToString:@"sections"]) {
8804 if ([argument isEqualToString:@"all"])
8805 argument = nil;
8806 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
8807 }
8808
8809 if ([base isEqualToString:@"sources"]) {
8810 if ([argument isEqualToString:@"add"]) {
8811 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8812 [(SourcesController *)controller showAddSourcePrompt];
8813 } else {
8814 NSArray *sources = [database_ sources];
8815 for (Source *source in sources) {
8816 if ([[source name] caseInsensitiveCompare:argument] == NSOrderedSame) {
8817 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
8818 break;
8819 }
8820 }
8821 }
8822 }
8823
8824 if ([base isEqualToString:@"launch"]) {
8825 [self launchApplicationWithIdentifier:argument suspended:NO];
8826 return nil;
8827 }
8828 } else if ([components count] == 3) {
8829 NSString *arg1 = [components objectAtIndex:1];
8830 NSString *arg2 = [components objectAtIndex:2];
8831
8832 if ([base isEqualToString:@"package"]) {
8833 if ([arg2 isEqualToString:@"settings"]) {
8834 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
8835 } else if ([arg2 isEqualToString:@"signature"]) {
8836 controller = [[[SignatureController alloc] initWithDatabase:database_ package:arg1] autorelease];
8837 } else if ([arg2 isEqualToString:@"files"]) {
8838 if (Package *package = [database_ packageWithName:arg1]) {
8839 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8840 [(FileTable *)controller setPackage:package];
8841 }
8842 }
8843 }
8844 }
8845
8846 [controller setDelegate:self];
8847 return controller;
8848 }
8849
8850 - (BOOL) openCydiaURL:(NSURL *)url {
8851 CYViewController *page([self pageForURL:url]);
8852
8853 if (page != nil) {
8854 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
8855 [nav setViewControllers:[NSArray arrayWithObject:page]];
8856 [tabbar_ setTransientViewController:nav];
8857 }
8858
8859 return page != nil;
8860 }
8861
8862 - (void) applicationOpenURL:(NSURL *)url {
8863 [super applicationOpenURL:url];
8864
8865 if (!loaded_) starturl_ = [url retain];
8866 else [self openCydiaURL:url];
8867 }
8868
8869 - (void) applicationWillResignActive:(UIApplication *)application {
8870 // Stop refreshing if you get a phone call or lock the device.
8871 if ([tabbar_ updating])
8872 [tabbar_ cancelUpdate];
8873
8874 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8875 [super applicationWillResignActive:application];
8876 }
8877
8878 - (void) addStashController {
8879 ++locked_;
8880 stash_ = [[StashController alloc] init];
8881 [window_ addSubview:[stash_ view]];
8882 }
8883
8884 - (void) removeStashController {
8885 [[stash_ view] removeFromSuperview];
8886 [stash_ release];
8887 --locked_;
8888 }
8889
8890 - (void) stash {
8891 [self setIdleTimerDisabled:YES];
8892
8893 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8894 [self setStatusBarShowsProgress:YES];
8895 UpdateExternalStatus(1);
8896
8897 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8898
8899 UpdateExternalStatus(0);
8900 [self setStatusBarShowsProgress:NO];
8901
8902 [self removeStashController];
8903
8904 if (ExecFork() == 0) {
8905 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8906 perror("launchctl stop");
8907 }
8908 }
8909
8910 - (void) setupViewControllers {
8911 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8912 [tabbar_ setDelegate:self];
8913
8914 NSMutableArray *items([NSMutableArray arrayWithObjects:
8915 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
8916 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
8917 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
8918 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
8919 nil]);
8920
8921 if (IsWildcat_) {
8922 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
8923 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
8924 } else {
8925 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
8926 }
8927
8928 NSMutableArray *controllers([NSMutableArray array]);
8929 for (UITabBarItem *item in items) {
8930 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8931 [controller setTabBarItem:item];
8932 [controllers addObject:controller];
8933 }
8934 [tabbar_ setViewControllers:controllers];
8935
8936 [tabbar_ setUpdateDelegate:self];
8937 }
8938
8939 - (CYEmulatedLoadingController *)showEmulatedLoadingControllerInView:(UIView *)view {
8940 static CYEmulatedLoadingController *fake = [[CYEmulatedLoadingController alloc] init];
8941 if (view != nil) {
8942 [view addSubview:[fake view]];
8943 } else {
8944 [[fake view] removeFromSuperview];
8945 }
8946
8947 return fake;
8948 }
8949
8950 - (void) applicationDidFinishLaunching:(id)unused {
8951 _trace();
8952 CydiaApp = self;
8953
8954 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
8955 [self setApplicationSupportsShakeToEdit:NO];
8956
8957 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
8958 initWithMemoryCapacity:524288
8959 diskCapacity:10485760
8960 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
8961 ] autorelease]];
8962
8963 [CYBrowserController _initialize];
8964
8965 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8966
8967 Font12_ = [[UIFont systemFontOfSize:12] retain];
8968 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8969 Font14_ = [[UIFont systemFontOfSize:14] retain];
8970 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8971 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8972
8973 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8974 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8975
8976 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
8977 [window_ orderFront:self];
8978 [window_ makeKey:self];
8979 [window_ setHidden:NO];
8980
8981 if (
8982 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8983 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8984 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8985 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8986 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8987 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8988 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8989 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8990 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8991 false
8992 ) {
8993 [self addStashController];
8994 // XXX: this would be much cleaner as a yieldToSelector:
8995 // that way the removeStashController could happen right here inline
8996 // we also could no longer require the useless stash_ field anymore
8997 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
8998 return;
8999 }
9000
9001 database_ = [Database sharedInstance];
9002
9003 [window_ setUserInteractionEnabled:NO];
9004 [self setupViewControllers];
9005 [self showEmulatedLoadingControllerInView:window_];
9006
9007 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9008 _trace();
9009 }
9010
9011 - (void) loadData {
9012 _trace();
9013 if (Role_ == nil) {
9014 [window_ setUserInteractionEnabled:YES];
9015
9016 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9017 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9018 if (IsWildcat_)
9019 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9020 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9021
9022 return;
9023 } else {
9024 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9025 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9026 [window_ setUserInteractionEnabled:NO];
9027 }
9028
9029 [self reloadData];
9030 PrintTimes();
9031
9032 [window_ addSubview:[tabbar_ view]];
9033 [self showEmulatedLoadingControllerInView:nil];
9034 [window_ setUserInteractionEnabled:YES];
9035
9036 // Show the home page.
9037 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:0];
9038 [navigation setViewControllers:[NSArray arrayWithObject:[self pageForURL:[NSURL URLWithString:@"cydia://home"]]]];
9039
9040 // (Try to) show the startup URL.
9041 if (starturl_ != nil) {
9042 [self openCydiaURL:starturl_];
9043 [starturl_ release];
9044 starturl_ = nil;
9045 }
9046 }
9047
9048 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9049 if (item != nil && IsWildcat_) {
9050 [sheet showFromBarButtonItem:item animated:YES];
9051 } else {
9052 [sheet showInView:window_];
9053 }
9054 }
9055
9056 @end
9057
9058 /*IMP alloc_;
9059 id Alloc_(id self, SEL selector) {
9060 id object = alloc_(self, selector);
9061 lprintf("[%s]A-%p\n", self->isa->name, object);
9062 return object;
9063 }*/
9064
9065 /*IMP dealloc_;
9066 id Dealloc_(id self, SEL selector) {
9067 id object = dealloc_(self, selector);
9068 lprintf("[%s]D-%p\n", self->isa->name, object);
9069 return object;
9070 }*/
9071
9072 Class $WebDefaultUIKitDelegate;
9073
9074 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9075 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9076 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9077 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9078 }
9079
9080 static NSNumber *shouldPlayKeyboardSounds;
9081
9082 Class $UIHardware;
9083
9084 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9085 switch (sound) {
9086 case 1104: // Keyboard Button Clicked
9087 case 1105: // Keyboard Delete Repeated
9088 if (shouldPlayKeyboardSounds == nil) {
9089 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9090 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9091 }
9092
9093 if (![shouldPlayKeyboardSounds boolValue])
9094 break;
9095
9096 default:
9097 _UIHardware$_playSystemSound$(self, _cmd, sound);
9098 }
9099 }
9100
9101 Class $UIApplication;
9102
9103 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9104 static BOOL initialized = NO;
9105 static BOOL started = NO;
9106
9107 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9108 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9109
9110 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9111 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9112 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9113 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9114
9115 if (initialized && !enabled) {
9116 initialized = NO;
9117 [bundle performSelector:@selector(_accessibilityStopServer)];
9118 } else if (enabled) {
9119 initialized = YES;
9120 if (!started) {
9121 started = YES;
9122 [bundle performSelector:@selector(_accessibilityStartServer)];
9123 }
9124 }
9125 }
9126 }
9127
9128 int main(int argc, char *argv[]) { _pooled
9129 _trace();
9130
9131 if (Class $UIDevice = objc_getClass("UIDevice")) {
9132 UIDevice *device([$UIDevice currentDevice]);
9133 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9134 } else
9135 IsWildcat_ = false;
9136
9137 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9138
9139 /* Library Hacks {{{ */
9140 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9141
9142 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9143 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9144 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9145 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9146 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9147 }
9148
9149 $UIHardware = objc_getClass("UIHardware");
9150 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9151 if (UIHardware$_playSystemSound$ != NULL) {
9152 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9153 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9154 }
9155
9156 $UIApplication = objc_getClass("UIApplication");
9157 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9158 if (UIApplication$_updateApplicationAccessibility != NULL) {
9159 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9160 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9161 }
9162 /* }}} */
9163 /* Set Locale {{{ */
9164 Locale_ = CFLocaleCopyCurrent();
9165 Languages_ = [NSLocale preferredLanguages];
9166 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9167 //NSLog(@"%@", [Languages_ description]);
9168
9169 const char *lang;
9170 if (Languages_ == nil || [Languages_ count] == 0)
9171 // XXX: consider just setting to C and then falling through?
9172 lang = NULL;
9173 else {
9174 lang = [[Languages_ objectAtIndex:0] UTF8String];
9175 setenv("LANG", lang, true);
9176 }
9177
9178 //std::setlocale(LC_ALL, lang);
9179 NSLog(@"Setting Language: %s", lang);
9180 /* }}} */
9181
9182 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9183
9184 /* Parse Arguments {{{ */
9185 bool substrate(false);
9186
9187 if (argc != 0) {
9188 char **args(argv);
9189 int arge(1);
9190
9191 for (int argi(1); argi != argc; ++argi)
9192 if (strcmp(argv[argi], "--") == 0) {
9193 arge = argi;
9194 argv[argi] = argv[0];
9195 argv += argi;
9196 argc -= argi;
9197 break;
9198 }
9199
9200 for (int argi(1); argi != arge; ++argi)
9201 if (strcmp(args[argi], "--substrate") == 0)
9202 substrate = true;
9203 else
9204 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9205 }
9206 /* }}} */
9207
9208 App_ = [[NSBundle mainBundle] bundlePath];
9209 Home_ = NSHomeDirectory();
9210 Advanced_ = YES;
9211
9212 setuid(0);
9213 setgid(0);
9214
9215 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9216 alloc_ = alloc->method_imp;
9217 alloc->method_imp = (IMP) &Alloc_;*/
9218
9219 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9220 dealloc_ = dealloc->method_imp;
9221 dealloc->method_imp = (IMP) &Dealloc_;*/
9222
9223 /* System Information {{{ */
9224 size_t size;
9225
9226 int maxproc;
9227 size = sizeof(maxproc);
9228 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9229 perror("sysctlbyname(\"kern.maxproc\", ?)");
9230 else if (maxproc < 64) {
9231 maxproc = 64;
9232 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9233 perror("sysctlbyname(\"kern.maxproc\", #)");
9234 }
9235
9236 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9237 char *osversion = new char[size];
9238 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9239 perror("sysctlbyname(\"kern.osversion\", ?)");
9240 else
9241 System_ = [NSString stringWithUTF8String:osversion];
9242
9243 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9244 char *machine = new char[size];
9245 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9246 perror("sysctlbyname(\"hw.machine\", ?)");
9247 else
9248 Machine_ = machine;
9249
9250 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9251 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9252 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9253 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9254 CFRelease(serial);
9255 }
9256
9257 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9258 NSData *data((NSData *) ecid);
9259 size_t length([data length]);
9260 uint8_t bytes[length];
9261 [data getBytes:bytes];
9262 char string[length * 2 + 1];
9263 for (size_t i(0); i != length; ++i)
9264 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9265 ChipID_ = [NSString stringWithUTF8String:string];
9266 CFRelease(ecid);
9267 }
9268
9269 IOObjectRelease(service);
9270 }
9271 }
9272
9273 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9274
9275 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9276 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9277 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9278
9279 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9280 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9281 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9282
9283 if (mcc != NULL && mnc != NULL)
9284 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9285
9286 if (mnc != NULL)
9287 CFRelease(mnc);
9288 if (mcc != NULL)
9289 CFRelease(mcc);
9290
9291 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9292 Build_ = [system objectForKey:@"ProductBuildVersion"];
9293 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9294 Product_ = [info objectForKey:@"SafariProductVersion"];
9295 Safari_ = [info objectForKey:@"CFBundleVersion"];
9296 }
9297 /* }}} */
9298 /* Load Database {{{ */
9299 _trace();
9300 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9301 _trace();
9302 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9303
9304 if (Metadata_ == NULL)
9305 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9306 else {
9307 Settings_ = [Metadata_ objectForKey:@"Settings"];
9308
9309 Packages_ = [Metadata_ objectForKey:@"Packages"];
9310 Sections_ = [Metadata_ objectForKey:@"Sections"];
9311 Sources_ = [Metadata_ objectForKey:@"Sources"];
9312
9313 Token_ = [Metadata_ objectForKey:@"Token"];
9314 }
9315
9316 if (Settings_ != nil)
9317 Role_ = [Settings_ objectForKey:@"Role"];
9318
9319 if (Sections_ == nil) {
9320 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9321 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9322 }
9323
9324 if (Sources_ == nil) {
9325 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9326 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9327 }
9328 /* }}} */
9329
9330 _trace();
9331 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9332 _trace();
9333
9334 if (Packages_ != nil) {
9335 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9336 _trace();
9337 [Metadata_ removeObjectForKey:@"Packages"];
9338 Packages_ = nil;
9339 Changed_ = true;
9340 }
9341
9342 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9343
9344 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9345 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9346 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9347 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9348 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9349 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9350
9351 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9352
9353 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9354 unlink("/tmp/.cydia.fw");
9355 goto firmware;
9356 } else if (access("/User", F_OK) != 0 || version < 2) {
9357 firmware:
9358 _trace();
9359 system("/usr/libexec/cydia/firmware.sh");
9360 _trace();
9361 }
9362
9363 _assert([[NSFileManager defaultManager]
9364 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9365 withIntermediateDirectories:YES
9366 attributes:nil
9367 error:NULL
9368 ]);
9369
9370 if (access("/tmp/cydia.chk", F_OK) == 0) {
9371 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9372 _assert(errno == ENOENT);
9373 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9374 _assert(errno == ENOENT);
9375 }
9376
9377 /* APT Initialization {{{ */
9378 _assert(pkgInitConfig(*_config));
9379 _assert(pkgInitSystem(*_config, _system));
9380
9381 if (lang != NULL)
9382 _config->Set("APT::Acquire::Translation", lang);
9383
9384 // XXX: this timeout might be important :(
9385 //_config->Set("Acquire::http::Timeout", 15);
9386
9387 _config->Set("Acquire::http::MaxParallel", 3);
9388 /* }}} */
9389 /* Color Choices {{{ */
9390 space_ = CGColorSpaceCreateDeviceRGB();
9391
9392 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9393 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9394 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9395 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9396 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9397 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9398 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9399 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9400 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9401
9402 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9403 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9404 /* }}}*/
9405 /* UIKit Configuration {{{ */
9406 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9407 if ($GSFontSetUseLegacyFontMetrics != NULL)
9408 $GSFontSetUseLegacyFontMetrics(YES);
9409
9410 // XXX: I have a feeling this was important
9411 //UIKeyboardDisableAutomaticAppearance();
9412 /* }}} */
9413
9414 Colon_ = UCLocalize("COLON_DELIMITED");
9415 Elision_ = UCLocalize("ELISION");
9416 Error_ = UCLocalize("ERROR");
9417 Warning_ = UCLocalize("WARNING");
9418
9419 _trace();
9420 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9421
9422 CGColorSpaceRelease(space_);
9423 CFRelease(Locale_);
9424
9425 return value;
9426 }