]> git.saurik.com Git - cydia.git/blob - MobileCydia.mm
Make PackageCell, SourceCell, and SectionCell have reasonable VoiceOver labels.
[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
406 #if !TraceLogging
407 #undef _trace
408 #define _trace(args...)
409 #endif
410
411 #if !ProfileTimes
412 #undef _profile
413 #define _profile(name) {
414 #undef _end
415 #define _end }
416 #define PrintTimes() do {} while (false)
417 #endif
418
419 /* Radix Sort {{{ */
420 typedef uint32_t (*SKRadixFunction)(id, void *);
421
422 @interface NSMutableArray (Radix)
423 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument;
424 @end
425
426 struct RadixItem_ {
427 size_t index;
428 uint32_t key;
429 };
430
431 @implementation NSMutableArray (Radix)
432
433 - (void) radixSortUsingFunction:(SKRadixFunction)function withContext:(void *)argument {
434 size_t count([self count]);
435 struct RadixItem_ *swap(new RadixItem_[count * 2]);
436
437 for (size_t i(0); i != count; ++i) {
438 RadixItem_ &item(swap[i]);
439 item.index = i;
440
441 id object([self objectAtIndex:i]);
442 item.key = function(object, argument);
443 }
444
445 struct RadixItem_ *lhs(swap), *rhs(swap + count);
446
447 static const size_t width = 32;
448 static const size_t bits = 11;
449 static const size_t slots = 1 << bits;
450 static const size_t passes = (width + (bits - 1)) / bits;
451
452 size_t *hist(new size_t[slots]);
453
454 for (size_t pass(0); pass != passes; ++pass) {
455 memset(hist, 0, sizeof(size_t) * slots);
456
457 for (size_t i(0); i != count; ++i) {
458 uint32_t key(lhs[i].key);
459 key >>= pass * bits;
460 key &= _not(uint32_t) >> width - bits;
461 ++hist[key];
462 }
463
464 size_t offset(0);
465 for (size_t i(0); i != slots; ++i) {
466 size_t local(offset);
467 offset += hist[i];
468 hist[i] = local;
469 }
470
471 for (size_t i(0); i != count; ++i) {
472 uint32_t key(lhs[i].key);
473 key >>= pass * bits;
474 key &= _not(uint32_t) >> width - bits;
475 rhs[hist[key]++] = lhs[i];
476 }
477
478 RadixItem_ *tmp(lhs);
479 lhs = rhs;
480 rhs = tmp;
481 }
482
483 delete [] hist;
484
485 const void **values(new const void *[count]);
486 for (size_t i(0); i != count; ++i)
487 values[i] = [self objectAtIndex:lhs[i].index];
488 CFArrayReplaceValues((CFMutableArrayRef) self, CFRangeMake(0, count), values, count);
489 delete [] values;
490
491 delete [] swap;
492 }
493
494 @end
495 /* }}} */
496 /* Insertion Sort {{{ */
497
498 CFIndex SKBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
499 const char *ptr = (const char *)list;
500 while (0 < count) {
501 CFIndex half = count / 2;
502 const char *probe = ptr + elementSize * half;
503 CFComparisonResult cr = comparator(element, probe, context);
504 if (0 == cr) return (probe - (const char *)list) / elementSize;
505 ptr = (cr < 0) ? ptr : probe + elementSize;
506 count = (cr < 0) ? half : (half + (count & 1) - 1);
507 }
508 return (ptr - (const char *)list) / elementSize;
509 }
510
511 CFIndex CFBSearch_(const void *element, CFIndex elementSize, const void *list, CFIndex count, CFComparatorFunction comparator, void *context) {
512 const char *ptr = (const char *)list;
513 while (0 < count) {
514 CFIndex half = count / 2;
515 const char *probe = ptr + elementSize * half;
516 CFComparisonResult cr = comparator(element, probe, context);
517 if (0 == cr) return (probe - (const char *)list) / elementSize;
518 ptr = (cr < 0) ? ptr : probe + elementSize;
519 count = (cr < 0) ? half : (half + (count & 1) - 1);
520 }
521 return (ptr - (const char *)list) / elementSize;
522 }
523
524 void CFArrayInsertionSortValues(CFMutableArrayRef array, CFRange range, CFComparatorFunction comparator, void *context) {
525 if (range.length == 0)
526 return;
527 const void **values(new const void *[range.length]);
528 CFArrayGetValues(array, range, values);
529
530 #if HistogramInsertionSort > 0
531 uint32_t total(0), *offsets(new uint32_t[range.length]);
532 #endif
533
534 for (CFIndex index(1); index != range.length; ++index) {
535 const void *value(values[index]);
536 //CFIndex correct(SKBSearch_(&value, sizeof(const void *), values, index, comparator, context));
537 CFIndex correct(index);
538 while (comparator(value, values[correct - 1], context) == kCFCompareLessThan) {
539 #if HistogramInsertionSort > 1
540 NSLog(@"%@ < %@", value, values[correct - 1]);
541 #endif
542 if (--correct == 0)
543 break;
544 }
545 if (correct != index) {
546 size_t offset(index - correct);
547 #if HistogramInsertionSort
548 total += offset;
549 ++offsets[offset];
550 if (offset > 10)
551 NSLog(@"Heavy Insertion Displacement: %u = %@", offset, value);
552 #endif
553 memmove(values + correct + 1, values + correct, sizeof(const void *) * offset);
554 values[correct] = value;
555 }
556 }
557
558 CFArrayReplaceValues(array, range, values, range.length);
559 delete [] values;
560
561 #if HistogramInsertionSort > 0
562 for (CFIndex index(0); index != range.length; ++index)
563 if (offsets[index] != 0)
564 NSLog(@"Insertion Displacement [%u]: %u", index, offsets[index]);
565 NSLog(@"Average Insertion Displacement: %f", double(total) / range.length);
566 delete [] offsets;
567 #endif
568 }
569
570 /* }}} */
571
572 /* Apple Bug Fixes {{{ */
573 @implementation UIWebDocumentView (Cydia)
574
575 - (void) _setScrollerOffset:(CGPoint)offset {
576 UIScroller *scroller([self _scroller]);
577
578 CGSize size([scroller contentSize]);
579 CGSize bounds([scroller bounds].size);
580
581 CGPoint max;
582 max.x = size.width - bounds.width;
583 max.y = size.height - bounds.height;
584
585 // wtf Apple?!
586 if (max.x < 0)
587 max.x = 0;
588 if (max.y < 0)
589 max.y = 0;
590
591 offset.x = offset.x < 0 ? 0 : offset.x > max.x ? max.x : offset.x;
592 offset.y = offset.y < 0 ? 0 : offset.y > max.y ? max.y : offset.y;
593
594 [scroller setOffset:offset];
595 }
596
597 @end
598 /* }}} */
599
600 @implementation WebScriptObject (NSFastEnumeration)
601
602 - (NSUInteger) countByEnumeratingWithState:(NSFastEnumerationState *)state objects:(id *)objects count:(NSUInteger)count {
603 size_t length([self count] - state->state);
604 if (length <= 0)
605 return 0;
606 else if (length > count)
607 length = count;
608 for (size_t i(0); i != length; ++i)
609 objects[i] = [self objectAtIndex:state->state++];
610 state->itemsPtr = objects;
611 state->mutationsPtr = (unsigned long *) self;
612 return length;
613 }
614
615 @end
616
617 NSUInteger DOMNodeList$countByEnumeratingWithState$objects$count$(DOMNodeList *self, SEL sel, NSFastEnumerationState *state, id *objects, NSUInteger count) {
618 size_t length([self length] - state->state);
619 if (length <= 0)
620 return 0;
621 else if (length > count)
622 length = count;
623 for (size_t i(0); i != length; ++i)
624 objects[i] = [self item:state->state++];
625 state->itemsPtr = objects;
626 state->mutationsPtr = (unsigned long *) self;
627 return length;
628 }
629
630 /* Cydia NSString Additions {{{ */
631 @interface NSString (Cydia)
632 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length;
633 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool;
634 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length;
635 - (NSComparisonResult) compareByPath:(NSString *)other;
636 - (NSString *) stringByCachingURLWithCurrentCDN;
637 - (NSString *) stringByAddingPercentEscapesIncludingReserved;
638 @end
639
640 @implementation NSString (Cydia)
641
642 + (NSString *) stringWithUTF8BytesNoCopy:(const char *)bytes length:(int)length {
643 return [[[NSString alloc] initWithBytesNoCopy:const_cast<char *>(bytes) length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
644 }
645
646 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length withZone:(NSZone *)zone inPool:(apr_pool_t *)pool {
647 char *data(reinterpret_cast<char *>(apr_palloc(pool, length)));
648 memcpy(data, bytes, length);
649 return [[[NSString allocWithZone:zone] initWithBytesNoCopy:data length:length encoding:NSUTF8StringEncoding freeWhenDone:NO] autorelease];
650 }
651
652 + (NSString *) stringWithUTF8Bytes:(const char *)bytes length:(int)length {
653 return [[[NSString alloc] initWithBytes:bytes length:length encoding:NSUTF8StringEncoding] autorelease];
654 }
655
656 - (NSComparisonResult) compareByPath:(NSString *)other {
657 NSString *prefix = [self commonPrefixWithString:other options:0];
658 size_t length = [prefix length];
659
660 NSRange lrange = NSMakeRange(length, [self length] - length);
661 NSRange rrange = NSMakeRange(length, [other length] - length);
662
663 lrange = [self rangeOfString:@"/" options:0 range:lrange];
664 rrange = [other rangeOfString:@"/" options:0 range:rrange];
665
666 NSComparisonResult value;
667
668 if (lrange.location == NSNotFound && rrange.location == NSNotFound)
669 value = NSOrderedSame;
670 else if (lrange.location == NSNotFound)
671 value = NSOrderedAscending;
672 else if (rrange.location == NSNotFound)
673 value = NSOrderedDescending;
674 else
675 value = NSOrderedSame;
676
677 NSString *lpath = lrange.location == NSNotFound ? [self substringFromIndex:length] :
678 [self substringWithRange:NSMakeRange(length, lrange.location - length)];
679 NSString *rpath = rrange.location == NSNotFound ? [other substringFromIndex:length] :
680 [other substringWithRange:NSMakeRange(length, rrange.location - length)];
681
682 NSComparisonResult result = [lpath compare:rpath];
683 return result == NSOrderedSame ? value : result;
684 }
685
686 - (NSString *) stringByCachingURLWithCurrentCDN {
687 return [self
688 stringByReplacingOccurrencesOfString:@"://cydia.saurik.com/"
689 withString:@"://cache.cydia.saurik.com/"
690 ];
691 }
692
693 - (NSString *) stringByAddingPercentEscapesIncludingReserved {
694 return [(id)CFURLCreateStringByAddingPercentEscapes(
695 kCFAllocatorDefault,
696 (CFStringRef) self,
697 NULL,
698 CFSTR(";/?:@&=+$,"),
699 kCFStringEncodingUTF8
700 ) autorelease];
701 }
702
703 @end
704 /* }}} */
705
706 /* C++ NSString Wrapper Cache {{{ */
707 static _finline CFStringRef CYStringCreate(const char *data, size_t size) {
708 return size == 0 ? NULL :
709 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingUTF8, NO, kCFAllocatorNull) ?:
710 CFStringCreateWithBytesNoCopy(kCFAllocatorDefault, reinterpret_cast<const uint8_t *>(data), size, kCFStringEncodingISOLatin1, NO, kCFAllocatorNull);
711 }
712
713 static _finline CFStringRef CYStringCreate(const char *data) {
714 return CYStringCreate(data, strlen(data));
715 }
716
717 class CYString {
718 private:
719 char *data_;
720 size_t size_;
721 CFStringRef cache_;
722
723 _finline void clear_() {
724 if (cache_ != NULL) {
725 CFRelease(cache_);
726 cache_ = NULL;
727 }
728 }
729
730 public:
731 _finline bool empty() const {
732 return size_ == 0;
733 }
734
735 _finline size_t size() const {
736 return size_;
737 }
738
739 _finline char *data() const {
740 return data_;
741 }
742
743 _finline void clear() {
744 size_ = 0;
745 clear_();
746 }
747
748 _finline CYString() :
749 data_(0),
750 size_(0),
751 cache_(NULL)
752 {
753 }
754
755 _finline ~CYString() {
756 clear_();
757 }
758
759 void operator =(const CYString &rhs) {
760 data_ = rhs.data_;
761 size_ = rhs.size_;
762
763 if (rhs.cache_ == nil)
764 cache_ = NULL;
765 else
766 cache_ = reinterpret_cast<CFStringRef>(CFRetain(rhs.cache_));
767 }
768
769 void copy(apr_pool_t *pool) {
770 char *temp(reinterpret_cast<char *>(apr_palloc(pool, size_ + 1)));
771 memcpy(temp, data_, size_);
772 temp[size_] = '\0';
773 data_ = temp;
774 }
775
776 void set(apr_pool_t *pool, const char *data, size_t size) {
777 if (size == 0)
778 clear();
779 else {
780 clear_();
781
782 data_ = const_cast<char *>(data);
783 size_ = size;
784
785 if (pool != NULL)
786 copy(pool);
787 }
788 }
789
790 _finline void set(apr_pool_t *pool, const char *data) {
791 set(pool, data, data == NULL ? 0 : strlen(data));
792 }
793
794 _finline void set(apr_pool_t *pool, const std::string &rhs) {
795 set(pool, rhs.data(), rhs.size());
796 }
797
798 bool operator ==(const CYString &rhs) const {
799 return size_ == rhs.size_ && memcmp(data_, rhs.data_, size_) == 0;
800 }
801
802 _finline operator CFStringRef() {
803 if (cache_ == NULL)
804 cache_ = CYStringCreate(data_, size_);
805 return cache_;
806 }
807
808 _finline operator id() {
809 return (NSString *) static_cast<CFStringRef>(*this);
810 }
811
812 _finline operator const char *() {
813 return reinterpret_cast<const char *>(data_);
814 }
815 };
816 /* }}} */
817 /* C++ NSString Algorithm Adapters {{{ */
818 extern "C" {
819 CF_EXPORT CFHashCode CFStringHashNSString(CFStringRef str);
820 }
821
822 struct NSStringMapHash :
823 std::unary_function<NSString *, size_t>
824 {
825 _finline size_t operator ()(NSString *value) const {
826 return CFStringHashNSString((CFStringRef) value);
827 }
828 };
829
830 struct NSStringMapLess :
831 std::binary_function<NSString *, NSString *, bool>
832 {
833 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
834 return [lhs compare:rhs] == NSOrderedAscending;
835 }
836 };
837
838 struct NSStringMapEqual :
839 std::binary_function<NSString *, NSString *, bool>
840 {
841 _finline bool operator ()(NSString *lhs, NSString *rhs) const {
842 return CFStringCompare((CFStringRef) lhs, (CFStringRef) rhs, 0) == kCFCompareEqualTo;
843 //CFEqual((CFTypeRef) lhs, (CFTypeRef) rhs);
844 //[lhs isEqualToString:rhs];
845 }
846 };
847 /* }}} */
848
849 /* Perl-Compatible RegEx {{{ */
850 class Pcre {
851 private:
852 pcre *code_;
853 pcre_extra *study_;
854 int capture_;
855 int *matches_;
856 const char *data_;
857
858 public:
859 Pcre(const char *regex) :
860 study_(NULL)
861 {
862 const char *error;
863 int offset;
864 code_ = pcre_compile(regex, 0, &error, &offset, NULL);
865
866 if (code_ == NULL) {
867 lprintf("%d:%s\n", offset, error);
868 _assert(false);
869 }
870
871 pcre_fullinfo(code_, study_, PCRE_INFO_CAPTURECOUNT, &capture_);
872 matches_ = new int[(capture_ + 1) * 3];
873 }
874
875 ~Pcre() {
876 pcre_free(code_);
877 delete matches_;
878 }
879
880 NSString *operator [](size_t match) {
881 return [NSString stringWithUTF8Bytes:(data_ + matches_[match * 2]) length:(matches_[match * 2 + 1] - matches_[match * 2])];
882 }
883
884 bool operator ()(NSString *data) {
885 // XXX: length is for characters, not for bytes
886 return operator ()([data UTF8String], [data length]);
887 }
888
889 bool operator ()(const char *data, size_t size) {
890 data_ = data;
891 return pcre_exec(code_, study_, data, size, 0, 0, matches_, (capture_ + 1) * 3) >= 0;
892 }
893 };
894 /* }}} */
895 /* Mime Addresses {{{ */
896 @interface Address : NSObject {
897 NSString *name_;
898 NSString *address_;
899 }
900
901 - (NSString *) name;
902 - (NSString *) address;
903
904 - (void) setAddress:(NSString *)address;
905
906 + (Address *) addressWithString:(NSString *)string;
907 - (Address *) initWithString:(NSString *)string;
908 @end
909
910 @implementation Address
911
912 - (void) dealloc {
913 [name_ release];
914 if (address_ != nil)
915 [address_ release];
916 [super dealloc];
917 }
918
919 - (NSString *) name {
920 return name_;
921 }
922
923 - (NSString *) address {
924 return address_;
925 }
926
927 - (void) setAddress:(NSString *)address {
928 if (address_ != nil)
929 [address_ autorelease];
930 if (address == nil)
931 address_ = nil;
932 else
933 address_ = [address retain];
934 }
935
936 + (Address *) addressWithString:(NSString *)string {
937 return [[[Address alloc] initWithString:string] autorelease];
938 }
939
940 + (NSArray *) _attributeKeys {
941 return [NSArray arrayWithObjects:@"address", @"name", nil];
942 }
943
944 - (NSArray *) attributeKeys {
945 return [[self class] _attributeKeys];
946 }
947
948 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
949 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
950 }
951
952 - (Address *) initWithString:(NSString *)string {
953 if ((self = [super init]) != nil) {
954 const char *data = [string UTF8String];
955 size_t size = [string length];
956
957 static Pcre address_r("^\"?(.*)\"? <([^>]*)>$");
958
959 if (address_r(data, size)) {
960 name_ = [address_r[1] retain];
961 address_ = [address_r[2] retain];
962 } else {
963 name_ = [string retain];
964 address_ = nil;
965 }
966 } return self;
967 }
968
969 @end
970 /* }}} */
971 /* CoreGraphics Primitives {{{ */
972 class CYColor {
973 private:
974 CGColorRef color_;
975
976 static CGColorRef Create_(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
977 CGFloat color[] = {red, green, blue, alpha};
978 return CGColorCreate(space, color);
979 }
980
981 public:
982 CYColor() :
983 color_(NULL)
984 {
985 }
986
987 CYColor(CGColorSpaceRef space, float red, float green, float blue, float alpha) :
988 color_(Create_(space, red, green, blue, alpha))
989 {
990 Set(space, red, green, blue, alpha);
991 }
992
993 void Clear() {
994 if (color_ != NULL)
995 CGColorRelease(color_);
996 }
997
998 ~CYColor() {
999 Clear();
1000 }
1001
1002 void Set(CGColorSpaceRef space, float red, float green, float blue, float alpha) {
1003 Clear();
1004 color_ = Create_(space, red, green, blue, alpha);
1005 }
1006
1007 operator CGColorRef() {
1008 return color_;
1009 }
1010 };
1011 /* }}} */
1012
1013 /* Random Global Variables {{{ */
1014 static const int PulseInterval_ = 50000;
1015
1016 static int Finish_;
1017 static NSArray *Finishes_;
1018
1019 #define SpringBoard_ "/System/Library/LaunchDaemons/com.apple.SpringBoard.plist"
1020 #define NotifyConfig_ "/etc/notify.conf"
1021
1022 static bool Queuing_;
1023
1024 static CYColor Blue_;
1025 static CYColor Blueish_;
1026 static CYColor Black_;
1027 static CYColor Off_;
1028 static CYColor White_;
1029 static CYColor Gray_;
1030 static CYColor Green_;
1031 static CYColor Purple_;
1032 static CYColor Purplish_;
1033
1034 static UIColor *InstallingColor_;
1035 static UIColor *RemovingColor_;
1036
1037 static NSString *App_;
1038 static NSString *Home_;
1039
1040 static BOOL Advanced_;
1041 static BOOL Ignored_;
1042
1043 static UIFont *Font12_;
1044 static UIFont *Font12Bold_;
1045 static UIFont *Font14_;
1046 static UIFont *Font18Bold_;
1047 static UIFont *Font22Bold_;
1048
1049 static const char *Machine_ = NULL;
1050 static NSString *System_ = nil;
1051 static NSString *SerialNumber_ = nil;
1052 static NSString *ChipID_ = nil;
1053 static NSString *Token_ = nil;
1054 static NSString *UniqueID_ = nil;
1055 static NSString *PLMN_ = nil;
1056 static NSString *Build_ = nil;
1057 static NSString *Product_ = nil;
1058 static NSString *Safari_ = nil;
1059
1060 static CFLocaleRef Locale_;
1061 static NSArray *Languages_;
1062 static CGColorSpaceRef space_;
1063
1064 static NSDictionary *SectionMap_;
1065 static NSMutableDictionary *Metadata_;
1066 static _transient NSMutableDictionary *Settings_;
1067 static _transient NSString *Role_;
1068 static _transient NSMutableDictionary *Packages_;
1069 static _transient NSMutableDictionary *Sections_;
1070 static _transient NSMutableDictionary *Sources_;
1071 static bool Changed_;
1072 static time_t now_;
1073
1074 static bool IsWildcat_;
1075 /* }}} */
1076
1077 /* Display Helpers {{{ */
1078 inline float Interpolate(float begin, float end, float fraction) {
1079 return (end - begin) * fraction + begin;
1080 }
1081
1082 /* XXX: localize this! */
1083 NSString *SizeString(double size) {
1084 bool negative = size < 0;
1085 if (negative)
1086 size = -size;
1087
1088 unsigned power = 0;
1089 while (size > 1024) {
1090 size /= 1024;
1091 ++power;
1092 }
1093
1094 static const char *powers_[] = {"B", "kB", "MB", "GB"};
1095
1096 return [NSString stringWithFormat:@"%s%.1f %s", (negative ? "-" : ""), size, powers_[power]];
1097 }
1098
1099 static _finline const char *StripVersion_(const char *version) {
1100 const char *colon(strchr(version, ':'));
1101 return colon == NULL ? version : colon + 1;
1102 }
1103
1104 NSString *LocalizeSection(NSString *section) {
1105 static Pcre title_r("^(.*?) \\((.*)\\)$");
1106 if (title_r(section)) {
1107 NSString *parent(title_r[1]);
1108 NSString *child(title_r[2]);
1109
1110 return [NSString stringWithFormat:UCLocalize("PARENTHETICAL"),
1111 LocalizeSection(parent),
1112 LocalizeSection(child)
1113 ];
1114 }
1115
1116 return [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
1117 }
1118
1119 NSString *Simplify(NSString *title) {
1120 const char *data = [title UTF8String];
1121 size_t size = [title length];
1122
1123 static Pcre square_r("^\\[(.*)\\]$");
1124 if (square_r(data, size))
1125 return Simplify(square_r[1]);
1126
1127 static Pcre paren_r("^\\((.*)\\)$");
1128 if (paren_r(data, size))
1129 return Simplify(paren_r[1]);
1130
1131 static Pcre title_r("^(.*?) \\((.*)\\)$");
1132 if (title_r(data, size))
1133 return Simplify(title_r[1]);
1134
1135 return title;
1136 }
1137 /* }}} */
1138
1139 NSString *GetLastUpdate() {
1140 NSDate *update = [Metadata_ objectForKey:@"LastUpdate"];
1141
1142 if (update == nil)
1143 return UCLocalize("NEVER_OR_UNKNOWN");
1144
1145 CFDateFormatterRef formatter = CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle);
1146 CFStringRef formatted = CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) update);
1147
1148 CFRelease(formatter);
1149
1150 return [(NSString *) formatted autorelease];
1151 }
1152
1153 bool isSectionVisible(NSString *section) {
1154 NSDictionary *metadata([Sections_ objectForKey:section]);
1155 NSNumber *hidden(metadata == nil ? nil : [metadata objectForKey:@"Hidden"]);
1156 return hidden == nil || ![hidden boolValue];
1157 }
1158
1159 @class Cydia;
1160
1161 /* Delegate Prototypes {{{ */
1162 @class Package;
1163 @class Source;
1164
1165 @interface NSObject (ProgressDelegate)
1166 @end
1167
1168 @protocol ProgressDelegate
1169 - (void) setProgressError:(NSString *)error withTitle:(NSString *)id;
1170 - (void) setProgressTitle:(NSString *)title;
1171 - (void) setProgressPercent:(float)percent;
1172 - (void) startProgress;
1173 - (void) addProgressOutput:(NSString *)output;
1174 - (bool) isCancelling:(size_t)received;
1175 @end
1176
1177 @protocol ConfigurationDelegate
1178 - (void) repairWithSelector:(SEL)selector;
1179 - (void) setConfigurationData:(NSString *)data;
1180 @end
1181
1182 @class CYPackageController;
1183
1184 @protocol CydiaDelegate
1185 - (void) retainNetworkActivityIndicator;
1186 - (void) releaseNetworkActivityIndicator;
1187 - (void) setPackageController:(CYPackageController *)view;
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 range = [[self shortDescription] rangeOfString:text options:MatchCompareOptions_];
2739 if (range.location != NSNotFound)
2740 return YES;
2741
2742 return NO;
2743 }
2744
2745 - (bool) hasSupportingRole {
2746 if (role_ == 0)
2747 return true;
2748 if (role_ == 1)
2749 return true;
2750 if ([Role_ isEqualToString:@"User"])
2751 return false;
2752 if (role_ == 2)
2753 return true;
2754 if ([Role_ isEqualToString:@"Hacker"])
2755 return false;
2756 if (role_ == 3)
2757 return true;
2758 if ([Role_ isEqualToString:@"Developer"])
2759 return false;
2760 _assert(false);
2761 }
2762
2763 - (BOOL) hasTag:(NSString *)tag {
2764 return tags_ == nil ? NO : [tags_ containsObject:tag];
2765 }
2766
2767 - (NSString *) primaryPurpose {
2768 for (NSString *tag in tags_)
2769 if ([tag hasPrefix:@"purpose::"])
2770 return [tag substringFromIndex:9];
2771 return nil;
2772 }
2773
2774 - (NSArray *) purposes {
2775 NSMutableArray *purposes([NSMutableArray arrayWithCapacity:2]);
2776 for (NSString *tag in tags_)
2777 if ([tag hasPrefix:@"purpose::"])
2778 [purposes addObject:[tag substringFromIndex:9]];
2779 return [purposes count] == 0 ? nil : purposes;
2780 }
2781
2782 - (bool) isCommercial {
2783 return [self hasTag:@"cydia::commercial"];
2784 }
2785
2786 - (void) setIndex:(size_t)index {
2787 if (metadata_->index_ != index)
2788 metadata_->index_ = index;
2789 }
2790
2791 - (CYString &) cyname {
2792 return name_.empty() ? id_ : name_;
2793 }
2794
2795 - (uint32_t) compareBySection:(NSArray *)sections {
2796 NSString *section([self section]);
2797 for (size_t i(0), e([sections count]); i != e; ++i) {
2798 if ([section isEqualToString:[[sections objectAtIndex:i] name]])
2799 return i;
2800 }
2801
2802 return _not(uint32_t);
2803 }
2804
2805 - (void) clear {
2806 @synchronized (database_) {
2807 pkgProblemResolver *resolver = [database_ resolver];
2808 resolver->Clear(iterator_);
2809
2810 pkgCacheFile &cache([database_ cache]);
2811 cache->SetReInstall(iterator_, false);
2812 cache->MarkKeep(iterator_, false);
2813 } }
2814
2815 - (void) install {
2816 @synchronized (database_) {
2817 pkgProblemResolver *resolver = [database_ resolver];
2818 resolver->Clear(iterator_);
2819 resolver->Protect(iterator_);
2820
2821 pkgCacheFile &cache([database_ cache]);
2822 cache->SetReInstall(iterator_, false);
2823 cache->MarkInstall(iterator_, false);
2824
2825 pkgDepCache::StateCache &state((*cache)[iterator_]);
2826 if (!state.Install())
2827 cache->SetReInstall(iterator_, true);
2828 } }
2829
2830 - (void) remove {
2831 @synchronized (database_) {
2832 pkgProblemResolver *resolver = [database_ resolver];
2833 resolver->Clear(iterator_);
2834 resolver->Remove(iterator_);
2835 resolver->Protect(iterator_);
2836
2837 pkgCacheFile &cache([database_ cache]);
2838 cache->SetReInstall(iterator_, false);
2839 cache->MarkDelete(iterator_, true);
2840 } }
2841
2842 - (bool) isUnfilteredAndSearchedForBy:(NSString *)search {
2843 _profile(Package$isUnfilteredAndSearchedForBy)
2844 bool value(true);
2845
2846 _profile(Package$isUnfilteredAndSearchedForBy$Unfiltered)
2847 value &= [self unfiltered];
2848 _end
2849
2850 _profile(Package$isUnfilteredAndSearchedForBy$Match)
2851 value &= [self matches:search];
2852 _end
2853
2854 return value;
2855 _end
2856 }
2857
2858 - (bool) isUnfilteredAndSelectedForBy:(NSString *)search {
2859 if ([search length] == 0)
2860 return false;
2861
2862 _profile(Package$isUnfilteredAndSelectedForBy)
2863 bool value(true);
2864
2865 _profile(Package$isUnfilteredAndSelectedForBy$Unfiltered)
2866 value &= [self unfiltered];
2867 _end
2868
2869 _profile(Package$isUnfilteredAndSelectedForBy$Match)
2870 value &= [[self name] compare:search options:MatchCompareOptions_ range:NSMakeRange(0, [search length])] == NSOrderedSame;
2871 _end
2872
2873 return value;
2874 _end
2875 }
2876
2877 - (bool) isInstalledAndUnfiltered:(NSNumber *)number {
2878 return ![self uninstalled] && (![number boolValue] && role_ != 7 || [self unfiltered]);
2879 }
2880
2881 - (bool) isVisibleInSection:(NSString *)name {
2882 NSString *section([self section]);
2883
2884 return (
2885 name == nil ||
2886 section == nil && [name length] == 0 ||
2887 [name isEqualToString:section]
2888 ) && [self visible];
2889 }
2890
2891 - (bool) isVisibleInSource:(Source *)source {
2892 return [self source] == source && [self visible];
2893 }
2894
2895 @end
2896 /* }}} */
2897 /* Section Class {{{ */
2898 @interface Section : NSObject {
2899 NSString *name_;
2900 unichar index_;
2901 size_t row_;
2902 size_t count_;
2903 NSString *localized_;
2904 }
2905
2906 - (NSComparisonResult) compareByLocalized:(Section *)section;
2907 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized;
2908 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize;
2909 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize;
2910 - (Section *) initWithIndex:(unichar)index row:(size_t)row;
2911 - (NSString *) name;
2912 - (unichar) index;
2913
2914 - (size_t) row;
2915 - (size_t) count;
2916
2917 - (void) addToRow;
2918 - (void) addToCount;
2919
2920 - (void) setCount:(size_t)count;
2921 - (NSString *) localized;
2922
2923 @end
2924
2925 @implementation Section
2926
2927 - (void) dealloc {
2928 [name_ release];
2929 if (localized_ != nil)
2930 [localized_ release];
2931 [super dealloc];
2932 }
2933
2934 - (NSComparisonResult) compareByLocalized:(Section *)section {
2935 NSString *lhs(localized_);
2936 NSString *rhs([section localized]);
2937
2938 /*if ([lhs length] != 0 && [rhs length] != 0) {
2939 unichar lhc = [lhs characterAtIndex:0];
2940 unichar rhc = [rhs characterAtIndex:0];
2941
2942 if (isalpha(lhc) && !isalpha(rhc))
2943 return NSOrderedAscending;
2944 else if (!isalpha(lhc) && isalpha(rhc))
2945 return NSOrderedDescending;
2946 }*/
2947
2948 return [lhs compare:rhs options:LaxCompareOptions_];
2949 }
2950
2951 - (Section *) initWithName:(NSString *)name localized:(NSString *)localized {
2952 if ((self = [self initWithName:name localize:NO]) != nil) {
2953 if (localized != nil)
2954 localized_ = [localized retain];
2955 } return self;
2956 }
2957
2958 - (Section *) initWithName:(NSString *)name localize:(BOOL)localize {
2959 return [self initWithName:name row:0 localize:localize];
2960 }
2961
2962 - (Section *) initWithName:(NSString *)name row:(size_t)row localize:(BOOL)localize {
2963 if ((self = [super init]) != nil) {
2964 name_ = [name retain];
2965 index_ = '\0';
2966 row_ = row;
2967 if (localize)
2968 localized_ = [LocalizeSection(name_) retain];
2969 } return self;
2970 }
2971
2972 /* XXX: localize the index thingees */
2973 - (Section *) initWithIndex:(unichar)index row:(size_t)row {
2974 if ((self = [super init]) != nil) {
2975 name_ = [[NSString stringWithCharacters:&index length:1] retain];
2976 index_ = index;
2977 row_ = row;
2978 } return self;
2979 }
2980
2981 - (NSString *) name {
2982 return name_;
2983 }
2984
2985 - (unichar) index {
2986 return index_;
2987 }
2988
2989 - (size_t) row {
2990 return row_;
2991 }
2992
2993 - (size_t) count {
2994 return count_;
2995 }
2996
2997 - (void) addToRow {
2998 ++row_;
2999 }
3000
3001 - (void) addToCount {
3002 ++count_;
3003 }
3004
3005 - (void) setCount:(size_t)count {
3006 count_ = count;
3007 }
3008
3009 - (NSString *) localized {
3010 return localized_;
3011 }
3012
3013 @end
3014 /* }}} */
3015
3016 static NSString *Colon_;
3017 static NSString *Elision_;
3018 static NSString *Error_;
3019 static NSString *Warning_;
3020
3021 /* Database Implementation {{{ */
3022 @implementation Database
3023
3024 + (Database *) sharedInstance {
3025 static Database *instance;
3026 if (instance == nil)
3027 instance = [[Database alloc] init];
3028 return instance;
3029 }
3030
3031 - (unsigned) era {
3032 return era_;
3033 }
3034
3035 - (void) releasePackages {
3036 CFArrayApplyFunction(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFArrayApplierFunction>(&CFRelease), NULL);
3037 CFArrayRemoveAllValues(packages_);
3038 }
3039
3040 - (void) dealloc {
3041 // XXX: actually implement this thing
3042 _assert(false);
3043 if (deadSources_)
3044 CFRelease(deadSources_);
3045 [self releasePackages];
3046 apr_pool_destroy(pool_);
3047 NSRecycleZone(zone_);
3048 [super dealloc];
3049 }
3050
3051 - (void) _readCydia:(NSNumber *)fd { _pooled
3052 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3053 std::istream is(&ib);
3054 std::string line;
3055
3056 static Pcre finish_r("^finish:([^:]*)$");
3057
3058 while (std::getline(is, line)) {
3059 const char *data(line.c_str());
3060 size_t size = line.size();
3061 lprintf("C:%s\n", data);
3062
3063 if (finish_r(data, size)) {
3064 NSString *finish = finish_r[1];
3065 int index = [Finishes_ indexOfObject:finish];
3066 if (index != INT_MAX && index > Finish_)
3067 Finish_ = index;
3068 }
3069 }
3070
3071 _assume(false);
3072 }
3073
3074 - (void) _readStatus:(NSNumber *)fd { _pooled
3075 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3076 std::istream is(&ib);
3077 std::string line;
3078
3079 static Pcre conffile_r("^status: [^ ]* : conffile-prompt : (.*?) *$");
3080 static Pcre pmstatus_r("^([^:]*):([^:]*):([^:]*):(.*)$");
3081
3082 while (std::getline(is, line)) {
3083 const char *data(line.c_str());
3084 size_t size(line.size());
3085 lprintf("S:%s\n", data);
3086
3087 if (conffile_r(data, size)) {
3088 [delegate_ setConfigurationData:conffile_r[1]];
3089 } else if (strncmp(data, "status: ", 8) == 0) {
3090 NSString *string = [NSString stringWithUTF8String:(data + 8)];
3091 [delegate_ setProgressTitle:string];
3092 } else if (pmstatus_r(data, size)) {
3093 std::string type([pmstatus_r[1] UTF8String]);
3094 NSString *id = pmstatus_r[2];
3095
3096 float percent([pmstatus_r[3] floatValue]);
3097 [delegate_ setProgressPercent:(percent / 100)];
3098
3099 NSString *string = pmstatus_r[4];
3100
3101 if (type == "pmerror")
3102 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3103 withObject:[NSArray arrayWithObjects:string, id, nil]
3104 waitUntilDone:YES
3105 ];
3106 else if (type == "pmstatus") {
3107 [delegate_ setProgressTitle:string];
3108 } else if (type == "pmconffile")
3109 [delegate_ setConfigurationData:string];
3110 else
3111 lprintf("E:unknown pmstatus\n");
3112 } else
3113 lprintf("E:unknown status\n");
3114 }
3115
3116 _assume(false);
3117 }
3118
3119 - (void) _readOutput:(NSNumber *)fd { _pooled
3120 __gnu_cxx::stdio_filebuf<char> ib([fd intValue], std::ios::in);
3121 std::istream is(&ib);
3122 std::string line;
3123
3124 while (std::getline(is, line)) {
3125 lprintf("O:%s\n", line.c_str());
3126 [delegate_ addProgressOutput:[NSString stringWithUTF8String:line.c_str()]];
3127 }
3128
3129 _assume(false);
3130 }
3131
3132 - (FILE *) input {
3133 return input_;
3134 }
3135
3136 - (Package *) packageWithName:(NSString *)name {
3137 @synchronized (self) {
3138 if (static_cast<pkgDepCache *>(cache_) == NULL)
3139 return nil;
3140 pkgCache::PkgIterator iterator(cache_->FindPkg([name UTF8String]));
3141 return iterator.end() ? nil : [Package packageWithIterator:iterator withZone:NULL inPool:pool_ database:self];
3142 } }
3143
3144 - (id) init {
3145 if ((self = [super init]) != nil) {
3146 policy_ = NULL;
3147 records_ = NULL;
3148 resolver_ = NULL;
3149 fetcher_ = NULL;
3150 lock_ = NULL;
3151
3152 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3153 apr_pool_create(&pool_, NULL);
3154
3155 size_t capacity(MetaFile_->active_);
3156 if (capacity == 0)
3157 capacity = 16384;
3158 else
3159 capacity += 1024;
3160
3161 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, capacity, NULL);
3162 deadSources_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, &kCFTypeArrayCallBacks);
3163
3164 int fds[2];
3165
3166 _assert(pipe(fds) != -1);
3167 cydiafd_ = fds[1];
3168
3169 _config->Set("APT::Keep-Fds::", cydiafd_);
3170 setenv("CYDIA", [[[[NSNumber numberWithInt:cydiafd_] stringValue] stringByAppendingString:@" 1"] UTF8String], _not(int));
3171
3172 [NSThread
3173 detachNewThreadSelector:@selector(_readCydia:)
3174 toTarget:self
3175 withObject:[NSNumber numberWithInt:fds[0]]
3176 ];
3177
3178 _assert(pipe(fds) != -1);
3179 statusfd_ = fds[1];
3180
3181 [NSThread
3182 detachNewThreadSelector:@selector(_readStatus:)
3183 toTarget:self
3184 withObject:[NSNumber numberWithInt:fds[0]]
3185 ];
3186
3187 _assert(pipe(fds) != -1);
3188 _assert(dup2(fds[0], 0) != -1);
3189 _assert(close(fds[0]) != -1);
3190
3191 input_ = fdopen(fds[1], "a");
3192
3193 _assert(pipe(fds) != -1);
3194 _assert(dup2(fds[1], 1) != -1);
3195 _assert(close(fds[1]) != -1);
3196
3197 [NSThread
3198 detachNewThreadSelector:@selector(_readOutput:)
3199 toTarget:self
3200 withObject:[NSNumber numberWithInt:fds[0]]
3201 ];
3202 } return self;
3203 }
3204
3205 - (pkgCacheFile &) cache {
3206 return cache_;
3207 }
3208
3209 - (pkgDepCache::Policy *) policy {
3210 return policy_;
3211 }
3212
3213 - (pkgRecords *) records {
3214 return records_;
3215 }
3216
3217 - (pkgProblemResolver *) resolver {
3218 return resolver_;
3219 }
3220
3221 - (pkgAcquire &) fetcher {
3222 return *fetcher_;
3223 }
3224
3225 - (pkgSourceList &) list {
3226 return *list_;
3227 }
3228
3229 - (NSArray *) packages {
3230 return (NSArray *) packages_;
3231 }
3232
3233 - (NSArray *) sources {
3234 NSMutableArray *sources([NSMutableArray arrayWithCapacity:sources_.size()]);
3235 for (SourceMap::const_iterator i(sources_.begin()); i != sources_.end(); ++i)
3236 [sources addObject:i->second];
3237 [sources addObjectsFromArray:(NSArray *)deadSources_];
3238 return sources;
3239 }
3240
3241 - (NSArray *) issues {
3242 if (cache_->BrokenCount() == 0)
3243 return nil;
3244
3245 NSMutableArray *issues([NSMutableArray arrayWithCapacity:4]);
3246
3247 for (Package *package in [self packages]) {
3248 if (![package broken])
3249 continue;
3250 pkgCache::PkgIterator pkg([package iterator]);
3251
3252 NSMutableArray *entry([NSMutableArray arrayWithCapacity:4]);
3253 [entry addObject:[package name]];
3254 [issues addObject:entry];
3255
3256 pkgCache::VerIterator ver(cache_[pkg].InstVerIter(cache_));
3257 if (ver.end())
3258 continue;
3259
3260 for (pkgCache::DepIterator dep(ver.DependsList()); !dep.end(); ) {
3261 pkgCache::DepIterator start;
3262 pkgCache::DepIterator end;
3263 dep.GlobOr(start, end); // ++dep
3264
3265 if (!cache_->IsImportantDep(end))
3266 continue;
3267 if ((cache_[end] & pkgDepCache::DepGInstall) != 0)
3268 continue;
3269
3270 NSMutableArray *failure([NSMutableArray arrayWithCapacity:4]);
3271 [entry addObject:failure];
3272 [failure addObject:[NSString stringWithUTF8String:start.DepType()]];
3273
3274 NSString *name([NSString stringWithUTF8String:start.TargetPkg().Name()]);
3275 if (Package *package = [self packageWithName:name])
3276 name = [package name];
3277 [failure addObject:name];
3278
3279 pkgCache::PkgIterator target(start.TargetPkg());
3280 if (target->ProvidesList != 0)
3281 [failure addObject:@"?"];
3282 else {
3283 pkgCache::VerIterator ver(cache_[target].InstVerIter(cache_));
3284 if (!ver.end())
3285 [failure addObject:[NSString stringWithUTF8String:ver.VerStr()]];
3286 else if (!cache_[target].CandidateVerIter(cache_).end())
3287 [failure addObject:@"-"];
3288 else if (target->ProvidesList == 0)
3289 [failure addObject:@"!"];
3290 else
3291 [failure addObject:@"%"];
3292 }
3293
3294 _forever {
3295 if (start.TargetVer() != 0)
3296 [failure addObject:[NSString stringWithFormat:@"%s %s", start.CompType(), start.TargetVer()]];
3297 if (start == end)
3298 break;
3299 ++start;
3300 }
3301 }
3302 }
3303
3304 return issues;
3305 }
3306
3307 - (bool) popErrorWithTitle:(NSString *)title {
3308 bool fatal(false);
3309 std::string message;
3310
3311 while (!_error->empty()) {
3312 std::string error;
3313 bool warning(!_error->PopMessage(error));
3314 if (!warning)
3315 fatal = true;
3316 for (;;) {
3317 size_t size(error.size());
3318 if (size == 0 || error[size - 1] != '\n')
3319 break;
3320 error.resize(size - 1);
3321 }
3322 lprintf("%c:[%s]\n", warning ? 'W' : 'E', error.c_str());
3323
3324 if (!message.empty())
3325 message += "\n\n";
3326 message += error;
3327 }
3328
3329 if (fatal && !message.empty())
3330 [delegate_ _setProgressError:[NSString stringWithUTF8String:message.c_str()] withTitle:[NSString stringWithFormat:Colon_, fatal ? Error_ : Warning_, title]];
3331
3332 return fatal;
3333 }
3334
3335 - (bool) popErrorWithTitle:(NSString *)title forOperation:(bool)success {
3336 return [self popErrorWithTitle:title] || !success;
3337 }
3338
3339 - (void) reloadData { CYPoolStart() {
3340 @synchronized (self) {
3341 ++era_;
3342
3343 [self releasePackages];
3344
3345 sources_.clear();
3346 CFArrayRemoveAllValues(deadSources_);
3347
3348 _error->Discard();
3349
3350 delete list_;
3351 list_ = NULL;
3352 manager_ = NULL;
3353 delete lock_;
3354 lock_ = NULL;
3355 delete fetcher_;
3356 fetcher_ = NULL;
3357 delete resolver_;
3358 resolver_ = NULL;
3359 delete records_;
3360 records_ = NULL;
3361 delete policy_;
3362 policy_ = NULL;
3363
3364 cache_.Close();
3365
3366 apr_pool_clear(pool_);
3367
3368 NSRecycleZone(zone_);
3369 zone_ = NSCreateZone(1024 * 1024, 256 * 1024, NO);
3370
3371 int chk(creat("/tmp/cydia.chk", 0644));
3372 if (chk != -1)
3373 close(chk);
3374
3375 NSString *title(UCLocalize("DATABASE"));
3376
3377 _trace();
3378 if (!cache_.Open(progress_, true)) { pop:
3379 std::string error;
3380 bool warning(!_error->PopMessage(error));
3381 lprintf("cache_.Open():[%s]\n", error.c_str());
3382
3383 if (error == "dpkg was interrupted, you must manually run 'dpkg --configure -a' to correct the problem. ")
3384 [delegate_ repairWithSelector:@selector(configure)];
3385 else if (error == "The package lists or status file could not be parsed or opened.")
3386 [delegate_ repairWithSelector:@selector(update)];
3387 // else if (error == "Could not open lock file /var/lib/dpkg/lock - open (13 Permission denied)")
3388 // else if (error == "Could not get lock /var/lib/dpkg/lock - open (35 Resource temporarily unavailable)")
3389 // else if (error == "The list of sources could not be read.")
3390 else
3391 [delegate_ _setProgressError:[NSString stringWithUTF8String:error.c_str()] withTitle:[NSString stringWithFormat:Colon_, warning ? Warning_ : Error_, title]];
3392
3393 if (warning)
3394 goto pop;
3395 _error->Discard();
3396 return;
3397 }
3398 _trace();
3399
3400 unlink("/tmp/cydia.chk");
3401
3402 now_ = [[NSDate date] timeIntervalSince1970];
3403
3404 policy_ = new pkgDepCache::Policy();
3405 records_ = new pkgRecords(cache_);
3406 resolver_ = new pkgProblemResolver(cache_);
3407 fetcher_ = new pkgAcquire(&status_);
3408 lock_ = NULL;
3409
3410 list_ = new pkgSourceList();
3411 if ([self popErrorWithTitle:title forOperation:list_->ReadMainList()])
3412 return;
3413
3414 if (cache_->DelCount() != 0 || cache_->InstCount() != 0) {
3415 [delegate_ _setProgressError:@"COUNTS_NONZERO_EX" withTitle:title];
3416 return;
3417 }
3418
3419 if ([self popErrorWithTitle:title forOperation:pkgApplyStatus(cache_)])
3420 return;
3421
3422 if (cache_->BrokenCount() != 0) {
3423 if ([self popErrorWithTitle:title forOperation:pkgFixBroken(cache_)])
3424 return;
3425
3426 if (cache_->BrokenCount() != 0) {
3427 [delegate_ _setProgressError:@"STILL_BROKEN_EX" withTitle:title];
3428 return;
3429 }
3430
3431 if ([self popErrorWithTitle:title forOperation:pkgMinimizeUpgrade(cache_)])
3432 return;
3433 }
3434
3435 for (pkgSourceList::const_iterator source = list_->begin(); source != list_->end(); ++source) {
3436 bool found = false;
3437 std::vector<pkgIndexFile *> *indices = (*source)->GetIndexFiles();
3438 for (std::vector<pkgIndexFile *>::const_iterator index = indices->begin(); index != indices->end(); ++index)
3439 // XXX: this could be more intelligent
3440 if (dynamic_cast<debPackagesIndex *>(*index) != NULL) {
3441 pkgCache::PkgFileIterator cached((*index)->FindInCache(cache_));
3442 if (!cached.end()) {
3443 sources_[cached->ID] = [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease];
3444 found = true;
3445 }
3446 }
3447 if (!found)
3448 CFArrayAppendValue(deadSources_, [[[Source alloc] initWithMetaIndex:*source inPool:pool_] autorelease]);
3449 }
3450
3451 {
3452 /*std::vector<Package *> packages;
3453 packages.reserve(std::max(10000U, [packages_ count] + 1000));
3454 [packages_ release];
3455 packages_ = nil;*/
3456
3457 _trace();
3458
3459 for (pkgCache::PkgIterator iterator = cache_->PkgBegin(); !iterator.end(); ++iterator)
3460 if (Package *package = [Package packageWithIterator:iterator withZone:zone_ inPool:pool_ database:self])
3461 //packages.push_back(package);
3462 CFArrayAppendValue(packages_, [package retain]);
3463
3464 _trace();
3465
3466 /*if (packages.empty())
3467 packages_ = [[NSArray alloc] init];
3468 else
3469 packages_ = [[NSArray alloc] initWithObjects:&packages.front() count:packages.size()];
3470 _trace();*/
3471
3472 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(16)];
3473 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(4)];
3474 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackagePrefixRadix) withContext:reinterpret_cast<void *>(0)];
3475
3476 /*_trace();
3477 PrintTimes();
3478 _trace();*/
3479
3480 _trace();
3481
3482 /*if (!packages.empty())
3483 CFQSortArray(&packages.front(), packages.size(), sizeof(packages.front()), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare_), NULL);*/
3484 //std::sort(packages.begin(), packages.end(), PackageNameOrdering());
3485
3486 //CFArraySortValues((CFMutableArrayRef) packages_, CFRangeMake(0, [packages_ count]), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3487
3488 CFArrayInsertionSortValues(packages_, CFRangeMake(0, CFArrayGetCount(packages_)), reinterpret_cast<CFComparatorFunction>(&PackageNameCompare), NULL);
3489
3490 //[packages_ sortUsingFunction:reinterpret_cast<NSComparisonResult (*)(id, id, void *)>(&PackageNameCompare) context:NULL];
3491
3492 _trace();
3493
3494 size_t count(CFArrayGetCount(packages_));
3495 MetaFile_->active_ = count;
3496
3497 for (size_t index(0); index != count; ++index)
3498 [(Package *) CFArrayGetValueAtIndex(packages_, index) setIndex:index];
3499
3500 _trace();
3501 }
3502 } } CYPoolEnd() _trace(); }
3503
3504 - (void) clear {
3505 @synchronized (self) {
3506 delete resolver_;
3507 resolver_ = new pkgProblemResolver(cache_);
3508
3509 for (pkgCache::PkgIterator iterator(cache_->PkgBegin()); !iterator.end(); ++iterator) {
3510 if (!cache_[iterator].Keep()) {
3511 cache_->MarkKeep(iterator, false);
3512 cache_->SetReInstall(iterator, false);
3513 }
3514 }
3515 } }
3516
3517 - (void) configure {
3518 NSString *dpkg = [NSString stringWithFormat:@"dpkg --configure -a --status-fd %u", statusfd_];
3519 _trace();
3520 system([dpkg UTF8String]);
3521 _trace();
3522 }
3523
3524 - (bool) clean {
3525 // XXX: I don't remember this condition
3526 if (lock_ != NULL)
3527 return false;
3528
3529 FileFd Lock;
3530 Lock.Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3531
3532 NSString *title(UCLocalize("CLEAN_ARCHIVES"));
3533
3534 if ([self popErrorWithTitle:title])
3535 return false;
3536
3537 pkgAcquire fetcher;
3538 fetcher.Clean(_config->FindDir("Dir::Cache::Archives"));
3539
3540 class LogCleaner :
3541 public pkgArchiveCleaner
3542 {
3543 protected:
3544 virtual void Erase(const char *File, std::string Pkg, std::string Ver, struct stat &St) {
3545 unlink(File);
3546 }
3547 } cleaner;
3548
3549 if ([self popErrorWithTitle:title forOperation:cleaner.Go(_config->FindDir("Dir::Cache::Archives") + "partial/", cache_)])
3550 return false;
3551
3552 return true;
3553 }
3554
3555 - (bool) prepare {
3556 fetcher_->Shutdown();
3557
3558 pkgRecords records(cache_);
3559
3560 lock_ = new FileFd();
3561 lock_->Fd(GetLock(_config->FindDir("Dir::Cache::Archives") + "lock"));
3562
3563 NSString *title(UCLocalize("PREPARE_ARCHIVES"));
3564
3565 if ([self popErrorWithTitle:title])
3566 return false;
3567
3568 pkgSourceList list;
3569 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3570 return false;
3571
3572 manager_ = (_system->CreatePM(cache_));
3573 if ([self popErrorWithTitle:title forOperation:manager_->GetArchives(fetcher_, &list, &records)])
3574 return false;
3575
3576 return true;
3577 }
3578
3579 - (void) perform {
3580 NSString *title(UCLocalize("PERFORM_SELECTIONS"));
3581
3582 NSMutableArray *before = [NSMutableArray arrayWithCapacity:16]; {
3583 pkgSourceList list;
3584 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3585 return;
3586 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3587 [before addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3588 }
3589
3590 if (fetcher_->Run(PulseInterval_) != pkgAcquire::Continue) {
3591 _trace();
3592 return;
3593 }
3594
3595 [CydiaApp retainNetworkActivityIndicator];
3596
3597 bool failed = false;
3598 for (pkgAcquire::ItemIterator item = fetcher_->ItemsBegin(); item != fetcher_->ItemsEnd(); item++) {
3599 if ((*item)->Status == pkgAcquire::Item::StatDone && (*item)->Complete)
3600 continue;
3601 if ((*item)->Status == pkgAcquire::Item::StatIdle)
3602 continue;
3603
3604 std::string uri = (*item)->DescURI();
3605 std::string error = (*item)->ErrorText;
3606
3607 lprintf("pAf:%s:%s\n", uri.c_str(), error.c_str());
3608 failed = true;
3609
3610 [delegate_ performSelectorOnMainThread:@selector(_setProgressErrorPackage:)
3611 withObject:[NSArray arrayWithObjects:
3612 [NSString stringWithUTF8String:error.c_str()],
3613 nil]
3614 waitUntilDone:YES
3615 ];
3616 }
3617
3618 [CydiaApp releaseNetworkActivityIndicator];
3619
3620 if (failed) {
3621 _trace();
3622 return;
3623 }
3624
3625 _system->UnLock();
3626 pkgPackageManager::OrderResult result = manager_->DoInstall(statusfd_);
3627
3628 if (_error->PendingError()) {
3629 _trace();
3630 return;
3631 }
3632
3633 if (result == pkgPackageManager::Failed) {
3634 _trace();
3635 return;
3636 }
3637
3638 if (result != pkgPackageManager::Completed) {
3639 _trace();
3640 return;
3641 }
3642
3643 NSMutableArray *after = [NSMutableArray arrayWithCapacity:16]; {
3644 pkgSourceList list;
3645 if ([self popErrorWithTitle:title forOperation:list.ReadMainList()])
3646 return;
3647 for (pkgSourceList::const_iterator source = list.begin(); source != list.end(); ++source)
3648 [after addObject:[NSString stringWithUTF8String:(*source)->GetURI().c_str()]];
3649 }
3650
3651 if (![before isEqualToArray:after])
3652 [self update];
3653 }
3654
3655 - (bool) upgrade {
3656 NSString *title(UCLocalize("UPGRADE"));
3657 if ([self popErrorWithTitle:title forOperation:pkgDistUpgrade(cache_)])
3658 return false;
3659 return true;
3660 }
3661
3662 - (void) update {
3663 [self updateWithStatus:status_];
3664 }
3665
3666 - (void) updateWithStatus:(Status &)status {
3667 _transient NSObject<ProgressDelegate> *delegate(status.getDelegate());
3668 NSString *title(UCLocalize("REFRESHING_DATA"));
3669
3670 pkgSourceList list;
3671 if (!list.ReadMainList())
3672 [delegate _setProgressError:@"Unable to read source list." withTitle:title];
3673
3674 FileFd lock;
3675 lock.Fd(GetLock(_config->FindDir("Dir::State::Lists") + "lock"));
3676 if ([self popErrorWithTitle:title])
3677 return;
3678
3679 if ([self popErrorWithTitle:title forOperation:ListUpdate(status, list, PulseInterval_)])
3680 /* XXX: ignore this because users suck and don't understand why refreshing is important: return */
3681 /* XXX: why the hell is an empty if statement a clang error? */ (void) 0;
3682
3683 [Metadata_ setObject:[NSDate date] forKey:@"LastUpdate"];
3684 Changed_ = true;
3685 }
3686
3687 - (void) setDelegate:(id)delegate {
3688 delegate_ = delegate;
3689 status_.setDelegate(delegate);
3690 progress_.setDelegate(delegate);
3691 }
3692
3693 - (Source *) getSource:(pkgCache::PkgFileIterator)file {
3694 SourceMap::const_iterator i(sources_.find(file->ID));
3695 return i == sources_.end() ? nil : i->second;
3696 }
3697
3698 - (NSString *) mappedSectionForPointer:(const char *)section {
3699 _H<NSString> *mapped;
3700
3701 _profile(Database$mappedSectionForPointer$Cache)
3702 mapped = &sections_[section];
3703 _end
3704
3705 if (*mapped == NULL) {
3706 size_t length(strlen(section));
3707 char spaced[length + 1];
3708
3709 _profile(Database$mappedSectionForPointer$Replace)
3710 for (size_t index(0); index != length; ++index)
3711 spaced[index] = section[index] == '_' ? ' ' : section[index];
3712 spaced[length] = '\0';
3713 _end
3714
3715 NSString *string;
3716
3717 _profile(Database$mappedSectionForPointer$stringWithUTF8String)
3718 string = [NSString stringWithUTF8String:spaced];
3719 _end
3720
3721 _profile(Database$mappedSectionForPointer$Map)
3722 string = [SectionMap_ objectForKey:string] ?: string;
3723 _end
3724
3725 *mapped = string;
3726 } return *mapped;
3727 }
3728
3729 @end
3730 /* }}} */
3731
3732 /* Web Scripting {{{ */
3733 @interface CydiaObject : NSObject {
3734 id indirect_;
3735 _transient id delegate_;
3736 }
3737
3738 - (id) initWithDelegate:(IndirectDelegate *)indirect;
3739 @end
3740
3741 @implementation CydiaObject
3742
3743 - (void) dealloc {
3744 [indirect_ release];
3745 [super dealloc];
3746 }
3747
3748 - (id) initWithDelegate:(IndirectDelegate *)indirect {
3749 if ((self = [super init]) != nil) {
3750 indirect_ = [indirect retain];
3751 } return self;
3752 }
3753
3754 - (void) setDelegate:(id)delegate {
3755 delegate_ = delegate;
3756 }
3757
3758 + (NSArray *) _attributeKeys {
3759 return [NSArray arrayWithObjects:@"device", @"firewire", @"imei", @"mac", @"serial", nil];
3760 }
3761
3762 - (NSArray *) attributeKeys {
3763 return [[self class] _attributeKeys];
3764 }
3765
3766 + (BOOL) isKeyExcludedFromWebScript:(const char *)name {
3767 return ![[self _attributeKeys] containsObject:[NSString stringWithUTF8String:name]] && [super isKeyExcludedFromWebScript:name];
3768 }
3769
3770 - (NSString *) device {
3771 return [[UIDevice currentDevice] uniqueIdentifier];
3772 }
3773
3774 #if 0 // XXX: implement!
3775 - (NSString *) mac {
3776 if (![indirect_ promptForSensitive:@"Mac Address"])
3777 return nil;
3778 }
3779
3780 - (NSString *) serial {
3781 if (![indirect_ promptForSensitive:@"Serial #"])
3782 return nil;
3783 }
3784
3785 - (NSString *) firewire {
3786 if (![indirect_ promptForSensitive:@"Firewire GUID"])
3787 return nil;
3788 }
3789
3790 - (NSString *) imei {
3791 if (![indirect_ promptForSensitive:@"IMEI"])
3792 return nil;
3793 }
3794 #endif
3795
3796 + (NSString *) webScriptNameForSelector:(SEL)selector {
3797 if (selector == @selector(close))
3798 return @"close";
3799 else if (selector == @selector(getInstalledPackages))
3800 return @"getInstalledPackages";
3801 else if (selector == @selector(getPackageById:))
3802 return @"getPackageById";
3803 else if (selector == @selector(installPackages:))
3804 return @"installPackages";
3805 else if (selector == @selector(setButtonImage:withStyle:toFunction:))
3806 return @"setButtonImage";
3807 else if (selector == @selector(setButtonTitle:withStyle:toFunction:))
3808 return @"setButtonTitle";
3809 else if (selector == @selector(setPopupHook:))
3810 return @"setPopupHook";
3811 else if (selector == @selector(setSpecial:))
3812 return @"setSpecial";
3813 else if (selector == @selector(setToken:))
3814 return @"setToken";
3815 else if (selector == @selector(setViewportWidth:))
3816 return @"setViewportWidth";
3817 else if (selector == @selector(supports:))
3818 return @"supports";
3819 else if (selector == @selector(stringWithFormat:arguments:))
3820 return @"format";
3821 else if (selector == @selector(localizedStringForKey:value:table:))
3822 return @"localize";
3823 else if (selector == @selector(du:))
3824 return @"du";
3825 else if (selector == @selector(statfs:))
3826 return @"statfs";
3827 else
3828 return nil;
3829 }
3830
3831 + (BOOL) isSelectorExcludedFromWebScript:(SEL)selector {
3832 return [self webScriptNameForSelector:selector] == nil;
3833 }
3834
3835 - (BOOL) supports:(NSString *)feature {
3836 return [feature isEqualToString:@"window.open"];
3837 }
3838
3839 - (NSArray *) getInstalledPackages {
3840 NSArray *packages([[Database sharedInstance] packages]);
3841 NSMutableArray *installed([NSMutableArray arrayWithCapacity:1024]);
3842 for (Package *package in packages)
3843 if ([package installed] != nil)
3844 [installed addObject:package];
3845 return installed;
3846 }
3847
3848 - (Package *) getPackageById:(NSString *)id {
3849 Package *package([[Database sharedInstance] packageWithName:id]);
3850 [package parse];
3851 return package;
3852 }
3853
3854 - (NSArray *) statfs:(NSString *)path {
3855 struct statfs stat;
3856
3857 if (path == nil || statfs([path UTF8String], &stat) == -1)
3858 return nil;
3859
3860 return [NSArray arrayWithObjects:
3861 [NSNumber numberWithUnsignedLong:stat.f_bsize],
3862 [NSNumber numberWithUnsignedLong:stat.f_blocks],
3863 [NSNumber numberWithUnsignedLong:stat.f_bfree],
3864 nil];
3865 }
3866
3867 - (NSNumber *) du:(NSString *)path {
3868 NSNumber *value(nil);
3869
3870 int fds[2];
3871 _assert(pipe(fds) != -1);
3872
3873 pid_t pid(ExecFork());
3874 if (pid == 0) {
3875 _assert(dup2(fds[1], 1) != -1);
3876 _assert(close(fds[0]) != -1);
3877 _assert(close(fds[1]) != -1);
3878 /* XXX: this should probably not use du */
3879 execl("/usr/libexec/cydia/du", "du", "-s", [path UTF8String], NULL);
3880 exit(1);
3881 _assert(false);
3882 }
3883
3884 _assert(close(fds[1]) != -1);
3885
3886 if (FILE *du = fdopen(fds[0], "r")) {
3887 char line[1024];
3888 while (fgets(line, sizeof(line), du) != NULL) {
3889 size_t length(strlen(line));
3890 while (length != 0 && line[length - 1] == '\n')
3891 line[--length] = '\0';
3892 if (char *tab = strchr(line, '\t')) {
3893 *tab = '\0';
3894 value = [NSNumber numberWithUnsignedLong:strtoul(line, NULL, 0)];
3895 }
3896 }
3897
3898 fclose(du);
3899 } else _assert(close(fds[0]));
3900
3901 int status;
3902 wait:
3903 if (waitpid(pid, &status, 0) == -1)
3904 if (errno == EINTR)
3905 goto wait;
3906 else _assert(false);
3907
3908 return value;
3909 }
3910
3911 - (void) close {
3912 [indirect_ close];
3913 }
3914
3915 - (void) installPackages:(NSArray *)packages {
3916 [delegate_ performSelectorOnMainThread:@selector(installPackages:) withObject:packages waitUntilDone:NO];
3917 }
3918
3919 - (void) setButtonImage:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3920 [indirect_ setButtonImage:button withStyle:style toFunction:function];
3921 }
3922
3923 - (void) setButtonTitle:(NSString *)button withStyle:(NSString *)style toFunction:(id)function {
3924 [indirect_ setButtonTitle:button withStyle:style toFunction:function];
3925 }
3926
3927 - (void) setSpecial:(id)function {
3928 [indirect_ setSpecial:function];
3929 }
3930
3931 - (void) setToken:(NSString *)token {
3932 if (Token_ != nil)
3933 [Token_ release];
3934 Token_ = [token retain];
3935
3936 [Metadata_ setObject:Token_ forKey:@"Token"];
3937 Changed_ = true;
3938 }
3939
3940 - (void) setPopupHook:(id)function {
3941 [indirect_ setPopupHook:function];
3942 }
3943
3944 - (void) setViewportWidth:(float)width {
3945 [indirect_ setViewportWidth:width];
3946 }
3947
3948 - (NSString *) stringWithFormat:(NSString *)format arguments:(WebScriptObject *)arguments {
3949 //NSLog(@"SWF:\"%@\" A:%@", format, [arguments description]);
3950 unsigned count([arguments count]);
3951 id values[count];
3952 for (unsigned i(0); i != count; ++i)
3953 values[i] = [arguments objectAtIndex:i];
3954 return [[[NSString alloc] initWithFormat:format arguments:*(reinterpret_cast<va_list *>(&values))] autorelease];
3955 }
3956
3957 - (NSString *) localizedStringForKey:(NSString *)key value:(NSString *)value table:(NSString *)table {
3958 if (reinterpret_cast<id>(value) == [WebUndefined undefined])
3959 value = nil;
3960 if (reinterpret_cast<id>(table) == [WebUndefined undefined])
3961 table = nil;
3962 return [[NSBundle mainBundle] localizedStringForKey:key value:value table:table];
3963 }
3964
3965 @end
3966 /* }}} */
3967
3968 /* @ Loading... Indicator {{{ */
3969 @interface CYLoadingIndicator : UIView {
3970 UIActivityIndicatorView *spinner_;
3971 UILabel *label_;
3972 UIView *container_;
3973 }
3974
3975 @property (readonly, nonatomic) UILabel *label;
3976 @property (readonly, nonatomic) UIActivityIndicatorView *activityIndicatorView;
3977
3978 @end
3979
3980 @implementation CYLoadingIndicator
3981
3982 - (id)initWithFrame:(CGRect)frame {
3983 if ((self = [super initWithFrame:frame])) {
3984 container_ = [[[UIView alloc] init] autorelease];
3985 [container_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleBottomMargin];
3986
3987 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleGray] autorelease];
3988 [spinner_ startAnimating];
3989 [container_ addSubview:spinner_];
3990
3991 label_ = [[[UILabel alloc] init] autorelease];
3992 [label_ setFont:[UIFont boldSystemFontOfSize:15.0f]];
3993 [label_ setBackgroundColor:[UIColor clearColor]];
3994 [label_ setTextColor:[UIColor blackColor]];
3995 [label_ setShadowColor:[UIColor whiteColor]];
3996 [label_ setShadowOffset:CGSizeMake(0, 1)];
3997 [label_ setText:[NSString stringWithFormat:Elision_, UCLocalize("LOADING"), nil]];
3998 [container_ addSubview:label_];
3999
4000 CGSize viewsize = frame.size;
4001 CGSize spinnersize = [spinner_ bounds].size;
4002 CGSize textsize = [[label_ text] sizeWithFont:[label_ font]];
4003 float bothwidth = spinnersize.width + textsize.width + 5.0f;
4004
4005 CGRect containrect = {
4006 CGPointMake(floorf((viewsize.width / 2) - (bothwidth / 2)), floorf((viewsize.height / 2) - (spinnersize.height / 2))),
4007 CGSizeMake(bothwidth, spinnersize.height)
4008 };
4009 CGRect textrect = {
4010 CGPointMake(spinnersize.width + 5.0f, floorf((spinnersize.height / 2) - (textsize.height / 2))),
4011 textsize
4012 };
4013 CGRect spinrect = {
4014 CGPointZero,
4015 spinnersize
4016 };
4017
4018 [container_ setFrame:containrect];
4019 [spinner_ setFrame:spinrect];
4020 [label_ setFrame:textrect];
4021 [self addSubview:container_];
4022 }
4023
4024 return self;
4025 }
4026
4027 - (UILabel *)label { return label_; }
4028 - (UIActivityIndicatorView *)activityIndicatorView { return spinner_; }
4029
4030 @end
4031 /* }}} */
4032 /* Emulated Loading Controller {{{ */
4033 @interface CYEmulatedLoadingController : CYViewController {
4034 CYLoadingIndicator *indicator_;
4035 UITabBar *tabbar_;
4036 UINavigationBar *navbar_;
4037 }
4038 @end
4039
4040 @implementation CYEmulatedLoadingController
4041
4042 - (CYEmulatedLoadingController *) init {
4043 if ((self = [super init])) {
4044 [[self view] setBackgroundColor:[UIColor pinStripeColor]];
4045
4046 indicator_ = [[CYLoadingIndicator alloc] initWithFrame:[[self view] bounds]];
4047 [indicator_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4048 [[self view] addSubview:indicator_];
4049 [indicator_ release];
4050
4051 tabbar_ = [[UITabBar alloc] initWithFrame:CGRectMake(0, 0, 0, 49.0f)];
4052 [tabbar_ setFrame:CGRectMake(0.0f, [[self view] bounds].size.height - [tabbar_ bounds].size.height, [[self view] bounds].size.width, [tabbar_ bounds].size.height)];
4053 [tabbar_ setAutoresizingMask:UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleWidth];
4054 [[self view] addSubview:tabbar_];
4055 [tabbar_ release];
4056
4057 navbar_ = [[UINavigationBar alloc] initWithFrame:CGRectMake(0, 0, 0, 44.0f)];
4058 [navbar_ setFrame:CGRectMake(0.0f, 0.0f, [[self view] bounds].size.width, [navbar_ bounds].size.height)];
4059 [navbar_ setAutoresizingMask:UIViewAutoresizingFlexibleBottomMargin | UIViewAutoresizingFlexibleWidth];
4060 [[self view] addSubview:navbar_];
4061 [navbar_ release];
4062 } return self;
4063 }
4064
4065 @end
4066 /* }}} */
4067
4068 /* Cydia Browser Controller {{{ */
4069 @interface CYBrowserController : BrowserController {
4070 CydiaObject *cydia_;
4071 }
4072
4073 @end
4074
4075 @implementation CYBrowserController
4076
4077 - (void) dealloc {
4078 [cydia_ release];
4079 [super dealloc];
4080 }
4081
4082 - (void) setHeaders:(NSDictionary *)headers forHost:(NSString *)host {
4083 }
4084
4085 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
4086 [super webView:view didClearWindowObject:window forFrame:frame];
4087
4088 WebDataSource *source([frame dataSource]);
4089 NSURLResponse *response([source response]);
4090 NSURL *url([response URL]);
4091 NSString *scheme([url scheme]);
4092
4093 NSHTTPURLResponse *http;
4094 if (scheme != nil && ([scheme isEqualToString:@"http"] || [scheme isEqualToString:@"https"]))
4095 http = (NSHTTPURLResponse *) response;
4096 else
4097 http = nil;
4098
4099 NSDictionary *headers([http allHeaderFields]);
4100 NSString *host([url host]);
4101 [self setHeaders:headers forHost:host];
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
4485 [output_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4486 //[output_ setTextFont:@"Courier New"];
4487 [output_ setFont:[[output_ font] fontWithSize:12]];
4488 [output_ setTextColor:[UIColor whiteColor]];
4489 [output_ setBackgroundColor:[UIColor clearColor]];
4490 [output_ setMarginTop:0];
4491 [output_ setAllowsRubberBanding:YES];
4492 [output_ setEditable:NO];
4493 [[self view] addSubview:output_];
4494
4495 close_ = [[UIPushButton alloc] init];
4496 [close_ setAutoresizingMask:(UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin)];
4497 [close_ setAutosizesToFit:NO];
4498 [close_ setDrawsShadow:YES];
4499 [close_ setStretchBackground:YES];
4500 [close_ setEnabled:YES];
4501 [close_ setTitleFont:[UIFont boldSystemFontOfSize:22]];
4502 [close_ addTarget:self action:@selector(closeButtonPushed) forEvents:UIControlEventTouchUpInside];
4503 [close_ setBackground:[UIImage applicationImageNamed:@"green-up.png"] forState:0];
4504 [close_ setBackground:[UIImage applicationImageNamed:@"green-dn.png"] forState:1];
4505 } return self;
4506 }
4507
4508 - (void) positionViews {
4509 CGRect bounds = [[self view] bounds];
4510 CGSize prgsize = [UIProgressBar defaultSize];
4511
4512 CGRect prgrect = {{
4513 (bounds.size.width - prgsize.width) / 2,
4514 bounds.size.height - prgsize.height - 20
4515 }, prgsize};
4516
4517 float closewidth = std::min(bounds.size.width - 20, 300.0f);
4518
4519 [progress_ setFrame:prgrect];
4520 [status_ setFrame:CGRectMake(
4521 10,
4522 bounds.size.height - prgsize.height - 50,
4523 bounds.size.width - 20,
4524 24
4525 )];
4526 [output_ setFrame:CGRectMake(
4527 10,
4528 20,
4529 bounds.size.width - 20,
4530 bounds.size.height - 62
4531 )];
4532 [close_ setFrame:CGRectMake(
4533 (bounds.size.width - closewidth) / 2,
4534 bounds.size.height - prgsize.height - 50,
4535 closewidth,
4536 32 + prgsize.height
4537 )];
4538 }
4539
4540 - (void) viewWillAppear:(BOOL)animated {
4541 [super viewDidAppear:animated];
4542 [[self navigationItem] setHidesBackButton:YES];
4543 [[[self navigationController] navigationBar] setBarStyle:UIBarStyleBlack];
4544
4545 [self positionViews];
4546 }
4547
4548 - (void)didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
4549 [self positionViews];
4550 }
4551
4552 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
4553 NSString *context([alert context]);
4554
4555 if ([context isEqualToString:@"conffile"]) {
4556 FILE *input = [database_ input];
4557 if (button == [alert cancelButtonIndex])
4558 fprintf(input, "N\n");
4559 else if (button == [alert firstOtherButtonIndex])
4560 fprintf(input, "Y\n");
4561 fflush(input);
4562 }
4563 }
4564
4565 - (void) closeButtonPushed {
4566 running_ = NO;
4567
4568 UpdateExternalStatus(0);
4569
4570 switch (Finish_) {
4571 case 0:
4572 [self dismissModalViewControllerAnimated:YES];
4573 break;
4574
4575 case 1:
4576 [delegate_ terminateWithSuccess];
4577 /*if ([delegate_ respondsToSelector:@selector(suspendWithAnimation:)])
4578 [delegate_ suspendWithAnimation:YES];
4579 else
4580 [delegate_ suspend];*/
4581 break;
4582
4583 case 2:
4584 _trace();
4585 goto reload;
4586
4587 case 3:
4588 _trace();
4589 goto reload;
4590
4591 reload:
4592 system("/usr/bin/sbreload");
4593 _trace();
4594 break;
4595
4596 case 4:
4597 _trace();
4598 if (void (*SBReboot)(mach_port_t) = reinterpret_cast<void (*)(mach_port_t)>(dlsym(RTLD_DEFAULT, "SBReboot")))
4599 SBReboot(SBSSpringBoardServerPort());
4600 else
4601 reboot2(RB_AUTOBOOT);
4602 break;
4603 }
4604 }
4605
4606 - (void) _retachThread {
4607 [[self navigationItem] setTitle:UCLocalize("COMPLETE")];
4608
4609 [[self view] addSubview:close_];
4610 [progress_ removeFromSuperview];
4611 [status_ removeFromSuperview];
4612
4613 [database_ popErrorWithTitle:title_];
4614 [delegate_ progressControllerIsComplete:self];
4615
4616 if (Finish_ < 4) {
4617 FileFd file;
4618 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4619 _error->Discard();
4620 else {
4621 MMap mmap(file, MMap::ReadOnly);
4622 SHA1Summation sha1;
4623 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4624 if (!(notifyconf_ == sha1.Result()))
4625 Finish_ = 4;
4626 }
4627 }
4628
4629 if (Finish_ < 3) {
4630 FileFd file;
4631 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4632 _error->Discard();
4633 else {
4634 MMap mmap(file, MMap::ReadOnly);
4635 SHA1Summation sha1;
4636 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4637 if (!(springlist_ == sha1.Result()))
4638 Finish_ = 3;
4639 }
4640 }
4641
4642 switch (Finish_) {
4643 case 0: [close_ setTitle:UCLocalize("RETURN_TO_CYDIA")]; break; /* XXX: Maybe UCLocalize("DONE")? */
4644 case 1: [close_ setTitle:UCLocalize("CLOSE_CYDIA")]; break;
4645 case 2: [close_ setTitle:UCLocalize("RESTART_SPRINGBOARD")]; break;
4646 case 3: [close_ setTitle:UCLocalize("RELOAD_SPRINGBOARD")]; break;
4647 case 4: [close_ setTitle:UCLocalize("REBOOT_DEVICE")]; break;
4648 }
4649
4650 _trace();
4651 system("su -c /usr/bin/uicache mobile");
4652 _trace();
4653
4654 UpdateExternalStatus(Finish_ == 0 ? 2 : 0);
4655
4656 [delegate_ setStatusBarShowsProgress:NO];
4657 }
4658
4659 - (void) _detachNewThreadData:(ProgressData *)data { _pooled
4660 [[data target] performSelector:[data selector] withObject:[data object]];
4661 [self performSelectorOnMainThread:@selector(_retachThread) withObject:nil waitUntilDone:YES];
4662 }
4663
4664 - (void) detachNewThreadSelector:(SEL)selector toTarget:(id)target withObject:(id)object title:(NSString *)title {
4665 UpdateExternalStatus(1);
4666
4667 if (title_ != nil)
4668 [title_ release];
4669 if (title == nil)
4670 title_ = nil;
4671 else
4672 title_ = [title retain];
4673
4674 [[self navigationItem] setTitle:title_];
4675
4676 [status_ setText:nil];
4677 [output_ setText:@""];
4678 [progress_ setProgress:0];
4679
4680 [close_ removeFromSuperview];
4681 [[self view] addSubview:progress_];
4682 [[self view] addSubview:status_];
4683
4684 [delegate_ setStatusBarShowsProgress:YES];
4685 running_ = YES;
4686
4687 {
4688 FileFd file;
4689 if (!file.Open(NotifyConfig_, FileFd::ReadOnly))
4690 _error->Discard();
4691 else {
4692 MMap mmap(file, MMap::ReadOnly);
4693 SHA1Summation sha1;
4694 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4695 notifyconf_ = sha1.Result();
4696 }
4697 }
4698
4699 {
4700 FileFd file;
4701 if (!file.Open(SpringBoard_, FileFd::ReadOnly))
4702 _error->Discard();
4703 else {
4704 MMap mmap(file, MMap::ReadOnly);
4705 SHA1Summation sha1;
4706 sha1.Add(reinterpret_cast<uint8_t *>(mmap.Data()), mmap.Size());
4707 springlist_ = sha1.Result();
4708 }
4709 }
4710
4711 [NSThread
4712 detachNewThreadSelector:@selector(_detachNewThreadData:)
4713 toTarget:self
4714 withObject:[[[ProgressData alloc]
4715 initWithSelector:selector
4716 target:target
4717 object:object
4718 ] autorelease]
4719 ];
4720 }
4721
4722 - (void) repairWithSelector:(SEL)selector {
4723 [self
4724 detachNewThreadSelector:selector
4725 toTarget:database_
4726 withObject:nil
4727 title:UCLocalize("REPAIRING")
4728 ];
4729 }
4730
4731 - (void) setConfigurationData:(NSString *)data {
4732 [self
4733 performSelectorOnMainThread:@selector(_setConfigurationData:)
4734 withObject:data
4735 waitUntilDone:YES
4736 ];
4737 }
4738
4739 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
4740 CYActionSheet *sheet([[[CYActionSheet alloc]
4741 initWithTitle:title
4742 buttons:[NSArray arrayWithObjects:UCLocalize("OKAY"), nil]
4743 defaultButtonIndex:0
4744 ] autorelease]);
4745
4746 [sheet setMessage:error];
4747 [sheet yieldToPopupAlertAnimated:YES];
4748 [sheet dismiss];
4749 }
4750
4751 - (void) setProgressTitle:(NSString *)title {
4752 [self
4753 performSelectorOnMainThread:@selector(_setProgressTitle:)
4754 withObject:title
4755 waitUntilDone:YES
4756 ];
4757 }
4758
4759 - (void) setProgressPercent:(float)percent {
4760 [self
4761 performSelectorOnMainThread:@selector(_setProgressPercent:)
4762 withObject:[NSNumber numberWithFloat:percent]
4763 waitUntilDone:YES
4764 ];
4765 }
4766
4767 - (void) startProgress {
4768 }
4769
4770 - (void) addProgressOutput:(NSString *)output {
4771 [self
4772 performSelectorOnMainThread:@selector(_addProgressOutput:)
4773 withObject:output
4774 waitUntilDone:YES
4775 ];
4776 }
4777
4778 - (bool) isCancelling:(size_t)received {
4779 return false;
4780 }
4781
4782 - (void) _setConfigurationData:(NSString *)data {
4783 static Pcre conffile_r("^'(.*)' '(.*)' ([01]) ([01])$");
4784
4785 if (!conffile_r(data)) {
4786 lprintf("E:invalid conffile\n");
4787 return;
4788 }
4789
4790 NSString *ofile = conffile_r[1];
4791 //NSString *nfile = conffile_r[2];
4792
4793 UIAlertView *alert = [[[UIAlertView alloc]
4794 initWithTitle:UCLocalize("CONFIGURATION_UPGRADE")
4795 message:[NSString stringWithFormat:@"%@\n\n%@", UCLocalize("CONFIGURATION_UPGRADE_EX"), ofile]
4796 delegate:self
4797 cancelButtonTitle:UCLocalize("KEEP_OLD_COPY")
4798 otherButtonTitles:UCLocalize("ACCEPT_NEW_COPY"),
4799 // XXX: UCLocalize("SEE_WHAT_CHANGED"),
4800 nil
4801 ] autorelease];
4802
4803 [alert setContext:@"conffile"];
4804 [alert show];
4805 }
4806
4807 - (void) _setProgressTitle:(NSString *)title {
4808 NSMutableArray *words([[title componentsSeparatedByString:@" "] mutableCopy]);
4809 for (size_t i(0), e([words count]); i != e; ++i) {
4810 NSString *word([words objectAtIndex:i]);
4811 if (Package *package = [database_ packageWithName:word])
4812 [words replaceObjectAtIndex:i withObject:[package name]];
4813 }
4814
4815 [status_ setText:[words componentsJoinedByString:@" "]];
4816 }
4817
4818 - (void) _setProgressPercent:(NSNumber *)percent {
4819 [progress_ setProgress:[percent floatValue]];
4820 }
4821
4822 - (void) _addProgressOutput:(NSString *)output {
4823 [output_ setText:[NSString stringWithFormat:@"%@\n%@", [output_ text], output]];
4824 CGSize size = [output_ contentSize];
4825 CGPoint offset = [output_ contentOffset];
4826 if (size.height - offset.y < [output_ frame].size.height + 20.f) {
4827 CGRect rect = {{0, size.height-1}, {size.width, 1}};
4828 [output_ scrollRectToVisible:rect animated:YES];
4829 }
4830 }
4831
4832 - (BOOL) isRunning {
4833 return running_;
4834 }
4835
4836 @end
4837 /* }}} */
4838
4839 /* Cell Content View {{{ */
4840 @protocol ContentDelegate
4841 - (void) drawContentRect:(CGRect)rect;
4842 @end
4843
4844 @interface ContentView : UIView {
4845 _transient id<ContentDelegate> delegate_;
4846 }
4847
4848 @end
4849
4850 @implementation ContentView
4851
4852 - (id) initWithFrame:(CGRect)frame {
4853 if ((self = [super initWithFrame:frame]) != nil) {
4854 [self setNeedsDisplayOnBoundsChange:YES];
4855 } return self;
4856 }
4857
4858 - (void) setDelegate:(id<ContentDelegate>)delegate {
4859 delegate_ = delegate;
4860 }
4861
4862 - (void) drawRect:(CGRect)rect {
4863 [super drawRect:rect];
4864 [delegate_ drawContentRect:rect];
4865 }
4866
4867 @end
4868 /* }}} */
4869 /* Cydia TableView Cell {{{ */
4870 @interface CYTableViewCell : UITableViewCell {
4871 ContentView *content_;
4872 bool highlighted_;
4873 }
4874
4875 @end
4876
4877 @implementation CYTableViewCell
4878
4879 - (void) dealloc {
4880 [content_ release];
4881 [super dealloc];
4882 }
4883
4884 - (void) _updateHighlightColorsForView:(id)view highlighted:(BOOL)highlighted {
4885 //NSLog(@"_updateHighlightColorsForView:%@ highlighted:%s [content_=%@]", view, highlighted ? "YES" : "NO", content_);
4886
4887 if (view == content_) {
4888 //NSLog(@"_updateHighlightColorsForView:content_ highlighted:%s", highlighted ? "YES" : "NO", content_);
4889 highlighted_ = highlighted;
4890 }
4891
4892 [super _updateHighlightColorsForView:view highlighted:highlighted];
4893 }
4894
4895 - (void) setSelected:(BOOL)selected animated:(BOOL)animated {
4896 //NSLog(@"setSelected:%s animated:%s", selected ? "YES" : "NO", animated ? "YES" : "NO");
4897 highlighted_ = selected;
4898
4899 [super setSelected:selected animated:animated];
4900 [content_ setNeedsDisplay];
4901 }
4902
4903 @end
4904 /* }}} */
4905
4906 /* Package Cell {{{ */
4907 @interface PackageCell : CYTableViewCell <
4908 ContentDelegate
4909 > {
4910 UIImage *icon_;
4911 NSString *name_;
4912 NSString *description_;
4913 bool commercial_;
4914 NSString *source_;
4915 UIImage *badge_;
4916 Package *package_;
4917 UIImage *placard_;
4918 }
4919
4920 - (PackageCell *) init;
4921 - (void) setPackage:(Package *)package;
4922
4923 - (void) drawContentRect:(CGRect)rect;
4924
4925 @end
4926
4927 @implementation PackageCell
4928
4929 - (void) clearPackage {
4930 if (icon_ != nil) {
4931 [icon_ release];
4932 icon_ = nil;
4933 }
4934
4935 if (name_ != nil) {
4936 [name_ release];
4937 name_ = nil;
4938 }
4939
4940 if (description_ != nil) {
4941 [description_ release];
4942 description_ = nil;
4943 }
4944
4945 if (source_ != nil) {
4946 [source_ release];
4947 source_ = nil;
4948 }
4949
4950 if (badge_ != nil) {
4951 [badge_ release];
4952 badge_ = nil;
4953 }
4954
4955 if (placard_ != nil) {
4956 [placard_ release];
4957 placard_ = nil;
4958 }
4959
4960 [package_ release];
4961 package_ = nil;
4962 }
4963
4964 - (void) dealloc {
4965 [self clearPackage];
4966 [super dealloc];
4967 }
4968
4969 - (PackageCell *) init {
4970 CGRect frame(CGRectMake(0, 0, 320, 74));
4971 if ((self = [super initWithFrame:frame reuseIdentifier:@"Package"]) != nil) {
4972 UIView *content([self contentView]);
4973 CGRect bounds([content bounds]);
4974
4975 content_ = [[ContentView alloc] initWithFrame:bounds];
4976 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
4977 [content addSubview:content_];
4978
4979 [content_ setDelegate:self];
4980 [content_ setOpaque:YES];
4981 } return self;
4982 }
4983
4984 - (void) _setBackgroundColor {
4985 UIColor *color;
4986 if (NSString *mode = [package_ mode]) {
4987 bool remove([mode isEqualToString:@"REMOVE"] || [mode isEqualToString:@"PURGE"]);
4988 color = remove ? RemovingColor_ : InstallingColor_;
4989 } else
4990 color = [UIColor whiteColor];
4991
4992 [content_ setBackgroundColor:color];
4993 [self setNeedsDisplay];
4994 }
4995
4996 - (NSString *) accessibilityLabel {
4997 return [NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), name_, description_];
4998 }
4999
5000 - (void) setPackage:(Package *)package {
5001 [self clearPackage];
5002 [package parse];
5003
5004 Source *source = [package source];
5005
5006 icon_ = [[package icon] retain];
5007 name_ = [[package name] retain];
5008
5009 if (IsWildcat_)
5010 description_ = [package longDescription];
5011 if (description_ == nil)
5012 description_ = [package shortDescription];
5013 if (description_ != nil)
5014 description_ = [description_ retain];
5015
5016 commercial_ = [package isCommercial];
5017
5018 package_ = [package retain];
5019
5020 NSString *label = nil;
5021 bool trusted = false;
5022
5023 if (source != nil) {
5024 label = [source label];
5025 trusted = [source trusted];
5026 } else if ([[package id] isEqualToString:@"firmware"])
5027 label = UCLocalize("APPLE");
5028 else
5029 label = [NSString stringWithFormat:UCLocalize("SLASH_DELIMITED"), UCLocalize("UNKNOWN"), UCLocalize("LOCAL")];
5030
5031 NSString *from(label);
5032
5033 NSString *section = [package simpleSection];
5034 if (section != nil && ![section isEqualToString:label]) {
5035 section = [[NSBundle mainBundle] localizedStringForKey:section value:nil table:@"Sections"];
5036 from = [NSString stringWithFormat:UCLocalize("PARENTHETICAL"), from, section];
5037 }
5038
5039 from = [NSString stringWithFormat:UCLocalize("FROM"), from];
5040 source_ = [from retain];
5041
5042 if (NSString *purpose = [package primaryPurpose])
5043 if ((badge_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/Purposes/%@.png", App_, purpose]]) != nil)
5044 badge_ = [badge_ retain];
5045
5046 if ([package installed] != nil)
5047 if ((placard_ = [UIImage imageAtPath:[NSString stringWithFormat:@"%@/installed.png", App_]]) != nil)
5048 placard_ = [placard_ retain];
5049
5050 [self _setBackgroundColor];
5051 [content_ setNeedsDisplay];
5052 }
5053
5054 - (void) drawContentRect:(CGRect)rect {
5055 bool highlighted(highlighted_);
5056 float width([self bounds].size.width);
5057
5058 #if 0
5059 CGContextRef context(UIGraphicsGetCurrentContext());
5060 [([[self selectedBackgroundView] superview] != nil ? [UIColor clearColor] : [self backgroundColor]) set];
5061 CGContextFillRect(context, rect);
5062 #endif
5063
5064 if (icon_ != nil) {
5065 CGRect rect;
5066 rect.size = [icon_ size];
5067
5068 rect.size.width /= 2;
5069 rect.size.height /= 2;
5070
5071 rect.origin.x = 25 - rect.size.width / 2;
5072 rect.origin.y = 25 - rect.size.height / 2;
5073
5074 [icon_ drawInRect:rect];
5075 }
5076
5077 if (badge_ != nil) {
5078 CGRect rect;
5079 rect.size = [badge_ size];
5080
5081 rect.size.width /= 2;
5082 rect.size.height /= 2;
5083
5084 rect.origin.x = 36 - rect.size.width / 2;
5085 rect.origin.y = 36 - rect.size.height / 2;
5086
5087 [badge_ drawInRect:rect];
5088 }
5089
5090 if (highlighted)
5091 UISetColor(White_);
5092
5093 if (!highlighted)
5094 UISetColor(commercial_ ? Purple_ : Black_);
5095 [name_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - (placard_ == nil ? 80 : 106)) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5096 [source_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
5097
5098 if (!highlighted)
5099 UISetColor(commercial_ ? Purplish_ : Gray_);
5100 [description_ drawAtPoint:CGPointMake(12, 46) forWidth:(width - 46) withFont:Font14_ lineBreakMode:UILineBreakModeTailTruncation];
5101
5102 if (placard_ != nil)
5103 [placard_ drawAtPoint:CGPointMake(width - 52, 9)];
5104 }
5105
5106 @end
5107 /* }}} */
5108 /* Section Cell {{{ */
5109 @interface SectionCell : CYTableViewCell <
5110 ContentDelegate
5111 > {
5112 NSString *basic_;
5113 NSString *section_;
5114 NSString *name_;
5115 NSString *count_;
5116 UIImage *icon_;
5117 UISwitch *switch_;
5118 BOOL editing_;
5119 }
5120
5121 - (void) setSection:(Section *)section editing:(BOOL)editing;
5122
5123 @end
5124
5125 @implementation SectionCell
5126
5127 - (void) clearSection {
5128 if (basic_ != nil) {
5129 [basic_ release];
5130 basic_ = nil;
5131 }
5132
5133 if (section_ != nil) {
5134 [section_ release];
5135 section_ = nil;
5136 }
5137
5138 if (name_ != nil) {
5139 [name_ release];
5140 name_ = nil;
5141 }
5142
5143 if (count_ != nil) {
5144 [count_ release];
5145 count_ = nil;
5146 }
5147 }
5148
5149 - (void) dealloc {
5150 [self clearSection];
5151 [icon_ release];
5152 [switch_ release];
5153 [super dealloc];
5154 }
5155
5156 - (id) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
5157 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
5158 icon_ = [[UIImage applicationImageNamed:@"folder.png"] retain];
5159 switch_ = [[UISwitch alloc] initWithFrame:CGRectMake(218, 9, 60, 25)];
5160 [switch_ addTarget:self action:@selector(onSwitch:) forEvents:UIControlEventValueChanged];
5161
5162 UIView *content([self contentView]);
5163 CGRect bounds([content bounds]);
5164
5165 content_ = [[ContentView alloc] initWithFrame:bounds];
5166 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5167 [content addSubview:content_];
5168 [content_ setBackgroundColor:[UIColor whiteColor]];
5169
5170 [content_ setDelegate:self];
5171 } return self;
5172 }
5173
5174 - (void) onSwitch:(id)sender {
5175 NSMutableDictionary *metadata([Sections_ objectForKey:basic_]);
5176 if (metadata == nil) {
5177 metadata = [NSMutableDictionary dictionaryWithCapacity:2];
5178 [Sections_ setObject:metadata forKey:basic_];
5179 }
5180
5181 [metadata setObject:[NSNumber numberWithBool:([switch_ isOn] == NO)] forKey:@"Hidden"];
5182 Changed_ = true;
5183 }
5184
5185 - (void) setSection:(Section *)section editing:(BOOL)editing {
5186 if (editing != editing_) {
5187 if (editing_)
5188 [switch_ removeFromSuperview];
5189 else
5190 [self addSubview:switch_];
5191 editing_ = editing;
5192 }
5193
5194 [self clearSection];
5195
5196 if (section == nil) {
5197 name_ = [UCLocalize("ALL_PACKAGES") retain];
5198 count_ = nil;
5199 } else {
5200 basic_ = [section name];
5201 if (basic_ != nil)
5202 basic_ = [basic_ retain];
5203
5204 section_ = [section localized];
5205 if (section_ != nil)
5206 section_ = [section_ retain];
5207
5208 name_ = [(section_ == nil || [section_ length] == 0 ? UCLocalize("NO_SECTION") : section_) retain];
5209 count_ = [[NSString stringWithFormat:@"%d", [section count]] retain];
5210
5211 if (editing_)
5212 [switch_ setOn:(isSectionVisible(basic_) ? 1 : 0) animated:NO];
5213 }
5214
5215 [self setAccessoryType:editing ? UITableViewCellAccessoryNone : UITableViewCellAccessoryDisclosureIndicator];
5216 [self setSelectionStyle:editing ? UITableViewCellSelectionStyleNone : UITableViewCellSelectionStyleBlue];
5217
5218 [content_ setNeedsDisplay];
5219 }
5220
5221 - (void) setFrame:(CGRect)frame {
5222 [super setFrame:frame];
5223
5224 CGRect rect([switch_ frame]);
5225 [switch_ setFrame:CGRectMake(frame.size.width - 102, 9, rect.size.width, rect.size.height)];
5226 }
5227
5228 - (NSString *) accessibilityLabel {
5229 return name_;
5230 }
5231
5232 - (void) drawContentRect:(CGRect)rect {
5233 bool highlighted(highlighted_ && !editing_);
5234
5235 [icon_ drawInRect:CGRectMake(8, 7, 32, 32)];
5236
5237 if (highlighted)
5238 UISetColor(White_);
5239
5240 float width(rect.size.width);
5241 if (editing_)
5242 width -= 87;
5243
5244 if (!highlighted)
5245 UISetColor(Black_);
5246 [name_ drawAtPoint:CGPointMake(48, 9) forWidth:(width - 70) withFont:Font22Bold_ lineBreakMode:UILineBreakModeTailTruncation];
5247
5248 CGSize size = [count_ sizeWithFont:Font14_];
5249
5250 UISetColor(White_);
5251 if (count_ != nil)
5252 [count_ drawAtPoint:CGPointMake(13 + (29 - size.width) / 2, 16) withFont:Font12Bold_];
5253 }
5254
5255 @end
5256 /* }}} */
5257
5258 /* File Table {{{ */
5259 @interface FileTable : CYViewController <
5260 UITableViewDataSource,
5261 UITableViewDelegate
5262 > {
5263 _transient Database *database_;
5264 Package *package_;
5265 NSString *name_;
5266 NSMutableArray *files_;
5267 UITableView *list_;
5268 }
5269
5270 - (id) initWithDatabase:(Database *)database;
5271 - (void) setPackage:(Package *)package;
5272
5273 @end
5274
5275 @implementation FileTable
5276
5277 - (void) dealloc {
5278 if (package_ != nil)
5279 [package_ release];
5280 if (name_ != nil)
5281 [name_ release];
5282 [files_ release];
5283 [list_ release];
5284 [super dealloc];
5285 }
5286
5287 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
5288 return files_ == nil ? 0 : [files_ count];
5289 }
5290
5291 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
5292 return 24.0f;
5293 }*/
5294
5295 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
5296 static NSString *reuseIdentifier = @"Cell";
5297
5298 UITableViewCell *cell = [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
5299 if (cell == nil) {
5300 cell = [[[UITableViewCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
5301 [cell setFont:[UIFont systemFontOfSize:16]];
5302 }
5303 [cell setText:[files_ objectAtIndex:indexPath.row]];
5304 [cell setSelectionStyle:UITableViewCellSelectionStyleNone];
5305
5306 return cell;
5307 }
5308
5309 - (id) initWithDatabase:(Database *)database {
5310 if ((self = [super init]) != nil) {
5311 database_ = database;
5312
5313 [[self navigationItem] setTitle:UCLocalize("INSTALLED_FILES")];
5314
5315 files_ = [[NSMutableArray arrayWithCapacity:32] retain];
5316
5317 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
5318 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5319 [list_ setRowHeight:24.0f];
5320 [[self view] addSubview:list_];
5321
5322 [list_ setDataSource:self];
5323 [list_ setDelegate:self];
5324 } return self;
5325 }
5326
5327 - (void) setPackage:(Package *)package {
5328 if (package_ != nil) {
5329 [package_ autorelease];
5330 package_ = nil;
5331 }
5332
5333 if (name_ != nil) {
5334 [name_ release];
5335 name_ = nil;
5336 }
5337
5338 [files_ removeAllObjects];
5339
5340 if (package != nil) {
5341 package_ = [package retain];
5342 name_ = [[package id] retain];
5343
5344 if (NSArray *files = [package files])
5345 [files_ addObjectsFromArray:files];
5346
5347 if ([files_ count] != 0) {
5348 if ([[files_ objectAtIndex:0] isEqualToString:@"/."])
5349 [files_ removeObjectAtIndex:0];
5350 [files_ sortUsingSelector:@selector(compareByPath:)];
5351
5352 NSMutableArray *stack = [NSMutableArray arrayWithCapacity:8];
5353 [stack addObject:@"/"];
5354
5355 for (int i(0), e([files_ count]); i != e; ++i) {
5356 NSString *file = [files_ objectAtIndex:i];
5357 while (![file hasPrefix:[stack lastObject]])
5358 [stack removeLastObject];
5359 NSString *directory = [stack lastObject];
5360 [stack addObject:[file stringByAppendingString:@"/"]];
5361 [files_ replaceObjectAtIndex:i withObject:[NSString stringWithFormat:@"%*s%@",
5362 ([stack count] - 2) * 3, "",
5363 [file substringFromIndex:[directory length]]
5364 ]];
5365 }
5366 }
5367 }
5368
5369 [list_ reloadData];
5370 }
5371
5372 - (void) reloadData {
5373 [self setPackage:[database_ packageWithName:name_]];
5374 }
5375
5376 @end
5377 /* }}} */
5378 /* Package Controller {{{ */
5379 @interface CYPackageController : CYBrowserController <
5380 UIActionSheetDelegate
5381 > {
5382 _transient Database *database_;
5383 Package *package_;
5384 NSString *name_;
5385 bool commercial_;
5386 NSMutableArray *buttons_;
5387 UIBarButtonItem *button_;
5388 }
5389
5390 - (id) initWithDatabase:(Database *)database;
5391 - (void) setPackage:(Package *)package;
5392
5393 @end
5394
5395 @implementation CYPackageController
5396
5397 - (void) dealloc {
5398 if (package_ != nil)
5399 [package_ release];
5400 if (name_ != nil)
5401 [name_ release];
5402
5403 [buttons_ release];
5404
5405 if (button_ != nil)
5406 [button_ release];
5407
5408 [super dealloc];
5409 }
5410
5411 - (void) release {
5412 if ([self retainCount] == 1)
5413 [delegate_ setPackageController:self];
5414 [super release];
5415 }
5416
5417 /* XXX: this is not safe at all... localization of /fail/ */
5418 - (void) _clickButtonWithName:(NSString *)name {
5419 if ([name isEqualToString:UCLocalize("CLEAR")])
5420 [delegate_ clearPackage:package_];
5421 else if ([name isEqualToString:UCLocalize("INSTALL")])
5422 [delegate_ installPackage:package_];
5423 else if ([name isEqualToString:UCLocalize("REINSTALL")])
5424 [delegate_ installPackage:package_];
5425 else if ([name isEqualToString:UCLocalize("REMOVE")])
5426 [delegate_ removePackage:package_];
5427 else if ([name isEqualToString:UCLocalize("UPGRADE")])
5428 [delegate_ installPackage:package_];
5429 else _assert(false);
5430 }
5431
5432 - (void) actionSheet:(UIActionSheet *)sheet clickedButtonAtIndex:(NSInteger)button {
5433 NSString *context([sheet context]);
5434
5435 if ([context isEqualToString:@"modify"]) {
5436 if (button != [sheet cancelButtonIndex]) {
5437 NSString *buttonName = [buttons_ objectAtIndex:button];
5438 [self _clickButtonWithName:buttonName];
5439 }
5440
5441 [sheet dismissWithClickedButtonIndex:-1 animated:YES];
5442 }
5443 }
5444
5445 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
5446 [super webView:view didClearWindowObject:window forFrame:frame];
5447 [window setValue:package_ forKey:@"package"];
5448 }
5449
5450 - (bool) _allowJavaScriptPanel {
5451 return commercial_;
5452 }
5453
5454 #if !AlwaysReload
5455 - (void) _customButtonClicked {
5456 int count([buttons_ count]);
5457 if (count == 0)
5458 return;
5459
5460 if (count == 1)
5461 [self _clickButtonWithName:[buttons_ objectAtIndex:0]];
5462 else {
5463 NSMutableArray *buttons = [NSMutableArray arrayWithCapacity:count];
5464 [buttons addObjectsFromArray:buttons_];
5465
5466 UIActionSheet *sheet = [[[UIActionSheet alloc]
5467 initWithTitle:nil
5468 delegate:self
5469 cancelButtonTitle:nil
5470 destructiveButtonTitle:nil
5471 otherButtonTitles:nil
5472 ] autorelease];
5473
5474 for (NSString *button in buttons) [sheet addButtonWithTitle:button];
5475 if (!IsWildcat_) {
5476 [sheet addButtonWithTitle:UCLocalize("CANCEL")];
5477 [sheet setCancelButtonIndex:[sheet numberOfButtons] - 1];
5478 }
5479 [sheet setContext:@"modify"];
5480
5481 [delegate_ showActionSheet:sheet fromItem:[[self navigationItem] rightBarButtonItem]];
5482 }
5483 }
5484
5485 // We don't want to allow non-commercial packages to do custom things to the install button,
5486 // so it must call customButtonClicked with a custom commercial_ == 1 fallthrough.
5487 - (void) customButtonClicked {
5488 if (commercial_)
5489 [super customButtonClicked];
5490 else
5491 [self _customButtonClicked];
5492 }
5493
5494 - (void) reloadButtonClicked {
5495 // Don't reload a commerical package by tapping the loading button,
5496 // but if it's not an Install button, we should forward it on.
5497 if (![package_ uninstalled])
5498 [self _customButtonClicked];
5499 }
5500
5501 - (void) applyLoadingTitle {
5502 // Don't show "Loading" as the title. Ever.
5503 }
5504
5505 - (UIBarButtonItem *) rightButton {
5506 return button_;
5507 }
5508 #endif
5509
5510 - (id) initWithDatabase:(Database *)database {
5511 if ((self = [super init]) != nil) {
5512 database_ = database;
5513 buttons_ = [[NSMutableArray alloc] initWithCapacity:4];
5514 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"package" ofType:@"html"]]];
5515 } return self;
5516 }
5517
5518 - (void) setPackage:(Package *)package {
5519 if (package_ != nil) {
5520 [package_ autorelease];
5521 package_ = nil;
5522 }
5523
5524 if (name_ != nil) {
5525 [name_ release];
5526 name_ = nil;
5527 }
5528
5529 [buttons_ removeAllObjects];
5530
5531 if (package != nil) {
5532 [package parse];
5533
5534 package_ = [package retain];
5535 name_ = [[package id] retain];
5536 commercial_ = [package isCommercial];
5537
5538 if ([package_ mode] != nil)
5539 [buttons_ addObject:UCLocalize("CLEAR")];
5540 if ([package_ source] == nil);
5541 else if ([package_ upgradableAndEssential:NO])
5542 [buttons_ addObject:UCLocalize("UPGRADE")];
5543 else if ([package_ uninstalled])
5544 [buttons_ addObject:UCLocalize("INSTALL")];
5545 else
5546 [buttons_ addObject:UCLocalize("REINSTALL")];
5547 if (![package_ uninstalled])
5548 [buttons_ addObject:UCLocalize("REMOVE")];
5549 }
5550
5551 if (button_ != nil)
5552 [button_ release];
5553
5554 NSString *title;
5555 switch ([buttons_ count]) {
5556 case 0: title = nil; break;
5557 case 1: title = [buttons_ objectAtIndex:0]; break;
5558 default: title = UCLocalize("MODIFY"); break;
5559 }
5560
5561 button_ = [[UIBarButtonItem alloc]
5562 initWithTitle:title
5563 style:UIBarButtonItemStylePlain
5564 target:self
5565 action:@selector(customButtonClicked)
5566 ];
5567
5568 [self reloadURL];
5569 }
5570
5571 - (bool) isLoading {
5572 return commercial_ ? [super isLoading] : false;
5573 }
5574
5575 - (void) reloadData {
5576 [self setPackage:[database_ packageWithName:name_]];
5577 }
5578
5579 @end
5580 /* }}} */
5581
5582 /* Package Table {{{ */
5583 @interface PackageTable : UIView <
5584 UITableViewDataSource,
5585 UITableViewDelegate
5586 > {
5587 _transient Database *database_;
5588 unsigned era_;
5589 NSMutableArray *packages_;
5590 NSMutableArray *sections_;
5591 UITableView *list_;
5592 NSMutableArray *index_;
5593 NSMutableDictionary *indices_;
5594 // XXX: this target_ seems to be delegate_. :(
5595 _transient id target_;
5596 SEL action_;
5597 // XXX: why do we even have this delegate_?
5598 _transient id delegate_;
5599 }
5600
5601 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action;
5602
5603 - (void) setDelegate:(id)delegate;
5604
5605 - (void) reloadData;
5606 - (void) resetCursor;
5607
5608 - (UITableView *) list;
5609
5610 - (void) setShouldHideHeaderInShortLists:(BOOL)hide;
5611
5612 - (void) deselectWithAnimation:(BOOL)animated;
5613
5614 @end
5615
5616 @implementation PackageTable
5617
5618 - (void) dealloc {
5619 [packages_ release];
5620 [sections_ release];
5621 [list_ release];
5622 [index_ release];
5623 [indices_ release];
5624
5625 [super dealloc];
5626 }
5627
5628 + (BOOL) hasIndexedCollation {
5629 return NO; // XXX: objc_getClass("UILocalizedIndexedCollation") != nil;
5630 }
5631
5632 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
5633 NSInteger count([sections_ count]);
5634 return count == 0 ? 1 : count;
5635 }
5636
5637 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
5638 if ([sections_ count] == 0 || [[sections_ objectAtIndex:section] count] == 0)
5639 return nil;
5640 return [[sections_ objectAtIndex:section] name];
5641 }
5642
5643 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
5644 if ([sections_ count] == 0)
5645 return 0;
5646 return [[sections_ objectAtIndex:section] count];
5647 }
5648
5649 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
5650 @synchronized (database_) {
5651 if ([database_ era] != era_)
5652 return nil;
5653
5654 Section *section([sections_ objectAtIndex:[path section]]);
5655 NSInteger row([path row]);
5656 Package *package([packages_ objectAtIndex:([section row] + row)]);
5657 return [[package retain] autorelease];
5658 } }
5659
5660 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
5661 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
5662 if (cell == nil)
5663 cell = [[[PackageCell alloc] init] autorelease];
5664 [cell setPackage:[self packageAtIndexPath:path]];
5665 return cell;
5666 }
5667
5668 - (void) deselectWithAnimation:(BOOL)animated {
5669 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
5670 }
5671
5672 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
5673 Package *package([self packageAtIndexPath:path]);
5674 package = [database_ packageWithName:[package id]];
5675 [target_ performSelector:action_ withObject:package];
5676 return path;
5677 }
5678
5679 - (NSArray *) sectionIndexTitlesForTableView:(UITableView *)tableView {
5680 // XXX: is 20 the most optimal number here?
5681 return [packages_ count] > 20 ? index_ : nil;
5682 }
5683
5684 - (NSInteger) tableView:(UITableView *)tableView sectionForSectionIndexTitle:(NSString *)title atIndex:(NSInteger)index {
5685 if ([[self class] hasIndexedCollation]) {
5686 return [[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionForSectionIndexTitleAtIndex:index];
5687 }
5688
5689 return index;
5690 }
5691
5692 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action {
5693 if ((self = [super initWithFrame:frame]) != nil) {
5694 database_ = database;
5695
5696 target_ = target;
5697 action_ = action;
5698
5699 index_ = [[self class] hasIndexedCollation]
5700 ? [[[objc_getClass("UILocalizedIndexedCollation") currentCollation] sectionIndexTitles] retain]
5701 : [[NSMutableArray alloc] initWithCapacity:32];
5702 indices_ = [[NSMutableDictionary alloc] initWithCapacity:32];
5703
5704 packages_ = [[NSMutableArray arrayWithCapacity:16] retain];
5705 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
5706
5707 list_ = [[UITableView alloc] initWithFrame:[self bounds] style:UITableViewStylePlain];
5708 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5709 [list_ setRowHeight:73];
5710 [self addSubview:list_];
5711
5712 [list_ setDataSource:self];
5713 [list_ setDelegate:self];
5714 } return self;
5715 }
5716
5717 - (void) setDelegate:(id)delegate {
5718 delegate_ = delegate;
5719 }
5720
5721 - (bool) hasPackage:(Package *)package {
5722 return true;
5723 }
5724
5725 - (void) reloadData {
5726 era_ = [database_ era];
5727 NSArray *packages = [database_ packages];
5728
5729 [packages_ removeAllObjects];
5730 [sections_ removeAllObjects];
5731
5732 _profile(PackageTable$reloadData$Filter)
5733 for (Package *package in packages)
5734 if ([self hasPackage:package])
5735 [packages_ addObject:package];
5736 _end
5737
5738 [indices_ removeAllObjects];
5739
5740 Section *section = nil;
5741
5742 if ([[self class] hasIndexedCollation]) {
5743 id collation = [objc_getClass("UILocalizedIndexedCollation") currentCollation];
5744 NSArray *titles = [collation sectionIndexTitles];
5745 int secidx = -1;
5746
5747 _profile(PackageTable$reloadData$Section)
5748 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5749 Package *package;
5750 int index;
5751
5752 _profile(PackageTable$reloadData$Section$Package)
5753 package = [packages_ objectAtIndex:offset];
5754 index = [collation sectionForObject:package collationStringSelector:@selector(name)];
5755 _end
5756
5757 while (secidx < index) {
5758 secidx += 1;
5759
5760 _profile(PackageTable$reloadData$Section$Allocate)
5761 section = [[[Section alloc] initWithName:[titles objectAtIndex:secidx] row:offset localize:NO] autorelease];
5762 _end
5763
5764 _profile(PackageTable$reloadData$Section$Add)
5765 [sections_ addObject:section];
5766 _end
5767 }
5768
5769 [section addToCount];
5770 }
5771 _end
5772 } else {
5773 [index_ removeAllObjects];
5774
5775 _profile(PackageTable$reloadData$Section)
5776 for (size_t offset(0), end([packages_ count]); offset != end; ++offset) {
5777 Package *package;
5778 unichar index;
5779
5780 _profile(PackageTable$reloadData$Section$Package)
5781 package = [packages_ objectAtIndex:offset];
5782 index = [package index];
5783 _end
5784
5785 if (section == nil || [section index] != index) {
5786 _profile(PackageTable$reloadData$Section$Allocate)
5787 section = [[[Section alloc] initWithIndex:index row:offset] autorelease];
5788 _end
5789
5790 [index_ addObject:[section name]];
5791 //[indices_ setObject:[NSNumber numberForInt:[sections_ count]] forKey:index];
5792
5793 _profile(PackageTable$reloadData$Section$Add)
5794 [sections_ addObject:section];
5795 _end
5796 }
5797
5798 [section addToCount];
5799 }
5800 _end
5801 }
5802
5803 _profile(PackageTable$reloadData$List)
5804 [list_ reloadData];
5805 _end
5806 }
5807
5808 - (void) resetCursor {
5809 [list_ scrollRectToVisible:CGRectMake(0, 0, 0, 0) animated:NO];
5810 }
5811
5812 - (UITableView *) list {
5813 return list_;
5814 }
5815
5816 - (void) setShouldHideHeaderInShortLists:(BOOL)hide {
5817 //XXX:[list_ setShouldHideHeaderInShortLists:hide];
5818 }
5819
5820 @end
5821 /* }}} */
5822 /* Filtered Package Table {{{ */
5823 @interface FilteredPackageTable : PackageTable {
5824 SEL filter_;
5825 IMP imp_;
5826 id object_;
5827 }
5828
5829 - (void) setObject:(id)object;
5830 - (void) setObject:(id)object forFilter:(SEL)filter;
5831
5832 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object;
5833
5834 @end
5835
5836 @implementation FilteredPackageTable
5837
5838 - (void) dealloc {
5839 if (object_ != nil)
5840 [object_ release];
5841 [super dealloc];
5842 }
5843
5844 - (void) setFilter:(SEL)filter {
5845 filter_ = filter;
5846
5847 /* XXX: this is an unsafe optimization of doomy hell */
5848 Method method(class_getInstanceMethod([Package class], filter));
5849 _assert(method != NULL);
5850 imp_ = method_getImplementation(method);
5851 _assert(imp_ != NULL);
5852 }
5853
5854 - (void) setObject:(id)object {
5855 if (object_ != nil)
5856 [object_ release];
5857 if (object == nil)
5858 object_ = nil;
5859 else
5860 object_ = [object retain];
5861 }
5862
5863 - (void) setObject:(id)object forFilter:(SEL)filter {
5864 [self setFilter:filter];
5865 [self setObject:object];
5866 }
5867
5868 - (bool) hasPackage:(Package *)package {
5869 _profile(FilteredPackageTable$hasPackage)
5870 return [package valid] && (*reinterpret_cast<bool (*)(id, SEL, id)>(imp_))(package, filter_, object_);
5871 _end
5872 }
5873
5874 - (id) initWithFrame:(CGRect)frame database:(Database *)database target:(id)target action:(SEL)action filter:(SEL)filter with:(id)object {
5875 if ((self = [super initWithFrame:frame database:database target:target action:action]) != nil) {
5876 [self setFilter:filter];
5877 object_ = [object retain];
5878 [self reloadData];
5879 } return self;
5880 }
5881
5882 @end
5883 /* }}} */
5884 /* Filtered Package Controller {{{ */
5885 @interface FilteredPackageController : CYViewController {
5886 _transient Database *database_;
5887 FilteredPackageTable *packages_;
5888 NSString *title_;
5889 }
5890
5891 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object;
5892
5893 @end
5894
5895 @implementation FilteredPackageController
5896
5897 - (void) dealloc {
5898 [packages_ release];
5899 [title_ release];
5900
5901 [super dealloc];
5902 }
5903
5904 - (void) viewDidAppear:(BOOL)animated {
5905 [super viewDidAppear:animated];
5906 [packages_ deselectWithAnimation:animated];
5907 }
5908
5909 - (void) didSelectPackage:(Package *)package {
5910 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
5911 [view setPackage:package];
5912 [view setDelegate:delegate_];
5913 [[self navigationController] pushViewController:view animated:YES];
5914 }
5915
5916 - (NSString *) title { return title_; }
5917
5918 - (id) initWithDatabase:(Database *)database title:(NSString *)title filter:(SEL)filter with:(id)object {
5919 if ((self = [super init]) != nil) {
5920 database_ = database;
5921 title_ = [title copy];
5922 [[self navigationItem] setTitle:title_];
5923
5924 packages_ = [[FilteredPackageTable alloc]
5925 initWithFrame:[[self view] bounds]
5926 database:database
5927 target:self
5928 action:@selector(didSelectPackage:)
5929 filter:filter
5930 with:object
5931 ];
5932
5933 [packages_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
5934 [[self view] addSubview:packages_];
5935 } return self;
5936 }
5937
5938 - (void) reloadData {
5939 [packages_ reloadData];
5940 }
5941
5942 - (void) setDelegate:(id)delegate {
5943 [super setDelegate:delegate];
5944 [packages_ setDelegate:delegate];
5945 }
5946
5947 @end
5948
5949 /* }}} */
5950
5951 /* Home Controller {{{ */
5952 @interface HomeController : CYBrowserController {
5953 }
5954 @end
5955
5956 @implementation HomeController
5957
5958 + (BOOL)shouldHideNavigationBar {
5959 return NO;
5960 }
5961
5962 - (void) _setMoreHeaders:(NSMutableURLRequest *)request {
5963 [super _setMoreHeaders:request];
5964
5965 if (ChipID_ != nil)
5966 [request setValue:ChipID_ forHTTPHeaderField:@"X-Chip-ID"];
5967 if (UniqueID_ != nil)
5968 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
5969 if (PLMN_ != nil)
5970 [request setValue:PLMN_ forHTTPHeaderField:@"X-Carrier-ID"];
5971 }
5972
5973 - (void) aboutButtonClicked {
5974 UIAlertView *alert([[[UIAlertView alloc] init] autorelease]);
5975
5976 [alert setTitle:UCLocalize("ABOUT_CYDIA")];
5977 [alert addButtonWithTitle:UCLocalize("CLOSE")];
5978 [alert setCancelButtonIndex:0];
5979
5980 [alert setMessage:
5981 @"Copyright (C) 2008-2010\n"
5982 "Jay Freeman (saurik)\n"
5983 "saurik@saurik.com\n"
5984 "http://www.saurik.com/"
5985 ];
5986
5987 [alert show];
5988 }
5989
5990 - (void) viewWillAppear:(BOOL)animated {
5991 [super viewWillAppear:animated];
5992
5993 if ([[self class] shouldHideNavigationBar])
5994 [[self navigationController] setNavigationBarHidden:YES animated:animated];
5995 }
5996
5997 - (void) viewWillDisappear:(BOOL)animated {
5998 [super viewWillDisappear:animated];
5999
6000 if ([[self class] shouldHideNavigationBar])
6001 [[self navigationController] setNavigationBarHidden:NO animated:animated];
6002 }
6003
6004 - (id) init {
6005 if ((self = [super init]) != nil) {
6006 [self loadURL:[NSURL URLWithString:CydiaURL(@"")]];
6007
6008 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6009 initWithTitle:UCLocalize("ABOUT")
6010 style:UIBarButtonItemStylePlain
6011 target:self
6012 action:@selector(aboutButtonClicked)
6013 ] autorelease]];
6014 } return self;
6015 }
6016
6017 @end
6018 /* }}} */
6019 /* Manage Controller {{{ */
6020 @interface ManageController : CYBrowserController {
6021 }
6022
6023 - (void) queueStatusDidChange;
6024 @end
6025
6026 @implementation ManageController
6027
6028 - (id) init {
6029 if ((self = [super init]) != nil) {
6030 [[self navigationItem] setTitle:UCLocalize("MANAGE")];
6031
6032 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"manage" ofType:@"html"]]];
6033
6034 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
6035 initWithTitle:UCLocalize("SETTINGS")
6036 style:UIBarButtonItemStylePlain
6037 target:self
6038 action:@selector(settingsButtonClicked)
6039 ] autorelease]];
6040
6041 [self queueStatusDidChange];
6042 } return self;
6043 }
6044
6045 - (void) settingsButtonClicked {
6046 [delegate_ showSettings];
6047 }
6048
6049 #if !AlwaysReload
6050 - (void) queueButtonClicked {
6051 [delegate_ queue];
6052 }
6053
6054 - (void) applyLoadingTitle {
6055 // No "Loading" title.
6056 }
6057
6058 - (void) applyRightButton {
6059 // No right button.
6060 }
6061 #endif
6062
6063 - (void) queueStatusDidChange {
6064 #if !AlwaysReload
6065 if (!IsWildcat_ && Queuing_) {
6066 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
6067 initWithTitle:UCLocalize("QUEUE")
6068 style:UIBarButtonItemStyleDone
6069 target:self
6070 action:@selector(queueButtonClicked)
6071 ] autorelease]];
6072 } else {
6073 [[self navigationItem] setRightBarButtonItem:nil];
6074 }
6075 #endif
6076 }
6077
6078 - (bool) isLoading {
6079 return false;
6080 }
6081
6082 @end
6083 /* }}} */
6084
6085 /* Refresh Bar {{{ */
6086 @interface RefreshBar : UINavigationBar {
6087 UIProgressIndicator *indicator_;
6088 UITextLabel *prompt_;
6089 UIProgressBar *progress_;
6090 UINavigationButton *cancel_;
6091 }
6092
6093 @end
6094
6095 @implementation RefreshBar
6096
6097 - (void) dealloc {
6098 [indicator_ release];
6099 [prompt_ release];
6100 [progress_ release];
6101 [cancel_ release];
6102 [super dealloc];
6103 }
6104
6105 - (void) positionViews {
6106 CGRect frame = [cancel_ frame];
6107 frame.size = [cancel_ sizeThatFits:frame.size];
6108 frame.origin.x = [self frame].size.width - frame.size.width - 5;
6109 frame.origin.y = ([self frame].size.height - frame.size.height) / 2;
6110 [cancel_ setFrame:frame];
6111
6112 CGSize prgsize = {75, 100};
6113 CGRect prgrect = {{
6114 [self frame].size.width - prgsize.width - 10,
6115 ([self frame].size.height - prgsize.height) / 2
6116 } , prgsize};
6117 [progress_ setFrame:prgrect];
6118
6119 CGSize indsize([UIProgressIndicator defaultSizeForStyle:[indicator_ activityIndicatorViewStyle]]);
6120 unsigned indoffset = ([self frame].size.height - indsize.height) / 2;
6121 CGRect indrect = {{indoffset, indoffset}, indsize};
6122 [indicator_ setFrame:indrect];
6123
6124 CGSize prmsize = {215, indsize.height + 4};
6125 CGRect prmrect = {{
6126 indoffset * 2 + indsize.width,
6127 unsigned([self frame].size.height - prmsize.height) / 2 - 1
6128 }, prmsize};
6129 [prompt_ setFrame:prmrect];
6130 }
6131
6132 - (void)setFrame:(CGRect)frame {
6133 [super setFrame:frame];
6134
6135 [self positionViews];
6136 }
6137
6138 - (id) initWithFrame:(CGRect)frame delegate:(id)delegate {
6139 if ((self = [super initWithFrame:frame])) {
6140 [self setAutoresizingMask:UIViewAutoresizingFlexibleWidth];
6141
6142 [self setBarStyle:UIBarStyleBlack];
6143
6144 UIBarStyle barstyle([self _barStyle:NO]);
6145 bool ugly(barstyle == UIBarStyleDefault);
6146
6147 UIProgressIndicatorStyle style = ugly ?
6148 UIProgressIndicatorStyleMediumBrown :
6149 UIProgressIndicatorStyleMediumWhite;
6150
6151 indicator_ = [[UIProgressIndicator alloc] initWithFrame:CGRectZero];
6152 [indicator_ setStyle:style];
6153 [indicator_ startAnimation];
6154 [self addSubview:indicator_];
6155
6156 prompt_ = [[UITextLabel alloc] initWithFrame:CGRectZero];
6157 [prompt_ setColor:[UIColor colorWithCGColor:(ugly ? Blueish_ : Off_)]];
6158 [prompt_ setBackgroundColor:[UIColor clearColor]];
6159 [prompt_ setFont:[UIFont systemFontOfSize:15]];
6160 [self addSubview:prompt_];
6161
6162 progress_ = [[UIProgressBar alloc] initWithFrame:CGRectZero];
6163 [progress_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleLeftMargin];
6164 [progress_ setStyle:0];
6165 [self addSubview:progress_];
6166
6167 cancel_ = [[UINavigationButton alloc] initWithTitle:UCLocalize("CANCEL") style:UINavigationButtonStyleHighlighted];
6168 [cancel_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
6169 [cancel_ addTarget:delegate action:@selector(cancelPressed) forControlEvents:UIControlEventTouchUpInside];
6170 [cancel_ setBarStyle:barstyle];
6171
6172 [self positionViews];
6173 } return self;
6174 }
6175
6176 - (void) cancel {
6177 [cancel_ removeFromSuperview];
6178 }
6179
6180 - (void) start {
6181 [prompt_ setText:UCLocalize("UPDATING_DATABASE")];
6182 [progress_ setProgress:0];
6183 [self addSubview:cancel_];
6184 }
6185
6186 - (void) stop {
6187 [cancel_ removeFromSuperview];
6188 }
6189
6190 - (void) setPrompt:(NSString *)prompt {
6191 [prompt_ setText:prompt];
6192 }
6193
6194 - (void) setProgress:(float)progress {
6195 [progress_ setProgress:progress];
6196 }
6197
6198 @end
6199 /* }}} */
6200
6201 @class CYNavigationController;
6202
6203 /* Cydia Tab Bar Controller {{{ */
6204 @interface CYTabBarController : UITabBarController <
6205 ProgressDelegate
6206 > {
6207 _transient Database *database_;
6208 RefreshBar *refreshbar_;
6209
6210 bool dropped_;
6211 bool updating_;
6212 // XXX: ok, "updatedelegate_"?...
6213 _transient NSObject<CydiaDelegate> *updatedelegate_;
6214
6215 id root_;
6216 }
6217
6218 - (void) dropBar:(BOOL)animated;
6219 - (void) beginUpdate;
6220 - (void) raiseBar:(BOOL)animated;
6221 - (BOOL) updating;
6222
6223 @end
6224
6225 @implementation CYTabBarController
6226
6227 - (void) reloadData {
6228 size_t count([[self viewControllers] count]);
6229 for (size_t i(0); i != count; ++i) {
6230 CYNavigationController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6231 [page reloadData];
6232 }
6233
6234 [(CYNavigationController *)[self transientViewController] reloadData];
6235 }
6236
6237 - (id) initWithDatabase:(Database *)database {
6238 if ((self = [super init]) != nil) {
6239 database_ = database;
6240
6241 [[self view] setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6242 [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(statusBarFrameChanged:) name:UIApplicationDidChangeStatusBarFrameNotification object:nil];
6243
6244 refreshbar_ = [[RefreshBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, [UINavigationBar defaultSize].height) delegate:self];
6245 } return self;
6246 }
6247
6248 - (void) setUpdate:(NSDate *)date {
6249 [self beginUpdate];
6250 }
6251
6252 - (void) beginUpdate {
6253 [refreshbar_ start];
6254 [self dropBar:YES];
6255
6256 [updatedelegate_ retainNetworkActivityIndicator];
6257 updating_ = true;
6258
6259 [NSThread
6260 detachNewThreadSelector:@selector(performUpdate)
6261 toTarget:self
6262 withObject:nil
6263 ];
6264 }
6265
6266 - (void) performUpdate { _pooled
6267 Status status;
6268 status.setDelegate(self);
6269 [database_ updateWithStatus:status];
6270
6271 [self
6272 performSelectorOnMainThread:@selector(completeUpdate)
6273 withObject:nil
6274 waitUntilDone:NO
6275 ];
6276 }
6277
6278 - (void) stopUpdateWithSelector:(SEL)selector {
6279 updating_ = false;
6280 [updatedelegate_ releaseNetworkActivityIndicator];
6281
6282 [self raiseBar:YES];
6283 [refreshbar_ stop];
6284
6285 [updatedelegate_ performSelector:selector withObject:nil afterDelay:0];
6286 }
6287
6288 - (void) completeUpdate {
6289 if (!updating_)
6290 return;
6291 [self stopUpdateWithSelector:@selector(reloadData)];
6292 }
6293
6294 - (void) cancelUpdate {
6295 [self stopUpdateWithSelector:@selector(updateData)];
6296 }
6297
6298 - (void) cancelPressed {
6299 [self cancelUpdate];
6300 }
6301
6302 - (BOOL) updating {
6303 return updating_;
6304 }
6305
6306 - (void) setProgressError:(NSString *)error withTitle:(NSString *)title {
6307 [refreshbar_ setPrompt:[NSString stringWithFormat:UCLocalize("COLON_DELIMITED"), UCLocalize("ERROR"), error]];
6308 }
6309
6310 - (void) startProgress {
6311 }
6312
6313 - (void) setProgressTitle:(NSString *)title {
6314 [self
6315 performSelectorOnMainThread:@selector(_setProgressTitle:)
6316 withObject:title
6317 waitUntilDone:YES
6318 ];
6319 }
6320
6321 - (bool) isCancelling:(size_t)received {
6322 return !updating_;
6323 }
6324
6325 - (void) setProgressPercent:(float)percent {
6326 [self
6327 performSelectorOnMainThread:@selector(_setProgressPercent:)
6328 withObject:[NSNumber numberWithFloat:percent]
6329 waitUntilDone:YES
6330 ];
6331 }
6332
6333 - (void) addProgressOutput:(NSString *)output {
6334 [self
6335 performSelectorOnMainThread:@selector(_addProgressOutput:)
6336 withObject:output
6337 waitUntilDone:YES
6338 ];
6339 }
6340
6341 - (void) _setProgressTitle:(NSString *)title {
6342 [refreshbar_ setPrompt:title];
6343 }
6344
6345 - (void) _setProgressPercent:(NSNumber *)percent {
6346 [refreshbar_ setProgress:[percent floatValue]];
6347 }
6348
6349 - (void) _addProgressOutput:(NSString *)output {
6350 }
6351
6352 - (void) setUpdateDelegate:(id)delegate {
6353 updatedelegate_ = delegate;
6354 }
6355
6356 - (CGFloat) statusBarHeight {
6357 if (UIInterfaceOrientationIsPortrait([self interfaceOrientation])) {
6358 return [[UIApplication sharedApplication] statusBarFrame].size.height;
6359 } else {
6360 return [[UIApplication sharedApplication] statusBarFrame].size.width;
6361 }
6362 }
6363
6364 - (UIView *) transitionView {
6365 if ([self respondsToSelector:@selector(_transitionView)])
6366 return [self _transitionView];
6367 else
6368 return MSHookIvar<id>(self, "_viewControllerTransitionView");
6369 }
6370
6371 - (void) dropBar:(BOOL)animated {
6372 if (dropped_)
6373 return;
6374 dropped_ = true;
6375
6376 UIView *transition([self transitionView]);
6377 [[self view] addSubview:refreshbar_];
6378
6379 CGRect barframe([refreshbar_ frame]);
6380
6381 if (kCFCoreFoundationVersionNumber >= kCFCoreFoundationVersionNumber_iPhoneOS_3_0) // XXX: _UIApplicationLinkedOnOrAfter(4)
6382 barframe.origin.y = [self statusBarHeight];
6383 else
6384 barframe.origin.y = 0;
6385
6386 [refreshbar_ setFrame:barframe];
6387
6388 if (animated)
6389 [UIView beginAnimations:nil context:NULL];
6390
6391 CGRect viewframe = [transition frame];
6392 viewframe.origin.y += barframe.size.height;
6393 viewframe.size.height -= barframe.size.height;
6394 [transition setFrame:viewframe];
6395
6396 if (animated)
6397 [UIView commitAnimations];
6398
6399 // Ensure bar has the proper width for our view, it might have changed
6400 barframe.size.width = viewframe.size.width;
6401 [refreshbar_ setFrame:barframe];
6402
6403 // XXX: fix Apple's layout bug
6404 [[root_ selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6405 }
6406
6407 - (void) raiseBar:(BOOL)animated {
6408 if (!dropped_)
6409 return;
6410 dropped_ = false;
6411
6412 UIView *transition([self transitionView]);
6413 [refreshbar_ removeFromSuperview];
6414
6415 CGRect barframe([refreshbar_ frame]);
6416
6417 if (animated)
6418 [UIView beginAnimations:nil context:NULL];
6419
6420 CGRect viewframe = [transition frame];
6421 viewframe.origin.y -= barframe.size.height;
6422 viewframe.size.height += barframe.size.height;
6423 [transition setFrame:viewframe];
6424
6425 if (animated)
6426 [UIView commitAnimations];
6427
6428 // XXX: fix Apple's layout bug
6429 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6430 }
6431
6432 #if 0
6433 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
6434 // XXX: fix Apple's layout bug
6435 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6436 }
6437 #endif
6438
6439 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
6440 bool dropped(dropped_);
6441
6442 if (dropped)
6443 [self raiseBar:NO];
6444
6445 [super didRotateFromInterfaceOrientation:fromInterfaceOrientation];
6446
6447 if (dropped)
6448 [self dropBar:NO];
6449
6450 // XXX: fix Apple's layout bug
6451 // SRK [[self selectedViewController] _updateLayoutForStatusBarAndInterfaceOrientation];
6452 }
6453
6454 - (void) statusBarFrameChanged:(NSNotification *)notification {
6455 if (dropped_) {
6456 [self raiseBar:NO];
6457 [self dropBar:NO];
6458 }
6459 }
6460
6461 - (void) dealloc {
6462 [refreshbar_ release];
6463 [[NSNotificationCenter defaultCenter] removeObserver:self];
6464 [super dealloc];
6465 }
6466
6467 @end
6468 /* }}} */
6469 /* Cydia Navigation Controller {{{ */
6470 @interface CYNavigationController : UINavigationController {
6471 _transient Database *database_;
6472 _transient id<UINavigationControllerDelegate> delegate_;
6473 }
6474
6475 - (id) initWithDatabase:(Database *)database;
6476 - (void) reloadData;
6477
6478 @end
6479
6480
6481 @implementation CYNavigationController
6482
6483 - (void) dealloc {
6484 [super dealloc];
6485 }
6486
6487 - (void) reloadData {
6488 size_t count([[self viewControllers] count]);
6489 for (size_t i(0); i != count; ++i) {
6490 CYViewController *page([[self viewControllers] objectAtIndex:(count - i - 1)]);
6491 [page reloadData];
6492 }
6493 }
6494
6495 - (void) setDelegate:(id<UINavigationControllerDelegate>)delegate {
6496 delegate_ = delegate;
6497 }
6498
6499 - (id) initWithDatabase:(Database *)database {
6500 if ((self = [super init]) != nil) {
6501 database_ = database;
6502 } return self;
6503 }
6504
6505 @end
6506 /* }}} */
6507
6508 /* Cydia:// Protocol {{{ */
6509 @interface CydiaURLProtocol : NSURLProtocol {
6510 }
6511
6512 @end
6513
6514 @implementation CydiaURLProtocol
6515
6516 + (BOOL) canInitWithRequest:(NSURLRequest *)request {
6517 NSURL *url([request URL]);
6518 if (url == nil)
6519 return NO;
6520 NSString *scheme([[url scheme] lowercaseString]);
6521 if (scheme == nil || ![scheme isEqualToString:@"cydia"])
6522 return NO;
6523 return YES;
6524 }
6525
6526 + (NSURLRequest *) canonicalRequestForRequest:(NSURLRequest *)request {
6527 return request;
6528 }
6529
6530 - (void) _returnPNGWithImage:(UIImage *)icon forRequest:(NSURLRequest *)request {
6531 id<NSURLProtocolClient> client([self client]);
6532 if (icon == nil)
6533 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorFileDoesNotExist userInfo:nil]];
6534 else {
6535 NSData *data(UIImagePNGRepresentation(icon));
6536
6537 NSURLResponse *response([[[NSURLResponse alloc] initWithURL:[request URL] MIMEType:@"image/png" expectedContentLength:-1 textEncodingName:nil] autorelease]);
6538 [client URLProtocol:self didReceiveResponse:response cacheStoragePolicy:NSURLCacheStorageNotAllowed];
6539 [client URLProtocol:self didLoadData:data];
6540 [client URLProtocolDidFinishLoading:self];
6541 }
6542 }
6543
6544 - (void) startLoading {
6545 id<NSURLProtocolClient> client([self client]);
6546 NSURLRequest *request([self request]);
6547
6548 NSURL *url([request URL]);
6549 NSString *href([url absoluteString]);
6550
6551 NSString *path([href substringFromIndex:8]);
6552 NSRange slash([path rangeOfString:@"/"]);
6553
6554 NSString *command;
6555 if (slash.location == NSNotFound) {
6556 command = path;
6557 path = nil;
6558 } else {
6559 command = [path substringToIndex:slash.location];
6560 path = [path substringFromIndex:(slash.location + 1)];
6561 }
6562
6563 Database *database([Database sharedInstance]);
6564
6565 if ([command isEqualToString:@"package-icon"]) {
6566 if (path == nil)
6567 goto fail;
6568 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6569 Package *package([database packageWithName:path]);
6570 if (package == nil)
6571 goto fail;
6572 UIImage *icon([package icon]);
6573 [self _returnPNGWithImage:icon forRequest:request];
6574 } else if ([command isEqualToString:@"source-icon"]) {
6575 if (path == nil)
6576 goto fail;
6577 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6578 NSString *source(Simplify(path));
6579 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sources/%@.png", App_, source]]);
6580 if (icon == nil)
6581 icon = [UIImage applicationImageNamed:@"unknown.png"];
6582 [self _returnPNGWithImage:icon forRequest:request];
6583 } else if ([command isEqualToString:@"uikit-image"]) {
6584 if (path == nil)
6585 goto fail;
6586 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6587 UIImage *icon(_UIImageWithName(path));
6588 [self _returnPNGWithImage:icon forRequest:request];
6589 } else if ([command isEqualToString:@"section-icon"]) {
6590 if (path == nil)
6591 goto fail;
6592 path = [path stringByReplacingPercentEscapesUsingEncoding:NSUTF8StringEncoding];
6593 NSString *section(Simplify(path));
6594 UIImage *icon([UIImage imageAtPath:[NSString stringWithFormat:@"%@/Sections/%@.png", App_, section]]);
6595 if (icon == nil)
6596 icon = [UIImage applicationImageNamed:@"unknown.png"];
6597 [self _returnPNGWithImage:icon forRequest:request];
6598 } else fail: {
6599 [client URLProtocol:self didFailWithError:[NSError errorWithDomain:NSURLErrorDomain code:NSURLErrorResourceUnavailable userInfo:nil]];
6600 }
6601 }
6602
6603 - (void) stopLoading {
6604 }
6605
6606 @end
6607 /* }}} */
6608
6609 /* Section Controller {{{ */
6610 @interface SectionController : FilteredPackageController {
6611 }
6612
6613 - (id) initWithDatabase:(Database *)database section:(NSString *)section;
6614
6615 @end
6616
6617 @implementation SectionController
6618
6619 - (id) initWithDatabase:(Database *)database section:(NSString *)name {
6620 NSString *title;
6621
6622 if (name == nil) {
6623 title = UCLocalize("ALL_PACKAGES");
6624 } else if (![name isEqual:@""]) {
6625 title = [[NSBundle mainBundle] localizedStringForKey:Simplify(name) value:nil table:@"Sections"];
6626 } else {
6627 title = UCLocalize("NO_SECTION");
6628 }
6629
6630 if ((self = [super initWithDatabase:database title:title filter:@selector(isVisibleInSection:) with:name]) != nil) {
6631 } return self;
6632 }
6633
6634 @end
6635 /* }}} */
6636 /* Sections Controller {{{ */
6637 @interface SectionsController : CYViewController <
6638 UITableViewDataSource,
6639 UITableViewDelegate
6640 > {
6641 _transient Database *database_;
6642 NSMutableArray *sections_;
6643 NSMutableArray *filtered_;
6644 UITableView *list_;
6645 BOOL editing_;
6646 }
6647
6648 - (id) initWithDatabase:(Database *)database;
6649 - (void) reloadData;
6650 - (void) resetView;
6651
6652 - (void) editButtonClicked;
6653
6654 @end
6655
6656 @implementation SectionsController
6657
6658 - (void) dealloc {
6659 [list_ setDataSource:nil];
6660 [list_ setDelegate:nil];
6661
6662 [sections_ release];
6663 [filtered_ release];
6664 [list_ release];
6665 [super dealloc];
6666 }
6667
6668 - (void) updateNavigationItem {
6669 [[self navigationItem] setTitle:editing_ ? UCLocalize("SECTION_VISIBILITY") : UCLocalize("SECTIONS")];
6670 if ([sections_ count] == 0) {
6671 [[self navigationItem] setRightBarButtonItem:nil];
6672 } else {
6673 [[self navigationItem] setRightBarButtonItem:[[UIBarButtonItem alloc]
6674 initWithBarButtonSystemItem:(editing_ ? UIBarButtonSystemItemDone : UIBarButtonSystemItemEdit)
6675 target:self
6676 action:@selector(editButtonClicked)
6677 ] animated:([[self navigationItem] rightBarButtonItem] != nil)];
6678 }
6679 }
6680
6681 - (void) setEditing:(BOOL)editing {
6682 if ((editing_ = editing))
6683 [list_ reloadData];
6684 else
6685 [delegate_ updateData];
6686
6687 [self updateNavigationItem];
6688 }
6689
6690 - (void) viewDidAppear:(BOOL)animated {
6691 [super viewDidAppear:animated];
6692 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6693 }
6694
6695 - (void) viewWillDisappear:(BOOL)animated {
6696 [super viewWillDisappear:animated];
6697 if (editing_) [self setEditing:NO];
6698 }
6699
6700 - (Section *) sectionAtIndexPath:(NSIndexPath *)indexPath {
6701 Section *section = (editing_ ? [sections_ objectAtIndex:[indexPath row]] : ([indexPath row] == 0 ? nil : [filtered_ objectAtIndex:([indexPath row] - 1)]));
6702 return section;
6703 }
6704
6705 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
6706 return editing_ ? [sections_ count] : [filtered_ count] + 1;
6707 }
6708
6709 /*- (CGFloat) tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
6710 return 45.0f;
6711 }*/
6712
6713 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
6714 static NSString *reuseIdentifier = @"SectionCell";
6715
6716 SectionCell *cell = (SectionCell *) [tableView dequeueReusableCellWithIdentifier:reuseIdentifier];
6717 if (cell == nil)
6718 cell = [[[SectionCell alloc] initWithFrame:CGRectZero reuseIdentifier:reuseIdentifier] autorelease];
6719
6720 [cell setSection:[self sectionAtIndexPath:indexPath] editing:editing_];
6721
6722 return cell;
6723 }
6724
6725 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
6726 if (editing_)
6727 return;
6728
6729 Section *section = [self sectionAtIndexPath:indexPath];
6730
6731 SectionController *controller = [[[SectionController alloc]
6732 initWithDatabase:database_
6733 section:[section name]
6734 ] autorelease];
6735 [controller setDelegate:delegate_];
6736
6737 [[self navigationController] pushViewController:controller animated:YES];
6738 }
6739
6740 - (id) initWithDatabase:(Database *)database {
6741 if ((self = [super init]) != nil) {
6742 database_ = database;
6743
6744 [[self navigationItem] setTitle:UCLocalize("SECTIONS")];
6745
6746 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6747 filtered_ = [[NSMutableArray arrayWithCapacity:16] retain];
6748
6749 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds]];
6750 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6751 [list_ setRowHeight:45.0f];
6752 [[self view] addSubview:list_];
6753
6754 [list_ setDataSource:self];
6755 [list_ setDelegate:self];
6756
6757 [self reloadData];
6758 } return self;
6759 }
6760
6761 - (void) reloadData {
6762 NSArray *packages = [database_ packages];
6763
6764 [sections_ removeAllObjects];
6765 [filtered_ removeAllObjects];
6766
6767 NSMutableDictionary *sections([NSMutableDictionary dictionaryWithCapacity:32]);
6768
6769 _trace();
6770 for (Package *package in packages) {
6771 NSString *name([package section]);
6772 NSString *key(name == nil ? @"" : name);
6773
6774 Section *section;
6775
6776 _profile(SectionsView$reloadData$Section)
6777 section = [sections objectForKey:key];
6778 if (section == nil) {
6779 _profile(SectionsView$reloadData$Section$Allocate)
6780 section = [[[Section alloc] initWithName:name localize:YES] autorelease];
6781 [sections setObject:section forKey:key];
6782 _end
6783 }
6784 _end
6785
6786 [section addToCount];
6787
6788 _profile(SectionsView$reloadData$Filter)
6789 if (![package valid] || ![package visible])
6790 continue;
6791 _end
6792
6793 [section addToRow];
6794 }
6795 _trace();
6796
6797 [sections_ addObjectsFromArray:[sections allValues]];
6798
6799 [sections_ sortUsingSelector:@selector(compareByLocalized:)];
6800
6801 for (Section *section in sections_) {
6802 size_t count([section row]);
6803 if (count == 0)
6804 continue;
6805
6806 section = [[[Section alloc] initWithName:[section name] localized:[section localized]] autorelease];
6807 [section setCount:count];
6808 [filtered_ addObject:section];
6809 }
6810
6811 [self updateNavigationItem];
6812 [list_ reloadData];
6813 _trace();
6814 }
6815
6816 - (void) resetView {
6817 if (editing_)
6818 [self editButtonClicked];
6819 }
6820
6821 - (void)editButtonClicked {
6822 [self setEditing:!editing_];
6823 }
6824
6825 @end
6826 /* }}} */
6827
6828 /* Changes Controller {{{ */
6829 @interface ChangesController : CYViewController <
6830 UITableViewDataSource,
6831 UITableViewDelegate
6832 > {
6833 _transient Database *database_;
6834 unsigned era_;
6835 CFMutableArrayRef packages_;
6836 NSMutableArray *sections_;
6837 UITableView *list_;
6838 unsigned upgrades_;
6839 BOOL hasSentFirstLoad_;
6840 }
6841
6842 - (id) initWithDatabase:(Database *)database;
6843
6844 @end
6845
6846 @implementation ChangesController
6847
6848 - (void) dealloc {
6849 [list_ setDelegate:nil];
6850 [list_ setDataSource:nil];
6851
6852 CFRelease(packages_);
6853
6854 [sections_ release];
6855 [list_ release];
6856 [super dealloc];
6857 }
6858
6859 - (void) viewDidAppear:(BOOL)animated {
6860 [super viewDidAppear:animated];
6861 if (!hasSentFirstLoad_) {
6862 hasSentFirstLoad_ = YES;
6863 [self performSelector:@selector(reloadData) withObject:nil afterDelay:0.0];
6864 } else {
6865 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
6866 }
6867 }
6868
6869 - (NSInteger) numberOfSectionsInTableView:(UITableView *)list {
6870 NSInteger count([sections_ count]);
6871 return count == 0 ? 1 : count;
6872 }
6873
6874 - (NSString *) tableView:(UITableView *)list titleForHeaderInSection:(NSInteger)section {
6875 if ([sections_ count] == 0)
6876 return nil;
6877 return [[sections_ objectAtIndex:section] name];
6878 }
6879
6880 - (NSInteger) tableView:(UITableView *)list numberOfRowsInSection:(NSInteger)section {
6881 if ([sections_ count] == 0)
6882 return 0;
6883 return [[sections_ objectAtIndex:section] count];
6884 }
6885
6886 - (Package *) packageAtIndex:(NSUInteger)index {
6887 return (Package *) CFArrayGetValueAtIndex(packages_, index);
6888 }
6889
6890 - (Package *) packageAtIndexPath:(NSIndexPath *)path {
6891 @synchronized (database_) {
6892 if ([database_ era] != era_)
6893 return nil;
6894
6895 NSUInteger sectionIndex([path section]);
6896 if (sectionIndex >= [sections_ count])
6897 return nil;
6898 Section *section([sections_ objectAtIndex:sectionIndex]);
6899 NSInteger row([path row]);
6900 return [[[self packageAtIndex:([section row] + row)] retain] autorelease];
6901 } }
6902
6903 - (UITableViewCell *) tableView:(UITableView *)table cellForRowAtIndexPath:(NSIndexPath *)path {
6904 PackageCell *cell((PackageCell *) [table dequeueReusableCellWithIdentifier:@"Package"]);
6905 if (cell == nil)
6906 cell = [[[PackageCell alloc] init] autorelease];
6907 [cell setPackage:[self packageAtIndexPath:path]];
6908 return cell;
6909 }
6910
6911 - (NSIndexPath *) tableView:(UITableView *)table willSelectRowAtIndexPath:(NSIndexPath *)path {
6912 Package *package([self packageAtIndexPath:path]);
6913 CYPackageController *view([[[CYPackageController alloc] initWithDatabase:database_] autorelease]);
6914 [view setDelegate:delegate_];
6915 [view setPackage:package];
6916 [[self navigationController] pushViewController:view animated:YES];
6917 return path;
6918 }
6919
6920 - (void) refreshButtonClicked {
6921 [delegate_ beginUpdate];
6922 [[self navigationItem] setLeftBarButtonItem:nil animated:YES];
6923 }
6924
6925 - (void) upgradeButtonClicked {
6926 [delegate_ distUpgrade];
6927 }
6928
6929 - (NSString *) title { return UCLocalize("CHANGES"); }
6930
6931 - (id) initWithDatabase:(Database *)database {
6932 if ((self = [super init]) != nil) {
6933 database_ = database;
6934 [[self navigationItem] setTitle:UCLocalize("CHANGES")];
6935
6936 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, 0, NULL);
6937 sections_ = [[NSMutableArray arrayWithCapacity:16] retain];
6938
6939 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
6940 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
6941 [list_ setRowHeight:73];
6942 [[self view] addSubview:list_];
6943
6944 [list_ setDataSource:self];
6945 [list_ setDelegate:self];
6946 } return self;
6947 }
6948
6949 - (void) _reloadPackages:(NSArray *)packages {
6950 CFRelease(packages_);
6951 packages_ = CFArrayCreateMutable(kCFAllocatorDefault, [packages count], NULL);
6952
6953 _trace();
6954 _profile(ChangesController$_reloadPackages$Filter)
6955 for (Package *package in packages)
6956 if ([package upgradableAndEssential:YES] || [package visible])
6957 CFArrayAppendValue(packages_, package);
6958 _end
6959 _trace();
6960 _profile(ChangesController$_reloadPackages$radixSort)
6961 [(NSMutableArray *) packages_ radixSortUsingFunction:reinterpret_cast<SKRadixFunction>(&PackageChangesRadix) withContext:NULL];
6962 _end
6963 _trace();
6964 }
6965
6966 - (void) reloadData {
6967 @synchronized (database_) {
6968 era_ = [database_ era];
6969 NSArray *packages = [database_ packages];
6970
6971 [sections_ removeAllObjects];
6972
6973 #if 1
6974 UIProgressHUD *hud([delegate_ addProgressHUD]);
6975 [hud setText:UCLocalize("LOADING")];
6976 //NSLog(@"HUD:%@::%@", delegate_, hud);
6977 [self yieldToSelector:@selector(_reloadPackages:) withObject:packages];
6978 [delegate_ removeProgressHUD:hud];
6979 #else
6980 [self _reloadPackages:packages];
6981 #endif
6982
6983 Section *upgradable = [[[Section alloc] initWithName:UCLocalize("AVAILABLE_UPGRADES") localize:NO] autorelease];
6984 Section *ignored = nil;
6985 Section *section = nil;
6986 time_t last = 0;
6987
6988 upgrades_ = 0;
6989 bool unseens = false;
6990
6991 CFDateFormatterRef formatter(CFDateFormatterCreate(NULL, Locale_, kCFDateFormatterMediumStyle, kCFDateFormatterMediumStyle));
6992
6993 for (size_t offset = 0, count = CFArrayGetCount(packages_); offset != count; ++offset) {
6994 Package *package = [self packageAtIndex:offset];
6995
6996 BOOL uae = [package upgradableAndEssential:YES];
6997
6998 if (!uae) {
6999 unseens = true;
7000 time_t seen([package seen]);
7001
7002 if (section == nil || last != seen) {
7003 last = seen;
7004
7005 NSString *name;
7006 name = (NSString *) CFDateFormatterCreateStringWithDate(NULL, formatter, (CFDateRef) [NSDate dateWithTimeIntervalSince1970:seen]);
7007 [name autorelease];
7008
7009 _profile(ChangesController$reloadData$Allocate)
7010 name = [NSString stringWithFormat:UCLocalize("NEW_AT"), name];
7011 section = [[[Section alloc] initWithName:name row:offset localize:NO] autorelease];
7012 [sections_ addObject:section];
7013 _end
7014 }
7015
7016 [section addToCount];
7017 } else if ([package ignored]) {
7018 if (ignored == nil) {
7019 ignored = [[[Section alloc] initWithName:UCLocalize("IGNORED_UPGRADES") row:offset localize:NO] autorelease];
7020 }
7021 [ignored addToCount];
7022 } else {
7023 ++upgrades_;
7024 [upgradable addToCount];
7025 }
7026 }
7027 _trace();
7028
7029 CFRelease(formatter);
7030
7031 if (unseens) {
7032 Section *last = [sections_ lastObject];
7033 size_t count = [last count];
7034 CFArrayReplaceValues(packages_, CFRangeMake(CFArrayGetCount(packages_) - count, count), NULL, 0);
7035 [sections_ removeLastObject];
7036 }
7037
7038 if ([ignored count] != 0)
7039 [sections_ insertObject:ignored atIndex:0];
7040 if (upgrades_ != 0)
7041 [sections_ insertObject:upgradable atIndex:0];
7042
7043 [list_ reloadData];
7044
7045 if (upgrades_ > 0)
7046 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7047 initWithTitle:[NSString stringWithFormat:UCLocalize("PARENTHETICAL"), UCLocalize("UPGRADE"), [NSString stringWithFormat:@"%u", upgrades_]]
7048 style:UIBarButtonItemStylePlain
7049 target:self
7050 action:@selector(upgradeButtonClicked)
7051 ] autorelease]];
7052
7053 if (![delegate_ updating])
7054 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7055 initWithTitle:UCLocalize("REFRESH")
7056 style:UIBarButtonItemStylePlain
7057 target:self
7058 action:@selector(refreshButtonClicked)
7059 ] autorelease]];
7060
7061 PrintTimes();
7062 } }
7063
7064 @end
7065 /* }}} */
7066 /* Search Controller {{{ */
7067 @interface SearchController : FilteredPackageController <
7068 UISearchBarDelegate
7069 > {
7070 UISearchBar *search_;
7071 }
7072
7073 - (id) initWithDatabase:(Database *)database;
7074 - (void) setSearchTerm:(NSString *)term;
7075 - (void) reloadData;
7076
7077 @end
7078
7079 @implementation SearchController
7080
7081 - (void) dealloc {
7082 [search_ release];
7083 [super dealloc];
7084 }
7085
7086 - (void) setSearchTerm:(NSString *)searchTerm {
7087 [search_ setText:searchTerm];
7088 }
7089
7090 - (void) searchBarSearchButtonClicked:(UISearchBar *)searchBar {
7091 [packages_ setObject:[search_ text] forFilter:@selector(isUnfilteredAndSearchedForBy:)];
7092 [search_ resignFirstResponder];
7093 [self reloadData];
7094 }
7095
7096 - (void) searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)text {
7097 [packages_ setObject:text forFilter:@selector(isUnfilteredAndSelectedForBy:)];
7098 [self reloadData];
7099 }
7100
7101 - (id) initWithDatabase:(Database *)database {
7102 return [super initWithDatabase:database title:UCLocalize("SEARCH") filter:@selector(isUnfilteredAndSearchedForBy:) with:nil];
7103 }
7104
7105 - (void)viewDidAppear:(BOOL)animated {
7106 [super viewDidAppear:animated];
7107 if (!search_) {
7108 search_ = [[UISearchBar alloc] initWithFrame:CGRectMake(0, 0, [[self view] bounds].size.width, 44.0f)];
7109 [search_ layoutSubviews];
7110 [search_ setPlaceholder:UCLocalize("SEARCH_EX")];
7111
7112 UITextField *textField;
7113 if ([search_ respondsToSelector:@selector(searchField)])
7114 textField = [search_ searchField];
7115 else
7116 textField = MSHookIvar<UITextField *>(search_, "_searchField");
7117
7118 [textField setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
7119 [search_ setDelegate:self];
7120 [textField setEnablesReturnKeyAutomatically:NO];
7121 [[self navigationItem] setTitleView:textField];
7122 }
7123 }
7124
7125 - (void) _reloadData {
7126 }
7127
7128 - (void) reloadData {
7129 _profile(SearchController$reloadData)
7130 [packages_ reloadData];
7131 _end
7132 PrintTimes();
7133 [packages_ resetCursor];
7134 }
7135
7136 - (void) didSelectPackage:(Package *)package {
7137 [search_ resignFirstResponder];
7138 [super didSelectPackage:package];
7139 }
7140
7141 @end
7142 /* }}} */
7143 /* Package Settings Controller {{{ */
7144 @interface PackageSettingsController : CYViewController <
7145 UITableViewDataSource,
7146 UITableViewDelegate
7147 > {
7148 _transient Database *database_;
7149 NSString *name_;
7150 Package *package_;
7151 UITableView *table_;
7152 UISwitch *subscribedSwitch_;
7153 UISwitch *ignoredSwitch_;
7154 UITableViewCell *subscribedCell_;
7155 UITableViewCell *ignoredCell_;
7156 }
7157
7158 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7159
7160 @end
7161
7162 @implementation PackageSettingsController
7163
7164 - (void) dealloc {
7165 [name_ release];
7166 if (package_ != nil)
7167 [package_ release];
7168 [table_ release];
7169 [subscribedSwitch_ release];
7170 [ignoredSwitch_ release];
7171 [subscribedCell_ release];
7172 [ignoredCell_ release];
7173
7174 [super dealloc];
7175 }
7176
7177 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7178 if (package_ == nil)
7179 return 0;
7180
7181 return 1;
7182 }
7183
7184 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7185 if (package_ == nil)
7186 return 0;
7187
7188 return 2;
7189 }
7190
7191 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7192 return UCLocalize("CHANGE_PACKAGE_SETTINGS");
7193 }
7194
7195 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
7196 return UCLocalize("SHOW_ALL_CHANGES_EX");
7197 }
7198
7199 - (void) onSubscribed:(id)control {
7200 bool value([control isOn]);
7201 if (package_ == nil)
7202 return;
7203 if ([package_ setSubscribed:value])
7204 [delegate_ updateData];
7205 }
7206
7207 - (void) onIgnored:(id)control {
7208 // TODO: set Held state - possibly call out to dpkg, etc.
7209 }
7210
7211 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7212 if (package_ == nil)
7213 return nil;
7214
7215 switch ([indexPath row]) {
7216 case 0: return subscribedCell_;
7217 case 1: return ignoredCell_;
7218
7219 _nodefault
7220 }
7221
7222 return nil;
7223 }
7224
7225 - (NSString *) title { return UCLocalize("SETTINGS"); }
7226
7227 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7228 if ((self = [super init])) {
7229 database_ = database;
7230 name_ = [package retain];
7231
7232 [[self navigationItem] setTitle:UCLocalize("SETTINGS")];
7233
7234 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
7235 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7236 [[self view] addSubview:table_];
7237
7238 subscribedSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7239 [subscribedSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7240 [subscribedSwitch_ addTarget:self action:@selector(onSubscribed:) forEvents:UIControlEventValueChanged];
7241
7242 ignoredSwitch_ = [[UISwitch alloc] initWithFrame:CGRectMake(0, 0, 50, 20)];
7243 [ignoredSwitch_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin];
7244 [ignoredSwitch_ addTarget:self action:@selector(onIgnored:) forEvents:UIControlEventValueChanged];
7245 // Disable this switch, since it only reflects (not modifies) the ignored state.
7246 [ignoredSwitch_ setUserInteractionEnabled:NO];
7247
7248 subscribedCell_ = [[UITableViewCell alloc] init];
7249 [subscribedCell_ setText:UCLocalize("SHOW_ALL_CHANGES")];
7250 [subscribedCell_ setAccessoryView:subscribedSwitch_];
7251 [subscribedCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7252
7253 ignoredCell_ = [[UITableViewCell alloc] init];
7254 [ignoredCell_ setText:UCLocalize("IGNORE_UPGRADES")];
7255 [ignoredCell_ setAccessoryView:ignoredSwitch_];
7256 [ignoredCell_ setSelectionStyle:UITableViewCellSelectionStyleNone];
7257 // FIXME: Ignored state is not saved.
7258 [ignoredCell_ setUserInteractionEnabled:NO];
7259
7260 [table_ setDataSource:self];
7261 [table_ setDelegate:self];
7262 [self reloadData];
7263 } return self;
7264 }
7265
7266 - (void) reloadData {
7267 if (package_ != nil)
7268 [package_ autorelease];
7269 package_ = [database_ packageWithName:name_];
7270 if (package_ != nil) {
7271 [package_ retain];
7272 [subscribedSwitch_ setOn:([package_ subscribed] ? 1 : 0) animated:NO];
7273 [ignoredSwitch_ setOn:([package_ ignored] ? 1 : 0) animated:NO];
7274 }
7275
7276 [table_ reloadData];
7277 }
7278
7279 @end
7280 /* }}} */
7281 /* Signature Controller {{{ */
7282 @interface SignatureController : CYBrowserController {
7283 _transient Database *database_;
7284 NSString *package_;
7285 }
7286
7287 - (id) initWithDatabase:(Database *)database package:(NSString *)package;
7288
7289 @end
7290
7291 @implementation SignatureController
7292
7293 - (void) dealloc {
7294 [package_ release];
7295 [super dealloc];
7296 }
7297
7298 - (void) webView:(WebView *)view didClearWindowObject:(WebScriptObject *)window forFrame:(WebFrame *)frame {
7299 // XXX: dude!
7300 [super webView:view didClearWindowObject:window forFrame:frame];
7301 }
7302
7303 - (id) initWithDatabase:(Database *)database package:(NSString *)package {
7304 if ((self = [super init]) != nil) {
7305 database_ = database;
7306 package_ = [package retain];
7307 [self reloadData];
7308 } return self;
7309 }
7310
7311 - (void) reloadData {
7312 [self loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"signature" ofType:@"html"]]];
7313 }
7314
7315 @end
7316 /* }}} */
7317
7318 /* Installed Controller {{{ */
7319 @interface InstalledController : FilteredPackageController {
7320 BOOL expert_;
7321 }
7322
7323 - (id) initWithDatabase:(Database *)database;
7324
7325 - (void) updateRoleButton;
7326 - (void) queueStatusDidChange;
7327
7328 @end
7329
7330 @implementation InstalledController
7331
7332 - (void) dealloc {
7333 [super dealloc];
7334 }
7335
7336 - (NSString *) title { return UCLocalize("INSTALLED"); }
7337
7338 - (id) initWithDatabase:(Database *)database {
7339 if ((self = [super initWithDatabase:database title:UCLocalize("INSTALLED") filter:@selector(isInstalledAndUnfiltered:) with:[NSNumber numberWithBool:YES]]) != nil) {
7340 [self updateRoleButton];
7341 [self queueStatusDidChange];
7342 } return self;
7343 }
7344
7345 #if !AlwaysReload
7346 - (void) queueButtonClicked {
7347 [delegate_ queue];
7348 }
7349 #endif
7350
7351 - (void) queueStatusDidChange {
7352 #if !AlwaysReload
7353 if (IsWildcat_) {
7354 if (Queuing_) {
7355 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7356 initWithTitle:UCLocalize("QUEUE")
7357 style:UIBarButtonItemStyleDone
7358 target:self
7359 action:@selector(queueButtonClicked)
7360 ] autorelease]];
7361 } else {
7362 [[self navigationItem] setLeftBarButtonItem:nil];
7363 }
7364 }
7365 #endif
7366 }
7367
7368 - (void) reloadData {
7369 [packages_ reloadData];
7370 }
7371
7372 - (void) updateRoleButton {
7373 if (Role_ != nil && ![Role_ isEqualToString:@"Developer"])
7374 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7375 initWithTitle:(expert_ ? UCLocalize("EXPERT") : UCLocalize("SIMPLE"))
7376 style:(expert_ ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7377 target:self
7378 action:@selector(roleButtonClicked)
7379 ] autorelease]];
7380 }
7381
7382 - (void) roleButtonClicked {
7383 [packages_ setObject:[NSNumber numberWithBool:expert_]];
7384 [packages_ reloadData];
7385 expert_ = !expert_;
7386
7387 [self updateRoleButton];
7388 }
7389
7390 - (void) setDelegate:(id)delegate {
7391 [super setDelegate:delegate];
7392 [packages_ setDelegate:delegate];
7393 }
7394
7395 @end
7396 /* }}} */
7397
7398 /* Source Cell {{{ */
7399 @interface SourceCell : CYTableViewCell <
7400 ContentDelegate
7401 > {
7402 UIImage *icon_;
7403 NSString *origin_;
7404 NSString *label_;
7405 }
7406
7407 - (void) setSource:(Source *)source;
7408
7409 @end
7410
7411 @implementation SourceCell
7412
7413 - (void) clearSource {
7414 [icon_ release];
7415 [origin_ release];
7416 [label_ release];
7417
7418 icon_ = nil;
7419 origin_ = nil;
7420 label_ = nil;
7421 }
7422
7423 - (void) setSource:(Source *)source {
7424 [self clearSource];
7425
7426 if (icon_ == nil)
7427 icon_ = [UIImage applicationImageNamed:[NSString stringWithFormat:@"Sources/%@.png", [source host]]];
7428 if (icon_ == nil)
7429 icon_ = [UIImage applicationImageNamed:@"unknown.png"];
7430 icon_ = [icon_ retain];
7431
7432 origin_ = [[source name] retain];
7433 label_ = [[source uri] retain];
7434
7435 [content_ setNeedsDisplay];
7436 }
7437
7438 - (void) dealloc {
7439 [self clearSource];
7440 [super dealloc];
7441 }
7442
7443 - (SourceCell *) initWithFrame:(CGRect)frame reuseIdentifier:(NSString *)reuseIdentifier {
7444 if ((self = [super initWithFrame:frame reuseIdentifier:reuseIdentifier]) != nil) {
7445 UIView *content([self contentView]);
7446 CGRect bounds([content bounds]);
7447
7448 content_ = [[ContentView alloc] initWithFrame:bounds];
7449 [content_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7450 [content_ setBackgroundColor:[UIColor whiteColor]];
7451 [content addSubview:content_];
7452
7453 [content_ setDelegate:self];
7454 [content_ setOpaque:YES];
7455 } return self;
7456 }
7457
7458 - (NSString *) accessibilityLabel {
7459 return label_;
7460 }
7461
7462 - (void) drawContentRect:(CGRect)rect {
7463 bool highlighted(highlighted_);
7464 float width(rect.size.width);
7465
7466 if (icon_ != nil)
7467 [icon_ drawInRect:CGRectMake(10, 10, 30, 30)];
7468
7469 if (highlighted)
7470 UISetColor(White_);
7471
7472 if (!highlighted)
7473 UISetColor(Black_);
7474 [origin_ drawAtPoint:CGPointMake(48, 8) forWidth:(width - 80) withFont:Font18Bold_ lineBreakMode:UILineBreakModeTailTruncation];
7475
7476 if (!highlighted)
7477 UISetColor(Blue_);
7478 [label_ drawAtPoint:CGPointMake(58, 29) forWidth:(width - 95) withFont:Font12_ lineBreakMode:UILineBreakModeTailTruncation];
7479 }
7480
7481 @end
7482 /* }}} */
7483 /* Source Controller {{{ */
7484 @interface SourceController : FilteredPackageController {
7485 }
7486
7487 - (id) initWithDatabase:(Database *)database source:(Source *)source;
7488
7489 @end
7490
7491 @implementation SourceController
7492
7493 - (id) initWithDatabase:(Database *)database source:(Source *)source {
7494 if ((self = [super initWithDatabase:database title:[source label] filter:@selector(isVisibleInSource:) with:source]) != nil) {
7495 } return self;
7496 }
7497
7498 @end
7499 /* }}} */
7500 /* Sources Controller {{{ */
7501 @interface SourcesController : CYViewController <
7502 UITableViewDataSource,
7503 UITableViewDelegate
7504 > {
7505 _transient Database *database_;
7506 UITableView *list_;
7507 NSMutableArray *sources_;
7508 int offset_;
7509
7510 NSString *href_;
7511 UIProgressHUD *hud_;
7512 NSError *error_;
7513
7514 //NSURLConnection *installer_;
7515 NSURLConnection *trivial_;
7516 NSURLConnection *trivial_bz2_;
7517 NSURLConnection *trivial_gz_;
7518 //NSURLConnection *automatic_;
7519
7520 BOOL cydia_;
7521 }
7522
7523 - (id) initWithDatabase:(Database *)database;
7524
7525 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated;
7526
7527 @end
7528
7529 @implementation SourcesController
7530
7531 - (void) _releaseConnection:(NSURLConnection *)connection {
7532 if (connection != nil) {
7533 [connection cancel];
7534 //[connection setDelegate:nil];
7535 [connection release];
7536 }
7537 }
7538
7539 - (void) dealloc {
7540 if (href_ != nil)
7541 [href_ release];
7542 if (hud_ != nil)
7543 [hud_ release];
7544 if (error_ != nil)
7545 [error_ release];
7546
7547 //[self _releaseConnection:installer_];
7548 [self _releaseConnection:trivial_];
7549 [self _releaseConnection:trivial_gz_];
7550 [self _releaseConnection:trivial_bz2_];
7551 //[self _releaseConnection:automatic_];
7552
7553 [sources_ release];
7554 [list_ release];
7555 [super dealloc];
7556 }
7557
7558 - (void) viewDidAppear:(BOOL)animated {
7559 [super viewDidAppear:animated];
7560 [list_ deselectRowAtIndexPath:[list_ indexPathForSelectedRow] animated:animated];
7561 }
7562
7563 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
7564 return offset_ == 0 ? 1 : 2;
7565 }
7566
7567 - (NSString *) tableView:(UITableView *)tableView titleForHeaderInSection:(NSInteger)section {
7568 switch (section + (offset_ == 0 ? 1 : 0)) {
7569 case 0: return UCLocalize("ENTERED_BY_USER");
7570 case 1: return UCLocalize("INSTALLED_BY_PACKAGE");
7571
7572 _nodefault
7573 }
7574 }
7575
7576 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
7577 int count = [sources_ count];
7578 switch (section) {
7579 case 0: return (offset_ == 0 ? count : offset_);
7580 case 1: return count - offset_;
7581
7582 _nodefault
7583 }
7584 }
7585
7586 - (Source *) sourceAtIndexPath:(NSIndexPath *)indexPath {
7587 unsigned idx = 0;
7588 switch (indexPath.section) {
7589 case 0: idx = indexPath.row; break;
7590 case 1: idx = indexPath.row + offset_; break;
7591
7592 _nodefault
7593 }
7594 return [sources_ objectAtIndex:idx];
7595 }
7596
7597 - (UITableViewCell *) tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
7598 static NSString *cellIdentifier = @"SourceCell";
7599
7600 SourceCell *cell = (SourceCell *) [tableView dequeueReusableCellWithIdentifier:cellIdentifier];
7601 if(cell == nil) cell = [[[SourceCell alloc] initWithFrame:CGRectZero reuseIdentifier:cellIdentifier] autorelease];
7602 [cell setSource:[self sourceAtIndexPath:indexPath]];
7603 [cell setAccessoryType:UITableViewCellAccessoryDisclosureIndicator];
7604
7605 return cell;
7606 }
7607
7608 - (void) tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
7609 Source *source = [self sourceAtIndexPath:indexPath];
7610
7611 SourceController *controller = [[[SourceController alloc]
7612 initWithDatabase:database_
7613 source:source
7614 ] autorelease];
7615
7616 [controller setDelegate:delegate_];
7617
7618 [[self navigationController] pushViewController:controller animated:YES];
7619 }
7620
7621 - (BOOL)tableView:(UITableView *)tableView canEditRowAtIndexPath:(NSIndexPath *)indexPath {
7622 Source *source = [self sourceAtIndexPath:indexPath];
7623 return [source record] != nil;
7624 }
7625
7626 - (void)tableView:(UITableView *)tableView commitEditingStyle:(UITableViewCellEditingStyle)editingStyle forRowAtIndexPath:(NSIndexPath *)indexPath {
7627 Source *source = [self sourceAtIndexPath:indexPath];
7628 [Sources_ removeObjectForKey:[source key]];
7629 [delegate_ syncData];
7630 }
7631
7632 - (void) complete {
7633 [Sources_ setObject:[NSDictionary dictionaryWithObjectsAndKeys:
7634 @"deb", @"Type",
7635 href_, @"URI",
7636 @"./", @"Distribution",
7637 nil] forKey:[NSString stringWithFormat:@"deb:%@:./", href_]];
7638
7639 [delegate_ syncData];
7640 }
7641
7642 - (NSString *) getWarning {
7643 NSString *href(href_);
7644 NSRange colon([href rangeOfString:@"://"]);
7645 if (colon.location != NSNotFound)
7646 href = [href substringFromIndex:(colon.location + 3)];
7647 href = [href stringByAddingPercentEscapes];
7648 href = [CydiaURL(@"api/repotag/") stringByAppendingString:href];
7649 href = [href stringByCachingURLWithCurrentCDN];
7650
7651 NSURL *url([NSURL URLWithString:href]);
7652
7653 NSStringEncoding encoding;
7654 NSError *error(nil);
7655
7656 if (NSString *warning = [NSString stringWithContentsOfURL:url usedEncoding:&encoding error:&error])
7657 return [warning length] == 0 ? nil : warning;
7658 return nil;
7659 }
7660
7661 - (void) _endConnection:(NSURLConnection *)connection {
7662 // XXX: the memory management in this method is horribly awkward
7663
7664 NSURLConnection **field = NULL;
7665 if (connection == trivial_)
7666 field = &trivial_;
7667 else if (connection == trivial_bz2_)
7668 field = &trivial_bz2_;
7669 else if (connection == trivial_gz_)
7670 field = &trivial_gz_;
7671 _assert(field != NULL);
7672 [connection release];
7673 *field = nil;
7674
7675 if (
7676 trivial_ == nil &&
7677 trivial_bz2_ == nil &&
7678 trivial_gz_ == nil
7679 ) {
7680 bool defer(false);
7681
7682 if (cydia_) {
7683 if (NSString *warning = [self yieldToSelector:@selector(getWarning)]) {
7684 defer = true;
7685
7686 UIAlertView *alert = [[[UIAlertView alloc]
7687 initWithTitle:UCLocalize("SOURCE_WARNING")
7688 message:warning
7689 delegate:self
7690 cancelButtonTitle:UCLocalize("CANCEL")
7691 otherButtonTitles:UCLocalize("ADD_ANYWAY"), nil
7692 ] autorelease];
7693
7694 [alert setContext:@"warning"];
7695 [alert setNumberOfRows:1];
7696 [alert show];
7697 } else
7698 [self complete];
7699 } else if (error_ != nil) {
7700 UIAlertView *alert = [[[UIAlertView alloc]
7701 initWithTitle:UCLocalize("VERIFICATION_ERROR")
7702 message:[error_ localizedDescription]
7703 delegate:self
7704 cancelButtonTitle:UCLocalize("OK")
7705 otherButtonTitles:nil
7706 ] autorelease];
7707
7708 [alert setContext:@"urlerror"];
7709 [alert show];
7710 } else {
7711 UIAlertView *alert = [[[UIAlertView alloc]
7712 initWithTitle:UCLocalize("NOT_REPOSITORY")
7713 message:UCLocalize("NOT_REPOSITORY_EX")
7714 delegate:self
7715 cancelButtonTitle:UCLocalize("OK")
7716 otherButtonTitles:nil
7717 ] autorelease];
7718
7719 [alert setContext:@"trivial"];
7720 [alert show];
7721 }
7722
7723 [delegate_ setStatusBarShowsProgress:NO];
7724 [delegate_ removeProgressHUD:hud_];
7725
7726 [hud_ autorelease];
7727 hud_ = nil;
7728
7729 if (!defer) {
7730 [href_ release];
7731 href_ = nil;
7732 }
7733
7734 if (error_ != nil) {
7735 [error_ release];
7736 error_ = nil;
7737 }
7738 }
7739 }
7740
7741 - (void) connection:(NSURLConnection *)connection didReceiveResponse:(NSHTTPURLResponse *)response {
7742 switch ([response statusCode]) {
7743 case 200:
7744 cydia_ = YES;
7745 }
7746 }
7747
7748 - (void) connection:(NSURLConnection *)connection didFailWithError:(NSError *)error {
7749 lprintf("connection:\"%s\" didFailWithError:\"%s\"", [href_ UTF8String], [[error localizedDescription] UTF8String]);
7750 if (error_ != nil)
7751 error_ = [error retain];
7752 [self _endConnection:connection];
7753 }
7754
7755 - (void) connectionDidFinishLoading:(NSURLConnection *)connection {
7756 [self _endConnection:connection];
7757 }
7758
7759 - (NSString *) title { return UCLocalize("SOURCES"); }
7760
7761 - (NSURLConnection *) _requestHRef:(NSString *)href method:(NSString *)method {
7762 NSMutableURLRequest *request = [NSMutableURLRequest
7763 requestWithURL:[NSURL URLWithString:href]
7764 cachePolicy:NSURLRequestUseProtocolCachePolicy
7765 timeoutInterval:120.0
7766 ];
7767
7768 [request setHTTPMethod:method];
7769
7770 if (Machine_ != NULL)
7771 [request setValue:[NSString stringWithUTF8String:Machine_] forHTTPHeaderField:@"X-Machine"];
7772 if (UniqueID_ != nil)
7773 [request setValue:UniqueID_ forHTTPHeaderField:@"X-Unique-ID"];
7774 if (Role_ != nil)
7775 [request setValue:Role_ forHTTPHeaderField:@"X-Role"];
7776
7777 return [[[NSURLConnection alloc] initWithRequest:request delegate:self] autorelease];
7778 }
7779
7780 - (void)alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
7781 NSString *context([alert context]);
7782
7783 if ([context isEqualToString:@"source"]) {
7784 switch (button) {
7785 case 1: {
7786 NSString *href = [[alert textField] text];
7787
7788 //installer_ = [[self _requestHRef:href method:@"GET"] retain];
7789
7790 if (![href hasSuffix:@"/"])
7791 href_ = [href stringByAppendingString:@"/"];
7792 else
7793 href_ = href;
7794 href_ = [href_ retain];
7795
7796 trivial_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages"] method:@"HEAD"] retain];
7797 trivial_bz2_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.bz2"] method:@"HEAD"] retain];
7798 trivial_gz_ = [[self _requestHRef:[href_ stringByAppendingString:@"Packages.gz"] method:@"HEAD"] retain];
7799 //trivial_bz2_ = [[self _requestHRef:[href stringByAppendingString:@"dists/Release"] method:@"HEAD"] retain];
7800
7801 cydia_ = false;
7802
7803 // XXX: this is stupid
7804 hud_ = [[delegate_ addProgressHUD] retain];
7805 [hud_ setText:UCLocalize("VERIFYING_URL")];
7806 } break;
7807
7808 case 0:
7809 break;
7810
7811 _nodefault
7812 }
7813
7814 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7815 } else if ([context isEqualToString:@"trivial"])
7816 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7817 else if ([context isEqualToString:@"urlerror"])
7818 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7819 else if ([context isEqualToString:@"warning"]) {
7820 switch (button) {
7821 case 1:
7822 [self complete];
7823 break;
7824
7825 case 0:
7826 break;
7827
7828 _nodefault
7829 }
7830
7831 [href_ release];
7832 href_ = nil;
7833
7834 [alert dismissWithClickedButtonIndex:-1 animated:YES];
7835 }
7836 }
7837
7838 - (id) initWithDatabase:(Database *)database {
7839 if ((self = [super init]) != nil) {
7840 [[self navigationItem] setTitle:UCLocalize("SOURCES")];
7841 [self updateButtonsForEditingStatus:NO animated:NO];
7842
7843 database_ = database;
7844 sources_ = [[NSMutableArray arrayWithCapacity:16] retain];
7845
7846 list_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStylePlain];
7847 [list_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
7848 [list_ setRowHeight:56];
7849 [[self view] addSubview:list_];
7850
7851 [list_ setDataSource:self];
7852 [list_ setDelegate:self];
7853
7854 [self reloadData];
7855 } return self;
7856 }
7857
7858 - (void) reloadData {
7859 pkgSourceList list;
7860 if (!list.ReadMainList())
7861 return;
7862
7863 [sources_ removeAllObjects];
7864 [sources_ addObjectsFromArray:[database_ sources]];
7865 _trace();
7866 [sources_ sortUsingSelector:@selector(compareByNameAndType:)];
7867 _trace();
7868
7869 int count([sources_ count]);
7870 offset_ = 0;
7871 for (int i = 0; i != count; i++) {
7872 if ([[sources_ objectAtIndex:i] record] == nil)
7873 break;
7874 offset_++;
7875 }
7876
7877 [list_ setEditing:NO];
7878 [self updateButtonsForEditingStatus:NO animated:NO];
7879 [list_ reloadData];
7880 }
7881
7882 - (void) showAddSourcePrompt {
7883 UIAlertView *alert = [[[UIAlertView alloc]
7884 initWithTitle:UCLocalize("ENTER_APT_URL")
7885 message:nil
7886 delegate:self
7887 cancelButtonTitle:UCLocalize("CANCEL")
7888 otherButtonTitles:UCLocalize("ADD_SOURCE"), nil
7889 ] autorelease];
7890
7891 [alert setContext:@"source"];
7892 [alert setTransform:CGAffineTransformTranslate([alert transform], 0.0, 100.0)];
7893
7894 [alert setNumberOfRows:1];
7895 [alert addTextFieldWithValue:@"http://" label:@""];
7896
7897 UITextInputTraits *traits = [[alert textField] textInputTraits];
7898 [traits setAutocapitalizationType:UITextAutocapitalizationTypeNone];
7899 [traits setAutocorrectionType:UITextAutocorrectionTypeNo];
7900 [traits setKeyboardType:UIKeyboardTypeURL];
7901 // XXX: UIReturnKeyDone
7902 [traits setReturnKeyType:UIReturnKeyNext];
7903
7904 [alert show];
7905 }
7906
7907 - (void) addButtonClicked {
7908 [self showAddSourcePrompt];
7909 }
7910
7911 - (void) updateButtonsForEditingStatus:(BOOL)editing animated:(BOOL)animated {
7912 [[self navigationItem] setLeftBarButtonItem:(editing ? [[[UIBarButtonItem alloc]
7913 initWithTitle:UCLocalize("ADD")
7914 style:UIBarButtonItemStylePlain
7915 target:self
7916 action:@selector(addButtonClicked)
7917 ] autorelease] : [[self navigationItem] backBarButtonItem]) animated:animated];
7918
7919 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
7920 initWithTitle:(editing ? UCLocalize("DONE") : UCLocalize("EDIT"))
7921 style:(editing ? UIBarButtonItemStyleDone : UIBarButtonItemStylePlain)
7922 target:self
7923 action:@selector(editButtonClicked)
7924 ] autorelease] animated:animated];
7925
7926 if (IsWildcat_ && !editing)
7927 [[self navigationItem] setLeftBarButtonItem:[[[UIBarButtonItem alloc]
7928 initWithTitle:UCLocalize("SETTINGS")
7929 style:UIBarButtonItemStylePlain
7930 target:self
7931 action:@selector(settingsButtonClicked)
7932 ] autorelease]];
7933 }
7934
7935 - (void) settingsButtonClicked {
7936 [delegate_ showSettings];
7937 }
7938
7939 - (void) editButtonClicked {
7940 [list_ setEditing:![list_ isEditing] animated:YES];
7941
7942 [self updateButtonsForEditingStatus:[list_ isEditing] animated:YES];
7943 }
7944
7945 @end
7946 /* }}} */
7947
7948 /* Settings Controller {{{ */
7949 @interface SettingsController : CYViewController <
7950 UITableViewDataSource,
7951 UITableViewDelegate
7952 > {
7953 _transient Database *database_;
7954 // XXX: ok, "roledelegate_"?...
7955 _transient id roledelegate_;
7956 UITableView *table_;
7957 UISegmentedControl *segment_;
7958 UIView *container_;
7959 }
7960
7961 - (void) showDoneButton;
7962 - (void) resizeSegmentedControl;
7963
7964 @end
7965
7966 @implementation SettingsController
7967 - (void) dealloc {
7968 [table_ release];
7969 [segment_ release];
7970 [container_ release];
7971
7972 [super dealloc];
7973 }
7974
7975 - (id) initWithDatabase:(Database *)database delegate:(id)delegate {
7976 if ((self = [super init])) {
7977 database_ = database;
7978 roledelegate_ = delegate;
7979
7980 [[self navigationItem] setTitle:UCLocalize("WHO_ARE_YOU")];
7981
7982 NSArray *items = [NSArray arrayWithObjects:
7983 UCLocalize("USER"),
7984 UCLocalize("HACKER"),
7985 UCLocalize("DEVELOPER"),
7986 nil];
7987 segment_ = [[UISegmentedControl alloc] initWithItems:items];
7988 container_ = [[UIView alloc] initWithFrame:CGRectMake(0, 0, [[self view] frame].size.width, 44.0f)];
7989 [container_ addSubview:segment_];
7990
7991 int index = -1;
7992 if ([Role_ isEqualToString:@"User"]) index = 0;
7993 if ([Role_ isEqualToString:@"Hacker"]) index = 1;
7994 if ([Role_ isEqualToString:@"Developer"]) index = 2;
7995 if (index != -1) {
7996 [segment_ setSelectedSegmentIndex:index];
7997 [self showDoneButton];
7998 }
7999
8000 [segment_ addTarget:self action:@selector(segmentChanged:) forControlEvents:UIControlEventValueChanged];
8001 [self resizeSegmentedControl];
8002
8003 table_ = [[UITableView alloc] initWithFrame:[[self view] bounds] style:UITableViewStyleGrouped];
8004 [table_ setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8005 [table_ setDelegate:self];
8006 [table_ setDataSource:self];
8007 [[self view] addSubview:table_];
8008 [table_ reloadData];
8009 } return self;
8010 }
8011
8012 - (void) resizeSegmentedControl {
8013 CGFloat width = [[self view] frame].size.width;
8014 [segment_ setFrame:CGRectMake(width / 32.0f, 0, width - (width / 32.0f * 2.0f), 44.0f)];
8015 }
8016
8017 - (void) viewWillAppear:(BOOL)animated {
8018 [super viewWillAppear:animated];
8019
8020 [self resizeSegmentedControl];
8021 }
8022
8023 - (void) willAnimateRotationToInterfaceOrientation:(UIInterfaceOrientation)interfaceOrientation duration:(NSTimeInterval)duration {
8024 [self resizeSegmentedControl];
8025 }
8026
8027 - (void) didRotateFromInterfaceOrientation:(UIInterfaceOrientation)fromInterfaceOrientation {
8028 [self resizeSegmentedControl];
8029 }
8030
8031 - (void) save {
8032 NSString *role(nil);
8033
8034 switch ([segment_ selectedSegmentIndex]) {
8035 case 0: role = @"User"; break;
8036 case 1: role = @"Hacker"; break;
8037 case 2: role = @"Developer"; break;
8038
8039 _nodefault
8040 }
8041
8042 if (![role isEqualToString:Role_]) {
8043 bool rolling(Role_ == nil);
8044 Role_ = role;
8045
8046 Settings_ = [NSMutableDictionary dictionaryWithObjectsAndKeys:
8047 Role_, @"Role",
8048 nil];
8049
8050 [Metadata_ setObject:Settings_ forKey:@"Settings"];
8051 Changed_ = true;
8052
8053 if (rolling)
8054 [roledelegate_ loadData];
8055 else
8056 [roledelegate_ updateData];
8057 }
8058 }
8059
8060 - (void) segmentChanged:(UISegmentedControl *)control {
8061 [self showDoneButton];
8062 }
8063
8064 - (void) saveAndClose {
8065 [self save];
8066
8067 [[self navigationItem] setRightBarButtonItem:nil];
8068 [[self navigationController] dismissModalViewControllerAnimated:YES];
8069 }
8070
8071 - (void) doneButtonClicked {
8072 UIActivityIndicatorView *spinner = [[[UIActivityIndicatorView alloc] initWithFrame:CGRectMake(0, 0, 20.0f, 20.0f)] autorelease];
8073 [spinner startAnimating];
8074 UIBarButtonItem *spinItem = [[[UIBarButtonItem alloc] initWithCustomView:spinner] autorelease];
8075 [[self navigationItem] setRightBarButtonItem:spinItem];
8076
8077 [self performSelector:@selector(saveAndClose) withObject:nil afterDelay:0];
8078 }
8079
8080 - (void) showDoneButton {
8081 [[self navigationItem] setRightBarButtonItem:[[[UIBarButtonItem alloc]
8082 initWithTitle:UCLocalize("DONE")
8083 style:UIBarButtonItemStyleDone
8084 target:self
8085 action:@selector(doneButtonClicked)
8086 ] autorelease] animated:([[self navigationItem] rightBarButtonItem] == nil)];
8087 }
8088
8089 - (NSInteger) numberOfSectionsInTableView:(UITableView *)tableView {
8090 // XXX: For not having a single cell in the table, this sure is a lot of sections.
8091 return 6;
8092 }
8093
8094 - (NSInteger) tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
8095 return 0; // :(
8096 }
8097
8098 - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
8099 return nil; // This method is required by the protocol.
8100 }
8101
8102 - (NSString *) tableView:(UITableView *)tableView titleForFooterInSection:(NSInteger)section {
8103 if (section == 1)
8104 return UCLocalize("ROLE_EX");
8105 if (section == 4)
8106 return [NSString stringWithFormat:
8107 @"%@: %@\n%@: %@\n%@: %@",
8108 UCLocalize("USER"), UCLocalize("USER_EX"),
8109 UCLocalize("HACKER"), UCLocalize("HACKER_EX"),
8110 UCLocalize("DEVELOPER"), UCLocalize("DEVELOPER_EX")
8111 ];
8112 else return nil;
8113 }
8114
8115 - (CGFloat) tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
8116 return section == 3 ? 44.0f : 0;
8117 }
8118
8119 - (UIView *) tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section {
8120 return section == 3 ? container_ : nil;
8121 }
8122
8123 @end
8124 /* }}} */
8125 /* Stash Controller {{{ */
8126 @interface StashController : CYViewController {
8127 // XXX: just delete these things
8128 _transient UIActivityIndicatorView *spinner_;
8129 _transient UILabel *status_;
8130 _transient UILabel *caption_;
8131 }
8132 @end
8133
8134 @implementation StashController
8135 - (id) init {
8136 if ((self = [super init])) {
8137 [[self view] setBackgroundColor:[UIColor viewFlipsideBackgroundColor]];
8138
8139 spinner_ = [[[UIActivityIndicatorView alloc] initWithActivityIndicatorStyle:UIActivityIndicatorViewStyleWhiteLarge] autorelease];
8140 CGRect spinrect = [spinner_ frame];
8141 spinrect.origin.x = ([[self view] frame].size.width / 2) - (spinrect.size.width / 2);
8142 spinrect.origin.y = [[self view] frame].size.height - 80.0f;
8143 [spinner_ setFrame:spinrect];
8144 [spinner_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin];
8145 [[self view] addSubview:spinner_];
8146 [spinner_ startAnimating];
8147
8148 CGRect captrect;
8149 captrect.size.width = [[self view] frame].size.width;
8150 captrect.size.height = 40.0f;
8151 captrect.origin.x = 0;
8152 captrect.origin.y = ([[self view] frame].size.height / 2) - (captrect.size.height * 2);
8153 caption_ = [[[UILabel alloc] initWithFrame:captrect] autorelease];
8154 [caption_ setText:UCLocalize("PREPARING_FILESYSTEM")];
8155 [caption_ setAutoresizingMask:UIViewAutoresizingFlexibleWidth | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8156 [caption_ setFont:[UIFont boldSystemFontOfSize:28.0f]];
8157 [caption_ setTextColor:[UIColor whiteColor]];
8158 [caption_ setBackgroundColor:[UIColor clearColor]];
8159 [caption_ setShadowColor:[UIColor blackColor]];
8160 [caption_ setTextAlignment:UITextAlignmentCenter];
8161 [[self view] addSubview:caption_];
8162
8163 CGRect statusrect;
8164 statusrect.size.width = [[self view] frame].size.width;
8165 statusrect.size.height = 30.0f;
8166 statusrect.origin.x = 0;
8167 statusrect.origin.y = ([[self view] frame].size.height / 2) - statusrect.size.height;
8168 status_ = [[[UILabel alloc] initWithFrame:statusrect] autorelease];
8169 [status_ setAutoresizingMask:UIViewAutoresizingFlexibleLeftMargin | UIViewAutoresizingFlexibleRightMargin | UIViewAutoresizingFlexibleTopMargin | UIViewAutoresizingFlexibleBottomMargin];
8170 [status_ setText:UCLocalize("EXIT_WHEN_COMPLETE")];
8171 [status_ setFont:[UIFont systemFontOfSize:16.0f]];
8172 [status_ setTextColor:[UIColor whiteColor]];
8173 [status_ setBackgroundColor:[UIColor clearColor]];
8174 [status_ setShadowColor:[UIColor blackColor]];
8175 [status_ setTextAlignment:UITextAlignmentCenter];
8176 [[self view] addSubview:status_];
8177 } return self;
8178 }
8179
8180 @end
8181 /* }}} */
8182
8183 @interface Cydia : UIApplication <
8184 ConfirmationControllerDelegate,
8185 ProgressControllerDelegate,
8186 CydiaDelegate,
8187 UINavigationControllerDelegate,
8188 UITabBarControllerDelegate
8189 > {
8190 // XXX: evaluate all fields for _transient
8191
8192 UIWindow *window_;
8193 CYTabBarController *tabbar_;
8194
8195 NSMutableArray *essential_;
8196 NSMutableArray *broken_;
8197
8198 Database *database_;
8199
8200 NSURL *starturl_;
8201
8202 unsigned locked_;
8203 unsigned activity_;
8204
8205 StashController *stash_;
8206
8207 bool loaded_;
8208 }
8209
8210 - (void) loadData;
8211
8212 @end
8213
8214 @implementation Cydia
8215
8216 - (void) beginUpdate {
8217 [tabbar_ beginUpdate];
8218 }
8219
8220 - (BOOL) updating {
8221 return [tabbar_ updating];
8222 }
8223
8224 - (void) _loaded {
8225 if ([broken_ count] != 0) {
8226 int count = [broken_ count];
8227
8228 UIAlertView *alert = [[[UIAlertView alloc]
8229 initWithTitle:(count == 1 ? UCLocalize("HALFINSTALLED_PACKAGE") : [NSString stringWithFormat:UCLocalize("HALFINSTALLED_PACKAGES"), count])
8230 message:UCLocalize("HALFINSTALLED_PACKAGE_EX")
8231 delegate:self
8232 cancelButtonTitle:UCLocalize("FORCIBLY_CLEAR")
8233 otherButtonTitles:UCLocalize("TEMPORARY_IGNORE"), nil
8234 ] autorelease];
8235
8236 [alert setContext:@"fixhalf"];
8237 [alert show];
8238 } else if (!Ignored_ && [essential_ count] != 0) {
8239 int count = [essential_ count];
8240
8241 UIAlertView *alert = [[[UIAlertView alloc]
8242 initWithTitle:(count == 1 ? UCLocalize("ESSENTIAL_UPGRADE") : [NSString stringWithFormat:UCLocalize("ESSENTIAL_UPGRADES"), count])
8243 message:UCLocalize("ESSENTIAL_UPGRADE_EX")
8244 delegate:self
8245 cancelButtonTitle:UCLocalize("TEMPORARY_IGNORE")
8246 otherButtonTitles:UCLocalize("UPGRADE_ESSENTIAL"), UCLocalize("COMPLETE_UPGRADE"), nil
8247 ] autorelease];
8248
8249 [alert setContext:@"upgrade"];
8250 [alert show];
8251 }
8252 }
8253
8254 - (void) _saveConfig {
8255 _trace();
8256 MetaFile_.Sync();
8257 _trace();
8258
8259 if (Changed_) {
8260 NSString *error(nil);
8261
8262 if (NSData *data = [NSPropertyListSerialization dataFromPropertyList:Metadata_ format:NSPropertyListBinaryFormat_v1_0 errorDescription:&error]) {
8263 _trace();
8264 NSError *error(nil);
8265 if (![data writeToFile:@"/var/lib/cydia/metadata.plist" options:NSAtomicWrite error:&error])
8266 NSLog(@"failure to save metadata data: %@", error);
8267 _trace();
8268
8269 Changed_ = false;
8270 } else {
8271 NSLog(@"failure to serialize metadata: %@", error);
8272 }
8273 }
8274 }
8275
8276 // Navigation controller for the queuing badge.
8277 - (CYNavigationController *) queueNavigationController {
8278 NSArray *controllers = [tabbar_ viewControllers];
8279 return [controllers objectAtIndex:3];
8280 }
8281
8282 - (void) _updateData {
8283 [self _saveConfig];
8284
8285 [tabbar_ reloadData];
8286
8287 CYNavigationController *navigation = [self queueNavigationController];
8288
8289 id queuedelegate = nil;
8290 if ([[navigation viewControllers] count] > 0)
8291 queuedelegate = [[navigation viewControllers] objectAtIndex:0];
8292
8293 [queuedelegate queueStatusDidChange];
8294 [[navigation tabBarItem] setBadgeValue:(Queuing_ ? UCLocalize("Q_D") : nil)];
8295 }
8296
8297 - (void) _refreshIfPossible {
8298 NSAutoreleasePool *pool = [[NSAutoreleasePool alloc] init];
8299
8300 bool recently = false;
8301 NSDate *update([Metadata_ objectForKey:@"LastUpdate"]);
8302 if (update != nil) {
8303 NSTimeInterval interval([update timeIntervalSinceNow]);
8304 if (interval <= 0 && interval > -(15*60))
8305 recently = true;
8306 }
8307
8308 // Don't automatic refresh if:
8309 // - We already refreshed recently.
8310 // - We already auto-refreshed this launch.
8311 // - Auto-refresh is disabled.
8312 if (recently || loaded_ || ManualRefresh) {
8313 [self performSelectorOnMainThread:@selector(_loaded) withObject:nil waitUntilDone:NO];
8314
8315 // If we are cancelling due to ManualRefresh or a recent refresh
8316 // we need to make sure it knows it's already loaded.
8317 loaded_ = true;
8318 return;
8319 } else {
8320 // We are going to load, so remember that.
8321 loaded_ = true;
8322 }
8323
8324 SCNetworkReachabilityFlags flags; {
8325 SCNetworkReachabilityRef reachability(SCNetworkReachabilityCreateWithName(NULL, "cydia.saurik.com"));
8326 SCNetworkReachabilityGetFlags(reachability, &flags);
8327 CFRelease(reachability);
8328 }
8329
8330 // XXX: this elaborate mess is what Apple is using to determine this? :(
8331 // XXX: do we care if the user has to intervene? maybe that's ok?
8332 bool reachable(
8333 (flags & kSCNetworkReachabilityFlagsReachable) != 0 && (
8334 (flags & kSCNetworkReachabilityFlagsConnectionRequired) == 0 || (
8335 (flags & kSCNetworkReachabilityFlagsConnectionOnDemand) != 0 ||
8336 (flags & kSCNetworkReachabilityFlagsConnectionOnTraffic) != 0
8337 ) && (flags & kSCNetworkReachabilityFlagsInterventionRequired) == 0 ||
8338 (flags & kSCNetworkReachabilityFlagsIsWWAN) != 0
8339 )
8340 );
8341
8342 // If we can reach the server, auto-refresh!
8343 if (reachable)
8344 [tabbar_ performSelectorOnMainThread:@selector(setUpdate:) withObject:update waitUntilDone:NO];
8345
8346 [pool release];
8347 }
8348
8349 - (void) refreshIfPossible {
8350 [NSThread detachNewThreadSelector:@selector(_refreshIfPossible) toTarget:self withObject:nil];
8351 }
8352
8353 - (void) _reloadData {
8354 UIProgressHUD *hud(loaded_ ? [self addProgressHUD] : nil);
8355 [hud setText:UCLocalize("RELOADING_DATA")];
8356
8357 [database_ yieldToSelector:@selector(reloadData) withObject:nil];
8358
8359 if (hud != nil)
8360 [self removeProgressHUD:hud];
8361
8362 size_t changes(0);
8363
8364 [essential_ removeAllObjects];
8365 [broken_ removeAllObjects];
8366
8367 NSArray *packages([database_ packages]);
8368 for (Package *package in packages) {
8369 if ([package half])
8370 [broken_ addObject:package];
8371 if ([package upgradableAndEssential:NO]) {
8372 if ([package essential])
8373 [essential_ addObject:package];
8374 ++changes;
8375 }
8376 }
8377
8378 NSLog(@"changes:#%u", changes);
8379
8380 UITabBarItem *changesItem = [[[tabbar_ viewControllers] objectAtIndex:2] tabBarItem];
8381 if (changes != 0) {
8382 _trace();
8383 NSString *badge([[NSNumber numberWithInt:changes] stringValue]);
8384 [changesItem setBadgeValue:badge];
8385 [changesItem setAnimatedBadge:([essential_ count] > 0)];
8386 [self setApplicationIconBadgeNumber:changes];
8387 } else {
8388 _trace();
8389 [changesItem setBadgeValue:nil];
8390 [changesItem setAnimatedBadge:NO];
8391 [self setApplicationIconBadgeNumber:0];
8392 }
8393
8394 [self _updateData];
8395
8396 [self refreshIfPossible];
8397 }
8398
8399 - (void) updateData {
8400 [self _updateData];
8401 }
8402
8403 - (void) update_ {
8404 [database_ update];
8405 }
8406
8407 - (void) syncData {
8408 FILE *file(fopen("/etc/apt/sources.list.d/cydia.list", "w"));
8409 _assert(file != NULL);
8410
8411 for (NSString *key in [Sources_ allKeys]) {
8412 NSDictionary *source([Sources_ objectForKey:key]);
8413
8414 fprintf(file, "%s %s %s\n",
8415 [[source objectForKey:@"Type"] UTF8String],
8416 [[source objectForKey:@"URI"] UTF8String],
8417 [[source objectForKey:@"Distribution"] UTF8String]
8418 );
8419 }
8420
8421 fclose(file);
8422
8423 [self _saveConfig];
8424
8425 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8426 CYNavigationController *navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8427 if (IsWildcat_)
8428 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8429 [tabbar_ presentModalViewController:navigation animated:YES];
8430
8431 [progress
8432 detachNewThreadSelector:@selector(update_)
8433 toTarget:self
8434 withObject:nil
8435 title:UCLocalize("UPDATING_SOURCES")
8436 ];
8437 }
8438
8439 - (void) reloadData {
8440 @synchronized (self) {
8441 [self _reloadData];
8442 }
8443 }
8444
8445 - (void) resolve {
8446 pkgProblemResolver *resolver = [database_ resolver];
8447
8448 resolver->InstallProtect();
8449 if (!resolver->Resolve(true))
8450 _error->Discard();
8451 }
8452
8453 - (bool) perform {
8454 if (![database_ prepare])
8455 return false;
8456
8457 ConfirmationController *page([[[ConfirmationController alloc] initWithDatabase:database_] autorelease]);
8458 [page setDelegate:self];
8459 CYNavigationController *confirm_([[[CYNavigationController alloc] initWithRootViewController:page] autorelease]);
8460 [confirm_ setDelegate:self];
8461
8462 if (IsWildcat_)
8463 [confirm_ setModalPresentationStyle:UIModalPresentationFormSheet];
8464 [tabbar_ presentModalViewController:confirm_ animated:YES];
8465
8466 return true;
8467 }
8468
8469 - (void) queue {
8470 @synchronized (self) {
8471 [self perform];
8472 }
8473 }
8474
8475 - (void) clearPackage:(Package *)package {
8476 @synchronized (self) {
8477 [package clear];
8478 [self resolve];
8479 [self perform];
8480 }
8481 }
8482
8483 - (void) installPackages:(NSArray *)packages {
8484 @synchronized (self) {
8485 for (Package *package in packages)
8486 [package install];
8487 [self resolve];
8488 [self perform];
8489 }
8490 }
8491
8492 - (void) installPackage:(Package *)package {
8493 @synchronized (self) {
8494 [package install];
8495 [self resolve];
8496 [self perform];
8497 }
8498 }
8499
8500 - (void) removePackage:(Package *)package {
8501 @synchronized (self) {
8502 [package remove];
8503 [self resolve];
8504 [self perform];
8505 }
8506 }
8507
8508 - (void) distUpgrade {
8509 @synchronized (self) {
8510 if (![database_ upgrade])
8511 return;
8512 [self perform];
8513 }
8514 }
8515
8516 - (void) complete {
8517 @synchronized (self) {
8518 [self _reloadData];
8519 }
8520 }
8521
8522 - (void) confirmWithNavigationController:(UINavigationController *)navigation {
8523 Queuing_ = false;
8524
8525 ProgressController *progress = [[[ProgressController alloc] initWithDatabase:database_ delegate:self] autorelease];
8526
8527 if (navigation != nil) {
8528 [navigation pushViewController:progress animated:YES];
8529 } else {
8530 navigation = [[[CYNavigationController alloc] initWithRootViewController:progress] autorelease];
8531 if (IsWildcat_)
8532 [navigation setModalPresentationStyle:UIModalPresentationFormSheet];
8533 [tabbar_ presentModalViewController:navigation animated:YES];
8534 }
8535
8536 [progress
8537 detachNewThreadSelector:@selector(perform)
8538 toTarget:database_
8539 withObject:nil
8540 title:UCLocalize("RUNNING")
8541 ];
8542
8543 ++locked_;
8544 }
8545
8546 - (void) progressControllerIsComplete:(ProgressController *)progress {
8547 --locked_;
8548 [self complete];
8549 }
8550
8551 - (void) tabBarController:(UITabBarController *)tabBarController didSelectViewController:(UIViewController *)viewController {
8552 CYNavigationController *controller = (CYNavigationController *) viewController;
8553
8554 if ([[controller viewControllers] count] == 0) {
8555 int index = [[tabbar_ viewControllers] indexOfObjectIdenticalTo:controller];
8556 CYViewController *root = nil;
8557
8558 if (index == 0)
8559 root = [[[HomeController alloc] init] autorelease];
8560 else if (index == 1)
8561 root = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8562 else if (index == 2)
8563 root = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8564
8565 if (IsWildcat_) {
8566 if (index == 3)
8567 root = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8568 else if (index == 4)
8569 root = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8570 else if (index == 5)
8571 root = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8572 } else {
8573 if (index == 3)
8574 root = [[[ManageController alloc] init] autorelease];
8575 else if (index == 4)
8576 root = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8577 }
8578
8579 [root setDelegate:self];
8580
8581 if (root != nil)
8582 [controller setViewControllers:[NSArray arrayWithObject:root]];
8583 }
8584 }
8585
8586 - (void) showSettings {
8587 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
8588 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
8589 if (IsWildcat_)
8590 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
8591 [tabbar_ presentModalViewController:nav animated:YES];
8592 }
8593
8594 - (void) retainNetworkActivityIndicator {
8595 if (activity_++ == 0)
8596 [self setNetworkActivityIndicatorVisible:YES];
8597 }
8598
8599 - (void) releaseNetworkActivityIndicator {
8600 if (--activity_ == 0)
8601 [self setNetworkActivityIndicatorVisible:NO];
8602 }
8603
8604 - (void) setPackageController:(CYPackageController *)view {
8605 WebThreadLock();
8606 [view setPackage:nil];
8607 WebThreadUnlock();
8608 }
8609
8610 - (void) cancelAndClear:(bool)clear {
8611 @synchronized (self) {
8612 if (clear) {
8613 [database_ clear];
8614 Queuing_ = false;
8615 } else {
8616 Queuing_ = true;
8617 }
8618
8619 [self _updateData];
8620 }
8621 }
8622
8623 - (void) alertView:(UIAlertView *)alert clickedButtonAtIndex:(NSInteger)button {
8624 NSString *context([alert context]);
8625
8626 if ([context isEqualToString:@"fixhalf"]) {
8627 if (button == [alert firstOtherButtonIndex]) {
8628 @synchronized (self) {
8629 for (Package *broken in broken_) {
8630 [broken remove];
8631
8632 NSString *id = [broken id];
8633 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.prerm", id] UTF8String]);
8634 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postrm", id] UTF8String]);
8635 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.preinst", id] UTF8String]);
8636 unlink([[NSString stringWithFormat:@"/var/lib/dpkg/info/%@.postinst", id] UTF8String]);
8637 }
8638
8639 [self resolve];
8640 [self perform];
8641 }
8642 } else if (button == [alert cancelButtonIndex]) {
8643 [broken_ removeAllObjects];
8644 [self _loaded];
8645 }
8646
8647 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8648 } else if ([context isEqualToString:@"upgrade"]) {
8649 if (button == [alert firstOtherButtonIndex]) {
8650 @synchronized (self) {
8651 for (Package *essential in essential_)
8652 [essential install];
8653
8654 [self resolve];
8655 [self perform];
8656 }
8657 } else if (button == [alert firstOtherButtonIndex] + 1) {
8658 [self distUpgrade];
8659 } else if (button == [alert cancelButtonIndex]) {
8660 Ignored_ = YES;
8661 }
8662
8663 [alert dismissWithClickedButtonIndex:-1 animated:YES];
8664 }
8665 }
8666
8667 - (void) system:(NSString *)command { _pooled
8668 _trace();
8669 system([command UTF8String]);
8670 _trace();
8671 }
8672
8673 - (void) applicationWillSuspend {
8674 [database_ clean];
8675 [super applicationWillSuspend];
8676 }
8677
8678 - (BOOL) isSafeToSuspend {
8679 // Use external process status API internally.
8680 // This is probably a really bad idea.
8681 // XXX: what is the point of this? does this solve anything at all?
8682 uint64_t status = 0;
8683 int notify_token;
8684 if (notify_register_check("com.saurik.Cydia.status", &notify_token) == NOTIFY_STATUS_OK) {
8685 notify_get_state(notify_token, &status);
8686 notify_cancel(notify_token);
8687 }
8688
8689 return locked_ == 0 && status == 0;
8690 }
8691
8692 - (void) applicationSuspend:(__GSEvent *)event {
8693 if ([self isSafeToSuspend])
8694 [super applicationSuspend:event];
8695 }
8696
8697 - (void) _animateSuspension:(BOOL)arg0 duration:(double)arg1 startTime:(double)arg2 scale:(float)arg3 {
8698 if ([self isSafeToSuspend])
8699 [super _animateSuspension:arg0 duration:arg1 startTime:arg2 scale:arg3];
8700 }
8701
8702 - (void) _setSuspended:(BOOL)value {
8703 if ([self isSafeToSuspend])
8704 [super _setSuspended:value];
8705 }
8706
8707 - (UIProgressHUD *) addProgressHUD {
8708 UIProgressHUD *hud([[[UIProgressHUD alloc] initWithWindow:window_] autorelease]);
8709 [hud setAutoresizingMask:UIViewAutoresizingFlexibleBoth];
8710
8711 [window_ setUserInteractionEnabled:NO];
8712 [hud show:YES];
8713
8714 UIViewController *target = tabbar_;
8715 while ([target modalViewController] != nil) target = [target modalViewController];
8716 [[target view] addSubview:hud];
8717
8718 ++locked_;
8719 return hud;
8720 }
8721
8722 - (void) removeProgressHUD:(UIProgressHUD *)hud {
8723 [hud show:NO];
8724 [hud removeFromSuperview];
8725 [window_ setUserInteractionEnabled:YES];
8726 --locked_;
8727 }
8728
8729 - (CYViewController *) pageForPackage:(NSString *)name {
8730 if (Package *package = [database_ packageWithName:name]) {
8731 CYPackageController *view = [[[CYPackageController alloc] initWithDatabase:database_] autorelease];
8732 [view setPackage:package];
8733 return view;
8734 } else {
8735 NSURL *url([NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"unknown" ofType:@"html"]]);
8736 url = [NSURL URLWithString:[[url absoluteString] stringByAppendingString:[NSString stringWithFormat:@"?%@", name]]];
8737 CYBrowserController *browser = [[[CYBrowserController alloc] init] autorelease];
8738 [browser loadURL:url];
8739 return browser;
8740 }
8741 }
8742
8743 - (CYViewController *) pageForURL:(NSURL *)url {
8744 NSString *scheme([[url scheme] lowercaseString]);
8745 if ([[url absoluteString] length] <= [scheme length] + 3)
8746 return nil;
8747 NSString *path([[url absoluteString] substringFromIndex:[scheme length] + 3]);
8748 NSArray *components([path pathComponents]);
8749
8750 if ([scheme isEqualToString:@"apptapp"] && [components count] > 0 && [[components objectAtIndex:0] isEqualToString:@"package"])
8751 return [self pageForPackage:[components objectAtIndex:1]];
8752
8753 if ([components count] < 1 || ![scheme isEqualToString:@"cydia"])
8754 return nil;
8755
8756 NSString *base([components objectAtIndex:0]);
8757
8758 CYViewController *controller = nil;
8759
8760 if ([base isEqualToString:@"url"]) {
8761 // This kind of URL can contain slashes in the argument, so we can't parse them below.
8762 NSString *destination = [[url absoluteString] substringFromIndex:([scheme length] + [@"://" length] + [base length] + [@"/" length])];
8763 controller = [[[CYBrowserController alloc] init] autorelease];
8764 [(CYBrowserController *)controller loadURL:[NSURL URLWithString:destination]];
8765 } else if ([components count] == 1) {
8766 if ([base isEqualToString:@"storage"]) {
8767 controller = [[[CYBrowserController alloc] init] autorelease];
8768 [(CYBrowserController *)controller loadURL:[NSURL fileURLWithPath:[[NSBundle mainBundle] pathForResource:@"storage" ofType:@"html"]]];
8769 }
8770
8771 if ([base isEqualToString:@"sources"]) {
8772 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8773 }
8774
8775 if ([base isEqualToString:@"home"]) {
8776 controller = [[[HomeController alloc] init] autorelease];
8777 }
8778
8779 if ([base isEqualToString:@"sections"]) {
8780 controller = [[[SectionsController alloc] initWithDatabase:database_] autorelease];
8781 }
8782
8783 if ([base isEqualToString:@"search"]) {
8784 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8785 }
8786
8787 if ([base isEqualToString:@"changes"]) {
8788 controller = [[[ChangesController alloc] initWithDatabase:database_] autorelease];
8789 }
8790
8791 if ([base isEqualToString:@"installed"]) {
8792 controller = [[[InstalledController alloc] initWithDatabase:database_] autorelease];
8793 }
8794 } else if ([components count] == 2) {
8795 NSString *argument = [components objectAtIndex:1];
8796
8797 if ([base isEqualToString:@"package"]) {
8798 controller = [self pageForPackage:argument];
8799 }
8800
8801 if ([base isEqualToString:@"search"]) {
8802 controller = [[[SearchController alloc] initWithDatabase:database_] autorelease];
8803 [(SearchController *)controller setSearchTerm:argument];
8804 }
8805
8806 if ([base isEqualToString:@"sections"]) {
8807 if ([argument isEqualToString:@"all"])
8808 argument = nil;
8809 controller = [[[SectionController alloc] initWithDatabase:database_ section:argument] autorelease];
8810 }
8811
8812 if ([base isEqualToString:@"sources"]) {
8813 if ([argument isEqualToString:@"add"]) {
8814 controller = [[[SourcesController alloc] initWithDatabase:database_] autorelease];
8815 [(SourcesController *)controller showAddSourcePrompt];
8816 } else {
8817 NSArray *sources = [database_ sources];
8818 for (Source *source in sources) {
8819 if ([[source name] caseInsensitiveCompare:argument] == NSOrderedSame) {
8820 controller = [[[SourceController alloc] initWithDatabase:database_ source:source] autorelease];
8821 break;
8822 }
8823 }
8824 }
8825 }
8826
8827 if ([base isEqualToString:@"launch"]) {
8828 [self launchApplicationWithIdentifier:argument suspended:NO];
8829 return nil;
8830 }
8831 } else if ([components count] == 3) {
8832 NSString *arg1 = [components objectAtIndex:1];
8833 NSString *arg2 = [components objectAtIndex:2];
8834
8835 if ([base isEqualToString:@"package"]) {
8836 if ([arg2 isEqualToString:@"settings"]) {
8837 controller = [[[PackageSettingsController alloc] initWithDatabase:database_ package:arg1] autorelease];
8838 } else if ([arg2 isEqualToString:@"signature"]) {
8839 controller = [[[SignatureController alloc] initWithDatabase:database_ package:arg1] autorelease];
8840 } else if ([arg2 isEqualToString:@"files"]) {
8841 if (Package *package = [database_ packageWithName:arg1]) {
8842 controller = [[[FileTable alloc] initWithDatabase:database_] autorelease];
8843 [(FileTable *)controller setPackage:package];
8844 }
8845 }
8846 }
8847 }
8848
8849 [controller setDelegate:self];
8850 return controller;
8851 }
8852
8853 - (BOOL) openCydiaURL:(NSURL *)url {
8854 CYViewController *page([self pageForURL:url]);
8855
8856 if (page != nil) {
8857 CYNavigationController *nav = [[[CYNavigationController alloc] init] autorelease];
8858 [nav setViewControllers:[NSArray arrayWithObject:page]];
8859 [tabbar_ setTransientViewController:nav];
8860 }
8861
8862 return page != nil;
8863 }
8864
8865 - (void) applicationOpenURL:(NSURL *)url {
8866 [super applicationOpenURL:url];
8867
8868 if (!loaded_) starturl_ = [url retain];
8869 else [self openCydiaURL:url];
8870 }
8871
8872 - (void) applicationWillResignActive:(UIApplication *)application {
8873 // Stop refreshing if you get a phone call or lock the device.
8874 if ([tabbar_ updating])
8875 [tabbar_ cancelUpdate];
8876
8877 if ([[self superclass] instancesRespondToSelector:@selector(applicationWillResignActive:)])
8878 [super applicationWillResignActive:application];
8879 }
8880
8881 - (void) addStashController {
8882 ++locked_;
8883 stash_ = [[StashController alloc] init];
8884 [window_ addSubview:[stash_ view]];
8885 }
8886
8887 - (void) removeStashController {
8888 [[stash_ view] removeFromSuperview];
8889 [stash_ release];
8890 --locked_;
8891 }
8892
8893 - (void) stash {
8894 [self setIdleTimerDisabled:YES];
8895
8896 [[UIApplication sharedApplication] setStatusBarStyle:UIStatusBarStyleBlackOpaque];
8897 [self setStatusBarShowsProgress:YES];
8898 UpdateExternalStatus(1);
8899
8900 [self yieldToSelector:@selector(system:) withObject:@"/usr/libexec/cydia/free.sh"];
8901
8902 UpdateExternalStatus(0);
8903 [self setStatusBarShowsProgress:NO];
8904
8905 [self removeStashController];
8906
8907 if (ExecFork() == 0) {
8908 execlp("launchctl", "launchctl", "stop", "com.apple.SpringBoard", NULL);
8909 perror("launchctl stop");
8910 }
8911 }
8912
8913 - (void) setupViewControllers {
8914 tabbar_ = [[CYTabBarController alloc] initWithDatabase:database_];
8915 [tabbar_ setDelegate:self];
8916
8917 NSMutableArray *items([NSMutableArray arrayWithObjects:
8918 [[[UITabBarItem alloc] initWithTitle:@"Cydia" image:[UIImage applicationImageNamed:@"home.png"] tag:0] autorelease],
8919 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SECTIONS") image:[UIImage applicationImageNamed:@"install.png"] tag:0] autorelease],
8920 [[[UITabBarItem alloc] initWithTitle:UCLocalize("CHANGES") image:[UIImage applicationImageNamed:@"changes.png"] tag:0] autorelease],
8921 [[[UITabBarItem alloc] initWithTitle:UCLocalize("SEARCH") image:[UIImage applicationImageNamed:@"search.png"] tag:0] autorelease],
8922 nil]);
8923
8924 if (IsWildcat_) {
8925 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("SOURCES") image:[UIImage applicationImageNamed:@"source.png"] tag:0] autorelease] atIndex:3];
8926 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("INSTALLED") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
8927 } else {
8928 [items insertObject:[[[UITabBarItem alloc] initWithTitle:UCLocalize("MANAGE") image:[UIImage applicationImageNamed:@"manage.png"] tag:0] autorelease] atIndex:3];
8929 }
8930
8931 NSMutableArray *controllers([NSMutableArray array]);
8932 for (UITabBarItem *item in items) {
8933 CYNavigationController *controller([[[CYNavigationController alloc] initWithDatabase:database_] autorelease]);
8934 [controller setTabBarItem:item];
8935 [controllers addObject:controller];
8936 }
8937 [tabbar_ setViewControllers:controllers];
8938
8939 [tabbar_ setUpdateDelegate:self];
8940 }
8941
8942 - (CYEmulatedLoadingController *)showEmulatedLoadingControllerInView:(UIView *)view {
8943 static CYEmulatedLoadingController *fake = [[CYEmulatedLoadingController alloc] init];
8944 if (view != nil) {
8945 [view addSubview:[fake view]];
8946 } else {
8947 [[fake view] removeFromSuperview];
8948 }
8949
8950 return fake;
8951 }
8952
8953 - (void) applicationDidFinishLaunching:(id)unused {
8954 _trace();
8955 CydiaApp = self;
8956
8957 if ([self respondsToSelector:@selector(setApplicationSupportsShakeToEdit:)])
8958 [self setApplicationSupportsShakeToEdit:NO];
8959
8960 [NSURLCache setSharedURLCache:[[[SDURLCache alloc]
8961 initWithMemoryCapacity:524288
8962 diskCapacity:10485760
8963 diskPath:[NSString stringWithFormat:@"%@/Library/Caches/com.saurik.Cydia/SDURLCache", @"/var/root"]
8964 ] autorelease]];
8965
8966 [CYBrowserController _initialize];
8967
8968 [NSURLProtocol registerClass:[CydiaURLProtocol class]];
8969
8970 Font12_ = [[UIFont systemFontOfSize:12] retain];
8971 Font12Bold_ = [[UIFont boldSystemFontOfSize:12] retain];
8972 Font14_ = [[UIFont systemFontOfSize:14] retain];
8973 Font18Bold_ = [[UIFont boldSystemFontOfSize:18] retain];
8974 Font22Bold_ = [[UIFont boldSystemFontOfSize:22] retain];
8975
8976 essential_ = [[NSMutableArray alloc] initWithCapacity:4];
8977 broken_ = [[NSMutableArray alloc] initWithCapacity:4];
8978
8979 window_ = [[UIWindow alloc] initWithFrame:[[UIScreen mainScreen] bounds]];
8980 [window_ orderFront:self];
8981 [window_ makeKey:self];
8982 [window_ setHidden:NO];
8983
8984 if (
8985 readlink("/Applications", NULL, 0) == -1 && errno == EINVAL ||
8986 readlink("/Library/Ringtones", NULL, 0) == -1 && errno == EINVAL ||
8987 readlink("/Library/Wallpaper", NULL, 0) == -1 && errno == EINVAL ||
8988 //readlink("/usr/bin", NULL, 0) == -1 && errno == EINVAL ||
8989 readlink("/usr/include", NULL, 0) == -1 && errno == EINVAL ||
8990 readlink("/usr/lib/pam", NULL, 0) == -1 && errno == EINVAL ||
8991 readlink("/usr/libexec", NULL, 0) == -1 && errno == EINVAL ||
8992 readlink("/usr/share", NULL, 0) == -1 && errno == EINVAL ||
8993 //readlink("/var/lib", NULL, 0) == -1 && errno == EINVAL ||
8994 false
8995 ) {
8996 [self addStashController];
8997 // XXX: this would be much cleaner as a yieldToSelector:
8998 // that way the removeStashController could happen right here inline
8999 // we also could no longer require the useless stash_ field anymore
9000 [self performSelector:@selector(stash) withObject:nil afterDelay:0];
9001 return;
9002 }
9003
9004 database_ = [Database sharedInstance];
9005
9006 [window_ setUserInteractionEnabled:NO];
9007 [self setupViewControllers];
9008 [self showEmulatedLoadingControllerInView:window_];
9009
9010 [self performSelector:@selector(loadData) withObject:nil afterDelay:0];
9011 _trace();
9012 }
9013
9014 - (void) loadData {
9015 _trace();
9016 if (Role_ == nil) {
9017 [window_ setUserInteractionEnabled:YES];
9018
9019 SettingsController *role = [[[SettingsController alloc] initWithDatabase:database_ delegate:self] autorelease];
9020 CYNavigationController *nav = [[[CYNavigationController alloc] initWithRootViewController:role] autorelease];
9021 if (IsWildcat_)
9022 [nav setModalPresentationStyle:UIModalPresentationFormSheet];
9023 [[self showEmulatedLoadingControllerInView:window_] presentModalViewController:nav animated:YES];
9024
9025 return;
9026 } else {
9027 if ([[self showEmulatedLoadingControllerInView:window_] modalViewController] != nil)
9028 [[self showEmulatedLoadingControllerInView:window_] dismissModalViewControllerAnimated:YES];
9029 [window_ setUserInteractionEnabled:NO];
9030 }
9031
9032 [self reloadData];
9033 PrintTimes();
9034
9035 [window_ addSubview:[tabbar_ view]];
9036 [self showEmulatedLoadingControllerInView:nil];
9037 [window_ setUserInteractionEnabled:YES];
9038
9039 // Show the home page.
9040 CYNavigationController *navigation = [[tabbar_ viewControllers] objectAtIndex:0];
9041 [navigation setViewControllers:[NSArray arrayWithObject:[self pageForURL:[NSURL URLWithString:@"cydia://home"]]]];
9042
9043 // (Try to) show the startup URL.
9044 if (starturl_ != nil) {
9045 [self openCydiaURL:starturl_];
9046 [starturl_ release];
9047 starturl_ = nil;
9048 }
9049 }
9050
9051 - (void) showActionSheet:(UIActionSheet *)sheet fromItem:(UIBarButtonItem *)item {
9052 if (item != nil && IsWildcat_) {
9053 [sheet showFromBarButtonItem:item animated:YES];
9054 } else {
9055 [sheet showInView:window_];
9056 }
9057 }
9058
9059 @end
9060
9061 /*IMP alloc_;
9062 id Alloc_(id self, SEL selector) {
9063 id object = alloc_(self, selector);
9064 lprintf("[%s]A-%p\n", self->isa->name, object);
9065 return object;
9066 }*/
9067
9068 /*IMP dealloc_;
9069 id Dealloc_(id self, SEL selector) {
9070 id object = dealloc_(self, selector);
9071 lprintf("[%s]D-%p\n", self->isa->name, object);
9072 return object;
9073 }*/
9074
9075 Class $WebDefaultUIKitDelegate;
9076
9077 MSHook(void, UIWebDocumentView$_setUIKitDelegate$, UIWebDocumentView *self, SEL _cmd, id delegate) {
9078 if (delegate == nil && $WebDefaultUIKitDelegate != nil)
9079 delegate = [$WebDefaultUIKitDelegate sharedUIKitDelegate];
9080 return _UIWebDocumentView$_setUIKitDelegate$(self, _cmd, delegate);
9081 }
9082
9083 static NSNumber *shouldPlayKeyboardSounds;
9084
9085 Class $UIHardware;
9086
9087 MSHook(void, UIHardware$_playSystemSound$, Class self, SEL _cmd, int sound) {
9088 switch (sound) {
9089 case 1104: // Keyboard Button Clicked
9090 case 1105: // Keyboard Delete Repeated
9091 if (shouldPlayKeyboardSounds == nil) {
9092 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.preferences.sounds.plist"] autorelease]);
9093 shouldPlayKeyboardSounds = [([dict objectForKey:@"keyboard"] ?: (id) kCFBooleanTrue) retain];
9094 }
9095
9096 if (![shouldPlayKeyboardSounds boolValue])
9097 break;
9098
9099 default:
9100 _UIHardware$_playSystemSound$(self, _cmd, sound);
9101 }
9102 }
9103
9104 Class $UIApplication;
9105
9106 MSHook(void, UIApplication$_updateApplicationAccessibility, UIApplication *self, SEL _cmd) {
9107 static BOOL initialized = NO;
9108 static BOOL started = NO;
9109
9110 NSDictionary *dict([[[NSDictionary alloc] initWithContentsOfFile:@"/var/mobile/Library/Preferences/com.apple.Accessibility.plist"] autorelease]);
9111 BOOL enabled = [[dict objectForKey:@"VoiceOverTouchEnabled"] boolValue] || [[dict objectForKey:@"VoiceOverTouchEnabledByiTunes"] boolValue];
9112
9113 if ([self respondsToSelector:@selector(_accessibilityBundlePrincipalClass)]) {
9114 id bundle = [self performSelector:@selector(_accessibilityBundlePrincipalClass)];
9115 if (![bundle respondsToSelector:@selector(_accessibilityStopServer)]) return;
9116 if (![bundle respondsToSelector:@selector(_accessibilityStartServer)]) return;
9117
9118 if (initialized && !enabled) {
9119 initialized = NO;
9120 [bundle performSelector:@selector(_accessibilityStopServer)];
9121 } else if (enabled) {
9122 initialized = YES;
9123 if (!started) {
9124 started = YES;
9125 [bundle performSelector:@selector(_accessibilityStartServer)];
9126 }
9127 }
9128 }
9129 }
9130
9131 int main(int argc, char *argv[]) { _pooled
9132 _trace();
9133
9134 if (Class $UIDevice = objc_getClass("UIDevice")) {
9135 UIDevice *device([$UIDevice currentDevice]);
9136 IsWildcat_ = [device respondsToSelector:@selector(isWildcat)] && [device isWildcat];
9137 } else
9138 IsWildcat_ = false;
9139
9140 PackageName = reinterpret_cast<CYString &(*)(Package *, SEL)>(method_getImplementation(class_getInstanceMethod([Package class], @selector(cyname))));
9141
9142 /* Library Hacks {{{ */
9143 class_addMethod(objc_getClass("DOMNodeList"), @selector(countByEnumeratingWithState:objects:count:), (IMP) &DOMNodeList$countByEnumeratingWithState$objects$count$, "I20@0:4^{NSFastEnumerationState}8^@12I16");
9144
9145 $WebDefaultUIKitDelegate = objc_getClass("WebDefaultUIKitDelegate");
9146 Method UIWebDocumentView$_setUIKitDelegate$(class_getInstanceMethod([WebView class], @selector(_setUIKitDelegate:)));
9147 if (UIWebDocumentView$_setUIKitDelegate$ != NULL) {
9148 _UIWebDocumentView$_setUIKitDelegate$ = reinterpret_cast<void (*)(UIWebDocumentView *, SEL, id)>(method_getImplementation(UIWebDocumentView$_setUIKitDelegate$));
9149 method_setImplementation(UIWebDocumentView$_setUIKitDelegate$, reinterpret_cast<IMP>(&$UIWebDocumentView$_setUIKitDelegate$));
9150 }
9151
9152 $UIHardware = objc_getClass("UIHardware");
9153 Method UIHardware$_playSystemSound$(class_getClassMethod($UIHardware, @selector(_playSystemSound:)));
9154 if (UIHardware$_playSystemSound$ != NULL) {
9155 _UIHardware$_playSystemSound$ = reinterpret_cast<void (*)(Class, SEL, int)>(method_getImplementation(UIHardware$_playSystemSound$));
9156 method_setImplementation(UIHardware$_playSystemSound$, reinterpret_cast<IMP>(&$UIHardware$_playSystemSound$));
9157 }
9158
9159 $UIApplication = objc_getClass("UIApplication");
9160 Method UIApplication$_updateApplicationAccessibility(class_getInstanceMethod($UIApplication, @selector(_updateApplicationAccessibility)));
9161 if (UIApplication$_updateApplicationAccessibility != NULL) {
9162 _UIApplication$_updateApplicationAccessibility = reinterpret_cast<void (*)(UIApplication *, SEL)>(method_getImplementation(UIApplication$_updateApplicationAccessibility));
9163 method_setImplementation(UIApplication$_updateApplicationAccessibility, reinterpret_cast<IMP>(&$UIApplication$_updateApplicationAccessibility));
9164 }
9165 /* }}} */
9166 /* Set Locale {{{ */
9167 Locale_ = CFLocaleCopyCurrent();
9168 Languages_ = [NSLocale preferredLanguages];
9169 //CFStringRef locale(CFLocaleGetIdentifier(Locale_));
9170 //NSLog(@"%@", [Languages_ description]);
9171
9172 const char *lang;
9173 if (Languages_ == nil || [Languages_ count] == 0)
9174 // XXX: consider just setting to C and then falling through?
9175 lang = NULL;
9176 else {
9177 lang = [[Languages_ objectAtIndex:0] UTF8String];
9178 setenv("LANG", lang, true);
9179 }
9180
9181 //std::setlocale(LC_ALL, lang);
9182 NSLog(@"Setting Language: %s", lang);
9183 /* }}} */
9184
9185 apr_app_initialize(&argc, const_cast<const char * const **>(&argv), NULL);
9186
9187 /* Parse Arguments {{{ */
9188 bool substrate(false);
9189
9190 if (argc != 0) {
9191 char **args(argv);
9192 int arge(1);
9193
9194 for (int argi(1); argi != argc; ++argi)
9195 if (strcmp(argv[argi], "--") == 0) {
9196 arge = argi;
9197 argv[argi] = argv[0];
9198 argv += argi;
9199 argc -= argi;
9200 break;
9201 }
9202
9203 for (int argi(1); argi != arge; ++argi)
9204 if (strcmp(args[argi], "--substrate") == 0)
9205 substrate = true;
9206 else
9207 fprintf(stderr, "unknown argument: %s\n", args[argi]);
9208 }
9209 /* }}} */
9210
9211 App_ = [[NSBundle mainBundle] bundlePath];
9212 Home_ = NSHomeDirectory();
9213 Advanced_ = YES;
9214
9215 setuid(0);
9216 setgid(0);
9217
9218 /*Method alloc = class_getClassMethod([NSObject class], @selector(alloc));
9219 alloc_ = alloc->method_imp;
9220 alloc->method_imp = (IMP) &Alloc_;*/
9221
9222 /*Method dealloc = class_getClassMethod([NSObject class], @selector(dealloc));
9223 dealloc_ = dealloc->method_imp;
9224 dealloc->method_imp = (IMP) &Dealloc_;*/
9225
9226 /* System Information {{{ */
9227 size_t size;
9228
9229 int maxproc;
9230 size = sizeof(maxproc);
9231 if (sysctlbyname("kern.maxproc", &maxproc, &size, NULL, 0) == -1)
9232 perror("sysctlbyname(\"kern.maxproc\", ?)");
9233 else if (maxproc < 64) {
9234 maxproc = 64;
9235 if (sysctlbyname("kern.maxproc", NULL, NULL, &maxproc, sizeof(maxproc)) == -1)
9236 perror("sysctlbyname(\"kern.maxproc\", #)");
9237 }
9238
9239 sysctlbyname("kern.osversion", NULL, &size, NULL, 0);
9240 char *osversion = new char[size];
9241 if (sysctlbyname("kern.osversion", osversion, &size, NULL, 0) == -1)
9242 perror("sysctlbyname(\"kern.osversion\", ?)");
9243 else
9244 System_ = [NSString stringWithUTF8String:osversion];
9245
9246 sysctlbyname("hw.machine", NULL, &size, NULL, 0);
9247 char *machine = new char[size];
9248 if (sysctlbyname("hw.machine", machine, &size, NULL, 0) == -1)
9249 perror("sysctlbyname(\"hw.machine\", ?)");
9250 else
9251 Machine_ = machine;
9252
9253 if (CFMutableDictionaryRef dict = IOServiceMatching("IOPlatformExpertDevice")) {
9254 if (io_service_t service = IOServiceGetMatchingService(kIOMasterPortDefault, dict)) {
9255 if (CFTypeRef serial = IORegistryEntryCreateCFProperty(service, CFSTR(kIOPlatformSerialNumberKey), kCFAllocatorDefault, 0)) {
9256 SerialNumber_ = [NSString stringWithString:(NSString *)serial];
9257 CFRelease(serial);
9258 }
9259
9260 if (CFTypeRef ecid = IORegistryEntrySearchCFProperty(service, kIODeviceTreePlane, CFSTR("unique-chip-id"), kCFAllocatorDefault, kIORegistryIterateRecursively)) {
9261 NSData *data((NSData *) ecid);
9262 size_t length([data length]);
9263 uint8_t bytes[length];
9264 [data getBytes:bytes];
9265 char string[length * 2 + 1];
9266 for (size_t i(0); i != length; ++i)
9267 sprintf(string + i * 2, "%.2X", bytes[length - i - 1]);
9268 ChipID_ = [NSString stringWithUTF8String:string];
9269 CFRelease(ecid);
9270 }
9271
9272 IOObjectRelease(service);
9273 }
9274 }
9275
9276 UniqueID_ = [[UIDevice currentDevice] uniqueIdentifier];
9277
9278 CFStringRef (*$CTSIMSupportCopyMobileSubscriberCountryCode)(CFAllocatorRef);
9279 $CTSIMSupportCopyMobileSubscriberCountryCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9280 CFStringRef mcc($CTSIMSupportCopyMobileSubscriberCountryCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberCountryCode)(kCFAllocatorDefault));
9281
9282 CFStringRef (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(CFAllocatorRef);
9283 $CTSIMSupportCopyMobileSubscriberNetworkCode = reinterpret_cast<CFStringRef (*)(CFAllocatorRef)>(dlsym(RTLD_DEFAULT, "CTSIMSupportCopyMobileSubscriberCountryCode"));
9284 CFStringRef mnc($CTSIMSupportCopyMobileSubscriberNetworkCode == NULL ? NULL : (*$CTSIMSupportCopyMobileSubscriberNetworkCode)(kCFAllocatorDefault));
9285
9286 if (mcc != NULL && mnc != NULL)
9287 PLMN_ = [NSString stringWithFormat:@"%@%@", mcc, mnc];
9288
9289 if (mnc != NULL)
9290 CFRelease(mnc);
9291 if (mcc != NULL)
9292 CFRelease(mcc);
9293
9294 if (NSDictionary *system = [NSDictionary dictionaryWithContentsOfFile:@"/System/Library/CoreServices/SystemVersion.plist"])
9295 Build_ = [system objectForKey:@"ProductBuildVersion"];
9296 if (NSDictionary *info = [NSDictionary dictionaryWithContentsOfFile:@"/Applications/MobileSafari.app/Info.plist"]) {
9297 Product_ = [info objectForKey:@"SafariProductVersion"];
9298 Safari_ = [info objectForKey:@"CFBundleVersion"];
9299 }
9300 /* }}} */
9301 /* Load Database {{{ */
9302 _trace();
9303 Metadata_ = [[[NSMutableDictionary alloc] initWithContentsOfFile:@"/var/lib/cydia/metadata.plist"] autorelease];
9304 _trace();
9305 SectionMap_ = [[[NSDictionary alloc] initWithContentsOfFile:[[NSBundle mainBundle] pathForResource:@"Sections" ofType:@"plist"]] autorelease];
9306
9307 if (Metadata_ == NULL)
9308 Metadata_ = [NSMutableDictionary dictionaryWithCapacity:2];
9309 else {
9310 Settings_ = [Metadata_ objectForKey:@"Settings"];
9311
9312 Packages_ = [Metadata_ objectForKey:@"Packages"];
9313 Sections_ = [Metadata_ objectForKey:@"Sections"];
9314 Sources_ = [Metadata_ objectForKey:@"Sources"];
9315
9316 Token_ = [Metadata_ objectForKey:@"Token"];
9317 }
9318
9319 if (Settings_ != nil)
9320 Role_ = [Settings_ objectForKey:@"Role"];
9321
9322 if (Sections_ == nil) {
9323 Sections_ = [[[NSMutableDictionary alloc] initWithCapacity:32] autorelease];
9324 [Metadata_ setObject:Sections_ forKey:@"Sections"];
9325 }
9326
9327 if (Sources_ == nil) {
9328 Sources_ = [[[NSMutableDictionary alloc] initWithCapacity:0] autorelease];
9329 [Metadata_ setObject:Sources_ forKey:@"Sources"];
9330 }
9331 /* }}} */
9332
9333 _trace();
9334 MetaFile_.Open("/var/lib/cydia/metadata.cb0");
9335 _trace();
9336
9337 if (Packages_ != nil) {
9338 CFDictionaryApplyFunction((CFDictionaryRef) Packages_, &PackageImport, NULL);
9339 _trace();
9340 [Metadata_ removeObjectForKey:@"Packages"];
9341 Packages_ = nil;
9342 Changed_ = true;
9343 }
9344
9345 Finishes_ = [NSArray arrayWithObjects:@"return", @"reopen", @"restart", @"reload", @"reboot", nil];
9346
9347 if (substrate && access("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", F_OK) == 0)
9348 dlopen("/Library/MobileSubstrate/DynamicLibraries/SimulatedKeyEvents.dylib", RTLD_LAZY | RTLD_GLOBAL);
9349 if (substrate && access("/Applications/WinterBoard.app/WinterBoard.dylib", F_OK) == 0)
9350 dlopen("/Applications/WinterBoard.app/WinterBoard.dylib", RTLD_LAZY | RTLD_GLOBAL);
9351 /*if (substrate && access("/Library/MobileSubstrate/MobileSubstrate.dylib", F_OK) == 0)
9352 dlopen("/Library/MobileSubstrate/MobileSubstrate.dylib", RTLD_LAZY | RTLD_GLOBAL);*/
9353
9354 int version([[NSString stringWithContentsOfFile:@"/var/lib/cydia/firmware.ver"] intValue]);
9355
9356 if (access("/tmp/.cydia.fw", F_OK) == 0) {
9357 unlink("/tmp/.cydia.fw");
9358 goto firmware;
9359 } else if (access("/User", F_OK) != 0 || version < 2) {
9360 firmware:
9361 _trace();
9362 system("/usr/libexec/cydia/firmware.sh");
9363 _trace();
9364 }
9365
9366 _assert([[NSFileManager defaultManager]
9367 createDirectoryAtPath:@"/var/cache/apt/archives/partial"
9368 withIntermediateDirectories:YES
9369 attributes:nil
9370 error:NULL
9371 ]);
9372
9373 if (access("/tmp/cydia.chk", F_OK) == 0) {
9374 if (unlink("/var/cache/apt/pkgcache.bin") == -1)
9375 _assert(errno == ENOENT);
9376 if (unlink("/var/cache/apt/srcpkgcache.bin") == -1)
9377 _assert(errno == ENOENT);
9378 }
9379
9380 /* APT Initialization {{{ */
9381 _assert(pkgInitConfig(*_config));
9382 _assert(pkgInitSystem(*_config, _system));
9383
9384 if (lang != NULL)
9385 _config->Set("APT::Acquire::Translation", lang);
9386
9387 // XXX: this timeout might be important :(
9388 //_config->Set("Acquire::http::Timeout", 15);
9389
9390 _config->Set("Acquire::http::MaxParallel", 3);
9391 /* }}} */
9392 /* Color Choices {{{ */
9393 space_ = CGColorSpaceCreateDeviceRGB();
9394
9395 Blue_.Set(space_, 0.2, 0.2, 1.0, 1.0);
9396 Blueish_.Set(space_, 0x19/255.f, 0x32/255.f, 0x50/255.f, 1.0);
9397 Black_.Set(space_, 0.0, 0.0, 0.0, 1.0);
9398 Off_.Set(space_, 0.9, 0.9, 0.9, 1.0);
9399 White_.Set(space_, 1.0, 1.0, 1.0, 1.0);
9400 Gray_.Set(space_, 0.4, 0.4, 0.4, 1.0);
9401 Green_.Set(space_, 0.0, 0.5, 0.0, 1.0);
9402 Purple_.Set(space_, 0.0, 0.0, 0.7, 1.0);
9403 Purplish_.Set(space_, 0.4, 0.4, 0.8, 1.0);
9404
9405 InstallingColor_ = [UIColor colorWithRed:0.88f green:1.00f blue:0.88f alpha:1.00f];
9406 RemovingColor_ = [UIColor colorWithRed:1.00f green:0.88f blue:0.88f alpha:1.00f];
9407 /* }}}*/
9408 /* UIKit Configuration {{{ */
9409 void (*$GSFontSetUseLegacyFontMetrics)(BOOL)(reinterpret_cast<void (*)(BOOL)>(dlsym(RTLD_DEFAULT, "GSFontSetUseLegacyFontMetrics")));
9410 if ($GSFontSetUseLegacyFontMetrics != NULL)
9411 $GSFontSetUseLegacyFontMetrics(YES);
9412
9413 // XXX: I have a feeling this was important
9414 //UIKeyboardDisableAutomaticAppearance();
9415 /* }}} */
9416
9417 Colon_ = UCLocalize("COLON_DELIMITED");
9418 Elision_ = UCLocalize("ELISION");
9419 Error_ = UCLocalize("ERROR");
9420 Warning_ = UCLocalize("WARNING");
9421
9422 _trace();
9423 int value(UIApplicationMain(argc, argv, @"Cydia", @"Cydia"));
9424
9425 CGColorSpaceRelease(space_);
9426 CFRelease(Locale_);
9427
9428 return value;
9429 }